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) {
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, {
+107 -148
View File
@@ -120,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 {
@@ -207,18 +208,6 @@ function buildLocalDraftThread(
projectId: draftThread.projectId,
title: "New thread",
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,
messages: [],
error,
@@ -497,6 +486,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
const dragDepthRef = useRef(0);
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(
(nextPrompt: string) => {
setComposerDraftPrompt(threadId, nextPrompt);
@@ -578,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,
@@ -851,7 +845,26 @@ 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.setError(targetThreadId, error);
return;
}
setLocalDraftErrorsByThreadId((existing) => {
if ((existing[targetThreadId] ?? null) === error) {
return existing;
}
return {
...existing,
[targetThreadId]: error,
};
});
},
[dispatch, state.threads],
);
const focusComposer = useCallback(() => {
const textarea = textareaRef.current;
@@ -865,49 +878,49 @@ export default function ChatView({ threadId }: ChatViewProps) {
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(() => {
if (!activeThreadId) return;
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: !activeThread?.terminalOpen,
});
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
setTerminalOpen(!terminalState.terminalOpen);
}, [activeThreadId, setTerminalOpen, terminalState.terminalOpen]);
const splitTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return;
dispatch({
type: "SPLIT_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
const terminalId = `terminal-${crypto.randomUUID()}`;
storeSplitTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
}, [activeThreadId, storeSplitTerminal, hasReachedTerminalLimit]);
const createNewTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return;
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
const terminalId = `terminal-${crypto.randomUUID()}`;
storeNewTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
}, [activeThreadId, storeNewTerminal, hasReachedTerminalLimit]);
const activateTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId) return;
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId,
});
storeSetActiveTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, dispatch],
[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" })
@@ -924,14 +937,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
} else {
void fallbackExitWrite();
}
dispatch({
type: "CLOSE_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId,
});
storeCloseTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
},
[activeThread?.terminalIds.length, activeThreadId, dispatch],
[activeThreadId, storeCloseTerminal, terminalState.terminalIds.length],
);
const runProjectScript = useCallback(
async (
@@ -956,32 +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;
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
setTerminalOpen(true);
if (shouldCreateNewTerminal) {
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
storeNewTerminal(activeThreadId, targetTerminalId);
} else {
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
storeSetActiveTerminal(activeThreadId, targetTerminalId);
}
setTerminalFocusRequestId((value) => value + 1);
@@ -1012,14 +1011,25 @@ export default function ChatView({ threadId }: ChatViewProps) {
data: `${script.command}\r`,
});
} catch (error) {
dispatch({
type: "SET_ERROR",
threadId: activeThreadId,
error: error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
});
setThreadError(
activeThreadId,
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(
async (input: {
@@ -1123,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;
@@ -1215,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;
@@ -1420,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);
@@ -1435,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 => {
@@ -1449,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 });
@@ -1465,12 +1475,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
}
splitTerminal();
return;
@@ -1479,20 +1485,16 @@ 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) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
}
createNewTerminal();
return;
@@ -1517,12 +1519,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
return () => window.removeEventListener("keydown", handler);
}, [
activeProject,
activeThread?.terminalOpen,
activeThread?.activeTerminalId,
terminalState.terminalOpen,
terminalState.activeTerminalId,
activeThreadId,
closeTerminal,
createNewTerminal,
dispatch,
setTerminalOpen,
runProjectScript,
splitTerminal,
keybindings,
@@ -1530,30 +1532,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
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[]) => {
if (!activeThreadId || files.length === 0) return;
@@ -1718,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;
}
@@ -1792,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);
}
}
@@ -1938,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));
}
@@ -2467,7 +2432,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
)}
{(() => {
if (!activeThread.terminalOpen || !activeProject) {
if (!terminalState.terminalOpen || !activeProject) {
return null;
}
return (
@@ -2476,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}
@@ -2489,13 +2454,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={(height) =>
dispatch({
type: "SET_THREAD_TERMINAL_HEIGHT",
threadId: activeThread.id,
height,
})
}
onHeightChange={setTerminalHeight}
/>
);
})()}
+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">
+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 -84
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,70 +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([]);
});
});
+222 -625
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,48 +7,15 @@ import {
type OrchestrationSessionStatus,
resolveModelSlug,
} from "@t3tools/contracts";
import { create } from "zustand";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
MAX_THREAD_TERMINAL_COUNT,
type ChatMessage,
type Project,
type RuntimeMode,
type Thread,
type ThreadTerminalGroup,
} 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 ────────────────────────────────────────────────────────────
export interface AppState {
@@ -87,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;
@@ -119,7 +76,6 @@ function readPersistedState(): AppState {
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
PERSISTED_STATE_KEY,
@@ -138,6 +94,8 @@ function persistState(state: AppState): void {
}
}
// ── Pure helpers ──────────────────────────────────────────────────────
function updateThread(
threads: Thread[],
threadId: ThreadId,
@@ -193,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 =
@@ -204,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 =
@@ -233,594 +186,238 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
return `/attachments/${encodeURIComponent(attachmentId)}`;
}
function normalizeTerminalIds(terminalIds: string[]): string[] {
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];
}
// ── Pure state transition functions ────────────────────────────────────
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));
}
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,
export function syncServerReadModel(
state: AppState,
readModel: OrchestrationReadModel,
): AppState {
const projects = mapProjectsFromReadModel(
readModel.projects.filter((project) => project.deletedAt === null),
state.projects,
);
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId =
terminalGroups[activeGroupIndex]?.id ??
terminalGroups[0]?.id ??
fallbackGroupId(activeTerminalId);
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 {
...thread,
terminalIds,
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
...state,
projects,
threads,
threadsHydrated: true,
};
}
function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
if (!thread.terminalIds.includes(terminalId)) {
return thread;
}
const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
if (remainingTerminalIds.length === 0) {
const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID);
return normalizeThreadTerminals({
...thread,
terminalOpen: false,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: nextTerminalGroupId,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
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,
});
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 setThreadTerminalActivity(
thread: Thread,
terminalId: string,
hasRunningSubprocess: boolean,
): Thread {
const normalizedThread = normalizeThreadTerminals(thread);
if (!normalizedThread.terminalIds.includes(terminalId)) {
return normalizedThread;
}
const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
if (hasRunningSubprocess) {
runningTerminalIds.add(terminalId);
} else {
runningTerminalIds.delete(terminalId);
}
return normalizeThreadTerminals({
...normalizedThread,
runningTerminalIds: [...runningTerminalIds],
});
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 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;
}
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,
}),
},
),
);
+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;
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: [],