Compare commits

...
Author SHA1 Message Date
Julius Marminge c283d2a85b 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
2026-03-02 10:23:53 -08:00
Julius Marminge 67dddb31df Remove draftThreadTerminalState re-exports; use threadTerminalState directly
- Delete draftThreadTerminalState.ts (was only re-exporting shared module)
- Replace draftThreadTerminalState.test.ts with threadTerminalState.test.ts
  using createDefaultThreadTerminalState and reduceThreadTerminalState
- Draft threads are first-class: same helpers and types as persisted threads

Made-with: Cursor
2026-03-02 10:07:18 -08:00
Julius Marminge a26f299b73 Unify draft and persisted thread terminal flow
- Add shared threadTerminalState.ts: ThreadTerminalState type, default state,
  normalize helpers, and single reduceThreadTerminalState() used by both flows
- Refactor store.ts to use shared terminal reducer and helpers; terminal
  actions map to reduceThreadTerminalState(threadTerminalSlice(thread), action)
- Make draftThreadTerminalState.ts re-export shared module (same shape/actions)
- Add terminalState to composer draft store: getDraftThreadTerminalState,
  setDraftThreadTerminalAction, clearDraftThreadTerminalState; draft thread
  shape matches Thread terminal slice
- ChatView: move draft terminal from useState into composer draft store; use
  same actions for draft and persisted; hydrate then clear draft terminal
  when reconciling server state

Made-with: Cursor
2026-03-02 10:07:18 -08:00
Julius MarmingeandClaude Opus 4.5 b1c85fa3cc Enable terminals for local draft threads
Adds local terminal state management for draft threads before they're
promoted to server threads. Terminal operations (open, split, create,
close, activate, resize) now work on draft threads and hydrate into
the server thread state when the draft is promoted.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-03-02 10:07:18 -08:00
12 changed files with 930 additions and 905 deletions

No files matched your search

