refactor(web): remove reducer pattern, use Zustand + pure functions

- Main store: replace useReducer with Zustand; pure state transition
  functions (syncServerReadModel, markThreadVisited, setError, etc.)
  called via store methods. Persist via subscribe.
- Terminal store: single store keyed by threadId; replace
  dispatchTerminalAction with direct methods (setTerminalOpen,
  setTerminalHeight, splitTerminal, newTerminal, setActiveTerminal,
  closeTerminal, setTerminalActivity). Pure reduceThreadTerminalState
  used internally.
- Update all consumers to call dispatch.method(...) and terminal
  store methods. Fix store tests to use markThreadUnread pure fn.
- Fix Fragment import in store.ts; fix unused get param for lint.

Made-with: Cursor
This commit is contained in:
Julius Marminge committed 2026-03-02 10:23:53 -08:00
1 parent 67dddb31df
commit c283d2a85b
11 files changed
+421 -830

No files matched your search

+3 -8
View File
@@ -114,12 +114,7 @@ export default function BranchToolbar({
});
}
if (hasServerThread) {
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
dispatch.setThreadBranch(activeThreadId, syncedBranch, null);
return;
}
setDraftThreadContext(threadId, {
@@ -147,7 +142,7 @@ export default function BranchToolbar({
const setThreadError = (error: string | null) => {
if (!activeThreadId) return;
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
dispatch.setError(activeThreadId, error);
};
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
@@ -176,7 +171,7 @@ export default function BranchToolbar({
});
}
if (hasServerThread) {
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
dispatch.setThreadBranch(activeThreadId, branch, worktreePath);
return;
}
setDraftThreadContext(threadId, {
+57 -212
View File
@@ -57,7 +57,6 @@ import {
type Thread,
type TurnDiffSummary,
} from "../types";
import type { ThreadTerminalState } from "../threadTerminalState";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
@@ -121,6 +120,7 @@ import {
useComposerDraftStore,
useComposerThreadDraft,
} from "../composerDraftStore";
import { useTerminalStateStore } from "../terminalStateStore";
import { clamp } from "effect/Number";
function formatMessageMeta(createdAt: string, duration: string | null): string {
@@ -199,7 +199,6 @@ function buildExpandedImagePreview(
function buildLocalDraftThread(
threadId: ThreadId,
draftThread: DraftThreadState,
draftTerminalState: ThreadTerminalState,
fallbackModel: string,
error: string | null,
): Thread {
@@ -209,13 +208,6 @@ function buildLocalDraftThread(
projectId: draftThread.projectId,
title: "New thread",
model: fallbackModel,
terminalOpen: draftTerminalState.terminalOpen,
terminalHeight: draftTerminalState.terminalHeight,
terminalIds: draftTerminalState.terminalIds,
runningTerminalIds: draftTerminalState.runningTerminalIds,
activeTerminalId: draftTerminalState.activeTerminalId,
terminalGroups: draftTerminalState.terminalGroups,
activeTerminalGroupId: draftTerminalState.activeTerminalGroupId,
session: null,
messages: [],
error,
@@ -229,46 +221,6 @@ function buildLocalDraftThread(
};
}
function threadTerminalsMatchState(thread: Thread, terminalState: ThreadTerminalState): boolean {
if (
thread.terminalOpen !== terminalState.terminalOpen ||
thread.terminalHeight !== terminalState.terminalHeight ||
thread.activeTerminalId !== terminalState.activeTerminalId ||
thread.activeTerminalGroupId !== terminalState.activeTerminalGroupId
) {
return false;
}
if (
thread.terminalIds.length !== terminalState.terminalIds.length ||
thread.runningTerminalIds.length !== terminalState.runningTerminalIds.length ||
thread.terminalGroups.length !== terminalState.terminalGroups.length
) {
return false;
}
if (!thread.terminalIds.every((terminalId, index) => terminalId === terminalState.terminalIds[index])) {
return false;
}
if (
!thread.runningTerminalIds.every(
(terminalId, index) => terminalId === terminalState.runningTerminalIds[index],
)
) {
return false;
}
return thread.terminalGroups.every((group, groupIndex) => {
const terminalStateGroup = terminalState.terminalGroups[groupIndex];
if (!terminalStateGroup || group.id !== terminalStateGroup.id) {
return false;
}
if (group.terminalIds.length !== terminalStateGroup.terminalIds.length) {
return false;
}
return group.terminalIds.every(
(terminalId, terminalIdIndex) => terminalId === terminalStateGroup.terminalIds[terminalIdIndex],
);
});
}
function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
return;
@@ -534,13 +486,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
const setDraftThreadTerminalAction = useComposerDraftStore((s) => s.setDraftThreadTerminalAction);
const clearDraftThreadTerminalState = useComposerDraftStore(
(s) => s.clearDraftThreadTerminalState,
);
const localDraftTerminalState = useComposerDraftStore((s) =>
s.getDraftThreadTerminalState(threadId),
);
const terminalState = useTerminalStateStore((s) => s.getTerminalState(threadId));
const storeSetTerminalOpen = useTerminalStateStore((s) => s.setTerminalOpen);
const storeSetTerminalHeight = useTerminalStateStore((s) => s.setTerminalHeight);
const storeSplitTerminal = useTerminalStateStore((s) => s.splitTerminal);
const storeNewTerminal = useTerminalStateStore((s) => s.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal);
const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal);
const setPrompt = useCallback(
(nextPrompt: string) => {
@@ -582,12 +534,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
? buildLocalDraftThread(
threadId,
draftThread,
localDraftTerminalState,
fallbackDraftProject?.model ?? DEFAULT_MODEL,
localDraftError,
)
: undefined,
[draftThread, fallbackDraftProject?.model, localDraftError, localDraftTerminalState, threadId],
[draftThread, fallbackDraftProject?.model, localDraftError, threadId],
);
const activeThread = serverThread ?? localDraftThread;
const isServerThread = serverThread !== undefined;
@@ -615,25 +566,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}, [serverThread, threadId]);
useEffect(() => {
if (!serverThread) {
return;
}
const draft = useComposerDraftStore.getState().draftThreadsByThreadId[threadId];
const draftTerminal = draft?.terminalState;
if (draftTerminal === undefined) {
return;
}
if (!threadTerminalsMatchState(serverThread, draftTerminal)) {
dispatch({
type: "HYDRATE_THREAD_TERMINALS",
threadId: serverThread.id,
terminalState: draftTerminal,
});
}
clearDraftThreadTerminalState(threadId);
}, [clearDraftThreadTerminalState, dispatch, serverThread, threadId]);
useEffect(() => {
if (!activeThread?.id) return;
if (!latestTurnSettled) return;
@@ -643,10 +575,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
dispatch({
type: "MARK_THREAD_VISITED",
threadId: activeThread.id,
});
dispatch.markThreadVisited(activeThread.id);
}, [
activeThread?.id,
activeThread?.lastVisitedAt,
@@ -916,16 +845,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
(activeThread.session !== null && activeThread.session.status !== "closed")),
);
const hasReachedTerminalLimit =
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
terminalState.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
const setThreadError = useCallback(
(targetThreadId: ThreadId | null, error: string | null) => {
if (!targetThreadId) return;
if (state.threads.some((thread) => thread.id === targetThreadId)) {
dispatch({
type: "SET_ERROR",
threadId: targetThreadId,
error,
});
dispatch.setError(targetThreadId, error);
return;
}
setLocalDraftErrorsByThreadId((existing) => {
@@ -956,86 +881,46 @@ export default function ChatView({ threadId }: ChatViewProps) {
const setTerminalOpen = useCallback(
(open: boolean) => {
if (!activeThreadId) return;
if (isLocalDraftThread) {
setDraftThreadTerminalAction(activeThreadId, { type: "set-open", open });
return;
}
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open,
});
storeSetTerminalOpen(activeThreadId, open);
},
[activeThreadId, dispatch, isLocalDraftThread, setDraftThreadTerminalAction],
[activeThreadId, storeSetTerminalOpen],
);
const setTerminalHeight = useCallback(
(height: number) => {
if (!activeThreadId) return;
if (isLocalDraftThread) {
setDraftThreadTerminalAction(activeThreadId, { type: "set-height", height });
return;
}
dispatch({
type: "SET_THREAD_TERMINAL_HEIGHT",
threadId: activeThreadId,
height,
});
storeSetTerminalHeight(activeThreadId, height);
},
[activeThreadId, dispatch, isLocalDraftThread, setDraftThreadTerminalAction],
[activeThreadId, storeSetTerminalHeight],
);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadId) return;
setTerminalOpen(!activeThread?.terminalOpen);
}, [activeThread?.terminalOpen, activeThreadId, setTerminalOpen]);
setTerminalOpen(!terminalState.terminalOpen);
}, [activeThreadId, setTerminalOpen, terminalState.terminalOpen]);
const splitTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return;
const terminalId = `terminal-${crypto.randomUUID()}`;
if (isLocalDraftThread) {
setDraftThreadTerminalAction(activeThreadId, { type: "split", terminalId });
} else {
dispatch({
type: "SPLIT_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId,
});
}
storeSplitTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch, hasReachedTerminalLimit, isLocalDraftThread, setDraftThreadTerminalAction]);
}, [activeThreadId, storeSplitTerminal, hasReachedTerminalLimit]);
const createNewTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return;
const terminalId = `terminal-${crypto.randomUUID()}`;
if (isLocalDraftThread) {
setDraftThreadTerminalAction(activeThreadId, { type: "new", terminalId });
} else {
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId,
});
}
storeNewTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch, hasReachedTerminalLimit, isLocalDraftThread, setDraftThreadTerminalAction]);
}, [activeThreadId, storeNewTerminal, hasReachedTerminalLimit]);
const activateTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId) return;
if (isLocalDraftThread) {
setDraftThreadTerminalAction(activeThreadId, { type: "set-active", terminalId });
} else {
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId,
});
}
storeSetActiveTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, dispatch, isLocalDraftThread, setDraftThreadTerminalAction],
[activeThreadId, storeSetActiveTerminal],
);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readNativeApi();
if (!activeThreadId || !api) return;
const isFinalTerminal = (activeThread?.terminalIds.length ?? 0) <= 1;
const isFinalTerminal = terminalState.terminalIds.length <= 1;
const fallbackExitWrite = () =>
api.terminal
.write({ threadId: activeThreadId, terminalId, data: "exit\n" })
@@ -1052,18 +937,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
} else {
void fallbackExitWrite();
}
if (isLocalDraftThread) {
setDraftThreadTerminalAction(activeThreadId, { type: "close", terminalId });
} else {
dispatch({
type: "CLOSE_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId,
});
}
storeCloseTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
},
[activeThread?.terminalIds.length, activeThreadId, dispatch, isLocalDraftThread, setDraftThreadTerminalAction],
[activeThreadId, storeCloseTerminal, terminalState.terminalIds.length],
);
const runProjectScript = useCallback(
async (
@@ -1088,42 +965,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd;
const baseTerminalId =
activeThread.activeTerminalId || activeThread.terminalIds[0] || DEFAULT_THREAD_TERMINAL_ID;
const isBaseTerminalBusy = activeThread.runningTerminalIds.includes(baseTerminalId);
terminalState.activeTerminalId ||
terminalState.terminalIds[0] ||
DEFAULT_THREAD_TERMINAL_ID;
const isBaseTerminalBusy = terminalState.runningTerminalIds.includes(baseTerminalId);
const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
const shouldCreateNewTerminal =
wantsNewTerminal && activeThread.terminalIds.length < MAX_THREAD_TERMINAL_COUNT;
wantsNewTerminal && terminalState.terminalIds.length < MAX_THREAD_TERMINAL_COUNT;
const targetTerminalId = shouldCreateNewTerminal
? `terminal-${crypto.randomUUID()}`
: baseTerminalId;
setTerminalOpen(true);
if (shouldCreateNewTerminal) {
if (isLocalDraftThread) {
setDraftThreadTerminalAction(activeThreadId, {
type: "new",
terminalId: targetTerminalId,
});
} else {
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
}
storeNewTerminal(activeThreadId, targetTerminalId);
} else {
if (isLocalDraftThread) {
setDraftThreadTerminalAction(activeThreadId, {
type: "set-active",
terminalId: targetTerminalId,
});
} else {
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
}
storeSetActiveTerminal(activeThreadId, targetTerminalId);
}
setTerminalFocusRequestId((value) => value + 1);
@@ -1170,7 +1027,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
isServerThread,
setTerminalOpen,
setThreadError,
setDraftThreadTerminalAction,
storeNewTerminal,
storeSetActiveTerminal,
],
);
const persistProjectScripts = useCallback(
@@ -1275,7 +1133,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return;
dispatch({ type: "SET_RUNTIME_MODE", mode });
dispatch.setRuntimeMode(mode);
scheduleComposerFocus();
const api = readNativeApi();
if (!api) return;
@@ -1367,14 +1225,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [activeThread?.id]);
useEffect(() => {
if (!activeThread?.id || activeThread.terminalOpen) return;
if (!activeThread?.id || terminalState.terminalOpen) return;
const frame = window.requestAnimationFrame(() => {
focusComposer();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [activeThread?.id, activeThread?.terminalOpen, focusComposer]);
}, [activeThread?.id, focusComposer, terminalState.terminalOpen]);
useEffect(() => {
composerImagesRef.current = composerImages;
@@ -1572,7 +1430,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => {
if (!activeThreadId) return;
const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false;
const current = Boolean(activeThread?.terminalOpen);
const current = Boolean(terminalState.terminalOpen);
if (!previous && current) {
setTerminalFocusRequestId((value) => value + 1);
@@ -1587,7 +1445,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
terminalOpenByThreadRef.current[activeThreadId] = current;
}, [activeThread?.terminalOpen, activeThreadId, focusComposer]);
}, [activeThreadId, focusComposer, terminalState.terminalOpen]);
useEffect(() => {
const isTerminalFocused = (): boolean => {
@@ -1601,7 +1459,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (!activeThreadId || event.defaultPrevented) return;
const shortcutContext = {
terminalFocus: isTerminalFocused(),
terminalOpen: Boolean(activeThread?.terminalOpen),
terminalOpen: Boolean(terminalState.terminalOpen),
};
const command = resolveShortcutCommand(event, keybindings, { context: shortcutContext });
@@ -1617,7 +1475,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
}
splitTerminal();
@@ -1627,15 +1485,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (command === "terminal.close") {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) return;
closeTerminal(activeThread.activeTerminalId);
if (!terminalState.terminalOpen) return;
closeTerminal(terminalState.activeTerminalId);
return;
}
if (command === "terminal.new") {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
}
createNewTerminal();
@@ -1661,8 +1519,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
return () => window.removeEventListener("keydown", handler);
}, [
activeProject,
activeThread?.terminalOpen,
activeThread?.activeTerminalId,
terminalState.terminalOpen,
terminalState.activeTerminalId,
activeThreadId,
closeTerminal,
createNewTerminal,
@@ -1838,11 +1696,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const shouldCreateWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;
if (shouldCreateWorktree && !activeThread.branch) {
dispatch({
type: "SET_ERROR",
threadId: threadIdForSend,
error: "Select a base branch before sending in New worktree mode.",
});
dispatch.setError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
return;
}
@@ -1912,12 +1766,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
// Keep local thread state in sync immediately so terminal drawer opens
// with the worktree cwd/env instead of briefly using the project root.
dispatch({
type: "SET_THREAD_BRANCH",
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
dispatch.setThreadBranch(threadIdForSend, result.worktree.branch, result.worktree.path);
}
}
@@ -2058,11 +1907,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: new Date().toISOString(),
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThreadId,
error: err instanceof Error ? err.message : "Failed to submit approval decision.",
});
dispatch.setError(activeThreadId, err instanceof Error ? err.message : "Failed to submit approval decision.");
} finally {
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
}
@@ -2587,7 +2432,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
)}
{(() => {
if (!activeThread.terminalOpen || !activeProject) {
if (!terminalState.terminalOpen || !activeProject) {
return null;
}
return (
@@ -2596,11 +2441,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId={activeThread.id}
cwd={gitCwd ?? activeProject.cwd}
runtimeEnv={threadTerminalRuntimeEnv}
height={activeThread.terminalHeight}
terminalIds={activeThread.terminalIds}
activeTerminalId={activeThread.activeTerminalId}
terminalGroups={activeThread.terminalGroups}
activeTerminalGroupId={activeThread.activeTerminalGroupId}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
+11 -5
View File
@@ -21,6 +21,7 @@ import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
import { useTerminalStateStore } from "../terminalStateStore";
import { toastManager } from "./ui/toast";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -126,8 +127,10 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
return null;
}
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
if (thread.runningTerminalIds.length === 0) {
function terminalStatusFromRunningIds(
runningTerminalIds: string[],
): TerminalStatusIndicator | null {
if (runningTerminalIds.length === 0) {
return null;
}
return {
@@ -234,6 +237,7 @@ export default function Sidebar() {
(store) => store.getDraftThreadByProjectId,
);
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const getTerminalState = useTerminalStateStore((s) => s.getTerminalState);
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const clearProjectDraftThreadId = useComposerDraftStore(
@@ -497,7 +501,7 @@ export default function Sidebar() {
position,
);
if (clicked === "mark-unread") {
dispatch({ type: "MARK_THREAD_UNREAD", threadId });
dispatch.markThreadUnread(threadId);
return;
}
if (clicked !== "delete") return;
@@ -769,7 +773,7 @@ export default function Sidebar() {
open={project.expanded}
onOpenChange={(open) => {
if (open === project.expanded) return;
dispatch({ type: "TOGGLE_PROJECT", projectId: project.id });
dispatch.toggleProject(project.id);
}}
>
<SidebarMenuItem>
@@ -811,7 +815,9 @@ export default function Sidebar() {
pendingApprovalByThreadId.get(thread.id) === true,
);
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusIndicator(thread);
const terminalStatus = terminalStatusFromRunningIds(
getTerminalState(thread.id).runningTerminalIds,
);
return (
<SidebarMenuSubItem key={thread.id} className="w-full">
-59
View File
@@ -6,13 +6,6 @@ import {
normalizeModelSlug,
type ReasoningEffort,
} from "@t3tools/contracts";
import {
createDefaultThreadTerminalState,
getDefaultThreadTerminalState,
reduceThreadTerminalState,
type ThreadTerminalAction,
type ThreadTerminalState,
} from "./threadTerminalState";
import type { ChatImageAttachment } from "./types";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
@@ -71,8 +64,6 @@ export interface DraftThreadState {
branch: string | null;
worktreePath: string | null;
envMode: DraftThreadEnvMode;
/** Terminal layout for draft thread; same shape as Thread terminal slice. Omitted when not set. */
terminalState?: ThreadTerminalState;
}
interface ProjectDraftThread extends DraftThreadState {
@@ -122,9 +113,6 @@ interface ComposerDraftStoreState {
) => void;
clearComposerContent: (threadId: ThreadId) => void;
clearThreadDraft: (threadId: ThreadId) => void;
getDraftThreadTerminalState: (threadId: ThreadId) => ThreadTerminalState;
setDraftThreadTerminalAction: (threadId: ThreadId, action: ThreadTerminalAction) => void;
clearDraftThreadTerminalState: (threadId: ThreadId) => void;
}
const EMPTY_PERSISTED_DRAFT_STORE_STATE: PersistedComposerDraftStoreState = {
@@ -678,53 +666,6 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
};
});
},
getDraftThreadTerminalState: (threadId) => {
if (threadId.length === 0) {
return getDefaultThreadTerminalState();
}
const draft = get().draftThreadsByThreadId[threadId];
return draft?.terminalState ?? getDefaultThreadTerminalState();
},
setDraftThreadTerminalAction: (threadId, action) => {
if (threadId.length === 0) {
return;
}
set((state) => {
const existing = state.draftThreadsByThreadId[threadId];
if (!existing) {
return state;
}
const current = existing.terminalState ?? createDefaultThreadTerminalState();
const next = reduceThreadTerminalState(current, action);
if (next === current) {
return state;
}
return {
draftThreadsByThreadId: {
...state.draftThreadsByThreadId,
[threadId]: { ...existing, terminalState: next },
},
};
});
},
clearDraftThreadTerminalState: (threadId) => {
if (threadId.length === 0) {
return;
}
set((state) => {
const existing = state.draftThreadsByThreadId[threadId];
if (!existing || existing.terminalState === undefined) {
return state;
}
const { terminalState: _removed, ...rest } = existing;
return {
draftThreadsByThreadId: {
...state.draftThreadsByThreadId,
[threadId]: rest,
},
};
});
},
setPrompt: (threadId, prompt) => {
if (threadId.length === 0) {
return;
+7 -11
View File
@@ -15,6 +15,7 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { preferredTerminalEditor } from "../terminal-links";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
@@ -144,7 +145,7 @@ function EventRouter() {
const snapshot = await api.orchestration.getSnapshot();
if (disposed) return;
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
dispatch.syncServerReadModel(snapshot);
if (pending) {
pending = false;
await flushSnapshotSync();
@@ -184,12 +185,11 @@ function EventRouter() {
if (hasRunningSubprocess === null) {
return;
}
dispatch({
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe(event.threadId),
terminalId: event.terminalId,
useTerminalStateStore.getState().setTerminalActivity(
ThreadId.makeUnsafe(event.threadId),
event.terminalId,
hasRunningSubprocess,
});
);
});
const unsubWelcome = onServerWelcome((payload) => {
void (async () => {
@@ -201,11 +201,7 @@ function EventRouter() {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return;
}
dispatch({
type: "SET_PROJECT_EXPANDED",
projectId: payload.bootstrapProjectId,
expanded: true,
});
dispatch.setProjectExpanded(payload.bootstrapProjectId, true);
if (pathnameRef.current !== "/") {
return;
+1 -4
View File
@@ -346,10 +346,7 @@ function SettingsRouteView() {
: "border-border bg-background text-muted-foreground hover:bg-accent"
}`}
onClick={() => {
dispatch({
type: "SET_RUNTIME_MODE",
mode: option.value,
});
dispatch.setRuntimeMode(option.value);
}}
>
<span className="flex flex-col">
+7 -123
View File
@@ -1,8 +1,8 @@
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { reducer, type AppState } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
import { markThreadUnread, type AppState } from "./store";
import type { Thread } from "./types";
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
@@ -11,18 +11,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
model: "gpt-5-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
turnDiffSummaries: [],
@@ -54,8 +42,8 @@ function makeState(thread: Thread): AppState {
};
}
describe("store reducer", () => {
it("marks a completed thread as unread by moving lastVisitedAt before completion", () => {
describe("store pure functions", () => {
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeState(
makeThread({
@@ -71,10 +59,7 @@ describe("store reducer", () => {
}),
);
const next = reducer(initialState, {
type: "MARK_THREAD_UNREAD",
threadId: ThreadId.makeUnsafe("thread-1"),
});
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
const updatedThread = next.threads[0];
expect(updatedThread).toBeDefined();
@@ -84,7 +69,7 @@ describe("store reducer", () => {
);
});
it("does not change a thread without a completed turn", () => {
it("markThreadUnread does not change a thread without a completed turn", () => {
const initialState = makeState(
makeThread({
latestTurn: null,
@@ -92,109 +77,8 @@ describe("store reducer", () => {
}),
);
const next = reducer(initialState, {
type: "MARK_THREAD_UNREAD",
threadId: ThreadId.makeUnsafe("thread-1"),
});
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
expect(next).toEqual(initialState);
});
});
describe("store terminal activity reducer", () => {
it("adds a terminal to runningTerminalIds when subprocess activity starts", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
},
],
}),
);
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe("thread-1"),
terminalId: "alt",
hasRunningSubprocess: true,
});
expect(next.threads[0]?.runningTerminalIds).toEqual(["alt"]);
});
it("removes a terminal from runningTerminalIds when subprocess activity stops", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
},
],
runningTerminalIds: ["alt"],
}),
);
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe("thread-1"),
terminalId: "alt",
hasRunningSubprocess: false,
});
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
});
it("ignores activity events for unknown terminal ids", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe("thread-1"),
terminalId: "missing",
hasRunningSubprocess: true,
});
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
});
it("hydrates terminal state for an existing thread", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "HYDRATE_THREAD_TERMINALS",
threadId: ThreadId.makeUnsafe("thread-1"),
terminalState: {
terminalOpen: true,
terminalHeight: 360,
terminalIds: ["default", "terminal-2"],
runningTerminalIds: ["terminal-2"],
activeTerminalId: "terminal-2",
terminalGroups: [
{
id: "group-default",
terminalIds: ["default"],
},
{
id: "group-terminal-2",
terminalIds: ["terminal-2"],
},
],
activeTerminalGroupId: "group-terminal-2",
},
});
expect(next.threads[0]).toMatchObject({
terminalOpen: true,
terminalHeight: 360,
terminalIds: ["default", "terminal-2"],
runningTerminalIds: ["terminal-2"],
activeTerminalId: "terminal-2",
terminalGroups: [
{ id: "group-default", terminalIds: ["default"] },
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
],
activeTerminalGroupId: "group-terminal-2",
});
});
});
+224 -388
View File
@@ -1,13 +1,4 @@
import {
type Dispatch,
type ReactNode,
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import { Fragment, type ReactNode, createElement, useEffect } from "react";
import {
DEFAULT_MODEL,
ProviderSessionId,
@@ -16,12 +7,7 @@ import {
type OrchestrationSessionStatus,
resolveModelSlug,
} from "@t3tools/contracts";
import {
createDefaultThreadTerminalState,
normalizeThreadTerminalState,
reduceThreadTerminalState,
type ThreadTerminalState,
} from "./threadTerminalState";
import { create } from "zustand";
import {
DEFAULT_RUNTIME_MODE,
type ChatMessage,
@@ -30,37 +16,6 @@ import {
type Thread,
} from "./types";
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
| { type: "HYDRATE_THREAD_TERMINALS"; threadId: ThreadId; terminalState: ThreadTerminalState }
| { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
| { type: "MARK_THREAD_UNREAD"; threadId: ThreadId }
| { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
| {
type: "SET_THREAD_TERMINAL_ACTIVITY";
threadId: ThreadId;
terminalId: string;
hasRunningSubprocess: boolean;
}
| { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
| { type: "SPLIT_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "NEW_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "CLOSE_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "SET_ERROR"; threadId: ThreadId; error: string | null }
| {
type: "SET_THREAD_BRANCH";
threadId: ThreadId;
branch: string | null;
worktreePath: string | null;
}
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
// ── State ────────────────────────────────────────────────────────────
export interface AppState {
@@ -90,11 +45,10 @@ const initialState: AppState = {
};
const persistedExpandedProjectCwds = new Set<string>();
// ── Helpers ──────────────────────────────────────────────────────────
// ── Persist helpers ──────────────────────────────────────────────────
function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
if (!raw) return initialState;
@@ -122,7 +76,6 @@ function readPersistedState(): AppState {
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
PERSISTED_STATE_KEY,
@@ -141,6 +94,8 @@ function persistState(state: AppState): void {
}
}
// ── Pure helpers ──────────────────────────────────────────────────────
function updateThread(
threads: Thread[],
threadId: ThreadId,
@@ -196,9 +151,7 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
}
function resolveWsHttpOrigin(): string {
if (typeof window === "undefined") {
return "";
}
if (typeof window === "undefined") return "";
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
const wsCandidate =
@@ -207,10 +160,7 @@ function resolveWsHttpOrigin(): string {
: typeof envWsUrl === "string" && envWsUrl.length > 0
? envWsUrl
: null;
if (!wsCandidate) {
return window.location.origin;
}
if (!wsCandidate) return window.location.origin;
try {
const wsUrl = new URL(wsCandidate);
const protocol =
@@ -236,352 +186,238 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
return `/attachments/${encodeURIComponent(attachmentId)}`;
}
function threadTerminalSlice(thread: Thread): ThreadTerminalState {
// ── Pure state transition functions ────────────────────────────────────
export function syncServerReadModel(
state: AppState,
readModel: OrchestrationReadModel,
): AppState {
const projects = mapProjectsFromReadModel(
readModel.projects.filter((project) => project.deletedAt === null),
state.projects,
);
const existingThreadById = new Map(
state.threads.map((thread) => [thread.id, thread] as const),
);
const threads = readModel.threads
.filter((thread) => thread.deletedAt === null)
.map((thread) => {
const existing = existingThreadById.get(thread.id);
return {
id: thread.id,
codexThreadId: thread.session?.providerThreadId ?? null,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(thread.model),
session: thread.session
? {
sessionId:
thread.session.providerSessionId ??
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
provider: toLegacyProvider(thread.session.providerName),
status: toLegacySessionStatus(thread.session.status),
orchestrationStatus: thread.session.status,
threadId: thread.session.providerThreadId,
activeTurnId: thread.session.activeTurnId ?? undefined,
createdAt: thread.session.updatedAt,
updatedAt: thread.session.updatedAt,
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
}
: null,
messages: thread.messages.map((message) => {
const attachments = message.attachments?.map((attachment) => ({
type: "image" as const,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
}));
const normalizedMessage: ChatMessage = {
id: message.id,
role: message.role,
text: message.text,
createdAt: message.createdAt,
streaming: message.streaming,
...(message.streaming ? {} : { completedAt: message.updatedAt }),
...(attachments && attachments.length > 0 ? { attachments } : {}),
};
return normalizedMessage;
}),
error: thread.session?.lastError ?? null,
createdAt: thread.createdAt,
latestTurn: thread.latestTurn,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
turnId: checkpoint.turnId,
completedAt: checkpoint.completedAt,
status: checkpoint.status,
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
checkpointTurnCount: checkpoint.checkpointTurnCount,
checkpointRef: checkpoint.checkpointRef,
files: checkpoint.files.map((file) => ({ ...file })),
})),
activities: thread.activities.map((activity) => ({ ...activity })),
};
});
return {
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
terminalIds: thread.terminalIds,
runningTerminalIds: thread.runningTerminalIds,
activeTerminalId: thread.activeTerminalId,
terminalGroups: thread.terminalGroups,
activeTerminalGroupId: thread.activeTerminalGroupId,
...state,
projects,
threads,
threadsHydrated: true,
};
}
function applyTerminalState(thread: Thread, terminal: ThreadTerminalState): Thread {
return { ...thread, ...terminal };
export function markThreadVisited(
state: AppState,
threadId: ThreadId,
visitedAt?: string,
): AppState {
const at = visitedAt ?? new Date().toISOString();
const visitedAtMs = Date.parse(at);
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => {
const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
if (
Number.isFinite(previousVisitedAtMs) &&
Number.isFinite(visitedAtMs) &&
previousVisitedAtMs >= visitedAtMs
) {
return thread;
}
return { ...thread, lastVisitedAt: at };
}),
};
}
function normalizeThreadTerminals(thread: Thread): Thread {
return applyTerminalState(thread, normalizeThreadTerminalState(threadTerminalSlice(thread)));
export function markThreadUnread(state: AppState, threadId: ThreadId): AppState {
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => {
if (!thread.latestTurn?.completedAt) return thread;
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) return thread;
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
if (thread.lastVisitedAt === unreadVisitedAt) return thread;
return { ...thread, lastVisitedAt: unreadVisitedAt };
}),
};
}
// ── Reducer ──────────────────────────────────────────────────────────
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "SYNC_SERVER_READ_MODEL": {
const projects = mapProjectsFromReadModel(
action.readModel.projects.filter((project) => project.deletedAt === null),
state.projects,
);
const existingThreadById = new Map(
state.threads.map((thread) => [thread.id, thread] as const),
);
const defaultTerminal = createDefaultThreadTerminalState();
const threads = action.readModel.threads
.filter((thread) => thread.deletedAt === null)
.map((thread) => {
const existing = existingThreadById.get(thread.id);
const terminalSlice: ThreadTerminalState = existing
? threadTerminalSlice(existing)
: defaultTerminal;
return normalizeThreadTerminals({
id: thread.id,
codexThreadId: thread.session?.providerThreadId ?? null,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(thread.model),
...terminalSlice,
session: thread.session
? {
sessionId:
thread.session.providerSessionId ??
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
provider: toLegacyProvider(thread.session.providerName),
status: toLegacySessionStatus(thread.session.status),
orchestrationStatus: thread.session.status,
threadId: thread.session.providerThreadId,
activeTurnId: thread.session.activeTurnId ?? undefined,
createdAt: thread.session.updatedAt,
updatedAt: thread.session.updatedAt,
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
}
: null,
messages: thread.messages.map((message) => {
const attachments = message.attachments?.map((attachment) => ({
type: "image" as const,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
}));
const normalizedMessage: ChatMessage = {
id: message.id,
role: message.role,
text: message.text,
createdAt: message.createdAt,
streaming: message.streaming,
...(message.streaming ? {} : { completedAt: message.updatedAt }),
...(attachments && attachments.length > 0 ? { attachments } : {}),
};
return normalizedMessage;
}),
error: thread.session?.lastError ?? null,
createdAt: thread.createdAt,
latestTurn: thread.latestTurn,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
turnId: checkpoint.turnId,
completedAt: checkpoint.completedAt,
status: checkpoint.status,
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
checkpointTurnCount: checkpoint.checkpointTurnCount,
checkpointRef: checkpoint.checkpointRef,
files: checkpoint.files.map((file) => ({ ...file })),
})),
activities: thread.activities.map((activity) => ({ ...activity })),
});
});
return {
...state,
projects,
threads,
threadsHydrated: true,
};
}
case "HYDRATE_THREAD_TERMINALS":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
applyTerminalState(thread, normalizeThreadTerminalState(action.terminalState)),
),
};
case "MARK_THREAD_VISITED": {
const visitedAt = action.visitedAt ?? new Date().toISOString();
const visitedAtMs = Date.parse(visitedAt);
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
if (
Number.isFinite(previousVisitedAtMs) &&
Number.isFinite(visitedAtMs) &&
previousVisitedAtMs >= visitedAtMs
) {
return thread;
}
return {
...thread,
lastVisitedAt: visitedAt,
};
}),
};
}
case "MARK_THREAD_UNREAD": {
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
if (!thread.latestTurn?.completedAt) {
return thread;
}
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) {
return thread;
}
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
if (thread.lastVisitedAt === unreadVisitedAt) {
return thread;
}
return {
...thread,
lastVisitedAt: unreadVisitedAt,
};
}),
};
}
case "TOGGLE_PROJECT":
return {
...state,
projects: state.projects.map((p) =>
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
),
};
case "SET_THREAD_TERMINAL_ACTIVITY":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
applyTerminalState(
thread,
reduceThreadTerminalState(threadTerminalSlice(thread), {
type: "set-activity",
terminalId: action.terminalId,
hasRunningSubprocess: action.hasRunningSubprocess,
}),
),
),
};
case "SET_PROJECT_EXPANDED":
return {
...state,
projects: state.projects.map((p) =>
p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
),
};
case "TOGGLE_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
applyTerminalState(
thread,
reduceThreadTerminalState(threadTerminalSlice(thread), {
type: "set-open",
open: !thread.terminalOpen,
}),
),
),
};
case "SET_THREAD_TERMINAL_OPEN":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
applyTerminalState(
thread,
reduceThreadTerminalState(threadTerminalSlice(thread), {
type: "set-open",
open: action.open,
}),
),
),
};
case "SET_THREAD_TERMINAL_HEIGHT":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
applyTerminalState(
thread,
reduceThreadTerminalState(threadTerminalSlice(thread), {
type: "set-height",
height: action.height,
}),
),
),
};
case "SPLIT_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
applyTerminalState(
thread,
reduceThreadTerminalState(threadTerminalSlice(thread), {
type: "split",
terminalId: action.terminalId,
}),
),
),
};
case "NEW_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
applyTerminalState(
thread,
reduceThreadTerminalState(threadTerminalSlice(thread), {
type: "new",
terminalId: action.terminalId,
}),
),
),
};
case "SET_THREAD_ACTIVE_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
applyTerminalState(
thread,
reduceThreadTerminalState(threadTerminalSlice(thread), {
type: "set-active",
terminalId: action.terminalId,
}),
),
),
};
case "CLOSE_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
applyTerminalState(
thread,
reduceThreadTerminalState(threadTerminalSlice(thread), {
type: "close",
terminalId: action.terminalId,
}),
),
),
};
case "SET_ERROR":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
error: action.error,
})),
};
case "SET_THREAD_BRANCH": {
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => {
// When the effective cwd changes (worktreePath differs), the old
// session is no longer valid — clear it so ensureSession creates a
// new one with the correct cwd on the next message.
const cwdChanged = t.worktreePath !== action.worktreePath;
return {
...t,
branch: action.branch,
worktreePath: action.worktreePath,
...(cwdChanged ? { session: null } : {}),
};
}),
};
}
case "SET_RUNTIME_MODE":
return {
...state,
runtimeMode: action.mode,
};
default:
return state;
}
export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
return {
...state,
projects: state.projects.map((p) =>
p.id === projectId ? { ...p, expanded: !p.expanded } : p,
),
};
}
// ── Context ──────────────────────────────────────────────────────────
export function setProjectExpanded(
state: AppState,
projectId: Project["id"],
expanded: boolean,
): AppState {
return {
...state,
projects: state.projects.map((p) =>
p.id === projectId ? { ...p, expanded } : p,
),
};
}
const StoreContext = createContext<{
state: AppState;
dispatch: Dispatch<Action>;
}>({ state: initialState, dispatch: () => {} });
export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
return {
...state,
threads: updateThread(state.threads, threadId, (t) => ({ ...t, error })),
};
}
export function setThreadBranch(
state: AppState,
threadId: ThreadId,
branch: string | null,
worktreePath: string | null,
): AppState {
return {
...state,
threads: updateThread(state.threads, threadId, (t) => {
const cwdChanged = t.worktreePath !== worktreePath;
return {
...t,
branch,
worktreePath,
...(cwdChanged ? { session: null } : {}),
};
}),
};
}
export function setRuntimeMode(state: AppState, mode: RuntimeMode): AppState {
return { ...state, runtimeMode: mode };
}
// ── Zustand store ────────────────────────────────────────────────────
interface AppStore extends AppState {
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
markThreadUnread: (threadId: ThreadId) => void;
toggleProject: (projectId: Project["id"]) => void;
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
setError: (threadId: ThreadId, error: string | null) => void;
setThreadBranch: (
threadId: ThreadId,
branch: string | null,
worktreePath: string | null,
) => void;
setRuntimeMode: (mode: RuntimeMode) => void;
}
export const useAppStore = create<AppStore>((set, _get) => ({
...readPersistedState(),
syncServerReadModel: (readModel) =>
set((state) => syncServerReadModel(state, readModel)),
markThreadVisited: (threadId, visitedAt) =>
set((state) => markThreadVisited(state, threadId, visitedAt)),
markThreadUnread: (threadId) =>
set((state) => markThreadUnread(state, threadId)),
toggleProject: (projectId) =>
set((state) => toggleProject(state, projectId)),
setProjectExpanded: (projectId, expanded) =>
set((state) => setProjectExpanded(state, projectId, expanded)),
setError: (threadId, error) =>
set((state) => setError(state, threadId, error)),
setThreadBranch: (threadId, branch, worktreePath) =>
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
setRuntimeMode: (mode) =>
set((state) => setRuntimeMode(state, mode)),
}));
// Persist on every state change (only runtimeMode + expandedProjectCwds)
useAppStore.subscribe((state) => persistState(state));
// ── useStore (state + store API for call sites that want both) ────────────────
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
useEffect(() => {
persistState(state);
}, [state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
persistState(useAppStore.getState());
}, []);
return createElement(Fragment, null, children);
}
export function useStore() {
return useContext(StoreContext);
const state = useAppStore((s) => ({
projects: s.projects,
threads: s.threads,
threadsHydrated: s.threadsHydrated,
runtimeMode: s.runtimeMode,
}));
return {
state,
dispatch: useAppStore.getState(),
};
}
+110
View File
@@ -0,0 +1,110 @@
/**
* Single Zustand store for terminal UI state keyed by threadId. Used by both
* persisted (server) threads and draft threads; threadId is stable for both.
*/
import type { ThreadId } from "@t3tools/contracts";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import {
createDefaultThreadTerminalState,
getDefaultThreadTerminalState,
reduceThreadTerminalState,
type ThreadTerminalAction,
type ThreadTerminalState,
} from "./threadTerminalState";
export const TERMINAL_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
function applyTerminalAction(
state: Record<ThreadId, ThreadTerminalState>,
threadId: ThreadId,
action: ThreadTerminalAction,
): Record<ThreadId, ThreadTerminalState> {
const current = state[threadId] ?? createDefaultThreadTerminalState();
const next = reduceThreadTerminalState(current, action);
if (next === current) {
return state;
}
return {
...state,
[threadId]: next,
};
}
interface TerminalStateStoreState {
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>;
getTerminalState: (threadId: ThreadId) => ThreadTerminalState;
setTerminalOpen: (threadId: ThreadId, open: boolean) => void;
setTerminalHeight: (threadId: ThreadId, height: number) => void;
splitTerminal: (threadId: ThreadId, terminalId: string) => void;
newTerminal: (threadId: ThreadId, terminalId: string) => void;
setActiveTerminal: (threadId: ThreadId, terminalId: string) => void;
closeTerminal: (threadId: ThreadId, terminalId: string) => void;
setTerminalActivity: (
threadId: ThreadId,
terminalId: string,
hasRunningSubprocess: boolean,
) => void;
clearTerminalState: (threadId: ThreadId) => void;
}
export const useTerminalStateStore = create<TerminalStateStoreState>()(
persist(
(set, get) => {
const updateTerminal = (threadId: ThreadId, action: ThreadTerminalAction) => {
if (threadId.length === 0) return;
set((state) => ({
terminalStateByThreadId: applyTerminalAction(
state.terminalStateByThreadId,
threadId,
action,
),
}));
};
return {
terminalStateByThreadId: {},
getTerminalState: (threadId) => {
if (threadId.length === 0) {
return getDefaultThreadTerminalState();
}
const state = get().terminalStateByThreadId[threadId];
return state ?? getDefaultThreadTerminalState();
},
setTerminalOpen: (threadId, open) => updateTerminal(threadId, { type: "set-open", open }),
setTerminalHeight: (threadId, height) =>
updateTerminal(threadId, { type: "set-height", height }),
splitTerminal: (threadId, terminalId) =>
updateTerminal(threadId, { type: "split", terminalId }),
newTerminal: (threadId, terminalId) =>
updateTerminal(threadId, { type: "new", terminalId }),
setActiveTerminal: (threadId, terminalId) =>
updateTerminal(threadId, { type: "set-active", terminalId }),
closeTerminal: (threadId, terminalId) =>
updateTerminal(threadId, { type: "close", terminalId }),
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
updateTerminal(threadId, { type: "set-activity", terminalId, hasRunningSubprocess }),
clearTerminalState: (threadId) => {
if (threadId.length === 0) return;
set((state) => {
if (state.terminalStateByThreadId[threadId] === undefined) {
return state;
}
const { [threadId]: _removed, ...rest } = state.terminalStateByThreadId;
return {
terminalStateByThreadId: rest as Record<ThreadId, ThreadTerminalState>,
};
});
},
};
},
{
name: TERMINAL_STATE_STORAGE_KEY,
version: 1,
storage: createJSONStorage(() => localStorage),
partialize: (state) => ({
terminalStateByThreadId: state.terminalStateByThreadId,
}),
},
),
);
-7
View File
@@ -79,13 +79,6 @@ export interface Thread {
projectId: ProjectId;
title: string;
model: string;
terminalOpen: boolean;
terminalHeight: number;
terminalIds: string[];
runningTerminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
session: ThreadSession | null;
messages: ChatMessage[];
error: string | null;
+1 -13
View File
@@ -1,7 +1,7 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
import type { Thread } from "./types";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
function makeThread(overrides: Partial<Thread> = {}): Thread {
@@ -11,18 +11,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
turnDiffSummaries: [],