Compare commits

..
Author SHA1 Message Date
Julius Marminge 70248fafe6 Allow non-required dev ports to exceed max in offset search
- Stop `findFirstAvailableOffset` only when a required port exceeds `MAX_PORT`
- Add test covering offsets where only non-required ports are out of range
2026-03-01 23:51:07 -08:00
Julius Marminge 7088a21e97 Auto-select next available dev ports per mode
- Probe localhost ports and increment offsets when base ports are taken
- Resolve server/web offsets by mode while honoring explicit port/dev-url overrides
- Add tests for offset selection and per-mode fallback behavior
2026-03-01 23:32:52 -08:00
16 changed files with 917 additions and 982 deletions

No files matched your search

@@ -19,17 +19,6 @@ const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return {
...document.schema,
$defs: document.definitions,
};
}
return document.schema;
}
function normalizeCodexError(
operation: string,
error: unknown,
@@ -215,7 +204,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
JSON.stringify(Schema.toJsonSchemaDocument(outputSchemaJson).schema),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
+1 -1
View File
@@ -1162,7 +1162,7 @@ const makeGitCore = Effect.gen(function* () {
});
// Refresh upstream refs in the background so checkout remains responsive.
yield* Effect.forkScoped(
yield* Effect.forkDetach(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
);
});
@@ -152,16 +152,4 @@ describe("tryHandleProjectFaviconRequest", () => {
expect(response.body).toBe("<svg>brand-obj-order</svg>");
});
});
it("serves a fallback favicon when no icon exists", async () => {
const projectDir = makeTempDir("t3code-favicon-route-fallback-");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toContain('data-fallback="project-favicon"');
});
});
});
+2 -11
View File
@@ -9,8 +9,6 @@ const FAVICON_MIME_TYPES: Record<string, string> = {
".ico": "image/x-icon",
};
const FALLBACK_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
// Well-known favicon paths checked in order.
const FAVICON_CANDIDATES = [
"favicon.svg",
@@ -87,14 +85,6 @@ function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
});
}
function serveFallbackFavicon(res: http.ServerResponse): void {
res.writeHead(200, {
"Content-Type": "image/svg+xml",
"Cache-Control": "public, max-age=3600",
});
res.end(FALLBACK_FAVICON_SVG);
}
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
if (url.pathname !== "/api/project-favicon") {
return false;
@@ -128,7 +118,8 @@ export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerRespons
const trySourceFiles = (index: number): void => {
if (index >= ICON_SOURCE_FILES.length) {
serveFallbackFavicon(res);
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("No favicon found");
return;
}
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
+8 -3
View File
@@ -114,7 +114,12 @@ export default function BranchToolbar({
});
}
if (hasServerThread) {
dispatch.setThreadBranch(activeThreadId, syncedBranch, null);
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
return;
}
setDraftThreadContext(threadId, {
@@ -142,7 +147,7 @@ export default function BranchToolbar({
const setThreadError = (error: string | null) => {
if (!activeThreadId) return;
dispatch.setError(activeThreadId, error);
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
};
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
@@ -171,7 +176,7 @@ export default function BranchToolbar({
});
}
if (hasServerThread) {
dispatch.setThreadBranch(activeThreadId, branch, worktreePath);
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
return;
}
setDraftThreadContext(threadId, {
+148 -107
View File
@@ -120,7 +120,6 @@ import {
useComposerDraftStore,
useComposerThreadDraft,
} from "../composerDraftStore";
import { useTerminalStateStore } from "../terminalStateStore";
import { clamp } from "effect/Number";
function formatMessageMeta(createdAt: string, duration: string | null): string {
@@ -208,6 +207,18 @@ 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,
@@ -486,14 +497,6 @@ 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);
@@ -575,7 +578,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
dispatch.markThreadVisited(activeThread.id);
dispatch({
type: "MARK_THREAD_VISITED",
threadId: activeThread.id,
});
}, [
activeThread?.id,
activeThread?.lastVisitedAt,
@@ -845,26 +851,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
(activeThread.session !== null && activeThread.session.status !== "closed")),
);
const hasReachedTerminalLimit =
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],
);
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
const focusComposer = useCallback(() => {
const textarea = textareaRef.current;
@@ -878,49 +865,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;
setTerminalOpen(!terminalState.terminalOpen);
}, [activeThreadId, setTerminalOpen, terminalState.terminalOpen]);
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: !activeThread?.terminalOpen,
});
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
const splitTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return;
const terminalId = `terminal-${crypto.randomUUID()}`;
storeSplitTerminal(activeThreadId, terminalId);
dispatch({
type: "SPLIT_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, storeSplitTerminal, hasReachedTerminalLimit]);
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
const createNewTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return;
const terminalId = `terminal-${crypto.randomUUID()}`;
storeNewTerminal(activeThreadId, terminalId);
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, storeNewTerminal, hasReachedTerminalLimit]);
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
const activateTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId) return;
storeSetActiveTerminal(activeThreadId, terminalId);
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId,
});
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, storeSetActiveTerminal],
[activeThreadId, dispatch],
);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readNativeApi();
if (!activeThreadId || !api) return;
const isFinalTerminal = terminalState.terminalIds.length <= 1;
const isFinalTerminal = (activeThread?.terminalIds.length ?? 0) <= 1;
const fallbackExitWrite = () =>
api.terminal
.write({ threadId: activeThreadId, terminalId, data: "exit\n" })
@@ -937,10 +924,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
} else {
void fallbackExitWrite();
}
storeCloseTerminal(activeThreadId, terminalId);
dispatch({
type: "CLOSE_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId,
});
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, storeCloseTerminal, terminalState.terminalIds.length],
[activeThread?.terminalIds.length, activeThreadId, dispatch],
);
const runProjectScript = useCallback(
async (
@@ -965,22 +956,32 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd;
const baseTerminalId =
terminalState.activeTerminalId ||
terminalState.terminalIds[0] ||
DEFAULT_THREAD_TERMINAL_ID;
const isBaseTerminalBusy = terminalState.runningTerminalIds.includes(baseTerminalId);
activeThread.activeTerminalId || activeThread.terminalIds[0] || DEFAULT_THREAD_TERMINAL_ID;
const isBaseTerminalBusy = activeThread.runningTerminalIds.includes(baseTerminalId);
const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
const shouldCreateNewTerminal =
wantsNewTerminal && terminalState.terminalIds.length < MAX_THREAD_TERMINAL_COUNT;
wantsNewTerminal && activeThread.terminalIds.length < MAX_THREAD_TERMINAL_COUNT;
const targetTerminalId = shouldCreateNewTerminal
? `terminal-${crypto.randomUUID()}`
: baseTerminalId;
setTerminalOpen(true);
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
if (shouldCreateNewTerminal) {
storeNewTerminal(activeThreadId, targetTerminalId);
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
} else {
storeSetActiveTerminal(activeThreadId, targetTerminalId);
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
}
setTerminalFocusRequestId((value) => value + 1);
@@ -1011,25 +1012,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
data: `${script.command}\r`,
});
} catch (error) {
setThreadError(
activeThreadId,
error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
);
dispatch({
type: "SET_ERROR",
threadId: activeThreadId,
error: error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
});
}
},
[
activeProject,
activeThread,
activeThreadId,
dispatch,
gitCwd,
isLocalDraftThread,
isServerThread,
setTerminalOpen,
setThreadError,
storeNewTerminal,
storeSetActiveTerminal,
],
[activeProject, activeThread, activeThreadId, dispatch, gitCwd, isServerThread],
);
const persistProjectScripts = useCallback(
async (input: {
@@ -1133,7 +1123,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return;
dispatch.setRuntimeMode(mode);
dispatch({ type: "SET_RUNTIME_MODE", mode });
scheduleComposerFocus();
const api = readNativeApi();
if (!api) return;
@@ -1225,14 +1215,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [activeThread?.id]);
useEffect(() => {
if (!activeThread?.id || terminalState.terminalOpen) return;
if (!activeThread?.id || activeThread.terminalOpen) return;
const frame = window.requestAnimationFrame(() => {
focusComposer();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [activeThread?.id, focusComposer, terminalState.terminalOpen]);
}, [activeThread?.id, activeThread?.terminalOpen, focusComposer]);
useEffect(() => {
composerImagesRef.current = composerImages;
@@ -1430,7 +1420,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => {
if (!activeThreadId) return;
const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false;
const current = Boolean(terminalState.terminalOpen);
const current = Boolean(activeThread?.terminalOpen);
if (!previous && current) {
setTerminalFocusRequestId((value) => value + 1);
@@ -1445,7 +1435,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
terminalOpenByThreadRef.current[activeThreadId] = current;
}, [activeThreadId, focusComposer, terminalState.terminalOpen]);
}, [activeThread?.terminalOpen, activeThreadId, focusComposer]);
useEffect(() => {
const isTerminalFocused = (): boolean => {
@@ -1459,7 +1449,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (!activeThreadId || event.defaultPrevented) return;
const shortcutContext = {
terminalFocus: isTerminalFocused(),
terminalOpen: Boolean(terminalState.terminalOpen),
terminalOpen: Boolean(activeThread?.terminalOpen),
};
const command = resolveShortcutCommand(event, keybindings, { context: shortcutContext });
@@ -1475,8 +1465,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
}
splitTerminal();
return;
@@ -1485,16 +1479,20 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (command === "terminal.close") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) return;
closeTerminal(terminalState.activeTerminalId);
if (!activeThread?.terminalOpen) return;
closeTerminal(activeThread.activeTerminalId);
return;
}
if (command === "terminal.new") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
}
createNewTerminal();
return;
@@ -1519,12 +1517,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
return () => window.removeEventListener("keydown", handler);
}, [
activeProject,
terminalState.terminalOpen,
terminalState.activeTerminalId,
activeThread?.terminalOpen,
activeThread?.activeTerminalId,
activeThreadId,
closeTerminal,
createNewTerminal,
setTerminalOpen,
dispatch,
runProjectScript,
splitTerminal,
keybindings,
@@ -1532,6 +1530,30 @@ 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;
@@ -1696,7 +1718,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
const shouldCreateWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;
if (shouldCreateWorktree && !activeThread.branch) {
dispatch.setError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
dispatch({
type: "SET_ERROR",
threadId: threadIdForSend,
error: "Select a base branch before sending in New worktree mode.",
});
return;
}
@@ -1766,7 +1792,12 @@ 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.setThreadBranch(threadIdForSend, result.worktree.branch, result.worktree.path);
dispatch({
type: "SET_THREAD_BRANCH",
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
}
}
@@ -1907,7 +1938,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: new Date().toISOString(),
});
} catch (err) {
dispatch.setError(activeThreadId, err instanceof Error ? err.message : "Failed to submit approval decision.");
dispatch({
type: "SET_ERROR",
threadId: activeThreadId,
error: err instanceof Error ? err.message : "Failed to submit approval decision.",
});
} finally {
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
}
@@ -2432,7 +2467,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
)}
{(() => {
if (!terminalState.terminalOpen || !activeProject) {
if (!activeThread.terminalOpen || !activeProject) {
return null;
}
return (
@@ -2441,11 +2476,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId={activeThread.id}
cwd={gitCwd ?? activeProject.cwd}
runtimeEnv={threadTerminalRuntimeEnv}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
height={activeThread.terminalHeight}
terminalIds={activeThread.terminalIds}
activeTerminalId={activeThread.activeTerminalId}
terminalGroups={activeThread.terminalGroups}
activeTerminalGroupId={activeThread.activeTerminalGroupId}
focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
@@ -2454,7 +2489,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={setTerminalHeight}
onHeightChange={(height) =>
dispatch({
type: "SET_THREAD_TERMINAL_HEIGHT",
threadId: activeThread.id,
height,
})
}
/>
);
})()}
+17 -21
View File
@@ -21,7 +21,6 @@ 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";
@@ -127,10 +126,8 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
return null;
}
function terminalStatusFromRunningIds(
runningTerminalIds: string[],
): TerminalStatusIndicator | null {
if (runningTerminalIds.length === 0) {
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
if (thread.runningTerminalIds.length === 0) {
return null;
}
return {
@@ -174,7 +171,7 @@ function T3Wordmark() {
return (
<svg
aria-label="T3"
className="h-2.5 w-auto shrink-0 text-foreground"
className="h-3 w-auto shrink-0 text-foreground"
viewBox="15.5309 37 94.3941 56.96"
xmlns="http://www.w3.org/2000/svg"
>
@@ -237,7 +234,6 @@ export default function Sidebar() {
(store) => store.getDraftThreadByProjectId,
);
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const terminalStateByThreadId = useTerminalStateStore((s) => s.terminalStateByThreadId);
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const clearProjectDraftThreadId = useComposerDraftStore(
@@ -316,7 +312,7 @@ export default function Sidebar() {
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
const branchMatches =
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
map.set(target.threadId, branchMatches ? status?.pr ?? null : null);
}
return map;
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
@@ -501,7 +497,7 @@ export default function Sidebar() {
position,
);
if (clicked === "mark-unread") {
dispatch.markThreadUnread(threadId);
dispatch({ type: "MARK_THREAD_UNREAD", threadId });
return;
}
if (clicked !== "delete") return;
@@ -693,7 +689,9 @@ export default function Sidebar() {
void handleNewThread(projectId, {
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
envMode:
activeDraftThread?.envMode ??
(activeThread?.worktreePath ? "worktree" : "local"),
});
};
@@ -713,14 +711,14 @@ export default function Sidebar() {
};
const wordmark = (
<div className="flex items-center gap-2">
<div className={`flex items-center gap-2 ${isElectron ? "-translate-y-px" : ""}`}>
<SidebarTrigger className="shrink-0 md:hidden" />
<div className="flex min-w-0 flex-1 items-center gap-1 mt-2 ml-1">
<div className="flex min-w-0 flex-1 items-center gap-1">
<T3Wordmark />
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
<span className="truncate text-base font-medium tracking-tight text-muted-foreground">
Code
</span>
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">
{APP_STAGE_LABEL}
</span>
</div>
@@ -742,10 +740,10 @@ export default function Sidebar() {
<>
{isElectron ? (
<>
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[88px]">
{wordmark}
</SidebarHeader>
<div className="px-4 py-2">{newThreadButton}</div>
<div className="px-4 pb-2">{newThreadButton}</div>
</>
) : (
<SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
@@ -773,7 +771,7 @@ export default function Sidebar() {
open={project.expanded}
onOpenChange={(open) => {
if (open === project.expanded) return;
dispatch.toggleProject(project.id);
dispatch({ type: "TOGGLE_PROJECT", projectId: project.id });
}}
>
<SidebarMenuItem>
@@ -815,9 +813,7 @@ export default function Sidebar() {
pendingApprovalByThreadId.get(thread.id) === true,
);
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
terminalStateByThreadId[thread.id]?.runningTerminalIds ?? [],
);
const terminalStatus = terminalStatusIndicator(thread);
return (
<SidebarMenuSubItem key={thread.id} className="w-full">
@@ -825,7 +821,7 @@ export default function Sidebar() {
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
isActive
? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
: "text-muted-foreground"
+11 -7
View File
@@ -15,7 +15,6 @@ 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";
@@ -145,7 +144,7 @@ function EventRouter() {
const snapshot = await api.orchestration.getSnapshot();
if (disposed) return;
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
dispatch.syncServerReadModel(snapshot);
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
if (pending) {
pending = false;
await flushSnapshotSync();
@@ -185,11 +184,12 @@ function EventRouter() {
if (hasRunningSubprocess === null) {
return;
}
useTerminalStateStore.getState().setTerminalActivity(
ThreadId.makeUnsafe(event.threadId),
event.terminalId,
dispatch({
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe(event.threadId),
terminalId: event.terminalId,
hasRunningSubprocess,
);
});
});
const unsubWelcome = onServerWelcome((payload) => {
void (async () => {
@@ -201,7 +201,11 @@ function EventRouter() {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return;
}
dispatch.setProjectExpanded(payload.bootstrapProjectId, true);
dispatch({
type: "SET_PROJECT_EXPANDED",
projectId: payload.bootstrapProjectId,
expanded: true,
});
if (pathnameRef.current !== "/") {
return;
+4 -1
View File
@@ -346,7 +346,10 @@ function SettingsRouteView() {
: "border-border bg-background text-muted-foreground hover:bg-accent"
}`}
onClick={() => {
dispatch.setRuntimeMode(option.value);
dispatch({
type: "SET_RUNTIME_MODE",
mode: option.value,
});
}}
>
<span className="flex flex-col">
+84 -7
View File
@@ -1,8 +1,8 @@
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { markThreadUnread, type AppState } from "./store";
import type { Thread } from "./types";
import { reducer, type AppState } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
@@ -11,6 +11,18 @@ 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: [],
@@ -42,8 +54,8 @@ function makeState(thread: Thread): AppState {
};
}
describe("store pure functions", () => {
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
describe("store reducer", () => {
it("marks a completed thread as unread by moving lastVisitedAt before completion", () => {
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeState(
makeThread({
@@ -59,7 +71,10 @@ describe("store pure functions", () => {
}),
);
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
const next = reducer(initialState, {
type: "MARK_THREAD_UNREAD",
threadId: ThreadId.makeUnsafe("thread-1"),
});
const updatedThread = next.threads[0];
expect(updatedThread).toBeDefined();
@@ -69,7 +84,7 @@ describe("store pure functions", () => {
);
});
it("markThreadUnread does not change a thread without a completed turn", () => {
it("does not change a thread without a completed turn", () => {
const initialState = makeState(
makeThread({
latestTurn: null,
@@ -77,8 +92,70 @@ describe("store pure functions", () => {
}),
);
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
const next = reducer(initialState, {
type: "MARK_THREAD_UNREAD",
threadId: 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([]);
});
});
+621 -228
View File
@@ -1,4 +1,13 @@
import { Fragment, type ReactNode, createElement, useEffect, useMemo } from "react";
import {
type Dispatch,
type ReactNode,
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import {
DEFAULT_MODEL,
ProviderSessionId,
@@ -7,15 +16,48 @@ 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 {
@@ -45,10 +87,11 @@ const initialState: AppState = {
};
const persistedExpandedProjectCwds = new Set<string>();
// ── Persist helpers ──────────────────────────────────────────────────
// ── Helpers ──────────────────────────────────────────────────────────
function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
if (!raw) return initialState;
@@ -76,6 +119,7 @@ function readPersistedState(): AppState {
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
PERSISTED_STATE_KEY,
@@ -94,8 +138,6 @@ function persistState(state: AppState): void {
}
}
// ── Pure helpers ──────────────────────────────────────────────────────
function updateThread(
threads: Thread[],
threadId: ThreadId,
@@ -151,7 +193,9 @@ 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 =
@@ -160,7 +204,10 @@ 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 =
@@ -186,248 +233,594 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
return `/attachments/${encodeURIComponent(attachmentId)}`;
}
// ── Pure state transition functions ────────────────────────────────────
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];
}
export function syncServerReadModel(
state: AppState,
readModel: OrchestrationReadModel,
): AppState {
const projects = mapProjectsFromReadModel(
readModel.projects.filter((project) => project.deletedAt === null),
state.projects,
);
const existingThreadById = new Map(
state.threads.map((thread) => [thread.id, thread] as const),
);
const threads = readModel.threads
.filter((thread) => thread.deletedAt === null)
.map((thread) => {
const existing = existingThreadById.get(thread.id);
return {
id: thread.id,
codexThreadId: thread.session?.providerThreadId ?? null,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(thread.model),
session: thread.session
? {
sessionId:
thread.session.providerSessionId ??
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
provider: toLegacyProvider(thread.session.providerName),
status: toLegacySessionStatus(thread.session.status),
orchestrationStatus: thread.session.status,
threadId: thread.session.providerThreadId,
activeTurnId: thread.session.activeTurnId ?? undefined,
createdAt: thread.session.updatedAt,
updatedAt: thread.session.updatedAt,
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
}
: null,
messages: thread.messages.map((message) => {
const attachments = message.attachments?.map((attachment) => ({
type: "image" as const,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
}));
const normalizedMessage: ChatMessage = {
id: message.id,
role: message.role,
text: message.text,
createdAt: message.createdAt,
streaming: message.streaming,
...(message.streaming ? {} : { completedAt: message.updatedAt }),
...(attachments && attachments.length > 0 ? { attachments } : {}),
};
return normalizedMessage;
}),
error: thread.session?.lastError ?? null,
createdAt: thread.createdAt,
latestTurn: thread.latestTurn,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
turnId: checkpoint.turnId,
completedAt: checkpoint.completedAt,
status: checkpoint.status,
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
checkpointTurnCount: checkpoint.checkpointTurnCount,
checkpointRef: checkpoint.checkpointRef,
files: checkpoint.files.map((file) => ({ ...file })),
})),
activities: thread.activities.map((activity) => ({ ...activity })),
};
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,
);
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId =
terminalGroups[activeGroupIndex]?.id ??
terminalGroups[0]?.id ??
fallbackGroupId(activeTerminalId);
return {
...state,
projects,
threads,
threadsHydrated: true,
...thread,
terminalIds,
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
};
}
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 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 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 };
}),
};
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 toggleProject(state: AppState, projectId: Project["id"]): AppState {
return {
...state,
projects: state.projects.map((p) =>
p.id === projectId ? { ...p, expanded: !p.expanded } : p,
),
};
}
// ── Reducer ──────────────────────────────────────────────────────────
export function setProjectExpanded(
state: AppState,
projectId: Project["id"],
expanded: boolean,
): AppState {
return {
...state,
projects: state.projects.map((p) =>
p.id === projectId ? { ...p, expanded } : p,
),
};
}
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);
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 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 {
...t,
branch,
worktreePath,
...(cwdChanged ? { session: null } : {}),
...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 setRuntimeMode(state: AppState, mode: RuntimeMode): AppState {
return { ...state, runtimeMode: mode };
}
// ── Context ──────────────────────────────────────────────────────────
// ── 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) ────────────────
const StoreContext = createContext<{
state: AppState;
dispatch: Dispatch<Action>;
}>({ state: initialState, dispatch: () => {} });
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
useEffect(() => {
persistState(useAppStore.getState());
}, []);
return createElement(Fragment, null, children);
persistState(state);
}, [state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
export function useStore() {
const state = useAppStore((s) => ({
projects: s.projects,
threads: s.threads,
threadsHydrated: s.threadsHydrated,
runtimeMode: s.runtimeMode,
}));
const dispatch = useMemo(() => {
const s = useAppStore.getState();
return {
syncServerReadModel: s.syncServerReadModel,
markThreadVisited: s.markThreadVisited,
markThreadUnread: s.markThreadUnread,
toggleProject: s.toggleProject,
setProjectExpanded: s.setProjectExpanded,
setError: s.setError,
setThreadBranch: s.setThreadBranch,
setRuntimeMode: s.setRuntimeMode,
};
}, []);
return { state, dispatch };
return useContext(StoreContext);
}
-110
View File
@@ -1,110 +0,0 @@
/**
* 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
@@ -1,87 +0,0 @@
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
@@ -1,374 +0,0 @@
/**
* 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 state;
return { ...normalized, terminalOpen: action.open };
}
if (action.type === "set-height") {
if (
!Number.isFinite(action.height) ||
action.height <= 0 ||
normalized.terminalHeight === action.height
) {
return state;
}
return { ...normalized, terminalHeight: action.height };
}
if (action.type === "set-active") {
if (!normalized.terminalIds.includes(action.terminalId)) {
return state;
}
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 state;
}
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 state;
}
const isNewTerminal = !normalized.terminalIds.includes(action.terminalId);
if (isNewTerminal && normalized.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
return state;
}
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,6 +79,13 @@ 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;
+13 -1
View File
@@ -1,7 +1,7 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import type { Thread } from "./types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
function makeThread(overrides: Partial<Thread> = {}): Thread {
@@ -11,6 +11,18 @@ 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: [],