Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 004658797e Fix store reactivity: stable dispatch ref, reactive terminal state, no-op guard
- useStore(): wrap dispatch actions in useMemo so the reference is stable
  across renders, preventing infinite effect loops in EventRouter
- Sidebar: subscribe to terminalStateByThreadId data instead of the
  getTerminalState function reference so terminal indicators re-render
- reduceThreadTerminalState: return original state (not normalized copy)
  for no-op actions so the reference equality guard in applyTerminalAction
  can short-circuit unnecessary store updates

Co-authored-by: Julius Marminge <[email protected]>
2026-03-02 18:40:49 +00:00
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
Julius Marminge 2c7101092a Set default cursor on sidebar session rows
- Add `cursor-default` to sidebar row classes in `Sidebar.tsx`
- Keeps list items from showing a pointer cursor while preserving hover/active styles
2026-03-02 00:06:23 -08:00
Julius Marminge 9f068356a4 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:53:31 -08:00
Julius Marminge f239c90628 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:53:31 -08:00
Julius Marminge 991dd05e72 Use forkScoped for background upstream refresh
- replace `Effect.forkDetach` with `Effect.forkScoped` when refreshing checked-out branch upstream refs
- keep checkout responsive while ensuring the background task stays tied to scope lifecycle
2026-03-01 23:24:22 -08:00
Julius Marminge 96bf54e293 Serve fallback project favicon when no icon file is found
- return an inline SVG favicon instead of 404 when project/icon files are missing
- add route test coverage for fallback response status and MIME type
2026-03-01 23:18:45 -08:00
Julius Marminge 5ca9b54d66 Preserve $defs in Codex output schema and refine sidebar header
- include JSON Schema `$defs` when writing Codex output schema files
- tighten sidebar wordmark sizing and spacing in Electron/web layouts
2026-03-01 23:11:44 -08:00
Julius Marminge 4ab5fca4ca Preserve draft env mode across thread and branch context updates
- Track and persist `envMode` in composer draft thread state
- Keep worktree mode for local drafts even when `worktreePath` is null
- Update branch toolbar/chat/sidebar to use effective draft env mode
- Add tests for env mode persistence and undefined option merges
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex 69a4fa8215 Show branch toolbar for local draft threads
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marminge 9e04bad0a5 Run setup script after promoting local draft threads
- allow `runProjectScript` for local draft threads when explicitly enabled
- move setup script execution to run after server thread creation
- gate setup script on worktree/base-branch availability and pass resolved worktree cwd
2026-03-01 22:36:35 -08:00
Julius Marminge a574d9c936 Cover runtime undefined draft thread options in store test
- Build options object with runtime `undefined` values via cast
- Pass object into `setProjectDraftThreadId` to verify handling path
2026-03-01 22:36:35 -08:00
Julius Marminge 005e13089a Preserve draft branch/worktree when update options are undefined
- Keep existing `branch` and `worktreePath` values when `setProjectDraftThreadId` receives `undefined`
- Add a regression test covering the undefined-update case
2026-03-01 22:36:35 -08:00
Julius Marminge d9cce6402a Clean up orphaned composer drafts and harden draft checks
- Remove stale `draftsByThreadId` entries when project-thread mappings are replaced or cleared
- Preserve drafts when a thread is still mapped to another project
- Parse persisted image `dataUrl` payloads more defensively and use `Object.hasOwn` for draft-thread existence checks
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex 508872e04b Preserve explicit DEFAULT_MODEL draft overrides
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex aced302b63 Address PR review feedback for draft model/error/persistence handling
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marminge 0b8dfee17b Simplify composer draft persistence and remove debug instrumentation
- Remove ChatView draft persistence debug logging and storage size plumbing
- Drop in-memory persisted draft cache; use JSON storage directly
- Reconcile attachment IDs from localStorage and streamline image hydration
2026-03-01 22:36:35 -08:00
Julius Marminge 6ab246676e Refactor draft thread lookups and cache persisted draft state
- replace `read*` draft selectors with `getDraftThread`/`getDraftThreadByProjectId`
- centralize persisted localStorage parsing/caching in `composerDraftStore`
- make ChatView fallback read persisted attachments from in-memory store state
2026-03-01 22:36:35 -08:00
Julius Marminge 122c94a24a Defer thread creation until first message send
- Track draft thread metadata in composer draft store
- Reuse and update local draft threads from Sidebar/ChatView
- Create server thread only when sending first message, with rollback on failure
- Add/expand draft-thread store tests for mapping and context updates
2026-03-01 22:36:35 -08:00
Julius Marminge b59c6d6ab1 Unify project draft thread state in composer draft store
- move project draft thread ID persistence/actions into `composerDraftStore`
- remove legacy `projectDraftThreads` module and update `ChatView`/`Sidebar` callers
- keep image dedupe stable across hydration and avoid revoking blob URLs on composer clear
- add store tests for project-thread mapping and composer clear behavior
- drop deprecated model slug aliases (`gpt-5`, `gpt-5-codex`, `gpt-5-codex-spark`)
2026-03-01 22:36:35 -08:00
Julius Marminge c9995995a4 Preserve draft metadata and dedupe composer image retries
- Reuse hidden draft threads while applying requested branch/worktree updates before navigation
- Export composer draft storage key and clone blob preview URLs when re-adding images after retry
- Deduplicate composer images by file signature (within and across calls) and add store tests for URL revoke behavior
2026-03-01 22:36:35 -08:00
Julius Marminge 545a9193e2 Persist per-thread composer drafts and reuse project draft threads
- add a zustand-backed composer draft store with localStorage persistence for prompt, cursor, model/effort, and image attachments
- wire ChatView to draft state, restore/clear drafts correctly, and warn when an attachment cannot be persisted
- track per-project draft thread IDs so Sidebar reuses hidden draft threads and excludes empty drafts from thread lists
2026-03-01 22:36:35 -08:00
Julius Marminge fa0205cba3 Run checks before release commit and set desktop buildVersion
- Move install, lint, typecheck, and test steps ahead of release commit/tag in `release.yml`
- Add `buildVersion` to staged desktop `package.json` and set it to the app version
2026-03-01 20:33:00 -08:00
github-actions[bot]andcodex 8a20bd7f54 chore(release): prepare v0.0.0-alpha.4
Co-authored-by: codex <[email protected]>
2026-03-02 04:23:28 +00:00
25 changed files with 1271 additions and 955 deletions