+3 -8
View File
@@ -114,12 +114,7 @@ export default function BranchToolbar({
}); });
} }
if (hasServerThread) { if (hasServerThread) {
dispatch({ dispatch.setThreadBranch(activeThreadId, syncedBranch, null);
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
return; return;
} }
setDraftThreadContext(threadId, { setDraftThreadContext(threadId, {
@@ -147,7 +142,7 @@ export default function BranchToolbar({
const setThreadError = (error: string | null) => { const setThreadError = (error: string | null) => {
if (!activeThreadId) return; if (!activeThreadId) return;
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error }); dispatch.setError(activeThreadId, error);
}; };
const setThreadBranch = (branch: string | null, worktreePath: string | null) => { const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
@@ -176,7 +171,7 @@ export default function BranchToolbar({
}); });
} }
if (hasServerThread) { if (hasServerThread) {
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath }); dispatch.setThreadBranch(activeThreadId, branch, worktreePath);
return; return;
} }
setDraftThreadContext(threadId, { setDraftThreadContext(threadId, {
+107 -148
View File
@@ -120,6 +120,7 @@ import {
useComposerDraftStore, useComposerDraftStore,
useComposerThreadDraft, useComposerThreadDraft,
} from "../composerDraftStore"; } from "../composerDraftStore";
import { useTerminalStateStore } from "../terminalStateStore";
import { clamp } from "effect/Number"; import { clamp } from "effect/Number";
function formatMessageMeta(createdAt: string, duration: string | null): string { function formatMessageMeta(createdAt: string, duration: string | null): string {
@@ -207,18 +208,6 @@ function buildLocalDraftThread(
projectId: draftThread.projectId, projectId: draftThread.projectId,
title: "New thread", title: "New thread",
model: fallbackModel, model: fallbackModel,
terminalOpen: false,
terminalHeight: 280,
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, session: null,
messages: [], messages: [],
error, error,
@@ -497,6 +486,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
const dragDepthRef = useRef(0); const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({}); const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
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( const setPrompt = useCallback(
(nextPrompt: string) => { (nextPrompt: string) => {
setComposerDraftPrompt(threadId, nextPrompt); setComposerDraftPrompt(threadId, nextPrompt);
@@ -578,10 +575,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN; const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return; if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
dispatch({ dispatch.markThreadVisited(activeThread.id);
type: "MARK_THREAD_VISITED",
threadId: activeThread.id,
});
}, [ }, [
activeThread?.id, activeThread?.id,
activeThread?.lastVisitedAt, activeThread?.lastVisitedAt,
@@ -851,7 +845,26 @@ export default function ChatView({ threadId }: ChatViewProps) {
(activeThread.session !== null && activeThread.session.status !== "closed")), (activeThread.session !== null && activeThread.session.status !== "closed")),
); );
const hasReachedTerminalLimit = 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.setError(targetThreadId, error);
return;
}
setLocalDraftErrorsByThreadId((existing) => {
if ((existing[targetThreadId] ?? null) === error) {
return existing;
}
return {
...existing,
[targetThreadId]: error,
};
});
},
[dispatch, state.threads],
);
const focusComposer = useCallback(() => { const focusComposer = useCallback(() => {
const textarea = textareaRef.current; const textarea = textareaRef.current;
@@ -865,49 +878,49 @@ export default function ChatView({ threadId }: ChatViewProps) {
focusComposer(); focusComposer();
}); });
}, [focusComposer]); }, [focusComposer]);
const setTerminalOpen = useCallback(
(open: boolean) => {
if (!activeThreadId) return;
storeSetTerminalOpen(activeThreadId, open);
},
[activeThreadId, storeSetTerminalOpen],
);
const setTerminalHeight = useCallback(
(height: number) => {
if (!activeThreadId) return;
storeSetTerminalHeight(activeThreadId, height);
},
[activeThreadId, storeSetTerminalHeight],
);
const toggleTerminalVisibility = useCallback(() => { const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadId) return; if (!activeThreadId) return;
dispatch({ setTerminalOpen(!terminalState.terminalOpen);
type: "SET_THREAD_TERMINAL_OPEN", }, [activeThreadId, setTerminalOpen, terminalState.terminalOpen]);
threadId: activeThreadId,
open: !activeThread?.terminalOpen,
});
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
const splitTerminal = useCallback(() => { const splitTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return; if (!activeThreadId || hasReachedTerminalLimit) return;
dispatch({ const terminalId = `terminal-${crypto.randomUUID()}`;
type: "SPLIT_THREAD_TERMINAL", storeSplitTerminal(activeThreadId, terminalId);
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
setTerminalFocusRequestId((value) => value + 1); setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch, hasReachedTerminalLimit]); }, [activeThreadId, storeSplitTerminal, hasReachedTerminalLimit]);
const createNewTerminal = useCallback(() => { const createNewTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return; if (!activeThreadId || hasReachedTerminalLimit) return;
dispatch({ const terminalId = `terminal-${crypto.randomUUID()}`;
type: "NEW_THREAD_TERMINAL", storeNewTerminal(activeThreadId, terminalId);
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
setTerminalFocusRequestId((value) => value + 1); setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch, hasReachedTerminalLimit]); }, [activeThreadId, storeNewTerminal, hasReachedTerminalLimit]);
const activateTerminal = useCallback( const activateTerminal = useCallback(
(terminalId: string) => { (terminalId: string) => {
if (!activeThreadId) return; if (!activeThreadId) return;
dispatch({ storeSetActiveTerminal(activeThreadId, terminalId);
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId,
});
setTerminalFocusRequestId((value) => value + 1); setTerminalFocusRequestId((value) => value + 1);
}, },
[activeThreadId, dispatch], [activeThreadId, storeSetActiveTerminal],
); );
const closeTerminal = useCallback( const closeTerminal = useCallback(
(terminalId: string) => { (terminalId: string) => {
const api = readNativeApi(); const api = readNativeApi();
if (!activeThreadId || !api) return; if (!activeThreadId || !api) return;
const isFinalTerminal = (activeThread?.terminalIds.length ?? 0) <= 1; const isFinalTerminal = terminalState.terminalIds.length <= 1;
const fallbackExitWrite = () => const fallbackExitWrite = () =>
api.terminal api.terminal
.write({ threadId: activeThreadId, terminalId, data: "exit\n" }) .write({ threadId: activeThreadId, terminalId, data: "exit\n" })
@@ -924,14 +937,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
} else { } else {
void fallbackExitWrite(); void fallbackExitWrite();
} }
dispatch({ storeCloseTerminal(activeThreadId, terminalId);
type: "CLOSE_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId,
});
setTerminalFocusRequestId((value) => value + 1); setTerminalFocusRequestId((value) => value + 1);
}, },
[activeThread?.terminalIds.length, activeThreadId, dispatch], [activeThreadId, storeCloseTerminal, terminalState.terminalIds.length],
); );
const runProjectScript = useCallback( const runProjectScript = useCallback(
async ( async (
@@ -956,32 +965,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
} }
const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd; const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd;
const baseTerminalId = const baseTerminalId =
activeThread.activeTerminalId || activeThread.terminalIds[0] || DEFAULT_THREAD_TERMINAL_ID; terminalState.activeTerminalId ||
const isBaseTerminalBusy = activeThread.runningTerminalIds.includes(baseTerminalId); terminalState.terminalIds[0] ||
DEFAULT_THREAD_TERMINAL_ID;
const isBaseTerminalBusy = terminalState.runningTerminalIds.includes(baseTerminalId);
const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy; const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
const shouldCreateNewTerminal = const shouldCreateNewTerminal =
wantsNewTerminal && activeThread.terminalIds.length < MAX_THREAD_TERMINAL_COUNT; wantsNewTerminal && terminalState.terminalIds.length < MAX_THREAD_TERMINAL_COUNT;
const targetTerminalId = shouldCreateNewTerminal const targetTerminalId = shouldCreateNewTerminal
? `terminal-${crypto.randomUUID()}` ? `terminal-${crypto.randomUUID()}`
: baseTerminalId; : baseTerminalId;
dispatch({ setTerminalOpen(true);
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
if (shouldCreateNewTerminal) { if (shouldCreateNewTerminal) {
dispatch({ storeNewTerminal(activeThreadId, targetTerminalId);
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
} else { } else {
dispatch({ storeSetActiveTerminal(activeThreadId, targetTerminalId);
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
} }
setTerminalFocusRequestId((value) => value + 1); setTerminalFocusRequestId((value) => value + 1);
@@ -1012,14 +1011,25 @@ export default function ChatView({ threadId }: ChatViewProps) {
data: `${script.command}\r`, data: `${script.command}\r`,
}); });
} catch (error) { } catch (error) {
dispatch({ setThreadError(
type: "SET_ERROR", activeThreadId,
threadId: activeThreadId, error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
error: error instanceof Error ? error.message : `Failed to run script "${script.name}".`, );
});
} }
}, },
[activeProject, activeThread, activeThreadId, dispatch, gitCwd, isServerThread], [
activeProject,
activeThread,
activeThreadId,
dispatch,
gitCwd,
isLocalDraftThread,
isServerThread,
setTerminalOpen,
setThreadError,
storeNewTerminal,
storeSetActiveTerminal,
],
); );
const persistProjectScripts = useCallback( const persistProjectScripts = useCallback(
async (input: { async (input: {
@@ -1123,7 +1133,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => { const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return; if (mode === state.runtimeMode) return;
dispatch({ type: "SET_RUNTIME_MODE", mode }); dispatch.setRuntimeMode(mode);
scheduleComposerFocus(); scheduleComposerFocus();
const api = readNativeApi(); const api = readNativeApi();
if (!api) return; if (!api) return;
@@ -1215,14 +1225,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [activeThread?.id]); }, [activeThread?.id]);
useEffect(() => { useEffect(() => {
if (!activeThread?.id || activeThread.terminalOpen) return; if (!activeThread?.id || terminalState.terminalOpen) return;
const frame = window.requestAnimationFrame(() => { const frame = window.requestAnimationFrame(() => {
focusComposer(); focusComposer();
}); });
return () => { return () => {
window.cancelAnimationFrame(frame); window.cancelAnimationFrame(frame);
}; };
}, [activeThread?.id, activeThread?.terminalOpen, focusComposer]); }, [activeThread?.id, focusComposer, terminalState.terminalOpen]);
useEffect(() => { useEffect(() => {
composerImagesRef.current = composerImages; composerImagesRef.current = composerImages;
@@ -1420,7 +1430,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => { useEffect(() => {
if (!activeThreadId) return; if (!activeThreadId) return;
const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false; const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false;
const current = Boolean(activeThread?.terminalOpen); const current = Boolean(terminalState.terminalOpen);
if (!previous && current) { if (!previous && current) {
setTerminalFocusRequestId((value) => value + 1); setTerminalFocusRequestId((value) => value + 1);
@@ -1435,7 +1445,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
} }
terminalOpenByThreadRef.current[activeThreadId] = current; terminalOpenByThreadRef.current[activeThreadId] = current;
}, [activeThread?.terminalOpen, activeThreadId, focusComposer]); }, [activeThreadId, focusComposer, terminalState.terminalOpen]);
useEffect(() => { useEffect(() => {
const isTerminalFocused = (): boolean => { const isTerminalFocused = (): boolean => {
@@ -1449,7 +1459,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (!activeThreadId || event.defaultPrevented) return; if (!activeThreadId || event.defaultPrevented) return;
const shortcutContext = { const shortcutContext = {
terminalFocus: isTerminalFocused(), terminalFocus: isTerminalFocused(),
terminalOpen: Boolean(activeThread?.terminalOpen), terminalOpen: Boolean(terminalState.terminalOpen),
}; };
const command = resolveShortcutCommand(event, keybindings, { context: shortcutContext }); const command = resolveShortcutCommand(event, keybindings, { context: shortcutContext });
@@ -1465,12 +1475,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (command === "terminal.split") { if (command === "terminal.split") {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
if (!activeThread?.terminalOpen) { if (!terminalState.terminalOpen) {
dispatch({ setTerminalOpen(true);
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
} }
splitTerminal(); splitTerminal();
return; return;
@@ -1479,20 +1485,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (command === "terminal.close") { if (command === "terminal.close") {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
if (!activeThread?.terminalOpen) return; if (!terminalState.terminalOpen) return;
closeTerminal(activeThread.activeTerminalId); closeTerminal(terminalState.activeTerminalId);
return; return;
} }
if (command === "terminal.new") { if (command === "terminal.new") {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
if (!activeThread?.terminalOpen) { if (!terminalState.terminalOpen) {
dispatch({ setTerminalOpen(true);
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
} }
createNewTerminal(); createNewTerminal();
return; return;
@@ -1517,12 +1519,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
return () => window.removeEventListener("keydown", handler); return () => window.removeEventListener("keydown", handler);
}, [ }, [
activeProject, activeProject,
activeThread?.terminalOpen, terminalState.terminalOpen,
activeThread?.activeTerminalId, terminalState.activeTerminalId,
activeThreadId, activeThreadId,
closeTerminal, closeTerminal,
createNewTerminal, createNewTerminal,
dispatch, setTerminalOpen,
runProjectScript, runProjectScript,
splitTerminal, splitTerminal,
keybindings, keybindings,
@@ -1530,30 +1532,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
toggleTerminalVisibility, toggleTerminalVisibility,
]); ]);
const setThreadError = useCallback(
(threadId: ThreadId | null, error: string | null) => {
if (!threadId) return;
if (state.threads.some((thread) => thread.id === threadId)) {
dispatch({
type: "SET_ERROR",
threadId,
error,
});
return;
}
setLocalDraftErrorsByThreadId((existing) => {
if ((existing[threadId] ?? null) === error) {
return existing;
}
return {
...existing,
[threadId]: error,
};
});
},
[dispatch, state.threads],
);
const addComposerImages = (files: File[]) => { const addComposerImages = (files: File[]) => {
if (!activeThreadId || files.length === 0) return; if (!activeThreadId || files.length === 0) return;
@@ -1718,11 +1696,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const shouldCreateWorktree = const shouldCreateWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath; isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;
if (shouldCreateWorktree && !activeThread.branch) { if (shouldCreateWorktree && !activeThread.branch) {
dispatch({ dispatch.setError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
type: "SET_ERROR",
threadId: threadIdForSend,
error: "Select a base branch before sending in New worktree mode.",
});
return; return;
} }
@@ -1792,12 +1766,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}); });
// Keep local thread state in sync immediately so terminal drawer opens // Keep local thread state in sync immediately so terminal drawer opens
// with the worktree cwd/env instead of briefly using the project root. // with the worktree cwd/env instead of briefly using the project root.
dispatch({ dispatch.setThreadBranch(threadIdForSend, result.worktree.branch, result.worktree.path);
type: "SET_THREAD_BRANCH",
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
} }
} }
@@ -1938,11 +1907,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
}); });
} catch (err) { } catch (err) {
dispatch({ dispatch.setError(activeThreadId, err instanceof Error ? err.message : "Failed to submit approval decision.");
type: "SET_ERROR",
threadId: activeThreadId,
error: err instanceof Error ? err.message : "Failed to submit approval decision.",
});
} finally { } finally {
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
} }
@@ -2467,7 +2432,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
)} )}
{(() => { {(() => {
if (!activeThread.terminalOpen || !activeProject) { if (!terminalState.terminalOpen || !activeProject) {
return null; return null;
} }
return ( return (
@@ -2476,11 +2441,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId={activeThread.id} threadId={activeThread.id}
cwd={gitCwd ?? activeProject.cwd} cwd={gitCwd ?? activeProject.cwd}
runtimeEnv={threadTerminalRuntimeEnv} runtimeEnv={threadTerminalRuntimeEnv}
height={activeThread.terminalHeight} height={terminalState.terminalHeight}
terminalIds={activeThread.terminalIds} terminalIds={terminalState.terminalIds}
activeTerminalId={activeThread.activeTerminalId} activeTerminalId={terminalState.activeTerminalId}
terminalGroups={activeThread.terminalGroups} terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={activeThread.activeTerminalGroupId} activeTerminalGroupId={terminalState.activeTerminalGroupId}
focusRequestId={terminalFocusRequestId} focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal} onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal} onNewTerminal={createNewTerminal}
@@ -2489,13 +2454,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined} closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal} onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal} onCloseTerminal={closeTerminal}
onHeightChange={(height) => onHeightChange={setTerminalHeight}
dispatch({
type: "SET_THREAD_TERMINAL_HEIGHT",
threadId: activeThread.id,
height,
})
}
/> />
); );
})()} })()}
+11 -5
View File
@@ -21,6 +21,7 @@ import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/
import { serverConfigQueryOptions } from "../lib/serverReactQuery"; import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi"; import { readNativeApi } from "../nativeApi";
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore"; import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
import { useTerminalStateStore } from "../terminalStateStore";
import { toastManager } from "./ui/toast"; import { toastManager } from "./ui/toast";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -126,8 +127,10 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
return null; return null;
} }
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null { function terminalStatusFromRunningIds(
if (thread.runningTerminalIds.length === 0) { runningTerminalIds: string[],
): TerminalStatusIndicator | null {
if (runningTerminalIds.length === 0) {
return null; return null;
} }
return { return {
@@ -234,6 +237,7 @@ export default function Sidebar() {
(store) => store.getDraftThreadByProjectId, (store) => store.getDraftThreadByProjectId,
); );
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread); const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const getTerminalState = useTerminalStateStore((s) => s.getTerminalState);
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId); const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const clearProjectDraftThreadId = useComposerDraftStore( const clearProjectDraftThreadId = useComposerDraftStore(
@@ -497,7 +501,7 @@ export default function Sidebar() {
position, position,
); );
if (clicked === "mark-unread") { if (clicked === "mark-unread") {
dispatch({ type: "MARK_THREAD_UNREAD", threadId }); dispatch.markThreadUnread(threadId);
return; return;
} }
if (clicked !== "delete") return; if (clicked !== "delete") return;
@@ -769,7 +773,7 @@ export default function Sidebar() {
open={project.expanded} open={project.expanded}
onOpenChange={(open) => { onOpenChange={(open) => {
if (open === project.expanded) return; if (open === project.expanded) return;
dispatch({ type: "TOGGLE_PROJECT", projectId: project.id }); dispatch.toggleProject(project.id);
}} }}
> >
<SidebarMenuItem> <SidebarMenuItem>
@@ -811,7 +815,9 @@ export default function Sidebar() {
pendingApprovalByThreadId.get(thread.id) === true, pendingApprovalByThreadId.get(thread.id) === true,
); );
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null); const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusIndicator(thread); const terminalStatus = terminalStatusFromRunningIds(
getTerminalState(thread.id).runningTerminalIds,
);
return ( return (
<SidebarMenuSubItem key={thread.id} className="w-full"> <SidebarMenuSubItem key={thread.id} className="w-full">
+7 -11
View File
@@ -15,6 +15,7 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery"; import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi"; import { readNativeApi } from "../nativeApi";
import { useStore } from "../store"; import { useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { preferredTerminalEditor } from "../terminal-links"; import { preferredTerminalEditor } from "../terminal-links";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity"; import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi"; import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
@@ -144,7 +145,7 @@ function EventRouter() {
const snapshot = await api.orchestration.getSnapshot(); const snapshot = await api.orchestration.getSnapshot();
if (disposed) return; if (disposed) return;
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence); latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot }); dispatch.syncServerReadModel(snapshot);
if (pending) { if (pending) {
pending = false; pending = false;
await flushSnapshotSync(); await flushSnapshotSync();
@@ -184,12 +185,11 @@ function EventRouter() {
if (hasRunningSubprocess === null) { if (hasRunningSubprocess === null) {
return; return;
} }
dispatch({ useTerminalStateStore.getState().setTerminalActivity(
type: "SET_THREAD_TERMINAL_ACTIVITY", ThreadId.makeUnsafe(event.threadId),
threadId: ThreadId.makeUnsafe(event.threadId), event.terminalId,
terminalId: event.terminalId,
hasRunningSubprocess, hasRunningSubprocess,
}); );
}); });
const unsubWelcome = onServerWelcome((payload) => { const unsubWelcome = onServerWelcome((payload) => {
void (async () => { void (async () => {
@@ -201,11 +201,7 @@ function EventRouter() {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) { if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return; return;
} }
dispatch({ dispatch.setProjectExpanded(payload.bootstrapProjectId, true);
type: "SET_PROJECT_EXPANDED",
projectId: payload.bootstrapProjectId,
expanded: true,
});
if (pathnameRef.current !== "/") { if (pathnameRef.current !== "/") {
return; return;
+1 -4
View File
@@ -346,10 +346,7 @@ function SettingsRouteView() {
: "border-border bg-background text-muted-foreground hover:bg-accent" : "border-border bg-background text-muted-foreground hover:bg-accent"
}`} }`}
onClick={() => { onClick={() => {
dispatch({ dispatch.setRuntimeMode(option.value);
type: "SET_RUNTIME_MODE",
mode: option.value,
});
}} }}
> >
<span className="flex flex-col"> <span className="flex flex-col">
+7 -84
View File
@@ -1,8 +1,8 @@
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { reducer, type AppState } from "./store"; import { markThreadUnread, type AppState } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types"; import type { Thread } from "./types";
function makeThread(overrides: Partial<Thread> = {}): Thread { function makeThread(overrides: Partial<Thread> = {}): Thread {
return { return {
@@ -11,18 +11,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
projectId: ProjectId.makeUnsafe("project-1"), projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread", title: "Thread",
model: "gpt-5-codex", 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, session: null,
messages: [], messages: [],
turnDiffSummaries: [], turnDiffSummaries: [],
@@ -54,8 +42,8 @@ function makeState(thread: Thread): AppState {
}; };
} }
describe("store reducer", () => { describe("store pure functions", () => {
it("marks a completed thread as unread by moving lastVisitedAt before completion", () => { it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z"; const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeState( const initialState = makeState(
makeThread({ makeThread({
@@ -71,10 +59,7 @@ describe("store reducer", () => {
}), }),
); );
const next = reducer(initialState, { const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
type: "MARK_THREAD_UNREAD",
threadId: ThreadId.makeUnsafe("thread-1"),
});
const updatedThread = next.threads[0]; const updatedThread = next.threads[0];
expect(updatedThread).toBeDefined(); 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( const initialState = makeState(
makeThread({ makeThread({
latestTurn: null, latestTurn: null,
@@ -92,70 +77,8 @@ describe("store reducer", () => {
}), }),
); );
const next = reducer(initialState, { const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
type: "MARK_THREAD_UNREAD",
threadId: ThreadId.makeUnsafe("thread-1"),
});
expect(next).toEqual(initialState); 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([]);
});
});
+222 -625
View File
@@ -1,13 +1,4 @@
import { import { Fragment, type ReactNode, createElement, useEffect } from "react";
type Dispatch,
type ReactNode,
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import { import {
DEFAULT_MODEL, DEFAULT_MODEL,
ProviderSessionId, ProviderSessionId,
@@ -16,48 +7,15 @@ import {
type OrchestrationSessionStatus, type OrchestrationSessionStatus,
resolveModelSlug, resolveModelSlug,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { create } from "zustand";
import { import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE, DEFAULT_RUNTIME_MODE,
MAX_THREAD_TERMINAL_COUNT,
type ChatMessage, type ChatMessage,
type Project, type Project,
type RuntimeMode, type RuntimeMode,
type Thread, type Thread,
type ThreadTerminalGroup,
} from "./types"; } from "./types";
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
| { 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 ──────────────────────────────────────────────────────────── // ── State ────────────────────────────────────────────────────────────
export interface AppState { export interface AppState {
@@ -87,11 +45,10 @@ const initialState: AppState = {
}; };
const persistedExpandedProjectCwds = new Set<string>(); const persistedExpandedProjectCwds = new Set<string>();
// ── Helpers ────────────────────────────────────────────────────────── // ── Persist helpers ──────────────────────────────────────────────────
function readPersistedState(): AppState { function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState; if (typeof window === "undefined") return initialState;
try { try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY); const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
if (!raw) return initialState; if (!raw) return initialState;
@@ -119,7 +76,6 @@ function readPersistedState(): AppState {
function persistState(state: AppState): void { function persistState(state: AppState): void {
if (typeof window === "undefined") return; if (typeof window === "undefined") return;
try { try {
window.localStorage.setItem( window.localStorage.setItem(
PERSISTED_STATE_KEY, PERSISTED_STATE_KEY,
@@ -138,6 +94,8 @@ function persistState(state: AppState): void {
} }
} }
// ── Pure helpers ──────────────────────────────────────────────────────
function updateThread( function updateThread(
threads: Thread[], threads: Thread[],
threadId: ThreadId, threadId: ThreadId,
@@ -193,9 +151,7 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
} }
function resolveWsHttpOrigin(): string { function resolveWsHttpOrigin(): string {
if (typeof window === "undefined") { if (typeof window === "undefined") return "";
return "";
}
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.(); const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined; const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
const wsCandidate = const wsCandidate =
@@ -204,10 +160,7 @@ function resolveWsHttpOrigin(): string {
: typeof envWsUrl === "string" && envWsUrl.length > 0 : typeof envWsUrl === "string" && envWsUrl.length > 0
? envWsUrl ? envWsUrl
: null; : null;
if (!wsCandidate) { if (!wsCandidate) return window.location.origin;
return window.location.origin;
}
try { try {
const wsUrl = new URL(wsCandidate); const wsUrl = new URL(wsCandidate);
const protocol = const protocol =
@@ -233,594 +186,238 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
return `/attachments/${encodeURIComponent(attachmentId)}`; return `/attachments/${encodeURIComponent(attachmentId)}`;
} }
function normalizeTerminalIds(terminalIds: string[]): string[] { // ── Pure state transition functions ────────────────────────────────────
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
if (unique.length > 0) {
return unique;
}
return [DEFAULT_THREAD_TERMINAL_ID];
}
function normalizeRunningTerminalIds( export function syncServerReadModel(
runningTerminalIds: string[], state: AppState,
terminalIds: string[], readModel: OrchestrationReadModel,
): string[] { ): AppState {
if (runningTerminalIds.length === 0) return []; const projects = mapProjectsFromReadModel(
const validTerminalIdSet = new Set(terminalIds); readModel.projects.filter((project) => project.deletedAt === null),
return [...new Set(runningTerminalIds)] state.projects,
.map((id) => id.trim())
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
}
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
}
function fallbackGroupId(terminalId: string): string {
return `group-${terminalId}`;
}
function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
}
function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
const validTerminalIdSet = new Set(terminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const groups: ThreadTerminalGroup[] = [];
for (const group of thread.terminalGroups) {
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (groupTerminalIds.length === 0) continue;
for (const terminalId of groupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
group.id.trim().length > 0
? group.id.trim()
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
groups.push({
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
terminalIds: groupTerminalIds,
});
}
for (const terminalId of terminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
groups.push({
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
terminalIds: [terminalId],
});
}
if (groups.length > 0) {
return groups;
}
return [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
];
}
function findGroupIndexByTerminalId(
terminalGroups: ThreadTerminalGroup[],
terminalId: string,
): number {
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
}
function normalizeThreadTerminals(thread: Thread): Thread {
const terminalIds = normalizeTerminalIds(thread.terminalIds);
const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
const activeGroupIndexFromId = terminalGroups.findIndex(
(group) => group.id === thread.activeTerminalGroupId,
); );
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId); const existingThreadById = new Map(
const activeGroupIndex = state.threads.map((thread) => [thread.id, thread] as const),
activeGroupIndexFromId >= 0 );
? activeGroupIndexFromId const threads = readModel.threads
: activeGroupIndexFromTerminal >= 0 .filter((thread) => thread.deletedAt === null)
? activeGroupIndexFromTerminal .map((thread) => {
: 0; const existing = existingThreadById.get(thread.id);
const activeTerminalGroupId = return {
terminalGroups[activeGroupIndex]?.id ?? id: thread.id,
terminalGroups[0]?.id ?? codexThreadId: thread.session?.providerThreadId ?? null,
fallbackGroupId(activeTerminalId); 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 { return {
...thread, ...state,
terminalIds, projects,
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds), threads,
activeTerminalId, threadsHydrated: true,
terminalGroups,
activeTerminalGroupId,
}; };
} }
function closeThreadTerminal(thread: Thread, terminalId: string): Thread { export function markThreadVisited(
if (!thread.terminalIds.includes(terminalId)) { state: AppState,
return thread; threadId: ThreadId,
} visitedAt?: string,
): AppState {
const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId); const at = visitedAt ?? new Date().toISOString();
if (remainingTerminalIds.length === 0) { const visitedAtMs = Date.parse(at);
const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID); return {
return normalizeThreadTerminals({ ...state,
...thread, threads: updateThread(state.threads, threadId, (thread) => {
terminalOpen: false, const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
terminalIds: [DEFAULT_THREAD_TERMINAL_ID], if (
runningTerminalIds: [], Number.isFinite(previousVisitedAtMs) &&
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID, Number.isFinite(visitedAtMs) &&
terminalGroups: [ previousVisitedAtMs >= visitedAtMs
{ ) {
id: nextTerminalGroupId, return thread;
terminalIds: [DEFAULT_THREAD_TERMINAL_ID], }
}, return { ...thread, lastVisitedAt: at };
], }),
activeTerminalGroupId: nextTerminalGroupId, };
});
}
const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
const closedTerminalGroup = thread.terminalGroups.find((group) =>
group.terminalIds.includes(terminalId),
);
const closedTerminalGroupIndex = closedTerminalGroup
? closedTerminalGroup.terminalIds.indexOf(terminalId)
: -1;
const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
(id) => id !== terminalId,
);
const nextActiveTerminalId =
thread.activeTerminalId === terminalId
? (remainingTerminalsInClosedGroup[
Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
] ??
remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
remainingTerminalIds[0] ??
DEFAULT_THREAD_TERMINAL_ID)
: thread.activeTerminalId;
const nextTerminalGroups = thread.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
return normalizeThreadTerminals({
...thread,
terminalIds: remainingTerminalIds,
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
activeTerminalId: nextActiveTerminalId,
terminalGroups: nextTerminalGroups,
});
} }
function setThreadTerminalActivity( export function markThreadUnread(state: AppState, threadId: ThreadId): AppState {
thread: Thread, return {
terminalId: string, ...state,
hasRunningSubprocess: boolean, threads: updateThread(state.threads, threadId, (thread) => {
): Thread { if (!thread.latestTurn?.completedAt) return thread;
const normalizedThread = normalizeThreadTerminals(thread); const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
if (!normalizedThread.terminalIds.includes(terminalId)) { if (Number.isNaN(latestTurnCompletedAtMs)) return thread;
return normalizedThread; const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
} if (thread.lastVisitedAt === unreadVisitedAt) return thread;
const runningTerminalIds = new Set(normalizedThread.runningTerminalIds); return { ...thread, lastVisitedAt: unreadVisitedAt };
if (hasRunningSubprocess) { }),
runningTerminalIds.add(terminalId); };
} else {
runningTerminalIds.delete(terminalId);
}
return normalizeThreadTerminals({
...normalizedThread,
runningTerminalIds: [...runningTerminalIds],
});
} }
// ── Reducer ────────────────────────────────────────────────────────── export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
return {
export function reducer(state: AppState, action: Action): AppState { ...state,
switch (action.type) { projects: state.projects.map((p) =>
case "SYNC_SERVER_READ_MODEL": { p.id === projectId ? { ...p, expanded: !p.expanded } : p,
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 threads = action.readModel.threads
.filter((thread) => thread.deletedAt === null)
.map((thread) => {
const existing = existingThreadById.get(thread.id);
return normalizeThreadTerminals({
id: thread.id,
codexThreadId: thread.session?.providerThreadId ?? null,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(thread.model),
terminalOpen: existing?.terminalOpen ?? false,
terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: existing?.runningTerminalIds ?? [],
activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: existing?.terminalGroups ?? [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId:
existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
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 "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) =>
setThreadTerminalActivity(thread, action.terminalId, 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, (t) => ({
...t,
terminalOpen: !t.terminalOpen,
})),
};
case "SET_THREAD_TERMINAL_OPEN":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
terminalOpen: action.open,
})),
};
case "SET_THREAD_TERMINAL_HEIGHT":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
terminalHeight: action.height,
})),
};
case "SPLIT_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
return normalizedThread;
}
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
...group,
terminalIds: [...group.terminalIds],
}));
let activeGroupIndex = terminalGroups.findIndex(
(group) => group.id === normalizedThread.activeTerminalGroupId,
);
if (activeGroupIndex < 0) {
activeGroupIndex = findGroupIndexByTerminalId(
terminalGroups,
normalizedThread.activeTerminalId,
);
}
if (activeGroupIndex < 0) {
terminalGroups.push({
id: fallbackGroupId(normalizedThread.activeTerminalId),
terminalIds: [normalizedThread.activeTerminalId],
});
activeGroupIndex = terminalGroups.length - 1;
}
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
if (existingGroupIndex >= 0) {
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
existingGroupIndex
]!.terminalIds.filter((id) => id !== action.terminalId);
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
terminalGroups.splice(existingGroupIndex, 1);
if (existingGroupIndex < activeGroupIndex) {
activeGroupIndex -= 1;
}
}
}
const destinationGroup = terminalGroups[activeGroupIndex];
if (!destinationGroup) {
return normalizedThread;
}
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
const anchorIndex = destinationGroup.terminalIds.indexOf(
normalizedThread.activeTerminalId,
);
if (anchorIndex >= 0) {
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
} else {
destinationGroup.terminalIds.push(action.terminalId);
}
}
return normalizeThreadTerminals({
...normalizedThread,
terminalIds,
activeTerminalId: action.terminalId,
activeTerminalGroupId: destinationGroup.id,
terminalGroups,
});
}),
};
case "NEW_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
return normalizedThread;
}
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
const terminalGroups = normalizedThread.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
const nextGroupId = fallbackGroupId(action.terminalId);
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
return normalizeThreadTerminals({
...normalizedThread,
terminalIds,
activeTerminalId: action.terminalId,
activeTerminalGroupId: nextGroupId,
terminalGroups,
});
}),
};
case "SET_THREAD_ACTIVE_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
if (!normalizedThread.terminalIds.includes(action.terminalId)) {
return thread;
}
const nextActiveGroupIndex = findGroupIndexByTerminalId(
normalizedThread.terminalGroups,
action.terminalId,
);
const activeTerminalGroupId =
nextActiveGroupIndex >= 0
? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
normalizedThread.activeTerminalGroupId)
: normalizedThread.activeTerminalGroupId;
return normalizeThreadTerminals({
...normalizedThread,
activeTerminalId: action.terminalId,
activeTerminalGroupId,
});
}),
};
case "CLOSE_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
closeThreadTerminal(thread, 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;
}
} }
// ── 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<{ export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
state: AppState; return {
dispatch: Dispatch<Action>; ...state,
}>({ state: initialState, dispatch: () => {} }); 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 }) { export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
useEffect(() => { useEffect(() => {
persistState(state); persistState(useAppStore.getState());
}, [state]); }, []);
return createElement(Fragment, null, children);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
} }
export function useStore() { 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,
}),
},
),
);
+87
View File
@@ -0,0 +1,87 @@
import { describe, expect, it } from "vitest";
import {
createDefaultThreadTerminalState,
reduceThreadTerminalState,
} from "./threadTerminalState";
describe("threadTerminalState", () => {
it("creates a closed default terminal state", () => {
expect(createDefaultThreadTerminalState()).toEqual({
terminalOpen: false,
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
});
});
it("opens and splits terminal tabs into the active group", () => {
const opened = reduceThreadTerminalState(createDefaultThreadTerminalState(), {
type: "set-open",
open: true,
});
const split = reduceThreadTerminalState(opened, {
type: "split",
terminalId: "terminal-2",
});
expect(split.terminalOpen).toBe(true);
expect(split.terminalIds).toEqual(["default", "terminal-2"]);
expect(split.activeTerminalId).toBe("terminal-2");
expect(split.terminalGroups).toEqual([
{
id: "group-default",
terminalIds: ["default", "terminal-2"],
},
]);
});
it("creates new terminals in a new group", () => {
const next = reduceThreadTerminalState(createDefaultThreadTerminalState(), {
type: "new",
terminalId: "terminal-2",
});
expect(next.terminalIds).toEqual(["default", "terminal-2"]);
expect(next.activeTerminalId).toBe("terminal-2");
expect(next.activeTerminalGroupId).toBe("group-terminal-2");
expect(next.terminalGroups).toEqual([
{ id: "group-default", terminalIds: ["default"] },
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
]);
});
it("resets to default when closing the last terminal", () => {
const closed = reduceThreadTerminalState(createDefaultThreadTerminalState(), {
type: "close",
terminalId: "default",
});
expect(closed).toEqual(createDefaultThreadTerminalState());
});
it("keeps a valid active terminal after closing an active split terminal", () => {
const splitOnce = reduceThreadTerminalState(createDefaultThreadTerminalState(), {
type: "split",
terminalId: "terminal-2",
});
const splitTwice = reduceThreadTerminalState(splitOnce, {
type: "split",
terminalId: "terminal-3",
});
const closed = reduceThreadTerminalState(splitTwice, {
type: "close",
terminalId: "terminal-3",
});
expect(closed.activeTerminalId).toBe("terminal-2");
expect(closed.terminalIds).toEqual(["default", "terminal-2"]);
expect(closed.terminalGroups).toEqual([
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
]);
});
});
+374
View File
@@ -0,0 +1,374 @@
/**
* Shared thread terminal state and reducer. Used by both the main app store
* (persisted threads) and the composer draft store (draft threads), so we can
* reuse the same shape and helpers and easily copy terminal state from draft
* to thread when reconciling server state.
*/
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT,
type ThreadTerminalGroup,
} from "./types";
/** Terminal slice shared by Thread and draft thread. Same shape in both stores. */
export interface ThreadTerminalState {
terminalOpen: boolean;
terminalHeight: number;
terminalIds: string[];
runningTerminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
}
export type ThreadTerminalAction =
| { type: "set-open"; open: boolean }
| { type: "set-height"; height: number }
| { type: "split"; terminalId: string }
| { type: "new"; terminalId: string }
| { type: "set-active"; terminalId: string }
| { type: "close"; terminalId: string }
| { type: "set-activity"; terminalId: string; hasRunningSubprocess: boolean };
// ─── Helpers (exported for store reducers that need to work with Thread) ───
export function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))].slice(
0,
MAX_THREAD_TERMINAL_COUNT,
);
return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID];
}
export function normalizeRunningTerminalIds(
runningTerminalIds: string[],
terminalIds: string[],
): string[] {
if (runningTerminalIds.length === 0) return [];
const validTerminalIdSet = new Set(terminalIds);
return [...new Set(runningTerminalIds)]
.map((id) => id.trim())
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
}
export function fallbackGroupId(terminalId: string): string {
return `group-${terminalId}`;
}
function assignUniqueGroupId(baseId: string, usedGroupIds: Set<string>): string {
let candidate = baseId;
let index = 2;
while (usedGroupIds.has(candidate)) {
candidate = `${baseId}-${index}`;
index += 1;
}
usedGroupIds.add(candidate);
return candidate;
}
export function findGroupIndexByTerminalId(
terminalGroups: ThreadTerminalGroup[],
terminalId: string,
): number {
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
}
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
}
/** Normalize groups to match terminalIds; used by both thread and draft. */
export function normalizeTerminalGroups(
terminalGroups: ThreadTerminalGroup[],
terminalIds: string[],
): ThreadTerminalGroup[] {
const validTerminalIdSet = new Set(terminalIds);
const assignedTerminalIds = new Set<string>();
const nextGroups: ThreadTerminalGroup[] = [];
const usedGroupIds = new Set<string>();
for (const group of terminalGroups) {
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (groupTerminalIds.length === 0) continue;
for (const terminalId of groupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
group.id.trim().length > 0
? group.id.trim()
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
nextGroups.push({
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
terminalIds: groupTerminalIds,
});
}
for (const terminalId of terminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
nextGroups.push({
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
terminalIds: [terminalId],
});
}
if (nextGroups.length === 0) {
return [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
];
}
return nextGroups;
}
// ─── Default & normalize ─────────────────────────────────────────────────
const DEFAULT_THREAD_TERMINAL_STATE: ThreadTerminalState = Object.freeze({
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
});
export function createDefaultThreadTerminalState(): ThreadTerminalState {
return { ...DEFAULT_THREAD_TERMINAL_STATE };
}
export function getDefaultThreadTerminalState(): ThreadTerminalState {
return DEFAULT_THREAD_TERMINAL_STATE;
}
export function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTerminalState {
const terminalIds = normalizeTerminalIds(state.terminalIds);
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const runningTerminalIds = normalizeRunningTerminalIds(
state.runningTerminalIds,
nextTerminalIds,
);
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
? state.activeTerminalId
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);
const activeGroupIdFromState = terminalGroups.some((group) => group.id === state.activeTerminalGroupId)
? state.activeTerminalGroupId
: null;
const activeGroupIdFromTerminal =
terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? null;
return {
terminalOpen: state.terminalOpen,
terminalHeight:
Number.isFinite(state.terminalHeight) && state.terminalHeight > 0
? state.terminalHeight
: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: nextTerminalIds,
runningTerminalIds,
activeTerminalId,
terminalGroups,
activeTerminalGroupId:
activeGroupIdFromState ??
activeGroupIdFromTerminal ??
terminalGroups[0]?.id ??
fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
};
}
// ─── Close terminal (shared) ─────────────────────────────────────────────
function closeTerminal(
state: ThreadTerminalState,
terminalId: string,
): ThreadTerminalState {
if (!state.terminalIds.includes(terminalId)) {
return state;
}
const remainingTerminalIds = state.terminalIds.filter((id) => id !== terminalId);
if (remainingTerminalIds.length === 0) {
return createDefaultThreadTerminalState();
}
const closedTerminalIndex = state.terminalIds.indexOf(terminalId);
const nextActiveTerminalId =
state.activeTerminalId === terminalId
? (remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
remainingTerminalIds[0] ??
DEFAULT_THREAD_TERMINAL_ID)
: state.activeTerminalId;
const terminalGroups = state.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
const nextActiveTerminalGroupId =
terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ??
terminalGroups[0]?.id ??
fallbackGroupId(nextActiveTerminalId);
return normalizeThreadTerminalState({
terminalOpen: state.terminalOpen,
terminalHeight: state.terminalHeight,
terminalIds: remainingTerminalIds,
runningTerminalIds: state.runningTerminalIds.filter((id) => id !== terminalId),
activeTerminalId: nextActiveTerminalId,
terminalGroups,
activeTerminalGroupId: nextActiveTerminalGroupId,
});
}
function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[] {
return groups.map((group) => ({
id: group.id,
terminalIds: [...group.terminalIds],
}));
}
// ─── Single reducer for both draft and persisted thread ────────────────────
export function reduceThreadTerminalState(
state: ThreadTerminalState,
action: ThreadTerminalAction,
): ThreadTerminalState {
const normalized = normalizeThreadTerminalState(state);
if (action.type === "set-open") {
if (normalized.terminalOpen === action.open) return normalized;
return { ...normalized, terminalOpen: action.open };
}
if (action.type === "set-height") {
if (
!Number.isFinite(action.height) ||
action.height <= 0 ||
normalized.terminalHeight === action.height
) {
return normalized;
}
return { ...normalized, terminalHeight: action.height };
}
if (action.type === "set-active") {
if (!normalized.terminalIds.includes(action.terminalId)) {
return normalized;
}
const activeTerminalGroupId =
normalized.terminalGroups.find((group) => group.terminalIds.includes(action.terminalId))?.id ??
normalized.activeTerminalGroupId;
return {
...normalized,
activeTerminalId: action.terminalId,
activeTerminalGroupId,
};
}
if (action.type === "close") {
return closeTerminal(normalized, action.terminalId);
}
if (action.type === "set-activity") {
if (!normalized.terminalIds.includes(action.terminalId)) {
return normalized;
}
const runningTerminalIds = new Set(normalized.runningTerminalIds);
if (action.hasRunningSubprocess) {
runningTerminalIds.add(action.terminalId);
} else {
runningTerminalIds.delete(action.terminalId);
}
return { ...normalized, runningTerminalIds: [...runningTerminalIds] };
}
if (!action.terminalId || action.terminalId.trim().length === 0) {
return normalized;
}
const isNewTerminal = !normalized.terminalIds.includes(action.terminalId);
if (isNewTerminal && normalized.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
return normalized;
}
const terminalIds = isNewTerminal
? [...normalized.terminalIds, action.terminalId]
: normalized.terminalIds;
const terminalGroups = copyTerminalGroups(normalized.terminalGroups);
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
if (existingGroupIndex >= 0) {
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
existingGroupIndex
]!.terminalIds.filter((id) => id !== action.terminalId);
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
terminalGroups.splice(existingGroupIndex, 1);
}
}
if (action.type === "new") {
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
const nextGroupId = assignUniqueGroupId(fallbackGroupId(action.terminalId), usedGroupIds);
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
return normalizeThreadTerminalState({
...normalized,
terminalOpen: true,
terminalIds,
activeTerminalId: action.terminalId,
terminalGroups,
activeTerminalGroupId: nextGroupId,
});
}
// split
let activeGroupIndex = terminalGroups.findIndex((group) => group.id === normalized.activeTerminalGroupId);
if (activeGroupIndex < 0) {
activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalized.activeTerminalId);
}
if (activeGroupIndex < 0) {
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
const nextGroupId = assignUniqueGroupId(
fallbackGroupId(normalized.activeTerminalId),
usedGroupIds,
);
terminalGroups.push({ id: nextGroupId, terminalIds: [normalized.activeTerminalId] });
activeGroupIndex = terminalGroups.length - 1;
}
const destinationGroup = terminalGroups[activeGroupIndex];
if (!destinationGroup) {
return normalized;
}
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
const anchorIndex = destinationGroup.terminalIds.indexOf(normalized.activeTerminalId);
if (anchorIndex >= 0) {
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
} else {
destinationGroup.terminalIds.push(action.terminalId);
}
}
return normalizeThreadTerminalState({
...normalized,
terminalOpen: true,
terminalIds,
activeTerminalId: action.terminalId,
terminalGroups,
activeTerminalGroupId: destinationGroup.id,
});
}
-7
View File
@@ -79,13 +79,6 @@ export interface Thread {
projectId: ProjectId; projectId: ProjectId;
title: string; title: string;
model: string; model: string;
terminalOpen: boolean;
terminalHeight: number;
terminalIds: string[];
runningTerminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
session: ThreadSession | null; session: ThreadSession | null;
messages: ChatMessage[]; messages: ChatMessage[];
error: string | null; error: string | null;
+1 -13
View File
@@ -1,7 +1,7 @@
import { ProjectId, ThreadId } from "@t3tools/contracts"; import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest"; 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"; import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
function makeThread(overrides: Partial<Thread> = {}): Thread { function makeThread(overrides: Partial<Thread> = {}): Thread {
@@ -11,18 +11,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
projectId: ProjectId.makeUnsafe("project-1"), projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread", title: "Thread",
model: "gpt-5.3-codex", 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, session: null,
messages: [], messages: [],
turnDiffSummaries: [], turnDiffSummaries: [],