No files matched your search

+12 -12
View File
@@ -84,6 +84,18 @@ jobs:
if: github.event_name == 'workflow_dispatch'
run: bun install
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
- name: Commit and push release version + tag
if: github.event_name == 'workflow_dispatch'
shell: bash
@@ -117,18 +129,6 @@ jobs:
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
fi
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
build:
name: Build ${{ matrix.label }}
needs: preflight
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.1.0",
"version": "0.0.0-alpha.4",
"bin": {
"t3": "./dist/index.mjs"
},
@@ -19,6 +19,17 @@ 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,
@@ -204,7 +215,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(Schema.toJsonSchemaDocument(outputSchemaJson).schema),
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
);
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.forkDetach(
yield* Effect.forkScoped(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
);
});
@@ -152,4 +152,16 @@ 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"');
});
});
});
+11 -2
View File
@@ -9,6 +9,8 @@ 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",
@@ -85,6 +87,14 @@ 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;
@@ -118,8 +128,7 @@ export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerRespons
const trySourceFiles = (index: number): void => {
if (index >= ICON_SOURCE_FILES.length) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("No favicon found");
serveFallbackFavicon(res);
return;
}
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"private": true,
"type": "module",
"scripts": {
+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}
/>
);
})()}
+21 -17
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 {
@@ -171,7 +174,7 @@ function T3Wordmark() {
return (
<svg
aria-label="T3"
className="h-3 w-auto shrink-0 text-foreground"
className="h-2.5 w-auto shrink-0 text-foreground"
viewBox="15.5309 37 94.3941 56.96"
xmlns="http://www.w3.org/2000/svg"
>
@@ -234,6 +237,7 @@ 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(
@@ -312,7 +316,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]);
@@ -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;
@@ -689,9 +693,7 @@ 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"),
});
};
@@ -711,14 +713,14 @@ export default function Sidebar() {
};
const wordmark = (
<div className={`flex items-center gap-2 ${isElectron ? "-translate-y-px" : ""}`}>
<div className="flex items-center gap-2">
<SidebarTrigger className="shrink-0 md:hidden" />
<div className="flex min-w-0 flex-1 items-center gap-1">
<div className="flex min-w-0 flex-1 items-center gap-1 mt-2 ml-1">
<T3Wordmark />
<span className="truncate text-base font-medium tracking-tight text-muted-foreground">
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
Code
</span>
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">
<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">
{APP_STAGE_LABEL}
</span>
</div>
@@ -740,10 +742,10 @@ export default function Sidebar() {
<>
{isElectron ? (
<>
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[88px]">
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
{wordmark}
</SidebarHeader>
<div className="px-4 pb-2">{newThreadButton}</div>
<div className="px-4 py-2">{newThreadButton}</div>
</>
) : (
<SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
@@ -771,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>
@@ -813,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(
terminalStateByThreadId[thread.id]?.runningTerminalIds ?? [],
);
return (
<SidebarMenuSubItem key={thread.id} className="w-full">
@@ -821,7 +825,7 @@ export default function Sidebar() {
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
className={`h-7 w-full translate-x-0 cursor-default 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"
+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([]);
});
});
+232 -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, useMemo } 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,248 @@ 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,
}));
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 };
}
+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 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,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: [],
+4 -4
View File
@@ -16,7 +16,7 @@
},
"apps/desktop": {
"name": "@t3tools/desktop",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"dependencies": {
"electron": "40.6.0",
},
@@ -32,7 +32,7 @@
},
"apps/server": {
"name": "t3",
"version": "0.1.0",
"version": "0.0.0-alpha.4",
"bin": {
"t3": "./dist/index.mjs",
},
@@ -60,7 +60,7 @@
},
"apps/web": {
"name": "@t3tools/web",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"dependencies": {
"@base-ui/react": "^1.2.0",
"@pierre/diffs": "^1.1.0-beta.16",
@@ -96,7 +96,7 @@
},
"packages/contracts": {
"name": "@t3tools/contracts",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"dependencies": {
"effect": "catalog:",
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.0",
"version": "0.0.0-alpha.4",
"private": true,
"files": [
"dist"
+2
View File
@@ -99,6 +99,7 @@ interface ResolvedBuildOptions {
interface StagePackageJson {
readonly name: string;
readonly version: string;
readonly buildVersion: string;
readonly private: true;
readonly description: string;
readonly author: string;
@@ -488,6 +489,7 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
const stagePackageJson: StagePackageJson = {
name: "t3-code-desktop",
version: appVersion,
buildVersion: appVersion,
private: true,
description: "T3 Code desktop build",
author: "T3 Tools",
+165 -14
View File
@@ -1,4 +1,5 @@
import { spawn } from "node:child_process";
import net from "node:net";
import { homedir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
@@ -6,6 +7,7 @@ import { pathToFileURL } from "node:url";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
const MODE_ARGS = {
dev: [
@@ -209,7 +211,133 @@ export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
return output;
}
export function runDevRunner(argv = process.argv) {
function portPairForOffset(offset) {
return {
serverPort: BASE_SERVER_PORT + offset,
webPort: BASE_WEB_PORT + offset,
};
}
async function canListenOnHost(port, host) {
return await new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", (error) => {
const code = error?.code;
if (code === "EADDRNOTAVAIL") {
// Host family unavailable on this machine (for example, no IPv6 loopback).
resolve(true);
return;
}
resolve(false);
});
server.once("listening", () => {
server.close(() => {
resolve(true);
});
});
server.listen({ host, port });
});
}
async function isPortAvailable(port) {
// Vite/dev traffic uses localhost loopback. Verify both IPv4 and IPv6 loopback
// so we don't pick a port that fails later on one address family.
const [ipv4, ipv6] = await Promise.all([
canListenOnHost(port, "127.0.0.1"),
canListenOnHost(port, "::1"),
]);
return ipv4 && ipv6;
}
const defaultCheckPortAvailability = isPortAvailable;
export async function findFirstAvailableOffset({
startOffset,
requireServerPort,
requireWebPort,
checkPortAvailability = defaultCheckPortAvailability,
}) {
for (let candidate = startOffset; ; candidate += 1) {
const { serverPort, webPort } = portPairForOffset(candidate);
const serverPortOutOfRange = serverPort > MAX_PORT;
const webPortOutOfRange = webPort > MAX_PORT;
if (
(requireServerPort && serverPortOutOfRange) ||
(requireWebPort && webPortOutOfRange) ||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
) {
break;
}
const checks = [];
if (requireServerPort) {
checks.push(checkPortAvailability(serverPort));
}
if (requireWebPort) {
checks.push(checkPortAvailability(webPort));
}
if (checks.length === 0) {
return candidate;
}
const availability = await Promise.all(checks);
if (availability.every(Boolean)) {
return candidate;
}
}
throw new Error(
`No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
);
}
export async function resolveModePortOffsets({
mode,
startOffset,
envOverrides,
checkPortAvailability,
}) {
const hasExplicitServerPort = typeof envOverrides.T3CODE_PORT === "string";
const hasExplicitDevUrl = typeof envOverrides.VITE_DEV_SERVER_URL === "string";
if (mode === "dev:web") {
if (hasExplicitDevUrl) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const webOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: false,
requireWebPort: true,
checkPortAvailability,
});
return { serverOffset: startOffset, webOffset };
}
if (mode === "dev:server") {
if (hasExplicitServerPort) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const serverOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability,
});
return { serverOffset, webOffset: serverOffset };
}
const sharedOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: !hasExplicitServerPort,
requireWebPort: !hasExplicitDevUrl,
checkPortAvailability,
});
return { serverOffset: sharedOffset, webOffset: sharedOffset };
}
export async function runDevRunner(argv = process.argv) {
const mode = argv[2];
const parsedArgs = parseDevRunnerArgs(argv.slice(3));
if (!mode || !(mode in MODE_ARGS)) {
@@ -218,24 +346,49 @@ export function runDevRunner(argv = process.argv) {
}
const { offset, source } = resolveOffset();
const serverPort = BASE_SERVER_PORT + offset;
const webPort = BASE_WEB_PORT + offset;
const { serverOffset, webOffset } = await resolveModePortOffsets({
mode,
startOffset: offset,
envOverrides: parsedArgs.envOverrides,
});
if (serverPort > 65535 || webPort > 65535) {
throw new Error(
`Port offset too large (${offset}). Computed ports: server=${serverPort}, web=${webPort}`,
);
const mergedEnvOverrides = { ...parsedArgs.envOverrides };
if (!("VITE_DEV_SERVER_URL" in mergedEnvOverrides)) {
const { webPort } = portPairForOffset(webOffset);
mergedEnvOverrides.PORT = String(webPort);
mergedEnvOverrides.ELECTRON_RENDERER_PORT = String(webPort);
mergedEnvOverrides.VITE_DEV_SERVER_URL = `http://localhost:${webPort}`;
}
const env = createDevRunnerEnv({
mode,
env: process.env,
offset,
envOverrides: parsedArgs.envOverrides,
offset: serverOffset,
envOverrides: mergedEnvOverrides,
});
const parsedServerPort = Number(env.T3CODE_PORT);
const parsedWebPort = Number(env.PORT);
if (
!Number.isInteger(parsedServerPort) ||
parsedServerPort < 1 ||
parsedServerPort > MAX_PORT ||
!Number.isInteger(parsedWebPort) ||
parsedWebPort < 1 ||
parsedWebPort > MAX_PORT
) {
throw new Error(
`Invalid computed dev ports: server='${String(env.T3CODE_PORT)}' web='${String(env.PORT)}'.`,
);
}
const selectionSuffix =
serverOffset !== offset || webOffset !== offset
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
: "";
console.info(
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort} stateDir=${env.T3CODE_STATE_DIR}`,
`[dev-runner] mode=${mode} source=${source}${selectionSuffix} serverPort=${parsedServerPort} webPort=${parsedWebPort} stateDir=${env.T3CODE_STATE_DIR}`,
);
if (parsedArgs.isDryRun) {
@@ -265,10 +418,8 @@ export function runDevRunner(argv = process.argv) {
const entrypointPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : "";
if (import.meta.url === entrypointPath) {
try {
runDevRunner();
} catch (error) {
runDevRunner().catch((error) => {
console.error("[dev-runner]", error);
process.exit(1);
}
});
}
+98
View File
@@ -3,7 +3,9 @@ import { describe, expect, it } from "vitest";
import {
DEFAULT_DEV_STATE_DIR,
createDevRunnerEnv,
findFirstAvailableOffset,
parseDevRunnerArgs,
resolveModePortOffsets,
} from "./dev-runner.mjs";
describe("parseDevRunnerArgs", () => {
@@ -123,3 +125,99 @@ describe("createDevRunnerEnv", () => {
).toThrow("Invalid T3CODE_PORT override");
});
});
describe("findFirstAvailableOffset", () => {
it("returns the starting offset when required ports are available", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async () => true,
});
expect(offset).toBe(0);
});
it("advances until all required ports are available", async () => {
const taken = new Set([3773, 5733, 3774, 5734]);
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offset).toBe(2);
});
it("allows offsets where only non-required ports exceed max", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 59_803,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: async () => true,
});
expect(offset).toBe(59_803);
});
});
describe("resolveModePortOffsets", () => {
it("uses a shared fallback offset for dev mode", async () => {
const taken = new Set([3773, 5733]);
const offsets = await resolveModePortOffsets({
mode: "dev",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("keeps server offset stable for dev:web and only shifts web offset", async () => {
const taken = new Set([5733]);
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 1 });
});
it("shifts only server offset for dev:server", async () => {
const taken = new Set([3773]);
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("respects explicit dev-url override for dev:web", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: { VITE_DEV_SERVER_URL: "http://localhost:9999" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
it("respects explicit server port override for dev:server", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: { T3CODE_PORT: "4888" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
});