Compare commits

...
Author SHA1 Message Date
Cursor Agent aac6796d8c Wrap migration ROLLBACK in try/catch to preserve original error
Match the pattern used in StateDb.transaction: if ROLLBACK itself
throws (e.g. bad DB connection state), the original migration error
is still re-thrown instead of being replaced by the rollback error.
2026-02-20 09:10:36 +00:00
Julius Marminge 05aa27a0d9 Document review thread closure matrix for Workstream 3
- Mark Workstream 3 as complete in the implementation plan
- Add disposition matrix for CR thread outcomes (superseded, fixed, declined)
- Include evidence anchors and suggested reply templates for PR thread closure
2026-02-20 00:50:42 -08:00
Julius Marminge e81c2acb78 Harden state persistence and tighten WS thread update API
- Fix persistence edge cases around pagination offsets, assistant message ordering, and checkpoint merge semantics
- Make state DB and sqlite adapter failures safer with better cleanup and runtime errors
- Treat `threads.update` as unsupported, keep `threads.updateTerminalState` canonical, and avoid failing revert RPCs on persistence-write errors
- Add focused server/web/contracts tests for the new failure and compatibility paths
2026-02-20 00:43:30 -08:00
Julius Marminge fda3073e0c Remove legacy renderer state import path and client schema
- drop `stateImportLegacyRendererState` handling from server, WS API, and contracts
- remove legacy renderer import tests and old web persistence schema/tests
- rely on current shared state/bootstrap flow instead of one-time legacy import
2026-02-20 00:22:30 -08:00
Julius Marminge 7214778b64 plan cr fixing 2026-02-20 00:21:31 -08:00
Julius Marminge 27bd9192ad clean 2026-02-19 21:55:12 -08:00
Julius Marminge 0da96d5c93 Merge branch 'main' into codething/48364d50 2026-02-19 21:54:25 -08:00
Julius Marminge 25dbfa7bc7 debug 2026-02-19 21:54:23 -08:00
Julius Marminge 781006f005 bump electron and node 2026-02-19 21:54:10 -08:00
Julius Marminge 78b7070042 Improve persistence and runtime SQLite compatibility
- add a SQLite adapter that works in both Bun and Node/Electron, with tests
- persist and backfill `assistantMessageId` on turn summaries to keep thread diffs linked
- prevent web state regressions by preserving turn summaries and deduplicating terminal/settings sync updates
2026-02-19 20:49:27 -08:00
Julius Marminge d8412eca9f error component 2026-02-19 18:42:39 -08:00
Julius Marminge 1332c488ad Add desktop DMG packaging and persisted app settings
- package desktop builds with branded icons, custom app identity, and `t3://app` production loading
- add app settings get/update RPC flow with persistence and tests for Codex binary/home paths
- wire web/desktop settings UX and menu action hooks to open Settings
2026-02-19 18:01:51 -08:00
Julius Marminge 749a2076d8 Merge pull request #77 from pingdotgg/codething/c71d8ea1
Improve DiffPanel turn chip strip navigation and scrolling UX
2026-02-19 16:09:52 -08:00
Cursor Agent f039878edd Remove duplicate inline wheel handler, use existing onTurnStripWheel useCallback in useEffect
Applied via @cursor push command
2026-02-20 00:09:44 +00:00
Julius Marmingeandgreptile-apps[bot] 632c1417ea Update apps/web/src/components/DiffPanel.tsx
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-02-19 16:04:25 -08:00
Julius Marmingeandcodex c00354c0b1 Use non-passive wheel listener for turn strip
Co-authored-by: codex <[email protected]>
2026-02-19 15:52:11 -08:00
Julius Marmingeandcodex a002239fc4 Merge origin/main into codething/c71d8ea1
Co-authored-by: codex <[email protected]>
2026-02-19 15:48:48 -08:00
Julius Marminge 70a13c298f Merge pull request #78 from pingdotgg/codething/53bdee92
Retarget open diff panel to the visited thread
2026-02-19 15:43:24 -08:00
Julius Marmingeandcodex 8a72a2a91d Merge origin/main into codething/53bdee92
Resolve PR conflicts while preserving route-scoped diff rendering and _chat desktop menu action handling.

Co-authored-by: codex <[email protected]>
2026-02-19 15:39:47 -08:00
Cursor Agent 842e327583 Extract stripDiffSearchParams helper to deduplicate diff param stripping logic
Consolidate the repeated pattern of destructuring and removing diff/diffTurnId/diffFilePath
search params into a single stripDiffSearchParams() function in diffRouteSearch.ts.
Replaces 5 identical destructuring blocks across 3 files with calls to the shared helper.

Applied via @cursor push command
2026-02-19 23:36:12 +00:00
Julius Marminge 891eb02d49 Move diff panel into thread route and lift worker pool provider
- Extract `DiffWorkerPoolProvider` into its own component and wrap `_chat` outlet with it
- Render/lazy-load `DiffPanel` from `/_chat/$threadId` so diff UI state and close behavior live with thread routing
- Keep responsive sheet vs inline diff presentation with route-level fallback loading UI
2026-02-19 09:49:50 -08:00
Theo Browne 8cea075a1e more todo 2026-02-19 04:35:52 -08:00
Theo Browne 84fc3e96e6 todo update 2026-02-19 04:34:17 -08:00
Theo Browne 2c9121553e restore streaming notifications from codex app server 2026-02-19 04:07:33 -08:00
Theo Browne 48bf123d0c prod builds 2026-02-19 04:04:04 -08:00
Theo Browne f8883d0495 settings page 2026-02-19 02:42:24 -08:00
Theo Browne 8cb2b3fcfe fix force closing 2026-02-19 02:03:03 -08:00
Julius Marminge cc3e1db22a Drive diff panel state from route search params
- Parse and validate `diff`, `diffTurnId`, and `diffFilePath` from chat route search
- Switch ChatView/DiffPanel diff open/target actions to router navigation instead of store actions
- Remove diff-specific state/actions from the app store and update reducer tests
2026-02-19 01:47:48 -08:00
Theo Browne daf8e5f53b dev build iconography 2026-02-19 01:42:56 -08:00
Theo Browne c89798ecb1 fix naming with annoying hacks 2026-02-19 01:35:50 -08:00
Julius Marminge b253d1f8ca Retarget diff panel to active route thread on visit
- Prefer route thread id over stored diff thread when rendering diffs
- When visiting a different thread with diff open, retarget diff state and clear stale turn/file selection
- Add reducer test coverage for open-diff retargeting behavior
2026-02-19 01:34:11 -08:00
Theo Browne a32701ef8d use icon 2026-02-19 01:21:16 -08:00
Julius Marminge f3b773f1f0 Improve DiffPanel turn chip strip navigation
- Add left/right controls, edge fades, and wheel-to-horizontal scrolling for turn chips
- Auto-scroll selected turn chip into view and hide the chip strip scrollbar
- Simplify chip metadata to show compact per-turn time
2026-02-19 01:14:53 -08:00
Theo Browne efbab1b104 branding v1 2026-02-19 00:58:32 -08:00
81 changed files with 3953 additions and 1896 deletions

No files matched your search

+1
View File
@@ -10,3 +10,4 @@ packages/*/dist
.env.local
build/
.logs/
release/
@@ -0,0 +1,179 @@
# Plan: Remove Legacy localStorage Migration Paths and Resolve CR Feedback Cohesively
## Summary
Delete all runtime migration pathways that ingest legacy browser localStorage state into the new SQLite-backed model, then resolve the remaining code review (CR) findings in grouped workstreams.
This plan intentionally removes migration code instead of improving it. The target is a single canonical state flow: server-backed bootstrap + state events only, with no legacy data import bridge.
## Goals
1. Remove legacy localStorage migration for renderer state completely.
2. Remove dead contracts, RPC methods, server handlers, client callers, and tests tied to that migration.
3. Resolve valid CR findings on the retained architecture.
4. Close review threads with explicit outcomes: fixed, superseded by deletion, or declined with rationale.
## Non-Goals
1. Preserving one-time automatic import of old renderer localStorage data.
2. Refactoring unrelated UX persistence (theme/editor preferences) unless directly required by CR items.
3. Large behavior changes outside correctness/reliability fixes raised in CR.
## Architecture Decision
- Canonical state source remains SQLite + `state.bootstrap` + `state.catchUp` + streamed `stateEvent` updates.
- Legacy renderer-state migration is removed entirely.
- Existing server-side `projects.json` import path is kept unless explicitly removed in a follow-up (it is not localStorage-based).
## Workstream 1: Delete Legacy localStorage Migration End-to-End [COMPLETE]
### 1.1 Contracts and WS protocol cleanup
- Remove `stateImportLegacyRendererState` from `packages/contracts/src/ws.ts`.
- Remove state import input/result schemas and exported types from `packages/contracts/src/state.ts`.
- Remove IPC surface for `state.importLegacyRendererState` in `packages/contracts/src/ipc.ts`.
- Update and prune contracts tests in `packages/contracts/src/state.test.ts` and any IPC/WS tests that reference removed symbols.
### 1.2 Server cleanup
- Remove `PersistenceService.importLegacyRendererState(...)` and associated metadata key/constants used only for this import path.
- Remove WS routing case for `WS_METHODS.stateImportLegacyRendererState` in `apps/server/src/wsServer.ts`.
- Remove server tests that exercise legacy renderer import via RPC and service unit tests.
- Ensure no dead helpers remain (payload mapping, metadata flags, schema imports, etc.).
### 1.3 Web client cleanup
- Remove legacy key constants and helper functions from `apps/web/src/routes/__root.tsx`:
- `CURRENT_RENDERER_STATE_KEY`
- `LEGACY_RENDERER_STATE_KEYS`
- `readLegacyRendererImportPayload`
- `clearLegacyRendererState`
- import-and-refresh bootstrap branch invoking `api.state.importLegacyRendererState(...)`
- Remove `hydratePersistedState` dependency from root route.
- Delete or narrow `apps/web/src/persistenceSchema.ts` to only what is still used. If unused after migration removal, delete file and tests.
- Remove `state.importLegacyRendererState` call path from `apps/web/src/wsNativeApi.ts`.
### 1.4 Dead-code verification pass
- `rg` for: `importLegacyRendererState`, `stateImportLegacyRendererState`, `renderer-state:v`, `hydratePersistedState`, legacy metadata keys.
- Ensure zero references remain in app code, contracts, and tests.
## Workstream 2: Resolve CR Findings in Surviving Code (Grouped by Relevance) [COMPLETE]
### Group A: Data integrity and transactional correctness (highest priority)
- `apps/server/src/persistenceService.ts`
- Fix `listMessages` pagination progress: use fetched row count for `nextOffset`.
- Guard `withTransaction` post-commit event emission so listener exceptions do not surface as transaction failures.
- Preserve `checkpointTurnCount = 0` in turn-summary merge logic.
- Prevent `item/started` from clobbering previously accumulated assistant text when events arrive out of order.
- `apps/server/src/wsServer.ts`
- Wrap/contain `applyCheckpointRevert` persistence update so provider revert success is not falsely returned as failure.
- `apps/server/src/stateDb.ts`
- Close DB when migration initialization fails in constructor.
- Preserve original transaction error if rollback also throws.
### Group B: API/contract clarity and ownership boundaries
- `apps/server/src/wsServer.ts` + `packages/contracts/src/ipc.ts` + `apps/web/src/wsNativeApi.ts`
- Remove ambiguous generic `threads.update` or make it explicit/unsupported (single canonical terminal-state update route).
- Align method names/types with actual handlers.
- `apps/server/src/wsServer.ts`
- Track ownership of injected `persistenceService`; only close internally owned instance in `stop()`.
- `apps/server/src/sqliteAdapter.ts`
- Add explicit guard/error message when `node:sqlite` is unavailable.
### Group C: Client consistency and race prevention
- `apps/web/src/appSettings.ts`
- Add hydration/update sequence guard so hydration cannot overwrite optimistic writes.
- `apps/web/src/store.ts`
- Harden `thread.upsert` normalization to avoid crashes on missing terminal arrays (safe defaults before terminal normalization).
- `apps/web/src/components/Sidebar.tsx`
- Fix no-API thread creation path (do not call API-gated `handleNewThread` in browser-only fallback).
- `apps/web/src/components/BranchToolbar.tsx` + `apps/web/src/components/ChatView.tsx`
- Remove duplicate `updateBranch` network write path.
### Group D: Test reliability and cleanup
- `apps/server/src/persistenceService.test.ts`
- Make timestamp helper deterministic.
- Ensure service instances are always closed via `try/finally`.
- Replace always-true catch-up sequence assertion with monotonic/defined sequence checks.
- Update/add tests for Group A/B/C behavior changes.
## Workstream 3: Review Thread Triage/Closure Strategy [COMPLETE]
### Threads closed by deletion (Workstream 1)
- Legacy renderer import flow/race concerns in root route.
- Legacy import schemas, WS method concerns, and related service import concerns.
- Any CR comments rooted in the removed migration path.
### Threads closed by fixes (Workstream 2)
- Transaction semantics, pagination correctness, branch update duplication, no-API thread creation, etc.
### Threads closed with rationale (no change)
- Keep concise “not adopted” notes only where behavior is intentional and safe.
### Disposition Matrix (Ready for PR Thread Closure)
- `superseded-by-deletion`
- Legacy renderer-state import path comments (root-route import race, legacy import RPC/schema/service concerns).
- Rationale: Workstream 1 deleted the entire runtime migration pathway and removed related contracts/callers/handlers.
- `fixed`
- `listMessages` pagination progress now advances by fetched row count.
- `withTransaction` post-commit event emission no longer surfaces listener exceptions as write failures.
- `checkpointTurnCount = 0` is preserved in summary merge logic.
- Out-of-order `item/started` no longer clobbers accumulated assistant text.
- Provider checkpoint revert no longer returns failure when persistence follow-up write fails.
- Generic `threads.update` is explicitly unsupported; canonical path is `threads.updateTerminalState`.
- `wsServer.stop()` now closes persistence only when internally owned.
- `StateDb` closes DB on migration failure and preserves original transaction error if rollback also fails.
- `sqliteAdapter` now emits explicit guidance when `node:sqlite` is unavailable.
- `appSettings` hydration now guards against overwriting optimistic writes.
- `thread.upsert` reducer path now safely defaults missing terminal arrays.
- Sidebar no-API fallback now creates a local thread.
- Duplicate `updateBranch` write path removed from `BranchToolbar`; canonical write remains in `ChatView` effect.
- `declined-with-rationale`
- None in this workstream. No remaining high/medium CR findings required intentional non-adoption.
### Evidence Anchors for Thread Replies
- Server behavior fixes:
- `apps/server/src/persistenceService.ts`
- `apps/server/src/wsServer.ts`
- `apps/server/src/stateDb.ts`
- `apps/server/src/sqliteAdapter.ts`
- Web/contracts fixes:
- `packages/contracts/src/ws.ts`
- `packages/contracts/src/ipc.ts`
- `apps/web/src/wsNativeApi.ts`
- `apps/web/src/appSettings.ts`
- `apps/web/src/store.ts`
- `apps/web/src/components/Sidebar.tsx`
- `apps/web/src/components/BranchToolbar.tsx`
- Regression coverage:
- `apps/server/src/persistenceService.test.ts`
- `apps/server/src/wsServer.test.ts`
- `apps/server/src/stateDb.test.ts`
- `apps/server/src/sqliteAdapter.test.ts`
- `apps/web/src/appSettings.test.ts`
- `apps/web/src/store.test.ts`
- `apps/web/src/components/Sidebar.logic.test.ts`
- `packages/contracts/src/ws.test.ts`
### Suggested Reply Templates
- `superseded-by-deletion`: "Superseded by Workstream 1 removal of legacy renderer-state migration path; related RPC/schema/client callsites were deleted."
- `fixed`: "Fixed in Workstream 2 with tests added; see referenced file(s) and regression coverage."
- `declined-with-rationale`: "Intentional behavior retained; safe by design and documented here with rationale and test coverage."
## Execution Order
1. Contracts + protocol deletions (Workstream 1.1).
2. Server deletion and compilation fixes (Workstream 1.2).
3. Web deletion and compilation fixes (Workstream 1.3).
4. Dead-code sweep and test pruning (Workstream 1.4).
5. Group A fixes + tests.
6. Group B fixes + tests.
7. Group C fixes + tests.
8. Group D test hardening.
9. Final lint/test pass; prepare review-thread response mapping.
## Validation Matrix
- Lint: `bun run lint`.
- Contracts tests: `bun --cwd packages/contracts test` (or workspace equivalent).
- Server tests (required for backend changes): `bun --cwd apps/server test`.
- Web tests: `bun --cwd apps/web test`.
- Grep-based dead-code validation for removed migration symbols.
## Done Criteria
1. No runtime path exists to import legacy renderer localStorage into server state.
2. No dead symbols remain for removed migration APIs.
3. CR high/medium validity issues in retained code are fixed or explicitly dispositioned.
4. Backend tests and project lint pass.
5. PR discussion can be answered thread-by-thread with: fixed / superseded / intentionally declined.
+1
View File
@@ -11,3 +11,4 @@
9. `09-event-state-test-expansion.md`
10. `10-unify-process-session-abstraction.md`
11. `11-centralized-sqlite-persistence-revamp.md`
12. `12-remove-legacy-localstorage-migrations-and-cr-hardening.md`
+14
View File
@@ -56,6 +56,9 @@ T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
bun run build
bun run start
# Build a shareable macOS .dmg (arm64 by default)
bun run dist:desktop:dmg
# Or from any project directory after publishing:
npx t3
```
@@ -69,6 +72,17 @@ npx t3
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
### Desktop `.dmg` packaging notes
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
### Running multiple dev instances
+3 -1
View File
@@ -2,6 +2,8 @@
## Small things
- [ ] Plan mode
- [ ] Submitting new messages should scroll to bottom
- [ ] 1 click copy in codeblocks
- [x] Pasting/adding images to submit with prompts
- [ ] Only show last 10 threads for a given project
@@ -12,7 +14,7 @@
- [x] "Response" bar should ONLY appear on work completed
- [x] "Response" bar should ONLY appear above the FINAL message in a series
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
- [ ] Insta focus input on new thread creation
- [x] Insta focus input on new thread creation
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
- [x] Making new thread should auto-focus input box
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
+1
View File
@@ -1 +1,2 @@
dist-electron/
.electron-runtime/
+3 -2
View File
@@ -2,19 +2,20 @@
"name": "@t3tools/desktop",
"version": "0.0.0",
"private": true,
"productName": "T3 Code (Alpha)",
"main": "dist-electron/main.js",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "tsdown",
"start": "electron dist-electron/main.js",
"start": "bun run scripts/start-electron.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"electron": "33.4.11"
"electron": "40.6.0"
},
"devDependencies": {
"@types/node": "^22.10.2",
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 313 KiB

+48 -6
View File
@@ -1,7 +1,10 @@
import { spawn } from "node:child_process";
import { spawnSync } from "node:child_process";
import electronmon from "electronmon";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
const devServerUrl = `http://localhost:${port}`;
@@ -14,18 +17,57 @@ await waitOn({
],
});
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(command, ["dist-electron/main.js"], {
stdio: "inherit",
const monitor = await electronmon({
cwd: desktopDir,
args: ["dist-electron/main.js"],
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
electronPath: resolveElectronPath(),
});
child.on("exit", (code) => {
process.exit(code ?? 0);
let shuttingDown = false;
function killChildTree(signal) {
if (process.platform === "win32") {
return;
}
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
}
async function shutdown(exitCode) {
if (shuttingDown) return;
shuttingDown = true;
try {
await Promise.race([
monitor.destroy(),
new Promise((resolve) => setTimeout(resolve, 1_500)),
]);
} catch {
// Best effort only; fallback process kill below handles stubborn children.
}
killChildTree("TERM");
setTimeout(() => {
killChildTree("KILL");
}, 1_200).unref();
process.exit(exitCode);
}
process.once("SIGINT", () => {
void shutdown(130);
});
process.once("SIGTERM", () => {
void shutdown(143);
});
process.once("SIGHUP", () => {
void shutdown(129);
});
+173
View File
@@ -0,0 +1,173 @@
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
import { spawnSync } from "node:child_process";
import {
copyFileSync,
cpSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_BUNDLE_ID = "com.t3tools.t3code";
const LAUNCHER_VERSION = 1;
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync(
"plutil",
["-replace", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
if (replaceResult.status === 0) {
return;
}
const insertResult = spawnSync(
"plutil",
["-insert", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
if (insertResult.status === 0) {
return;
}
const details = [replaceResult.stderr, insertResult.stderr]
.filter(Boolean)
.join("\n");
throw new Error(
`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim(),
);
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
const resourcesDir = join(appBundlePath, "Contents", "Resources");
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
if (!existsSync(frameworksDir)) {
return;
}
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
continue;
}
if (!entry.name.startsWith("Electron Helper")) {
continue;
}
const helperPlistPath = join(
frameworksDir,
entry.name,
"Contents",
"Info.plist",
);
if (!existsSync(helperPlistPath)) {
continue;
}
const suffix = entry.name
.replace("Electron Helper", "")
.replace(".app", "")
.trim();
const helperName = suffix
? `${APP_DISPLAY_NAME} Helper ${suffix}`
: `${APP_DISPLAY_NAME} Helper`;
const helperIdSuffix = suffix
.replace(/[()]/g, "")
.trim()
.toLowerCase()
.replace(/\s+/g, "-");
const helperBundleId = helperIdSuffix
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
: `${APP_BUNDLE_ID}.helper`;
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
setPlistString(helperPlistPath, "CFBundleName", helperName);
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
}
}
function readJson(path) {
try {
return JSON.parse(readFileSync(path, "utf8"));
} catch {
return null;
}
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = resolve(electronBinaryPath, "../../..");
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(
targetAppBundlePath,
"Contents",
"MacOS",
"Electron",
);
const iconPath = join(desktopDir, "resources", "icon.icns");
const metadataPath = join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
const expectedMetadata = {
launcherVersion: LAUNCHER_VERSION,
sourceAppBundlePath,
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: statSync(iconPath).mtimeMs,
};
const currentMetadata = readJson(metadataPath);
if (
existsSync(targetBinaryPath) &&
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
return targetBinaryPath;
}
rmSync(targetAppBundlePath, { recursive: true, force: true });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
return targetBinaryPath;
}
export function resolveElectronPath() {
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
if (process.platform !== "darwin") {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
+20
View File
@@ -0,0 +1,20 @@
import { spawn } from "node:child_process";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
});
child.on("exit", (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 0);
});
+327 -20
View File
@@ -5,7 +5,16 @@ import net from "node:net";
import os from "node:os";
import path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
import {
app,
BrowserWindow,
dialog,
ipcMain,
Menu,
type MenuItemConstructorOptions,
protocol,
shell,
} from "electron";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
@@ -16,11 +25,13 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const ROOT_DIR = path.resolve(__dirname, "../../..");
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess | null = null;
@@ -30,6 +41,235 @@ let backendWsUrl = "";
let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
let desktopProtocolRegistered = false;
protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
function resolveAppRoot(): string {
if (!app.isPackaged) {
return ROOT_DIR;
}
return app.getAppPath();
}
function resolveBackendEntry(): string {
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
}
function resolveBackendCwd(): string {
if (!app.isPackaged) {
return resolveAppRoot();
}
return os.homedir();
}
function resolveDesktopStaticDir(): string | null {
const appRoot = resolveAppRoot();
const candidates = [
path.join(appRoot, "apps/server/dist/client"),
path.join(appRoot, "apps/web/dist"),
];
for (const candidate of candidates) {
if (fs.existsSync(path.join(candidate, "index.html"))) {
return candidate;
}
}
return null;
}
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
if (normalizedPath.includes("..")) {
return path.join(staticRoot, "index.html");
}
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
const resolvedPath = path.join(staticRoot, requestedPath);
if (path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = path.join(resolvedPath, "index.html");
if (fs.existsSync(nestedIndex)) {
return nestedIndex;
}
return path.join(staticRoot, "index.html");
}
function isStaticAssetRequest(requestUrl: string): boolean {
try {
const url = new URL(requestUrl);
return path.extname(url.pathname).length > 0;
} catch {
return false;
}
}
function registerDesktopProtocol(): void {
if (isDevelopment || desktopProtocolRegistered) return;
const staticRoot = resolveDesktopStaticDir();
if (!staticRoot) {
throw new Error("Desktop static bundle missing. Build apps/server (with bundled client) first.");
}
const staticRootResolved = path.resolve(staticRoot);
const staticRootPrefix = `${staticRootResolved}${path.sep}`;
const fallbackIndex = path.join(staticRootResolved, "index.html");
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
try {
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url);
if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
if (isAssetRequest) {
callback({ error: -6 });
return;
}
callback({ path: fallbackIndex });
return;
}
callback({ path: resolvedCandidate });
} catch {
callback({ path: fallbackIndex });
}
});
desktopProtocolRegistered = true;
}
function dispatchMenuAction(action: string): void {
const existingWindow = BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
const targetWindow = existingWindow ?? createWindow();
if (!existingWindow) {
mainWindow = targetWindow;
}
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
if (!targetWindow.isVisible()) {
targetWindow.show();
}
targetWindow.focus();
};
if (targetWindow.webContents.isLoadingMainFrame()) {
targetWindow.webContents.once("did-finish-load", send);
return;
}
send();
}
function configureApplicationMenu(): void {
const template: MenuItemConstructorOptions[] = [];
if (process.platform === "darwin") {
template.push({
label: app.name,
submenu: [
{ role: "about" },
{
label: "Settings...",
accelerator: "CmdOrCtrl+,",
click: () => dispatchMenuAction("open-settings"),
},
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
});
}
template.push(
{
label: "File",
submenu: [
...(process.platform === "darwin"
? []
: [
{
label: "Settings...",
accelerator: "CmdOrCtrl+,",
click: () => dispatchMenuAction("open-settings"),
},
{ type: "separator" as const },
]),
{ role: process.platform === "darwin" ? "close" : "quit" },
],
},
{ role: "editMenu" },
{ role: "viewMenu" },
{ role: "windowMenu" },
);
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
function resolveResourcePath(fileName: string): string | null {
const candidates = [
path.join(__dirname, "../resources", fileName),
path.join(process.resourcesPath, "resources", fileName),
path.join(process.resourcesPath, fileName),
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
return candidate;
}
}
return null;
}
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
return resolveResourcePath(`icon.${ext}`);
}
function configureAppIdentity(): void {
app.setName(APP_DISPLAY_NAME);
app.setAboutPanelOptions({
applicationName: APP_DISPLAY_NAME,
});
if (process.platform === "win32") {
app.setAppUserModelId(APP_USER_MODEL_ID);
}
if (process.platform === "darwin" && app.dock) {
const iconPath = resolveIconPath("png");
if (iconPath) {
app.dock.setIcon(iconPath);
}
}
}
async function reserveLoopbackPort(): Promise<number> {
return new Promise((resolve, reject) => {
@@ -60,6 +300,42 @@ function backendEnv(): NodeJS.ProcessEnv {
};
}
function resolveBackendLaunch(backendEntry: string): {
command: string;
args: string[];
env: NodeJS.ProcessEnv;
} {
const runtimeOverride = process.env.T3CODE_BACKEND_RUNTIME?.trim();
if (runtimeOverride && runtimeOverride.length > 0) {
if (runtimeOverride === "electron-node") {
return {
command: process.execPath,
args: [backendEntry],
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
};
}
return {
command: runtimeOverride,
args: [backendEntry],
env: backendEnv(),
};
}
// Default to Node-mode execution under Electron in both dev and production.
// This matches main and avoids runtime-specific PTY behavior differences.
return {
command: process.execPath,
args: [backendEntry],
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
};
}
function scheduleBackendRestart(reason: string): void {
if (isQuitting || restartTimer) return;
@@ -76,19 +352,16 @@ function scheduleBackendRestart(reason: string): void {
function startBackend(): void {
if (isQuitting || backendProcess) return;
if (!fs.existsSync(BACKEND_ENTRY)) {
scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`);
const backendEntry = resolveBackendEntry();
if (!fs.existsSync(backendEntry)) {
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
return;
}
const child = spawn(process.execPath, [BACKEND_ENTRY], {
cwd: ROOT_DIR,
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
const launch = resolveBackendLaunch(backendEntry);
const child = spawn(launch.command, launch.args, {
cwd: resolveBackendCwd(),
env: launch.env,
stdio: "inherit",
});
backendProcess = child;
@@ -124,10 +397,10 @@ function stopBackend(): void {
backendProcess = null;
if (!child) return;
if (!child.killed) {
if (child.exitCode === null && child.signalCode === null) {
child.kill("SIGTERM");
setTimeout(() => {
if (!child.killed) {
if (child.exitCode === null && child.signalCode === null) {
child.kill("SIGKILL");
}
}, 2_000).unref();
@@ -204,6 +477,13 @@ function registerIpcHandlers(): void {
});
}
function getIconOption(): { icon: string } | Record<string, never> {
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
const ext = process.platform === "win32" ? "ico" : "png";
const iconPath = resolveIconPath(ext);
return iconPath ? { icon: iconPath } : {};
}
function createWindow(): BrowserWindow {
const window = new BrowserWindow({
width: 1100,
@@ -212,6 +492,8 @@ function createWindow(): BrowserWindow {
minHeight: 620,
show: false,
autoHideMenuBar: true,
...getIconOption(),
title: APP_DISPLAY_NAME,
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 16, y: 18 },
webPreferences: {
@@ -223,6 +505,13 @@ function createWindow(): BrowserWindow {
});
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
window.on("page-title-updated", (event) => {
event.preventDefault();
window.setTitle(APP_DISPLAY_NAME);
});
window.webContents.on("did-finish-load", () => {
window.setTitle(APP_DISPLAY_NAME);
});
window.once("ready-to-show", () => {
window.show();
});
@@ -231,10 +520,7 @@ function createWindow(): BrowserWindow {
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
window.webContents.openDevTools({ mode: "detach" });
} else {
if (!fs.existsSync(WEB_ENTRY)) {
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
}
void window.loadFile(WEB_ENTRY);
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
}
window.on("closed", () => {
@@ -246,6 +532,8 @@ function createWindow(): BrowserWindow {
return window;
}
configureAppIdentity();
async function bootstrap(): Promise<void> {
backendPort = await reserveLoopbackPort();
backendAuthToken = randomBytes(24).toString("hex");
@@ -263,6 +551,9 @@ app.on("before-quit", () => {
});
app.whenReady().then(() => {
configureAppIdentity();
configureApplicationMenu();
registerDesktopProtocol();
void bootstrap();
app.on("activate", () => {
@@ -277,3 +568,19 @@ app.on("window-all-closed", () => {
app.quit();
}
});
if (process.platform !== "win32") {
process.on("SIGINT", () => {
if (isQuitting) return;
isQuitting = true;
stopBackend();
app.quit();
});
process.on("SIGTERM", () => {
if (isQuitting) return;
isQuitting = true;
stopBackend();
app.quit();
});
}
+12
View File
@@ -4,6 +4,7 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
@@ -13,4 +14,15 @@ contextBridge.exposeInMainWorld("desktopBridge", {
showContextMenu: (items: { id: string; label: string }[]) =>
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
onMenuAction: (listener: (action: string) => void) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
listener(action);
};
ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
};
},
});
+7 -2
View File
@@ -163,9 +163,14 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
updatedAt: now,
};
const child = spawn("codex", ["app-server"], {
const codexBinaryPath = input.codexBinaryPath?.trim() || "codex";
const codexHomePath = input.codexHomePath?.trim();
const child = spawn(codexBinaryPath, ["app-server"], {
cwd: resolvedCwd,
env: process.env,
env: {
...process.env,
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
});
const output = readline.createInterface({ input: child.stdout });
+379 -169
View File
@@ -8,6 +8,7 @@ import type { ProviderEvent } from "@t3tools/contracts";
import { PersistenceService } from "./persistenceService";
const tempDirs: string[] = [];
const ISO_BASE_MS = Date.parse("2026-02-19T00:00:00.000Z");
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
@@ -16,7 +17,7 @@ function makeTempDir(prefix: string): string {
}
function iso(offsetMs = 0): string {
return new Date(Date.now() + offsetMs).toISOString();
return new Date(ISO_BASE_MS + offsetMs).toISOString();
}
afterEach(() => {
@@ -26,6 +27,49 @@ afterEach(() => {
});
describe("PersistenceService", () => {
it("stores app settings in metadata with partial updates", () => {
const stateDir = makeTempDir("t3code-persistence-settings-state-");
const dbPath = path.join(stateDir, "state.sqlite");
const service = new PersistenceService({ dbPath });
try {
expect(service.getAppSettings()).toEqual({
codexBinaryPath: "",
codexHomePath: "",
});
expect(
service.updateAppSettings({
codexBinaryPath: " /opt/codex/bin/codex ",
}),
).toEqual({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "",
});
expect(
service.updateAppSettings({
codexHomePath: " /Users/theo/.codex ",
}),
).toEqual({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "/Users/theo/.codex",
});
} finally {
service.close();
}
const reopened = new PersistenceService({ dbPath });
try {
expect(reopened.getAppSettings()).toEqual({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "/Users/theo/.codex",
});
} finally {
reopened.close();
}
});
it("persists projects/threads/messages and serves bootstrap + catch-up", () => {
const stateDir = makeTempDir("t3code-persistence-state-");
const projectDir = makeTempDir("t3code-persistence-project-");
@@ -33,106 +77,111 @@ describe("PersistenceService", () => {
dbPath: path.join(stateDir, "state.sqlite"),
});
const addedProject = service.addProject({ cwd: projectDir });
expect(addedProject.created).toBe(true);
try {
const addedProject = service.addProject({ cwd: projectDir });
expect(addedProject.created).toBe(true);
const createdThread = service.createThread({
projectId: addedProject.project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
const createdThread = service.createThread({
projectId: addedProject.project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-1", createdThread.id, "runtime-thread-1");
service.persistUserMessageForTurn({
sessionId: "sess-1",
clientMessageId: "msg-user-1",
clientMessageText: "hello world",
input: "hello world",
attachments: [],
});
service.bindSessionToThread("sess-1", createdThread.id, "runtime-thread-1");
service.persistUserMessageForTurn({
sessionId: "sess-1",
clientMessageId: "msg-user-1",
clientMessageText: "hello world",
input: "hello world",
attachments: [],
});
const baseEvent: Omit<ProviderEvent, "id" | "createdAt" | "method" | "payload"> = {
kind: "notification",
provider: "codex",
sessionId: "sess-1",
};
const baseEvent: Omit<ProviderEvent, "id" | "createdAt" | "method" | "payload"> = {
kind: "notification",
provider: "codex",
sessionId: "sess-1",
};
service.ingestProviderEvent({
...baseEvent,
id: "evt-1",
createdAt: iso(10),
method: "item/started",
payload: {
item: {
type: "agentMessage",
id: "assistant-msg-1",
text: "",
service.ingestProviderEvent({
...baseEvent,
id: "evt-1",
createdAt: iso(10),
method: "item/started",
payload: {
item: {
type: "agentMessage",
id: "assistant-msg-1",
text: "",
},
},
},
});
});
service.ingestProviderEvent({
...baseEvent,
id: "evt-2",
createdAt: iso(20),
method: "item/agentMessage/delta",
itemId: "assistant-msg-1",
textDelta: "hi",
payload: {
service.ingestProviderEvent({
...baseEvent,
id: "evt-2",
createdAt: iso(20),
method: "item/agentMessage/delta",
itemId: "assistant-msg-1",
delta: "hi",
},
});
service.ingestProviderEvent({
...baseEvent,
id: "evt-3",
createdAt: iso(30),
method: "item/completed",
payload: {
item: {
type: "agentMessage",
id: "assistant-msg-1",
text: "hi there",
textDelta: "hi",
payload: {
itemId: "assistant-msg-1",
delta: "hi",
},
},
});
});
service.ingestProviderEvent({
...baseEvent,
id: "evt-4",
createdAt: iso(40),
method: "turn/completed",
turnId: "turn-1",
payload: {
turn: {
id: "turn-1",
status: "completed",
service.ingestProviderEvent({
...baseEvent,
id: "evt-3",
createdAt: iso(30),
method: "item/completed",
payload: {
item: {
type: "agentMessage",
id: "assistant-msg-1",
text: "hi there",
},
},
},
});
});
const snapshot = service.loadSnapshot();
expect(snapshot.projects).toHaveLength(1);
expect(snapshot.threads).toHaveLength(1);
const thread = snapshot.threads[0];
expect(thread?.messages.map((message) => message.id)).toEqual([
"msg-user-1",
"assistant-msg-1",
]);
expect(thread?.messages[1]?.text).toBe("hi there");
expect(thread?.turnDiffSummaries[0]?.turnId).toBe("turn-1");
service.ingestProviderEvent({
...baseEvent,
id: "evt-4",
createdAt: iso(40),
method: "turn/completed",
turnId: "turn-1",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
});
const catchUp = service.catchUp({ afterSeq: 0 });
expect(catchUp.events.length).toBeGreaterThan(0);
expect(catchUp.events.every((event, index, events) => event.seq === events[index]?.seq)).toBe(
true,
);
expect(catchUp.events.some((event) => event.eventType === "project.upsert")).toBe(true);
expect(catchUp.events.some((event) => event.eventType === "thread.upsert")).toBe(true);
expect(catchUp.events.some((event) => event.eventType === "message.upsert")).toBe(true);
const snapshot = service.loadSnapshot();
expect(snapshot.projects).toHaveLength(1);
expect(snapshot.threads).toHaveLength(1);
const thread = snapshot.threads[0];
expect(thread?.messages.map((message) => message.id)).toEqual([
"msg-user-1",
"assistant-msg-1",
]);
expect(thread?.messages[1]?.text).toBe("hi there");
expect(thread?.turnDiffSummaries[0]?.turnId).toBe("turn-1");
expect(thread?.turnDiffSummaries[0]?.assistantMessageId).toBe("assistant-msg-1");
service.close();
const catchUp = service.catchUp({ afterSeq: 0 });
expect(catchUp.events.length).toBeGreaterThan(0);
const sequences = catchUp.events.map((event) => event.seq);
expect(sequences.every((sequence) => Number.isInteger(sequence))).toBe(true);
for (let index = 1; index < sequences.length; index += 1) {
expect(sequences[index]).toBeGreaterThan(sequences[index - 1] ?? Number.NEGATIVE_INFINITY);
}
expect(catchUp.events.some((event) => event.eventType === "project.upsert")).toBe(true);
expect(catchUp.events.some((event) => event.eventType === "thread.upsert")).toBe(true);
expect(catchUp.events.some((event) => event.eventType === "message.upsert")).toBe(true);
} finally {
service.close();
}
});
it("stores turn diff summaries parsed from checkpoint diffs", () => {
@@ -142,98 +191,259 @@ describe("PersistenceService", () => {
dbPath: path.join(stateDir, "state.sqlite"),
});
const project = service.addProject({ cwd: projectDir }).project;
const thread = service.createThread({
projectId: project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-1", thread.id, "runtime-thread-1");
try {
const project = service.addProject({ cwd: projectDir }).project;
const thread = service.createThread({
projectId: project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-1", thread.id, "runtime-thread-1");
service.persistTurnDiffSummaryFromCheckpoint({
sessionId: "sess-1",
runtimeThreadId: "runtime-thread-1",
turnId: "turn-1",
checkpointTurnCount: 1,
completedAt: "2026-02-19T00:00:00.000Z",
status: "completed",
diff: [
"diff --git a/src/app.ts b/src/app.ts",
"index 1111111..2222222 100644",
"--- a/src/app.ts",
"+++ b/src/app.ts",
"@@ -1,1 +1,2 @@",
"-console.log('a')",
"+console.log('b')",
"+console.log('c')",
].join("\n"),
});
service.persistTurnDiffSummaryFromCheckpoint({
sessionId: "sess-1",
runtimeThreadId: "runtime-thread-1",
turnId: "turn-1",
checkpointTurnCount: 1,
completedAt: "2026-02-19T00:00:00.000Z",
status: "completed",
diff: [
"diff --git a/src/app.ts b/src/app.ts",
"index 1111111..2222222 100644",
"--- a/src/app.ts",
"+++ b/src/app.ts",
"@@ -1,1 +1,2 @@",
"-console.log('a')",
"+console.log('b')",
"+console.log('c')",
].join("\n"),
});
const snapshot = service.loadSnapshot();
const summary = snapshot.threads[0]?.turnDiffSummaries[0];
expect(summary?.turnId).toBe("turn-1");
expect(summary?.checkpointTurnCount).toBe(1);
expect(summary?.files[0]?.path).toBe("src/app.ts");
expect(summary?.files[0]?.additions).toBe(2);
expect(summary?.files[0]?.deletions).toBe(1);
service.ingestProviderEvent({
id: "evt-agent-msg-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-19T00:00:01.000Z",
method: "item/completed",
turnId: "turn-1",
itemId: "assistant-msg-1",
payload: {
item: {
type: "agentMessage",
id: "assistant-msg-1",
text: "done",
},
threadId: "runtime-thread-1",
turnId: "turn-1",
},
});
service.close();
const snapshot = service.loadSnapshot();
const summary = snapshot.threads[0]?.turnDiffSummaries[0];
expect(summary?.turnId).toBe("turn-1");
expect(summary?.checkpointTurnCount).toBe(1);
expect(summary?.assistantMessageId).toBe("assistant-msg-1");
expect(summary?.files[0]?.path).toBe("src/app.ts");
expect(summary?.files[0]?.additions).toBe(2);
expect(summary?.files[0]?.deletions).toBe(1);
} finally {
service.close();
}
});
it("imports legacy renderer state once and reports idempotent re-imports", () => {
const stateDir = makeTempDir("t3code-persistence-legacy-state-");
const projectDir = makeTempDir("t3code-persistence-legacy-project-");
it("advances listMessages.nextOffset by fetched row count even when rows fail to parse", () => {
const stateDir = makeTempDir("t3code-persistence-list-messages-state-");
const projectDir = makeTempDir("t3code-persistence-list-messages-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
const firstImport = service.importLegacyRendererState({
projects: [
{
id: "project-legacy-1",
name: "legacy",
cwd: projectDir,
scripts: [],
},
],
threads: [
{
id: "thread-legacy-1",
projectId: "project-legacy-1",
title: "Imported",
model: "gpt-5.3-codex",
createdAt: "2026-02-19T00:00:00.000Z",
messages: [
{
id: "msg-legacy-1",
role: "user",
text: "legacy message",
createdAt: "2026-02-19T00:00:01.000Z",
streaming: false,
},
],
},
],
});
expect(firstImport).toEqual({
imported: true,
alreadyImported: false,
});
try {
const project = service.addProject({ cwd: projectDir }).project;
const thread = service.createThread({
projectId: project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-1", thread.id, "runtime-thread-1");
const secondImport = service.importLegacyRendererState({
projects: [],
threads: [],
});
expect(secondImport).toEqual({
imported: false,
alreadyImported: true,
});
service.persistUserMessageForTurn({
sessionId: "sess-1",
clientMessageId: "msg-1",
clientMessageText: "first",
input: "first",
attachments: [],
});
service.persistUserMessageForTurn({
sessionId: "sess-1",
clientMessageId: "msg-2",
clientMessageText: "second",
input: "second",
attachments: [],
});
const snapshot = service.loadSnapshot();
expect(snapshot.projects).toHaveLength(1);
expect(snapshot.threads).toHaveLength(1);
expect(snapshot.threads[0]?.messages).toHaveLength(1);
const db = (
service as unknown as {
db: { prepare: (sql: string) => { run: (...params: unknown[]) => unknown } };
}
).db;
db.prepare("UPDATE documents SET data_json = ? WHERE id = ?;").run(
"{bad-json",
`message:${thread.id}:msg-1`,
);
service.close();
const firstPage = service.listMessages({
threadId: thread.id,
limit: 1,
offset: 0,
});
expect(firstPage.messages).toEqual([]);
expect(firstPage.total).toBe(2);
expect(firstPage.nextOffset).toBe(1);
const secondPage = service.listMessages({
threadId: thread.id,
limit: 1,
offset: firstPage.nextOffset ?? 0,
});
expect(secondPage.messages.map((message) => message.id)).toEqual(["msg-2"]);
expect(secondPage.nextOffset).toBeNull();
} finally {
service.close();
}
});
it("does not throw when state event listeners fail after commit", () => {
const stateDir = makeTempDir("t3code-persistence-state-events-");
const projectDir = makeTempDir("t3code-persistence-state-events-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
try {
service.on("stateEvent", () => {
throw new Error("listener failed");
});
const result = service.addProject({ cwd: projectDir });
expect(result.created).toBe(true);
expect(service.listProjects()).toHaveLength(1);
} finally {
service.close();
}
});
it("preserves checkpointTurnCount=0 when merging turn summaries", () => {
const stateDir = makeTempDir("t3code-persistence-checkpoint-zero-state-");
const projectDir = makeTempDir("t3code-persistence-checkpoint-zero-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
try {
const project = service.addProject({ cwd: projectDir }).project;
const thread = service.createThread({
projectId: project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-1", thread.id, "runtime-thread-1");
service.persistTurnDiffSummaryFromCheckpoint({
sessionId: "sess-1",
runtimeThreadId: "runtime-thread-1",
turnId: "turn-1",
checkpointTurnCount: 0,
completedAt: "2026-02-19T00:00:00.000Z",
diff: "",
});
service.ingestProviderEvent({
id: "evt-assistant-completed",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-19T00:00:01.000Z",
method: "item/completed",
turnId: "turn-1",
payload: {
item: {
type: "agentMessage",
id: "assistant-msg-1",
text: "done",
},
},
});
const snapshot = service.loadSnapshot();
const summary = snapshot.threads[0]?.turnDiffSummaries.find(
(entry) => entry.turnId === "turn-1",
);
expect(summary?.checkpointTurnCount).toBe(0);
expect(summary?.assistantMessageId).toBe("assistant-msg-1");
} finally {
service.close();
}
});
it("does not let out-of-order item/started overwrite accumulated assistant text", () => {
const stateDir = makeTempDir("t3code-persistence-item-order-state-");
const projectDir = makeTempDir("t3code-persistence-item-order-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
try {
const project = service.addProject({ cwd: projectDir }).project;
const thread = service.createThread({
projectId: project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-1", thread.id, "runtime-thread-1");
service.ingestProviderEvent({
id: "evt-delta",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-19T00:00:02.000Z",
method: "item/agentMessage/delta",
itemId: "assistant-msg-1",
textDelta: "hello",
payload: {
itemId: "assistant-msg-1",
delta: "hello",
},
});
service.ingestProviderEvent({
id: "evt-started-late",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-19T00:00:03.000Z",
method: "item/started",
payload: {
item: {
type: "agentMessage",
id: "assistant-msg-1",
text: "",
},
},
});
const messages = service.listMessages({
threadId: thread.id,
limit: 10,
offset: 0,
}).messages;
const assistantMessage = messages.find((message) => message.id === "assistant-msg-1");
expect(assistantMessage?.text).toBe("hello");
} finally {
service.close();
}
});
});
+208 -141
View File
@@ -6,6 +6,10 @@ import path from "node:path";
import { parsePatchFiles } from "@pierre/diffs";
import {
DEFAULT_MODEL,
type AppSettings,
type AppSettingsUpdateInput,
appSettingsSchema,
appSettingsUpdateInputSchema,
type ProjectAddInput,
type ProjectAddResult,
type ProjectListResult,
@@ -19,8 +23,6 @@ import {
type StateCatchUpInput,
type StateCatchUpResult,
type StateEvent,
type StateImportLegacyRendererStateInput,
type StateImportLegacyRendererStateResult,
type StateListMessagesInput,
type StateListMessagesResult,
type StateMessage,
@@ -46,7 +48,6 @@ import {
stateCatchUpInputSchema,
stateCatchUpResultSchema,
stateEventSchema,
stateImportLegacyRendererStateInputSchema,
stateListMessagesInputSchema,
stateListMessagesResultSchema,
stateMessageSchema,
@@ -66,7 +67,7 @@ import {
import { StateDb } from "./stateDb";
const METADATA_KEY_PROJECTS_JSON_IMPORTED = "migration.projects_json_imported";
const METADATA_KEY_LEGACY_RENDERER_IMPORTED = "migration.legacy_renderer_imported";
const METADATA_KEY_APP_SETTINGS = "app.settings.v1";
const MAX_TERMINAL_COUNT = 4;
const DEFAULT_TERMINAL_ID = "default";
const DEFAULT_TERMINAL_HEIGHT = 280;
@@ -166,6 +167,13 @@ function asString(value: unknown): string | undefined {
return typeof value === "string" && value.length > 0 ? value : undefined;
}
function normalizeProviderItemType(value: string | undefined): string | undefined {
if (!value) return undefined;
const normalized = value.trim();
if (normalized.length === 0) return undefined;
return normalized.replace(/[_\-\s]+/g, "").toLowerCase();
}
function parseThreadIdFromEventPayload(payload: unknown): string | null {
const record = asObject(payload);
const threadId = asString(record?.threadId) ?? asString(record?.thread_id);
@@ -450,6 +458,25 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
this.stateDb.close();
}
getAppSettings(): AppSettings {
const metadataValue = this.readMetadata(METADATA_KEY_APP_SETTINGS);
const parsed = appSettingsSchema.safeParse(metadataValue);
if (parsed.success) {
return parsed.data;
}
return appSettingsSchema.parse({});
}
updateAppSettings(raw: AppSettingsUpdateInput): AppSettings {
const patch = appSettingsUpdateInputSchema.parse(raw);
const next = appSettingsSchema.parse({
...this.getAppSettings(),
...patch,
});
this.writeMetadata(METADATA_KEY_APP_SETTINGS, next);
return next;
}
listProjects(): ProjectListResult {
const rows = this.db
.prepare(
@@ -686,7 +713,22 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
const parsedThread = this.parseJson(row.data_json, stateThreadSchema);
if (!parsedThread) continue;
const messages = this.listMessagesForThread(parsedThread.id);
const turnDiffSummaries = this.listTurnSummariesForThread(parsedThread.id);
const turnDiffSummaries = this.listTurnSummariesForThread(parsedThread.id).map((summary) => {
if (summary.assistantMessageId) {
return summary;
}
const assistantMessageId = this.findAssistantMessageIdForTurn({
turnId: summary.turnId,
runtimeThreadId: parsedThread.codexThreadId,
});
if (!assistantMessageId) {
return summary;
}
return stateTurnSummarySchema.parse({
...summary,
assistantMessageId,
});
});
threads.push({
...parsedThread,
turnDiffSummaries,
@@ -750,7 +792,7 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
}
}
const nextOffset = input.offset + messages.length;
const nextOffset = input.offset + rows.length;
return stateListMessagesResultSchema.parse({
messages,
total,
@@ -758,114 +800,6 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
});
}
importLegacyRendererState(raw: StateImportLegacyRendererStateInput): StateImportLegacyRendererStateResult {
const input = stateImportLegacyRendererStateInputSchema.parse(raw);
const alreadyImported = this.readMetadataBoolean(METADATA_KEY_LEGACY_RENDERER_IMPORTED);
if (alreadyImported) {
return { imported: false, alreadyImported: true };
}
this.stateDb.transaction(() => {
const now = nowIso();
const projectIdByCwd = new Map<string, string>();
for (const project of input.projects) {
const normalizedCwd = normalizeCwd(project.cwd);
if (!isDirectory(normalizedCwd)) {
continue;
}
if (projectIdByCwd.has(normalizedCwd)) {
continue;
}
const existing = this.findProjectByNormalizedCwd(normalizedCwd);
const nextProject = stateProjectSchema.parse({
id: existing?.id ?? project.id,
cwd: normalizedCwd,
name: project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
scripts: normalizeProjectScripts(project.scripts),
createdAt: project.createdAt ?? existing?.createdAt ?? now,
updatedAt: project.updatedAt ?? now,
});
this.upsertProjectDocument(nextProject);
projectIdByCwd.set(normalizedCwd, nextProject.id);
}
const projectIdMap = new Map<string, string>();
for (const project of input.projects) {
const normalizedCwd = normalizeCwd(project.cwd);
const mappedProjectId = projectIdByCwd.get(normalizedCwd);
if (!mappedProjectId) continue;
projectIdMap.set(project.id, mappedProjectId);
}
for (const thread of input.threads) {
const mappedProjectId = projectIdMap.get(thread.projectId);
if (!mappedProjectId) continue;
const normalizedThread = normalizeThread(
stateThreadSchema.parse({
id: thread.id,
codexThreadId: thread.codexThreadId ?? null,
projectId: mappedProjectId,
title: thread.title,
model: thread.model,
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
terminalIds: thread.terminalIds,
activeTerminalId: thread.activeTerminalId,
terminalGroups: thread.terminalGroups,
activeTerminalGroupId:
thread.activeTerminalGroupId ?? fallbackGroupId(thread.activeTerminalId),
createdAt: thread.createdAt,
updatedAt: thread.lastVisitedAt ?? thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: thread.branch ?? null,
worktreePath: thread.worktreePath ?? null,
turnDiffSummaries: [],
}),
);
this.upsertThreadDocument(normalizedThread);
const sortedMessages = [...thread.messages].toSorted((a, b) =>
a.createdAt.localeCompare(b.createdAt),
);
for (const message of sortedMessages) {
const messageRecord = stateMessageSchema.parse({
id: message.id,
threadId: normalizedThread.id,
role: message.role,
text: message.text,
attachments: message.attachments,
createdAt: message.createdAt,
updatedAt: message.createdAt,
streaming: false,
});
this.upsertMessageDocument(normalizedThread, messageRecord);
}
for (const summary of thread.turnDiffSummaries) {
const parsedSummary = stateTurnSummarySchema.parse(summary);
this.upsertTurnSummaryDocument(normalizedThread, parsedSummary);
}
}
this.writeMetadata(
METADATA_KEY_LEGACY_RENDERER_IMPORTED,
{
importedAt: nowIso(),
threadCount: input.threads.length,
projectCount: input.projects.length,
},
true,
);
});
return {
imported: true,
alreadyImported: false,
};
}
bindSessionToThread(sessionId: string, threadId: string, runtimeThreadId?: string | null): void {
if (!sessionId || !threadId) return;
this.sessionThreadIds.set(sessionId, threadId);
@@ -992,17 +926,19 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
if (event.method === "item/started") {
const assistantItemId = parseAssistantItemId(event);
if (assistantItemId) {
const existing = this.getMessageById(nextThread.id, assistantItemId);
const payload = asObject(event.payload);
const item = asObject(payload?.item);
const seedText = asString(item?.text) ?? "";
const text = existing?.text.length ? existing.text : seedText;
const assistantMessage = stateMessageSchema.parse({
id: assistantItemId,
threadId: nextThread.id,
role: "assistant",
text: seedText,
createdAt: event.createdAt,
updatedAt: event.createdAt,
streaming: true,
text,
createdAt: existing?.createdAt ?? event.createdAt,
updatedAt: existing?.updatedAt ?? event.createdAt,
streaming: existing?.streaming ?? true,
});
this.upsertMessageDocument(nextThread, assistantMessage);
this.appendStateEvent(
@@ -1044,29 +980,58 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
if (event.method === "item/completed") {
const payload = asObject(event.payload);
const item = asObject(payload?.item);
if (asString(item?.type) === "agentMessage") {
if (normalizeProviderItemType(asString(item?.type)) === "agentmessage") {
const messageId = asString(item?.id);
if (messageId) {
const existing = this.getMessageById(nextThread.id, messageId);
const fullText = asString(item?.text) ?? existing?.text ?? "";
const message = stateMessageSchema.parse({
id: messageId,
threadId: nextThread.id,
role: "assistant",
text: fullText,
createdAt: existing?.createdAt ?? event.createdAt,
updatedAt: event.createdAt,
streaming: false,
});
this.upsertMessageDocument(nextThread, message);
this.appendStateEvent(
pendingEvents,
"message.upsert",
`${nextThread.id}:${message.id}`,
{ threadId: nextThread.id, message },
message.updatedAt,
);
if (!messageId) {
return;
}
const existing = this.getMessageById(nextThread.id, messageId);
const fullText = asString(item?.text) ?? existing?.text ?? "";
const message = stateMessageSchema.parse({
id: messageId,
threadId: nextThread.id,
role: "assistant",
text: fullText,
createdAt: existing?.createdAt ?? event.createdAt,
updatedAt: event.createdAt,
streaming: false,
});
this.upsertMessageDocument(nextThread, message);
this.appendStateEvent(
pendingEvents,
"message.upsert",
`${nextThread.id}:${message.id}`,
{ threadId: nextThread.id, message },
message.updatedAt,
);
const completedTurnId = parseTurnIdFromEvent(event) ?? nextThread.latestTurnId;
if (!completedTurnId) {
return;
}
const existingSummary = this.getTurnSummaryByTurnId(nextThread.id, completedTurnId);
if (!existingSummary || existingSummary.assistantMessageId === messageId) {
return;
}
const summary = this.upsertTurnSummary(
nextThread,
completedTurnId,
{
completedAt: existingSummary.completedAt,
assistantMessageId: messageId,
},
"merge",
);
this.appendStateEvent(
pendingEvents,
"turn_summary.upsert",
`${nextThread.id}:${summary.turnId}`,
{ threadId: nextThread.id, turnSummary: summary },
summary.completedAt,
);
}
}
@@ -1099,12 +1064,19 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
);
if (completedTurnId) {
const assistantMessageId =
this.findAssistantMessageIdForTurn({
sessionId: event.sessionId,
turnId: completedTurnId,
runtimeThreadId,
}) ?? this.findLatestAssistantMessageIdForThread(nextThread.id);
const summary = this.upsertTurnSummary(
nextThread,
completedTurnId,
{
completedAt: event.createdAt,
...(turnStatus ? { status: turnStatus } : {}),
...(assistantMessageId ? { assistantMessageId } : {}),
},
"merge",
);
@@ -1140,12 +1112,19 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
const turnId = parseTurnIdFromEvent(event);
const diff = asString(asObject(event.payload)?.diff);
if (turnId && diff) {
const assistantMessageId =
this.findAssistantMessageIdForTurn({
sessionId: event.sessionId,
turnId,
runtimeThreadId,
}) ?? this.findLatestAssistantMessageIdForThread(nextThread.id);
const summary = this.upsertTurnSummary(
nextThread,
turnId,
{
completedAt: event.createdAt,
files: summarizeUnifiedDiff(diff),
...(assistantMessageId ? { assistantMessageId } : {}),
},
"merge",
);
@@ -1188,6 +1167,12 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
}
this.withTransaction((pendingEvents) => {
const assistantMessageId =
this.findAssistantMessageIdForTurn({
sessionId: input.sessionId,
turnId,
runtimeThreadId: input.runtimeThreadId,
}) ?? this.findLatestAssistantMessageIdForThread(thread.id);
const summary = this.upsertTurnSummary(
thread,
turnId,
@@ -1196,6 +1181,7 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
...(input.status ? { status: input.status } : {}),
checkpointTurnCount: input.checkpointTurnCount,
files: summarizeUnifiedDiff(input.diff),
...(assistantMessageId ? { assistantMessageId } : {}),
},
"replace",
);
@@ -1378,7 +1364,11 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
const pendingEvents: StateEvent[] = [];
const result = this.stateDb.transaction(() => fn(pendingEvents));
for (const event of pendingEvents) {
this.emit("stateEvent", event);
try {
this.emit("stateEvent", event);
} catch {
// Listener failures should not break already-committed writes.
}
}
return result;
}
@@ -1491,7 +1481,7 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
...(patch.assistantMessageId ?? existing?.assistantMessageId
? { assistantMessageId: patch.assistantMessageId ?? existing?.assistantMessageId }
: {}),
...(patch.checkpointTurnCount ?? existing?.checkpointTurnCount
...(patch.checkpointTurnCount !== undefined || existing?.checkpointTurnCount !== undefined
? { checkpointTurnCount: patch.checkpointTurnCount ?? existing?.checkpointTurnCount }
: {}),
files:
@@ -1551,6 +1541,83 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
return this.parseJson(row.data_json, stateTurnSummarySchema);
}
private findAssistantMessageIdForTurn(input: {
turnId: string;
sessionId?: string;
runtimeThreadId?: string | null;
}): string | undefined {
const queries: Array<{ sql: string; params: unknown[] }> = [];
if (input.sessionId) {
queries.push({
sql: `SELECT item_id, payload_json
FROM provider_events
WHERE session_id = ? AND turn_id = ? AND method = 'item/completed'
ORDER BY created_at DESC;`,
params: [input.sessionId, input.turnId],
});
}
if (input.runtimeThreadId) {
queries.push({
sql: `SELECT item_id, payload_json
FROM provider_events
WHERE thread_id = ? AND turn_id = ? AND method = 'item/completed'
ORDER BY created_at DESC;`,
params: [input.runtimeThreadId, input.turnId],
});
}
queries.push({
sql: `SELECT item_id, payload_json
FROM provider_events
WHERE turn_id = ? AND method = 'item/completed'
ORDER BY created_at DESC;`,
params: [input.turnId],
});
for (const query of queries) {
const rows = this.db.prepare(query.sql).all(...query.params) as Array<{
item_id: string | null;
payload_json: string | null;
}>;
for (const row of rows) {
const payload = row.payload_json ? this.tryParseJson(row.payload_json) : null;
const item = asObject(asObject(payload)?.item);
const itemType = normalizeProviderItemType(asString(item?.type));
if (itemType !== "agentmessage") {
continue;
}
const messageId = asString(item?.id) ?? (row.item_id ?? undefined);
if (messageId) {
return messageId;
}
}
}
return undefined;
}
private findLatestAssistantMessageIdForThread(threadId: string): string | undefined {
const rows = this.db
.prepare(
`SELECT data_json
FROM documents
WHERE kind = 'message' AND thread_id = ?
ORDER BY sort_key DESC, updated_at DESC;`,
)
.all(threadId) as Array<{ data_json: string }>;
for (const row of rows) {
const message = this.parseJson(row.data_json, stateMessageSchema);
if (!message) {
continue;
}
if (message.role === "assistant") {
return message.id;
}
}
return undefined;
}
private listMessagesForThread(threadId: string): StateMessage[] {
const rows = this.db
.prepare(
+43
View File
@@ -0,0 +1,43 @@
import { describe, expect, it, vi } from "vitest";
import { openSqliteDatabase } from "./sqliteAdapter";
describe("sqliteAdapter", () => {
it("opens a database and runs basic statements", () => {
const db = openSqliteDatabase(":memory:");
db.exec("CREATE TABLE sample (id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT NOT NULL);");
const insertResult = db.prepare("INSERT INTO sample (value) VALUES (?);").run("hello") as {
changes?: number;
lastInsertRowid?: number;
};
expect(insertResult.changes).toBe(1);
const row = db.prepare("SELECT value FROM sample WHERE id = ?;").get(1) as
| { value?: string }
| undefined;
expect(row?.value).toBe("hello");
const rows = db.prepare("SELECT value FROM sample ORDER BY id ASC;").all() as Array<{
value?: string;
}>;
expect(rows.map((entry) => entry.value)).toEqual(["hello"]);
db.close();
});
it("throws a helpful error when node:sqlite is unavailable", () => {
const missingModuleError = new Error("No such built-in module: node:sqlite");
(missingModuleError as NodeJS.ErrnoException).code = "ERR_UNKNOWN_BUILTIN_MODULE";
const requireFn = vi.fn((specifier: string) => {
if (specifier === "node:sqlite") {
throw missingModuleError;
}
throw new Error(`Unexpected module request: ${specifier}`);
});
expect(() => openSqliteDatabase(":memory:", requireFn as never, false)).toThrow(
"node:sqlite is unavailable",
);
});
});
+119
View File
@@ -0,0 +1,119 @@
import { createRequire } from "node:module";
import path from "node:path";
export interface SqliteStatement {
run: (...params: unknown[]) => unknown;
get: (...params: unknown[]) => unknown;
all: (...params: unknown[]) => unknown[];
}
export interface SqliteDatabase {
exec: (sql: string) => void;
prepare: (sql: string) => SqliteStatement;
close: () => void;
}
interface NodeSqliteModule {
DatabaseSync: new (filename: string) => {
exec: (sql: string) => void;
prepare: (sql: string) => SqliteStatement;
close: () => void;
};
}
interface BunSqliteStatement {
run: (...params: unknown[]) => unknown;
get: (...params: unknown[]) => unknown;
all: (...params: unknown[]) => unknown[];
}
interface BunSqliteModule {
Database: new (filename: string) => {
exec: (sql: string) => unknown;
query: (sql: string) => BunSqliteStatement;
close: () => void;
};
}
function isNodeSqliteUnavailableError(error: unknown): boolean {
if (!(error instanceof Error)) {
return false;
}
const code = (error as NodeJS.ErrnoException).code;
if (code === "ERR_UNKNOWN_BUILTIN_MODULE" || code === "MODULE_NOT_FOUND") {
return true;
}
return error.message.includes("node:sqlite");
}
function openNodeSqliteDatabase(
requireFn: ReturnType<typeof createRequire>,
dbPath: string,
): SqliteDatabase {
let nodeSqlite: NodeSqliteModule;
try {
nodeSqlite = requireFn("node:sqlite") as NodeSqliteModule;
} catch (error) {
if (isNodeSqliteUnavailableError(error)) {
throw new Error(
"node:sqlite is unavailable in this runtime. Use Node.js 22+ (or run the server with Bun).",
{ cause: error },
);
}
throw error;
}
if (typeof nodeSqlite.DatabaseSync !== "function") {
throw new Error(
"node:sqlite was loaded but DatabaseSync is missing. Upgrade Node.js or run the server with Bun.",
);
}
const db = new nodeSqlite.DatabaseSync(dbPath);
return {
exec: (sql) => {
db.exec(sql);
},
prepare: (sql) => db.prepare(sql),
close: () => {
db.close();
},
};
}
function openBunSqliteDatabase(
requireFn: ReturnType<typeof createRequire>,
dbPath: string,
): SqliteDatabase {
const bunSqlite = requireFn("bun:sqlite") as BunSqliteModule;
const db = new bunSqlite.Database(dbPath);
return {
exec: (sql) => {
db.exec(sql);
},
prepare: (sql) => {
const statement = db.query(sql);
return {
run: (...params: unknown[]) => statement.run(...params),
get: (...params: unknown[]) => statement.get(...params),
all: (...params: unknown[]) => statement.all(...params),
};
},
close: () => {
db.close();
},
};
}
export function openSqliteDatabase(
dbPath: string,
requireFn: ReturnType<typeof createRequire> = createRequire(
path.join(process.cwd(), "t3code-sqlite-adapter.cjs"),
),
runtimeIsBun = Boolean(process.versions.bun),
): SqliteDatabase {
if (runtimeIsBun) {
// Development mode runs in Bun, so use Bun's SQLite adapter
return openBunSqliteDatabase(requireFn, dbPath);
}
return openNodeSqliteDatabase(requireFn, dbPath);
}
+60 -1
View File
@@ -2,10 +2,12 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { StateDb } from "./stateDb";
import * as sqliteAdapter from "./sqliteAdapter";
import { STATE_DB_SCHEMA_VERSION } from "./stateMigrations";
import * as stateMigrations from "./stateMigrations";
const tempDirs: string[] = [];
@@ -19,6 +21,7 @@ afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
vi.restoreAllMocks();
});
describe("StateDb", () => {
@@ -43,4 +46,60 @@ describe("StateDb", () => {
stateDb.close();
});
it("closes the database when migrations fail during construction", () => {
const tempDir = makeTempDir("t3code-state-db-migration-fail-");
const dbPath = path.join(tempDir, "state.sqlite");
const close = vi.fn();
const fakeDb = {
exec: vi.fn(),
prepare: vi.fn(),
close,
};
vi.spyOn(sqliteAdapter, "openSqliteDatabase").mockReturnValue(
fakeDb as unknown as sqliteAdapter.SqliteDatabase,
);
vi.spyOn(stateMigrations, "runStateMigrations").mockImplementation(() => {
throw new Error("migration failed");
});
expect(() => new StateDb({ dbPath })).toThrow("migration failed");
expect(close).toHaveBeenCalledTimes(1);
});
it("preserves the original transaction error when rollback fails", () => {
const tempDir = makeTempDir("t3code-state-db-rollback-fail-");
const dbPath = path.join(tempDir, "state.sqlite");
const rollbackError = new Error("rollback failed");
const exec = vi.fn((sql: string) => {
if (sql === "ROLLBACK;") {
throw rollbackError;
}
});
const fakeDb = {
exec,
prepare: vi.fn(),
close: vi.fn(),
};
vi.spyOn(sqliteAdapter, "openSqliteDatabase").mockReturnValue(
fakeDb as unknown as sqliteAdapter.SqliteDatabase,
);
vi.spyOn(stateMigrations, "runStateMigrations").mockImplementation(() => {});
const stateDb = new StateDb({ dbPath });
const originalError = new Error("operation failed");
let thrown: unknown;
try {
stateDb.transaction(() => {
throw originalError;
});
} catch (error) {
thrown = error;
}
expect(thrown).toBe(originalError);
expect(exec).toHaveBeenCalledWith("ROLLBACK;");
stateDb.close();
});
});
+18 -5
View File
@@ -1,7 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import { openSqliteDatabase, type SqliteDatabase } from "./sqliteAdapter";
import { runStateMigrations } from "./stateMigrations";
export interface StateDbOptions {
@@ -10,13 +10,22 @@ export interface StateDbOptions {
export class StateDb {
readonly dbPath: string;
readonly db: DatabaseSync;
readonly db: SqliteDatabase;
constructor(options: StateDbOptions) {
this.dbPath = path.resolve(options.dbPath);
fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
this.db = new DatabaseSync(this.dbPath);
runStateMigrations(this.db);
this.db = openSqliteDatabase(this.dbPath);
try {
runStateMigrations(this.db);
} catch (error) {
try {
this.db.close();
} catch {
// Best effort close on failed initialization.
}
throw error;
}
}
close(): void {
@@ -30,7 +39,11 @@ export class StateDb {
this.db.exec("COMMIT;");
return result;
} catch (error) {
this.db.exec("ROLLBACK;");
try {
this.db.exec("ROLLBACK;");
} catch {
// Preserve the original transactional failure.
}
throw error;
}
}
+10 -6
View File
@@ -1,15 +1,15 @@
import type { DatabaseSync } from "node:sqlite";
import type { SqliteDatabase } from "./sqliteAdapter";
export const STATE_DB_SCHEMA_VERSION = 1;
export function applyStateDbPragmas(db: DatabaseSync): void {
export function applyStateDbPragmas(db: SqliteDatabase): void {
db.exec("PRAGMA journal_mode=WAL;");
db.exec("PRAGMA synchronous=FULL;");
db.exec("PRAGMA busy_timeout=5000;");
db.exec("PRAGMA foreign_keys=ON;");
}
function readUserVersion(db: DatabaseSync): number {
function readUserVersion(db: SqliteDatabase): number {
const row = db.prepare("PRAGMA user_version;").get() as { user_version?: number } | undefined;
const value = row?.user_version;
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
@@ -18,7 +18,7 @@ function readUserVersion(db: DatabaseSync): number {
return value;
}
function migrationV1(db: DatabaseSync): void {
function migrationV1(db: SqliteDatabase): void {
db.exec(`
CREATE TABLE IF NOT EXISTS documents (
id TEXT PRIMARY KEY,
@@ -74,7 +74,7 @@ function migrationV1(db: DatabaseSync): void {
`);
}
export function runStateMigrations(db: DatabaseSync): void {
export function runStateMigrations(db: SqliteDatabase): void {
applyStateDbPragmas(db);
const userVersion = readUserVersion(db);
@@ -90,7 +90,11 @@ export function runStateMigrations(db: DatabaseSync): void {
db.exec(`PRAGMA user_version=${STATE_DB_SCHEMA_VERSION};`);
db.exec("COMMIT;");
} catch (error) {
db.exec("ROLLBACK;");
try {
db.exec("ROLLBACK;");
} catch {
// Preserve the original migration error if rollback also throws.
}
throw error;
}
}
+171 -71
View File
@@ -29,6 +29,7 @@ import type {
} from "@t3tools/contracts";
import type { TerminalManager } from "./terminalManager";
import { PersistenceService } from "./persistenceService";
import { ProviderManager } from "./providerManager";
interface PendingMessages {
queue: unknown[];
@@ -235,6 +236,7 @@ describe("WebSocket Server", () => {
let server: ReturnType<typeof createServer> | null = null;
const connections: WebSocket[] = [];
const tempDirs: string[] = [];
const injectedPersistenceServices: PersistenceService[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
@@ -253,13 +255,17 @@ describe("WebSocket Server", () => {
runStackedAction: (input: { cwd: string; action: string }) => Promise<unknown>;
};
terminalManager?: TerminalManager;
persistenceService?: PersistenceService;
} = {},
): ReturnType<typeof createServer> {
const stateDir = options.stateDir ?? makeTempDir("t3code-ws-state-");
const persistenceService = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
});
const persistenceService =
options.persistenceService ??
new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
});
injectedPersistenceServices.push(persistenceService);
return createServer({
port: 0,
cwd: options.cwd ?? "/test/project",
@@ -280,6 +286,9 @@ describe("WebSocket Server", () => {
await server.stop();
}
server = null;
for (const service of injectedPersistenceServices.splice(0, injectedPersistenceServices.length)) {
service.close();
}
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
@@ -660,6 +669,42 @@ describe("WebSocket Server", () => {
expect(response.result).toEqual([]);
});
it("persists app settings through appSettings RPC methods", async () => {
const stateDir = makeTempDir("t3code-ws-app-settings-");
server = createTestServer({ cwd: "/test", stateDir });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const initial = await sendRequest(ws, WS_METHODS.appSettingsGet);
expect(initial.error).toBeUndefined();
expect(initial.result).toEqual({
codexBinaryPath: "",
codexHomePath: "",
});
const updated = await sendRequest(ws, WS_METHODS.appSettingsUpdate, {
codexBinaryPath: " /opt/codex/bin/codex ",
codexHomePath: " /Users/theo/.codex ",
});
expect(updated.error).toBeUndefined();
expect(updated.result).toEqual({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "/Users/theo/.codex",
});
const roundTrip = await sendRequest(ws, WS_METHODS.appSettingsGet);
expect(roundTrip.error).toBeUndefined();
expect(roundTrip.result).toEqual({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "/Users/theo/.codex",
});
});
it("supports state bootstrap and ordered catch-up events", async () => {
const stateDir = makeTempDir("t3code-ws-state-bootstrap-");
const projectCwd = makeTempDir("t3code-ws-state-project-");
@@ -753,73 +798,6 @@ describe("WebSocket Server", () => {
expect(secondEvent.seq).toBeGreaterThan(firstEvent.seq);
});
it("imports legacy renderer state idempotently", async () => {
const stateDir = makeTempDir("t3code-ws-legacy-import-");
const projectCwd = makeTempDir("t3code-ws-legacy-import-project-");
server = createTestServer({ cwd: "/test", stateDir });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const firstImport = await sendRequest(ws, WS_METHODS.stateImportLegacyRendererState, {
projects: [
{
id: "project-legacy-1",
name: "legacy",
cwd: projectCwd,
scripts: [],
},
],
threads: [
{
id: "thread-legacy-1",
projectId: "project-legacy-1",
title: "Legacy Thread",
model: "gpt-5.3-codex",
createdAt: "2026-02-19T00:00:00.000Z",
messages: [
{
id: "msg-legacy-1",
role: "user",
text: "hello from legacy",
createdAt: "2026-02-19T00:00:01.000Z",
streaming: false,
},
],
},
],
});
expect(firstImport.error).toBeUndefined();
expect(firstImport.result).toEqual({
imported: true,
alreadyImported: false,
});
const secondImport = await sendRequest(ws, WS_METHODS.stateImportLegacyRendererState, {
projects: [],
threads: [],
});
expect(secondImport.error).toBeUndefined();
expect(secondImport.result).toEqual({
imported: false,
alreadyImported: true,
});
const bootstrap = await sendRequest(ws, WS_METHODS.stateBootstrap);
expect(bootstrap.error).toBeUndefined();
const snapshot = bootstrap.result as {
projects: Array<{ id: string }>;
threads: Array<{ id: string; messages: Array<{ id: string }> }>;
};
expect(snapshot.projects).toHaveLength(1);
expect(snapshot.threads).toHaveLength(1);
expect(snapshot.threads[0]?.messages[0]?.id).toBe("msg-legacy-1");
});
it("returns unknown-session errors for checkpoint RPCs without an active provider session", async () => {
server = createTestServer({ cwd: "/test" });
await server.start();
@@ -852,6 +830,91 @@ describe("WebSocket Server", () => {
expect(diffResponse.error?.message).toContain("Unknown provider session");
});
it("returns provider revert results even if checkpoint revert persistence fails", async () => {
const stateDir = makeTempDir("t3code-ws-revert-failure-state-");
const persistenceService = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
});
const revertResult = {
threadId: "runtime-thread-1",
turnCount: 0,
messageCount: 0,
rolledBackTurns: 1,
checkpoints: [
{
id: "root",
turnCount: 0,
messageCount: 0,
label: "Start of conversation",
isCurrent: true,
},
],
};
vi.spyOn(ProviderManager.prototype, "revertToCheckpoint").mockResolvedValue(revertResult);
vi.spyOn(persistenceService, "applyCheckpointRevert").mockImplementation(() => {
throw new Error("persistence write failed");
});
server = createTestServer({ cwd: "/test", stateDir, persistenceService });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.providersRevertToCheckpoint, {
sessionId: "sess-1",
turnCount: 0,
});
expect(response.error).toBeUndefined();
expect(response.result).toEqual(revertResult);
});
it("rejects threads.update and keeps threads.updateTerminalState as the canonical route", async () => {
const stateDir = makeTempDir("t3code-ws-threads-update-state-");
const projectCwd = makeTempDir("t3code-ws-threads-update-project-");
server = createTestServer({ cwd: "/test", stateDir });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const addedProject = await sendRequest(ws, WS_METHODS.projectsAdd, { cwd: projectCwd });
expect(addedProject.error).toBeUndefined();
const projectId = (addedProject.result as { project: { id: string } }).project.id;
const createdThread = await sendRequest(ws, WS_METHODS.threadsCreate, {
projectId,
title: "Thread Terminal State",
model: "gpt-5.3-codex",
});
expect(createdThread.error).toBeUndefined();
const threadId = (createdThread.result as { thread: { id: string } }).thread.id;
const deprecatedResponse = await sendRequest(ws, "threads.update", {
threadId,
terminalOpen: true,
});
expect(deprecatedResponse.result).toBeUndefined();
expect(deprecatedResponse.error?.message).toContain('"threads.update" is unsupported');
const canonicalResponse = await sendRequest(ws, WS_METHODS.threadsUpdateTerminalState, {
threadId,
terminalOpen: true,
});
expect(canonicalResponse.error).toBeUndefined();
expect((canonicalResponse.result as { thread: { terminalOpen: boolean } }).thread.terminalOpen).toBe(
true,
);
});
it("routes terminal RPC methods and broadcasts terminal events", async () => {
const cwd = makeTempDir("t3code-ws-terminal-cwd-");
const terminalManager = new MockTerminalManager();
@@ -940,6 +1003,43 @@ describe("WebSocket Server", () => {
expect(terminalManager.listenerCount("event")).toBe(0);
});
it("does not close an injected persistence service on stop", async () => {
const stateDir = makeTempDir("t3code-ws-injected-persistence-state-");
const persistenceService = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
});
const closeSpy = vi.spyOn(persistenceService, "close");
server = createServer({
port: 0,
cwd: "/test",
persistenceService,
});
await server.start();
await server.stop();
server = null;
expect(closeSpy).not.toHaveBeenCalled();
persistenceService.close();
});
it("closes internally owned persistence service on stop", async () => {
const stateDir = makeTempDir("t3code-ws-internal-persistence-state-");
const closeSpy = vi.spyOn(PersistenceService.prototype, "close");
server = createServer({
port: 0,
cwd: "/test",
stateDbPath: path.join(stateDir, "state.sqlite"),
});
await server.start();
await server.stop();
server = null;
expect(closeSpy).toHaveBeenCalledTimes(1);
});
it("returns validation errors for invalid terminal open params", async () => {
server = createTestServer({ cwd: "/test" });
await server.start();
+28 -10
View File
@@ -90,6 +90,7 @@ export function createServer(options: ServerOptions) {
new PersistenceService({
dbPath: stateDbPath ?? path.join(os.homedir(), ".t3", "state.sqlite"),
});
const ownsPersistenceService = providedPersistenceService === undefined;
const providerManager = new ProviderManager({ persistenceService });
const terminalManager = providedTerminalManager ?? new TerminalManager();
const gitManager = providedGitManager ?? new GitManager();
@@ -346,12 +347,20 @@ export function createServer(options: ServerOptions) {
turnCount: number;
};
const result = await providerManager.revertToCheckpoint(params as never);
persistenceService.applyCheckpointRevert({
sessionId: params.sessionId,
runtimeThreadId: result.threadId,
turnCount: result.turnCount,
messageCount: result.messageCount,
});
try {
persistenceService.applyCheckpointRevert({
sessionId: params.sessionId,
runtimeThreadId: result.threadId,
turnCount: result.turnCount,
messageCount: result.messageCount,
});
} catch (error) {
logger.warn("failed to persist checkpoint revert", {
sessionId: params.sessionId,
turnCount: params.turnCount,
error,
});
}
return result;
}
@@ -364,13 +373,20 @@ export function createServer(options: ServerOptions) {
case WS_METHODS.stateCatchUp:
return persistenceService.catchUp(request.params as never);
case WS_METHODS.stateImportLegacyRendererState:
return persistenceService.importLegacyRendererState(request.params as never);
case WS_METHODS.appSettingsGet:
return persistenceService.getAppSettings();
case WS_METHODS.appSettingsUpdate:
return persistenceService.updateAppSettings((request.params ?? {}) as never);
case WS_METHODS.threadsCreate:
return persistenceService.createThread(request.params as never);
case WS_METHODS.threadsUpdate:
case "threads.update":
throw new Error(
`"threads.update" is unsupported; use ${WS_METHODS.threadsUpdateTerminalState}`,
);
case WS_METHODS.threadsUpdateTerminalState:
return persistenceService.updateThreadTerminalState(request.params as never);
@@ -539,7 +555,9 @@ export function createServer(options: ServerOptions) {
providerManager.stopAll();
providerManager.dispose();
terminalManager.dispose();
persistenceService.close();
if (ownsPersistenceService) {
persistenceService.close();
}
for (const client of clients) {
client.close();
+3 -1
View File
@@ -3,13 +3,15 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300..800;1,9..40,300..800&display=swap"
rel="stylesheet"
/>
<title>T3 Code</title>
<title>T3 Code (Alpha)</title>
</head>
<body>
<div id="root"></div>
Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 279 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 10C0 4.47715 4.47715 0 10 0H118C123.523 0 128 4.47715 128 10V118C128 123.523 123.523 128 118 128H10C4.47715 128 0 123.523 0 118V10Z" fill="black"/>
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+159
View File
@@ -0,0 +1,159 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const LOCAL_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:local:v1";
const LEGACY_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
type StorageMap = Map<string, string>;
interface Deferred<T> {
promise: Promise<T>;
resolve: (value: T) => void;
reject: (error?: unknown) => void;
}
function createDeferred<T>(): Deferred<T> {
let resolve!: (value: T) => void;
let reject!: (error?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return {
promise,
resolve,
reject,
};
}
async function flushMicrotasks(times = 3): Promise<void> {
if (times <= 0) return;
await Promise.resolve();
await flushMicrotasks(times - 1);
}
function installWindowMock(initialStorage?: StorageMap): StorageMap {
const storage = initialStorage ?? new Map<string, string>();
const localStorageMock = {
length: 0,
clear: () => {
storage.clear();
localStorageMock.length = 0;
},
getItem: (key: string) => storage.get(key) ?? null,
key: (index: number) => Array.from(storage.keys())[index] ?? null,
removeItem: (key: string) => {
storage.delete(key);
localStorageMock.length = storage.size;
},
setItem: (key: string, value: string) => {
storage.set(key, value);
localStorageMock.length = storage.size;
},
};
localStorageMock.length = storage.size;
const windowMock = {
localStorage: localStorageMock as Storage,
addEventListener: () => undefined,
removeEventListener: () => undefined,
};
Object.defineProperty(globalThis, "window", {
configurable: true,
value: windowMock,
});
return storage;
}
describe("appSettings", () => {
afterEach(() => {
vi.resetModules();
Reflect.deleteProperty(globalThis, "window");
});
it("returns a stable snapshot reference when settings have not changed", async () => {
installWindowMock();
const module = await import("./appSettings");
const first = module.getAppSettingsSnapshot();
const second = module.getAppSettingsSnapshot();
expect(second).toBe(first);
});
it("returns a new snapshot reference when local settings change", async () => {
const storage = installWindowMock();
const module = await import("./appSettings");
const first = module.getAppSettingsSnapshot();
storage.set(LOCAL_APP_SETTINGS_STORAGE_KEY, JSON.stringify({ confirmThreadDelete: false }));
const second = module.getAppSettingsSnapshot();
expect(second).not.toBe(first);
expect(second.confirmThreadDelete).toBe(false);
});
it("prevents hydration from overwriting optimistic backend writes", async () => {
installWindowMock();
const getDeferred = createDeferred<{ codexBinaryPath: string; codexHomePath: string }>();
const updateDeferred = createDeferred<{ codexBinaryPath: string; codexHomePath: string }>();
const get = vi.fn(() => getDeferred.promise);
const update = vi.fn(() => updateDeferred.promise);
window.nativeApi = {
appSettings: {
get,
update,
},
} as unknown as NonNullable<Window["nativeApi"]>;
const module = await import("./appSettings");
const hydration = module.ensureAppSettingsHydrated();
module.updateAppSettings({ codexBinaryPath: "/opt/codex/new" });
getDeferred.resolve({ codexBinaryPath: "/opt/codex/stale", codexHomePath: "" });
await hydration;
expect(module.getAppSettingsSnapshot().codexBinaryPath).toBe("/opt/codex/new");
expect(update).toHaveBeenCalledTimes(1);
updateDeferred.resolve({ codexBinaryPath: "/opt/codex/new", codexHomePath: "" });
await flushMicrotasks();
expect(module.getAppSettingsSnapshot().codexBinaryPath).toBe("/opt/codex/new");
});
it("prevents hydration from overwriting optimistic local writes", async () => {
const storage = installWindowMock(
new Map([
[
LEGACY_APP_SETTINGS_STORAGE_KEY,
JSON.stringify({
confirmThreadDelete: true,
}),
],
]),
);
const getDeferred = createDeferred<{ codexBinaryPath: string; codexHomePath: string }>();
const get = vi.fn(() => getDeferred.promise);
window.nativeApi = {
appSettings: {
get,
update: vi.fn(async () => ({ codexBinaryPath: "", codexHomePath: "" })),
},
} as unknown as NonNullable<Window["nativeApi"]>;
const module = await import("./appSettings");
const hydration = module.ensureAppSettingsHydrated();
module.updateAppSettings({ confirmThreadDelete: false });
getDeferred.resolve({ codexBinaryPath: "", codexHomePath: "" });
await hydration;
expect(module.getAppSettingsSnapshot().confirmThreadDelete).toBe(false);
expect(storage.get(LOCAL_APP_SETTINGS_STORAGE_KEY)).toBe(
JSON.stringify({ confirmThreadDelete: false }),
);
});
});
+319
View File
@@ -0,0 +1,319 @@
import {
type AppSettings as BackendAppSettings,
appSettingsSchema as backendAppSettingsSchema,
appSettingsUpdateInputSchema,
} from "@t3tools/contracts";
import { useCallback, useEffect, useSyncExternalStore } from "react";
import { z } from "zod";
import { readNativeApi } from "./session-logic";
const LOCAL_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:local:v1";
const LEGACY_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const localAppSettingsSchema = z.object({
confirmThreadDelete: z.boolean().default(true),
});
const legacyAppSettingsSchema = backendAppSettingsSchema.extend({
confirmThreadDelete: z.boolean().default(true),
});
const appSettingsSchema = backendAppSettingsSchema.extend({
confirmThreadDelete: z.boolean().default(true),
});
export type AppSettings = z.infer<typeof appSettingsSchema>;
const DEFAULT_BACKEND_APP_SETTINGS: BackendAppSettings = backendAppSettingsSchema.parse({});
const DEFAULT_LOCAL_APP_SETTINGS = localAppSettingsSchema.parse({});
const DEFAULT_APP_SETTINGS: AppSettings = {
...DEFAULT_BACKEND_APP_SETTINGS,
...DEFAULT_LOCAL_APP_SETTINGS,
};
let listeners: Array<() => void> = [];
let cachedBackendSettings: BackendAppSettings = DEFAULT_BACKEND_APP_SETTINGS;
let cachedBackendCacheKey = JSON.stringify(DEFAULT_BACKEND_APP_SETTINGS);
let cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
let cachedLocalCacheKey: string | undefined;
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
let cachedSnapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
let backendHydrationPromise: Promise<void> | null = null;
let backendHydrated = false;
let backendUpdateSequence = 0;
let optimisticWriteSequence = 0;
function emitChange(): void {
for (const listener of listeners) {
listener();
}
}
function setCachedBackendSettings(next: BackendAppSettings): void {
cachedBackendSettings = next;
cachedBackendCacheKey = JSON.stringify(next);
}
function parseLegacySettings(value: string | null): z.infer<typeof legacyAppSettingsSchema> | null {
if (!value) {
return null;
}
try {
const parsed = JSON.parse(value) as unknown;
return legacyAppSettingsSchema.parse(parsed);
} catch {
return null;
}
}
function readLegacySettingsSnapshot(): z.infer<typeof legacyAppSettingsSchema> | null {
if (typeof window === "undefined") {
return null;
}
return parseLegacySettings(window.localStorage.getItem(LEGACY_APP_SETTINGS_STORAGE_KEY));
}
function readLocalSettingsSnapshot() {
if (typeof window === "undefined") {
return DEFAULT_LOCAL_APP_SETTINGS;
}
const rawLocal = window.localStorage.getItem(LOCAL_APP_SETTINGS_STORAGE_KEY);
const rawLegacy = rawLocal === null ? window.localStorage.getItem(LEGACY_APP_SETTINGS_STORAGE_KEY) : null;
const cacheKey = rawLocal !== null ? `local:${rawLocal}` : `legacy:${rawLegacy ?? ""}`;
if (cacheKey === cachedLocalCacheKey) {
return cachedLocalSettings;
}
if (rawLocal !== null) {
try {
const parsed = JSON.parse(rawLocal) as unknown;
cachedLocalSettings = localAppSettingsSchema.parse(parsed);
} catch {
cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
}
} else {
const legacySettings = parseLegacySettings(rawLegacy);
cachedLocalSettings = localAppSettingsSchema.parse({
confirmThreadDelete: legacySettings?.confirmThreadDelete ?? DEFAULT_LOCAL_APP_SETTINGS.confirmThreadDelete,
});
}
cachedLocalCacheKey = cacheKey;
return cachedLocalSettings;
}
function persistLocalSettings(next: z.infer<typeof localAppSettingsSchema>): void {
if (typeof window === "undefined") return;
const normalized = localAppSettingsSchema.parse(next);
const raw = JSON.stringify(normalized);
try {
window.localStorage.setItem(LOCAL_APP_SETTINGS_STORAGE_KEY, raw);
} catch {
// Best-effort persistence only.
}
cachedLocalSettings = normalized;
cachedLocalCacheKey = `local:${raw}`;
}
function normalizeBackendSettings(value: unknown): BackendAppSettings {
const parsed = backendAppSettingsSchema.safeParse(value);
if (parsed.success) {
return parsed.data;
}
return DEFAULT_BACKEND_APP_SETTINGS;
}
async function hydrateBackendSettings(): Promise<void> {
if (typeof window === "undefined" || backendHydrated) {
return;
}
if (backendHydrationPromise) {
await backendHydrationPromise;
return;
}
const hydrationSequence = optimisticWriteSequence;
const hasOptimisticWriteSinceHydration = () => hydrationSequence !== optimisticWriteSequence;
backendHydrationPromise = (async () => {
const api = readNativeApi();
if (!api?.appSettings || typeof api.appSettings.get !== "function") {
backendHydrated = true;
return;
}
const legacySettings = readLegacySettingsSnapshot();
let next = normalizeBackendSettings(await api.appSettings.get());
if (!hasOptimisticWriteSinceHydration()) {
const migrationPatch = appSettingsUpdateInputSchema.parse({
...(next.codexBinaryPath.length === 0 && legacySettings?.codexBinaryPath
? { codexBinaryPath: legacySettings.codexBinaryPath }
: {}),
...(next.codexHomePath.length === 0 && legacySettings?.codexHomePath
? { codexHomePath: legacySettings.codexHomePath }
: {}),
});
const hasMigrationPatch =
migrationPatch.codexBinaryPath !== undefined || migrationPatch.codexHomePath !== undefined;
if (hasMigrationPatch) {
next = normalizeBackendSettings(await api.appSettings.update(migrationPatch));
}
}
if (!hasOptimisticWriteSinceHydration()) {
setCachedBackendSettings(next);
if (legacySettings) {
persistLocalSettings({
confirmThreadDelete: legacySettings.confirmThreadDelete,
});
}
emitChange();
}
backendHydrated = true;
if (legacySettings) {
try {
window.localStorage.removeItem(LEGACY_APP_SETTINGS_STORAGE_KEY);
} catch {
// Best-effort legacy cleanup only.
}
}
})()
.catch(() => undefined)
.finally(() => {
backendHydrationPromise = null;
});
await backendHydrationPromise;
}
export function getAppSettingsSnapshot(): AppSettings {
const localSettings = readLocalSettingsSnapshot();
const snapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
if (snapshotKey === cachedSnapshotKey) {
return cachedSnapshot;
}
cachedSnapshot = appSettingsSchema.parse({
...cachedBackendSettings,
...localSettings,
});
cachedSnapshotKey = snapshotKey;
return cachedSnapshot;
}
export function ensureAppSettingsHydrated(): Promise<void> {
return hydrateBackendSettings();
}
export function updateAppSettings(patch: Partial<AppSettings>): void {
const parsedPatch = appSettingsSchema.partial().parse(patch);
let didChange = false;
let didOptimisticWrite = false;
const markOptimisticWrite = () => {
if (didOptimisticWrite) return;
didOptimisticWrite = true;
optimisticWriteSequence += 1;
};
if (parsedPatch.confirmThreadDelete !== undefined) {
markOptimisticWrite();
persistLocalSettings({
...readLocalSettingsSnapshot(),
confirmThreadDelete: parsedPatch.confirmThreadDelete,
});
didChange = true;
}
const backendPatch = appSettingsUpdateInputSchema.parse({
...(parsedPatch.codexBinaryPath !== undefined
? { codexBinaryPath: parsedPatch.codexBinaryPath }
: {}),
...(parsedPatch.codexHomePath !== undefined ? { codexHomePath: parsedPatch.codexHomePath } : {}),
});
const hasBackendPatch =
backendPatch.codexBinaryPath !== undefined || backendPatch.codexHomePath !== undefined;
if (hasBackendPatch) {
markOptimisticWrite();
const previous = cachedBackendSettings;
const optimisticNext = backendAppSettingsSchema.parse({
...cachedBackendSettings,
...backendPatch,
});
setCachedBackendSettings(optimisticNext);
backendHydrated = true;
didChange = true;
const updateSequence = ++backendUpdateSequence;
const api = readNativeApi();
if (api?.appSettings && typeof api.appSettings.update === "function") {
void api.appSettings
.update(backendPatch)
.then((response) => {
if (updateSequence !== backendUpdateSequence) return;
setCachedBackendSettings(normalizeBackendSettings(response));
emitChange();
})
.catch(() => {
if (updateSequence !== backendUpdateSequence) return;
setCachedBackendSettings(previous);
emitChange();
});
}
}
if (didChange) {
emitChange();
}
}
function subscribe(listener: () => void): () => void {
listeners.push(listener);
const onStorage = (event: StorageEvent) => {
if (
event.key === null ||
event.key === LOCAL_APP_SETTINGS_STORAGE_KEY ||
event.key === LEGACY_APP_SETTINGS_STORAGE_KEY
) {
emitChange();
}
};
window.addEventListener("storage", onStorage);
return () => {
listeners = listeners.filter((entry) => entry !== listener);
window.removeEventListener("storage", onStorage);
};
}
export function useAppSettings() {
const settings = useSyncExternalStore(subscribe, getAppSettingsSnapshot, () => DEFAULT_APP_SETTINGS);
useEffect(() => {
void ensureAppSettingsHydrated();
}, []);
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
updateAppSettings(patch);
}, []);
const resetSettings = useCallback(() => {
updateSettings(DEFAULT_APP_SETTINGS);
}, [updateSettings]);
return {
settings,
updateSettings,
resetSettings,
defaults: DEFAULT_APP_SETTINGS,
} as const;
}
+3
View File
@@ -0,0 +1,3 @@
export const APP_BASE_NAME = "T3 Code";
export const APP_STAGE_LABEL = import.meta.env.DEV ? "Dev" : "Alpha";
export const APP_DISPLAY_NAME = `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
@@ -120,7 +120,6 @@ export default function BranchToolbar({
if (sessionId && worktreePath !== activeWorktreePath) {
void api?.providers.stopSession({ sessionId }).catch(() => undefined);
}
void api?.threads.updateBranch({ threadId: activeThreadId, branch, worktreePath }).catch(() => undefined);
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
};
+102 -46
View File
@@ -28,6 +28,7 @@ import {
} from "react";
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { type VirtualItem, useVirtualizer } from "@tanstack/react-virtual";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
@@ -35,6 +36,8 @@ import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
import { isElectron } from "../env";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useAppSettings } from "../appSettings";
import { buildBootstrapInput } from "../historyBootstrap";
import {
type ComposerTriggerKind,
@@ -374,8 +377,11 @@ interface ChatViewProps {
export default function ChatView({ threadId }: ChatViewProps) {
const { state, dispatch } = useStore();
const navigate = useNavigate();
const rawSearch = useSearch({ strict: false });
const api = useNativeApi();
const { resolvedTheme } = useTheme();
const { settings: appSettings } = useAppSettings();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(
gitCreateWorktreeMutationOptions({ api, queryClient }),
@@ -409,8 +415,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
const checkpointHydrationSessionRequestRef = useRef(new Set<string>());
const checkpointTurnCountSyncFingerprintRef = useRef(new Map<string, string>());
const terminalStateSyncFingerprintRef = useRef(new Map<string, string>());
const activeThread = state.threads.find((t) => t.id === threadId);
const diffSearch = useMemo(
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
[rawSearch],
);
const diffOpen = diffSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const activeSessionId = activeThread?.session?.sessionId ?? null;
const activeThreadRuntimeId =
@@ -642,6 +654,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
const runtimeApprovalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
const runtimeSandboxMode =
state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
const codexBinaryPath = appSettings.codexBinaryPath.trim();
const codexHomePath = appSettings.codexHomePath.trim();
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
const composerTrigger = useMemo(
() => detectComposerTrigger(prompt, composerCursor),
@@ -750,6 +764,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const hasReachedTerminalLimit =
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
const activeThreadTerminalSyncId = activeThread?.id;
const activeThreadTerminalSyncOpen = activeThread?.terminalOpen;
const activeThreadTerminalSyncHeight = activeThread?.terminalHeight;
const activeThreadTerminalSyncIds = activeThread?.terminalIds;
const activeThreadTerminalSyncActiveId = activeThread?.activeTerminalId;
const activeThreadTerminalSyncGroups = activeThread?.terminalGroups;
const activeThreadTerminalSyncActiveGroupId = activeThread?.activeTerminalGroupId;
useEffect(() => {
if (!api || !activeThread) return;
@@ -783,27 +804,49 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [activeThread?.id, activeThread?.branch, activeThread?.worktreePath, api]);
useEffect(() => {
if (!api || !activeThread) return;
if (
!api ||
!activeThreadTerminalSyncId ||
activeThreadTerminalSyncOpen === undefined ||
activeThreadTerminalSyncHeight === undefined ||
activeThreadTerminalSyncIds === undefined ||
activeThreadTerminalSyncActiveId === undefined ||
activeThreadTerminalSyncGroups === undefined
) {
return;
}
const payload = {
threadId: activeThreadTerminalSyncId,
terminalOpen: activeThreadTerminalSyncOpen,
terminalHeight: activeThreadTerminalSyncHeight,
terminalIds: activeThreadTerminalSyncIds,
activeTerminalId: activeThreadTerminalSyncActiveId,
terminalGroups: activeThreadTerminalSyncGroups,
...(activeThreadTerminalSyncActiveGroupId !== undefined
? { activeTerminalGroupId: activeThreadTerminalSyncActiveGroupId }
: {}),
};
const fingerprint = JSON.stringify(payload);
const previousFingerprint = terminalStateSyncFingerprintRef.current.get(payload.threadId);
if (previousFingerprint === fingerprint) return;
terminalStateSyncFingerprintRef.current.set(payload.threadId, fingerprint);
void api.threads
.updateTerminalState({
threadId: activeThread.id,
terminalOpen: activeThread.terminalOpen,
terminalHeight: activeThread.terminalHeight,
terminalIds: activeThread.terminalIds,
activeTerminalId: activeThread.activeTerminalId,
terminalGroups: activeThread.terminalGroups,
activeTerminalGroupId: activeThread.activeTerminalGroupId,
})
.catch(() => undefined);
.updateTerminalState(payload)
.catch(() => {
const currentFingerprint = terminalStateSyncFingerprintRef.current.get(payload.threadId);
if (currentFingerprint === fingerprint) {
terminalStateSyncFingerprintRef.current.delete(payload.threadId);
}
});
}, [
activeThread?.id,
activeThread?.terminalOpen,
activeThread?.terminalHeight,
activeThread?.terminalIds,
activeThread?.activeTerminalId,
activeThread?.terminalGroups,
activeThread?.activeTerminalGroupId,
api,
activeThreadTerminalSyncId,
activeThreadTerminalSyncOpen,
activeThreadTerminalSyncHeight,
activeThreadTerminalSyncIds,
activeThreadTerminalSyncActiveId,
activeThreadTerminalSyncGroups,
activeThreadTerminalSyncActiveGroupId,
]);
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
@@ -1571,6 +1614,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
cwd: cwdOverride ?? activeThread.worktreePath ?? activeProject.cwd,
model: selectedModel || undefined,
resumeThreadId: priorCodexThreadId ?? undefined,
...(codexBinaryPath.length > 0 ? { codexBinaryPath } : {}),
...(codexHomePath.length > 0 ? { codexHomePath } : {}),
approvalPolicy: runtimeApprovalPolicy,
sandboxMode: runtimeSandboxMode,
});
@@ -1611,6 +1656,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeProject,
activeThread,
api,
codexBinaryPath,
codexHomePath,
dispatch,
runtimeApprovalPolicy,
runtimeSandboxMode,
@@ -2013,32 +2060,29 @@ export default function ChatView({ threadId }: ChatViewProps) {
setExpandedImage(image);
}, []);
const onToggleDiff = useCallback(() => {
if (state.diffOpen) {
dispatch({ type: "CLOSE_DIFF" });
return;
}
if (!activeThread) {
dispatch({ type: "TOGGLE_DIFF" });
return;
}
dispatch({
type: "OPEN_DIFF",
threadId: activeThread.id,
void navigate({
to: "/$threadId",
params: { threadId },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return diffOpen ? rest : { ...rest, diff: "1" };
},
});
}, [activeThread, dispatch, state.diffOpen]);
}, [diffOpen, navigate, threadId]);
const onOpenTurnDiff = useCallback(
(turnId: string, filePath?: string) => {
if (!activeThread) return;
dispatch({
type: "OPEN_DIFF",
threadId: activeThread.id,
turnId,
...(filePath ? { filePath } : {}),
void navigate({
to: "/$threadId",
params: { threadId },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return filePath
? { ...rest, diff: "1", diffTurnId: turnId, diffFilePath: filePath }
: { ...rest, diff: "1", diffTurnId: turnId };
},
});
},
[activeThread, dispatch],
[navigate, threadId],
);
const onRevertUserMessage = useCallback(
(messageId: string) => {
@@ -2086,7 +2130,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
keybindings={keybindings}
api={api}
gitCwd={gitCwd}
diffOpen={state.diffOpen}
diffOpen={diffOpen}
onRunProjectScript={(script) => {
void runProjectScript(script);
}}
@@ -2871,11 +2915,16 @@ const MessagesTimeline = memo(function MessagesTimeline({
row.message.id,
);
if (!turnSummary) return null;
const checkpointFilesState = turnCheckpointFilesByTurnId.get(turnSummary.turnId);
const checkpointFilesState = turnCheckpointFilesByTurnId.get(
turnSummary.turnId,
);
const checkpointFiles = checkpointFilesState?.files ?? [];
const summaryStat = checkpointFiles.reduce(
(acc, file) => {
if (typeof file.additions !== "number" || typeof file.deletions !== "number") {
if (
typeof file.additions !== "number" ||
typeof file.deletions !== "number"
) {
return acc;
}
return {
@@ -2886,7 +2935,9 @@ const MessagesTimeline = memo(function MessagesTimeline({
{ additions: 0, deletions: 0 },
);
const changedFileCountLabel =
checkpointFilesState?.status === "ready" ? String(checkpointFiles.length) : "...";
checkpointFilesState?.status === "ready"
? String(checkpointFiles.length)
: "...";
return (
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
<div className="mb-1.5 flex items-center justify-between gap-2">
@@ -2897,7 +2948,9 @@ const MessagesTimeline = memo(function MessagesTimeline({
<span className="mx-1">•</span>
<span className="text-success">+{summaryStat.additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{summaryStat.deletions}</span>
<span className="text-destructive">
-{summaryStat.deletions}
</span>
</>
)}
</p>
@@ -2905,12 +2958,15 @@ const MessagesTimeline = memo(function MessagesTimeline({
type="button"
size="xs"
variant="outline"
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
onClick={() =>
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
}
>
View diff
</Button>
</div>
{!checkpointFilesState || checkpointFilesState.status === "pending" ? (
{!checkpointFilesState ||
checkpointFilesState.status === "pending" ? (
<p className="text-[11px] text-muted-foreground/70">
Waiting for checkpoint metadata...
</p>
+171 -76
View File
@@ -1,22 +1,17 @@
import { parsePatchFiles } from "@pierre/diffs";
import {
FileDiff,
type FileDiffMetadata,
Virtualizer,
WorkerPoolContextProvider,
} from "@pierre/diffs/react";
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
import { useQuery } from "@tanstack/react-query";
import { useParams } from "@tanstack/react-router";
import { Columns2Icon, Rows3Icon } from "lucide-react";
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { isElectron } from "../env";
import { useNativeApi } from "../hooks/useNativeApi";
import { useTheme } from "../hooks/useTheme";
import { buildPatchCacheKey } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { formatTimestamp } from "../session-logic";
import { useStore } from "../store";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
@@ -72,42 +67,37 @@ function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
}
function formatTurnChipTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
}).format(new Date(isoDate));
}
interface DiffPanelProps {
mode?: "inline" | "sheet";
}
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
const workerPoolSize = useMemo(() => {
const cores = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
}, []);
return (
<WorkerPoolContextProvider
poolOptions={{
workerFactory: () =>
new Worker(new URL("../workers/diffs.worker.ts", import.meta.url), { type: "module" }),
poolSize: workerPoolSize,
totalASTLRUCacheSize: 240,
}}
highlighterOptions={{
tokenizeMaxLineLength: 1_000,
}}
>
{children}
</WorkerPoolContextProvider>
);
}
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const api = useNativeApi();
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const { state, dispatch } = useStore();
const { state } = useStore();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const patchViewportRef = useRef<HTMLDivElement>(null);
const turnStripRef = useRef<HTMLDivElement>(null);
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
const params = useParams({ strict: false });
const rawSearch = useSearch({ strict: false });
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
const activeThreadId = state.diffThreadId ?? routeThreadId;
const diffSearch = useMemo(
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
[rawSearch],
);
const activeThreadId = routeThreadId;
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
const activeThreadRuntimeId =
activeThread?.codexThreadId ?? activeThread?.session?.threadId ?? null;
@@ -115,10 +105,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const canApplyStoredTarget = Boolean(activeThread && state.diffThreadId === activeThread.id);
const selectedTurnId = canApplyStoredTarget ? state.diffTurnId : null;
const selectedFilePath =
canApplyStoredTarget && selectedTurnId !== null ? state.diffFilePath : null;
const selectedTurnId = diffSearch.diffTurnId ?? null;
const selectedFilePath = selectedTurnId !== null ? (diffSearch.diffFilePath ?? null) : null;
const selectedTurn =
selectedTurnId === null
? undefined
@@ -218,19 +206,84 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const selectTurn = (turnId: string) => {
if (!activeThread) return;
dispatch({
type: "SET_DIFF_TARGET",
threadId: activeThread.id,
turnId,
void navigate({
to: "/$threadId",
params: { threadId: activeThread.id },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return { ...rest, diff: "1", diffTurnId: turnId };
},
});
};
const selectWholeConversation = () => {
if (!activeThread) return;
dispatch({
type: "SET_DIFF_TARGET",
threadId: activeThread.id,
void navigate({
to: "/$threadId",
params: { threadId: activeThread.id },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return { ...rest, diff: "1" };
},
});
};
const updateTurnStripScrollState = useCallback(() => {
const element = turnStripRef.current;
if (!element) {
setCanScrollTurnStripLeft(false);
setCanScrollTurnStripRight(false);
return;
}
const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
setCanScrollTurnStripLeft(element.scrollLeft > 4);
setCanScrollTurnStripRight(element.scrollLeft < maxScrollLeft - 4);
}, []);
const scrollTurnStripBy = useCallback((offset: number) => {
const element = turnStripRef.current;
if (!element) return;
element.scrollBy({ left: offset, behavior: "smooth" });
}, []);
const onTurnStripWheel = useCallback((event: WheelEvent) => {
const element = turnStripRef.current;
if (!element) return;
if (element.scrollWidth <= element.clientWidth + 1) return;
if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
event.preventDefault();
element.scrollBy({ left: event.deltaY, behavior: "auto" });
}, []);
useEffect(() => {
const element = turnStripRef.current;
if (!element) return;
updateTurnStripScrollState();
const onScroll = () => updateTurnStripScrollState();
element.addEventListener("scroll", onScroll, { passive: true });
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
resizeObserver.observe(element);
return () => {
element.removeEventListener("scroll", onScroll);
element.removeEventListener("wheel", onTurnStripWheel);
resizeObserver.disconnect();
};
}, [updateTurnStripScrollState, onTurnStripWheel]);
useEffect(() => {
updateTurnStripScrollState();
}, [turnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
useEffect(() => {
const element = turnStripRef.current;
if (!element) return;
const selectedChip = element.querySelector<HTMLElement>("[data-turn-chip-selected='true']");
selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
}, [selectedTurn?.turnId, selectedTurnId]);
const shouldUseDragRegion = isElectron && mode === "inline";
@@ -245,49 +298,98 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
>
<div
className={cn(
"flex items-center justify-between border-b border-border px-4",
"flex items-center justify-between gap-2 border-b border-border px-4",
shouldUseDragRegion ? "drag-region h-[52px]" : "py-3",
)}
>
<div className="flex gap-1.5 overflow-x-auto pb-0.5">
<button type="button" className="shrink-0 rounded-md" onClick={selectWholeConversation}>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
selectedTurnId === null
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
>
<div className="text-[10px] font-medium">All turns</div>
<div className="text-[8px] opacity-70">Conversation</div>
</div>
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
{canScrollTurnStripLeft && (
<div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-gradient-to-r from-card to-transparent" />
)}
{canScrollTurnStripRight && (
<div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-gradient-to-l from-card to-transparent" />
)}
<button
type="button"
className={cn(
"absolute left-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
canScrollTurnStripLeft
? "border-border/70 hover:border-border hover:text-foreground"
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
)}
onClick={() => scrollTurnStripBy(-180)}
disabled={!canScrollTurnStripLeft}
aria-label="Scroll turn list left"
>
<ChevronLeftIcon className="size-3.5" />
</button>
{turnDiffSummaries.map((summary, index) => (
<button
type="button"
className={cn(
"absolute right-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
canScrollTurnStripRight
? "border-border/70 hover:border-border hover:text-foreground"
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
)}
onClick={() => scrollTurnStripBy(180)}
disabled={!canScrollTurnStripRight}
aria-label="Scroll turn list right"
>
<ChevronRightIcon className="size-3.5" />
</button>
<div
ref={turnStripRef}
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
>
<button
key={summary.turnId}
type="button"
className="shrink-0 rounded-md"
onClick={() => selectTurn(summary.turnId)}
title={summary.turnId}
onClick={selectWholeConversation}
data-turn-chip-selected={selectedTurnId === null}
>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
summary.turnId === selectedTurn?.turnId
selectedTurnId === null
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
>
<div className="text-[10px] font-medium">
Turn {turnDiffSummaries.length - index}
</div>
<div className="text-[8px] opacity-70">{formatTimestamp(summary.completedAt)}</div>
<div className="text-[10px] leading-tight font-medium">All turns</div>
</div>
</button>
))}
{turnDiffSummaries.map((summary, index) => (
<button
key={summary.turnId}
type="button"
className="shrink-0 rounded-md"
onClick={() => selectTurn(summary.turnId)}
title={summary.turnId}
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
summary.turnId === selectedTurn?.turnId
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
>
<div className="flex items-center gap-1">
<span className="text-[10px] leading-tight font-medium">
Turn {turnDiffSummaries.length - index}
</span>
<span className="text-[9px] leading-tight opacity-70">
{formatTurnChipTimestamp(summary.completedAt)}
</span>
</div>
</div>
</button>
))}
</div>
</div>
<ToggleGroup
className="shrink-0 [-webkit-app-region:no-drag]"
variant="outline"
size="xs"
value={[diffRenderMode]}
@@ -318,13 +420,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
) : (
<>
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
{!canApplyStoredTarget && state.diffThreadId && (
<div className="px-3 pt-2">
<p className="mb-2 text-[11px] text-muted-foreground/65">
Showing diffs for the active thread.
</p>
</div>
)}
{checkpointDiffError && !renderablePatch && (
<div className="px-3">
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
@@ -0,0 +1,26 @@
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
import { useMemo, type ReactNode } from "react";
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
const workerPoolSize = useMemo(() => {
const cores = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
}, []);
return (
<WorkerPoolContextProvider
poolOptions={{
workerFactory: () =>
new Worker(new URL("../workers/diffs.worker.ts", import.meta.url), { type: "module" }),
poolSize: workerPoolSize,
totalASTLRUCacheSize: 240,
}}
highlighterOptions={{
tokenizeMaxLineLength: 1_000,
}}
>
{children}
</WorkerPoolContextProvider>
);
}
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL } from "../model-logic";
import { createLocalThreadForProject } from "./Sidebar.logic";
describe("createLocalThreadForProject", () => {
it("creates a local thread with the project's configured model", () => {
const thread = createLocalThreadForProject({
projectId: "project-1",
projects: [
{
id: "project-1",
name: "Project",
cwd: "/tmp/project",
model: "custom-project-model",
expanded: true,
scripts: [],
},
],
options: {
branch: "feature/test",
worktreePath: "/tmp/project/worktrees/feature-test",
},
});
expect(thread.projectId).toBe("project-1");
expect(thread.model).toBe("custom-project-model");
expect(thread.branch).toBe("feature/test");
expect(thread.worktreePath).toBe("/tmp/project/worktrees/feature-test");
});
it("falls back to the default model when the project is missing", () => {
const thread = createLocalThreadForProject({
projectId: "missing-project",
projects: [],
});
expect(thread.projectId).toBe("missing-project");
expect(thread.model).toBe(DEFAULT_MODEL);
expect(thread.branch).toBeNull();
expect(thread.worktreePath).toBeNull();
});
});
+25
View File
@@ -0,0 +1,25 @@
import { DEFAULT_MODEL } from "../model-logic";
import { createThread } from "../threadFactory";
import type { Project, Thread } from "../types";
interface CreateLocalThreadInput {
projectId: string;
projects: Project[];
options?: {
branch?: string | null;
worktreePath?: string | null;
};
}
export function createLocalThreadForProject({
projectId,
projects,
options,
}: CreateLocalThreadInput): Thread {
const model = projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
return createThread(projectId, {
model,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
});
}
+50 -24
View File
@@ -1,10 +1,11 @@
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
import { TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { APP_STAGE_LABEL } from "../branding";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
@@ -15,8 +16,8 @@ import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { toastManager } from "./ui/toast";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { createLocalThreadForProject } from "./Sidebar.logic";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
function formatRelativeTime(iso: string): string {
@@ -115,6 +116,7 @@ export default function Sidebar() {
const { state, dispatch } = useStore();
const api = useNativeApi();
const navigate = useNavigate();
const { settings: appSettings } = useAppSettings();
const params = useParams({ strict: false });
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
@@ -125,7 +127,6 @@ export default function Sidebar() {
const removeWorktreeMutation = useMutation(
gitRemoveWorktreeMutationOptions({ api, queryClient }),
);
const { theme, setTheme } = useTheme();
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
@@ -146,7 +147,22 @@ export default function Sidebar() {
worktreePath?: string | null;
},
) => {
if (!api) return;
if (!api) {
const localThread = createLocalThreadForProject({
projectId,
projects: state.projects,
...(options ? { options } : {}),
});
dispatch({
type: "ADD_THREAD",
thread: localThread,
});
void navigate({
to: "/$threadId",
params: { threadId: localThread.id },
});
return;
}
void (async () => {
try {
const result = await api.threads.create({
@@ -306,6 +322,17 @@ export default function Sidebar() {
const thread = state.threads.find((t) => t.id === threadId);
if (!thread) return;
if (appSettings.confirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
[
`Delete thread \"${thread.title}\"?`,
"This permanently clears conversation history for this thread.",
].join("\n"),
);
if (!confirmed) {
return;
}
}
const threadProject = state.projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
const displayWorktreePath = orphanedWorktreePath
@@ -384,7 +411,16 @@ export default function Sidebar() {
});
}
},
[api, dispatch, navigate, removeWorktreeMutation, routeThreadId, state.projects, state.threads],
[
api,
appSettings.confirmThreadDelete,
dispatch,
navigate,
removeWorktreeMutation,
routeThreadId,
state.projects,
state.threads,
],
);
const handleProjectContextMenu = useCallback(
@@ -467,24 +503,14 @@ export default function Sidebar() {
<div
className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
>
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
T3 <span className="font-normal text-muted-foreground">Code</span>
</span>
<button
type="button"
className="rounded-md p-1.5 text-muted-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-muted-foreground"
onClick={() => setTheme(THEME_CYCLE[theme])}
aria-label={`Theme: ${theme}`}
title={`Theme: ${theme}`}
>
{theme === "system" ? (
<MonitorIcon className="size-3.5" />
) : theme === "light" ? (
<SunIcon className="size-3.5" />
) : (
<MoonIcon className="size-3.5" />
)}
</button>
<div className="flex min-w-0 flex-1 items-center gap-2">
<span className="truncate text-sm font-semibold tracking-tight text-foreground">
T3 <span className="font-normal text-muted-foreground">Code</span>
</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">
{APP_STAGE_LABEL}
</span>
</div>
</div>
{/* New thread (global) */}
@@ -252,6 +252,7 @@ function TerminalViewport({
),
);
});
let didReceiveRenderableEventSinceOpen = false;
const themeObserver = new MutationObserver(() => {
const activeTerminal = terminalRef.current;
@@ -279,9 +280,14 @@ function TerminalViewport({
...(runtimeEnv ? { env: runtimeEnv } : {}),
});
if (disposed) return;
activeTerminal.write("\u001bc");
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
const shouldHydrateFromSnapshot =
snapshot.history.length > 0 || !didReceiveRenderableEventSinceOpen;
if (shouldHydrateFromSnapshot) {
// Avoid clearing output that arrived before open() resolved.
activeTerminal.write("\u001bc");
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
}
}
if (autoFocus) {
window.requestAnimationFrame(() => {
@@ -302,6 +308,10 @@ function TerminalViewport({
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
if (event.type !== "activity") {
didReceiveRenderableEventSinceOpen = true;
}
if (event.type === "output") {
activeTerminal.write(event.data);
return;
+74
View File
@@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import { parseDiffRouteSearch } from "./diffRouteSearch";
describe("parseDiffRouteSearch", () => {
it("parses valid diff search values", () => {
const parsed = parseDiffRouteSearch({
diff: "1",
diffTurnId: "turn-1",
diffFilePath: "src/app.ts",
});
expect(parsed).toEqual({
diff: "1",
diffTurnId: "turn-1",
diffFilePath: "src/app.ts",
});
});
it("treats numeric and boolean diff toggles as open", () => {
expect(
parseDiffRouteSearch({
diff: 1,
diffTurnId: "turn-1",
}),
).toEqual({
diff: "1",
diffTurnId: "turn-1",
});
expect(
parseDiffRouteSearch({
diff: true,
diffTurnId: "turn-1",
}),
).toEqual({
diff: "1",
diffTurnId: "turn-1",
});
});
it("drops turn and file values when diff is closed", () => {
const parsed = parseDiffRouteSearch({
diff: "0",
diffTurnId: "turn-1",
diffFilePath: "src/app.ts",
});
expect(parsed).toEqual({});
});
it("drops file value when turn is not selected", () => {
const parsed = parseDiffRouteSearch({
diff: "1",
diffFilePath: "src/app.ts",
});
expect(parsed).toEqual({
diff: "1",
});
});
it("normalizes whitespace-only values", () => {
const parsed = parseDiffRouteSearch({
diff: "1",
diffTurnId: " ",
diffFilePath: " ",
});
expect(parsed).toEqual({
diff: "1",
});
});
});
+36
View File
@@ -0,0 +1,36 @@
export interface DiffRouteSearch {
diff?: "1";
diffTurnId?: string;
diffFilePath?: string;
}
function isDiffOpenValue(value: unknown): boolean {
return value === "1" || value === 1 || value === true;
}
function normalizeSearchString(value: unknown): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const normalized = value.trim();
return normalized.length > 0 ? normalized : undefined;
}
export function stripDiffSearchParams<T extends Record<string, unknown>>(
params: T,
): Omit<T, "diff" | "diffTurnId" | "diffFilePath"> {
const { diff: _diff, diffTurnId: _diffTurnId, diffFilePath: _diffFilePath, ...rest } = params;
return rest as Omit<T, "diff" | "diffTurnId" | "diffFilePath">;
}
export function parseDiffRouteSearch(search: Record<string, unknown>): DiffRouteSearch {
const diff = isDiffOpenValue(search.diff) ? "1" : undefined;
const diffTurnId = diff ? normalizeSearchString(search.diffTurnId) : undefined;
const diffFilePath = diff && diffTurnId ? normalizeSearchString(search.diffFilePath) : undefined;
return {
...(diff ? { diff } : {}),
...(diffTurnId ? { diffTurnId } : {}),
...(diffFilePath ? { diffFilePath } : {}),
};
}
+10
View File
@@ -190,6 +190,16 @@ input {
background: rgba(255, 255, 255, 0.18);
}
.turn-chip-strip {
scrollbar-width: none;
-ms-overflow-style: none;
overscroll-behavior-x: contain;
}
.turn-chip-strip::-webkit-scrollbar {
display: none;
}
/* Terminal drawer scrollbar parity with chat */
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical {
width: 6px !important;
+2
View File
@@ -9,12 +9,14 @@ import "@xterm/xterm/css/xterm.css";
import "highlight.js/styles/github-dark.css";
import "./index.css";
import { APP_DISPLAY_NAME } from "./branding";
import { isElectron } from "./env";
import { routeTree } from "./routeTree.gen";
const history = isElectron ? createHashHistory() : createBrowserHistory();
const queryClient = new QueryClient();
document.title = APP_DISPLAY_NAME;
const router = createRouter({
routeTree,
-507
View File
@@ -1,507 +0,0 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import type { Thread } from "./types";
describe("hydratePersistedState", () => {
it("returns null for invalid payloads", () => {
expect(hydratePersistedState('{"projects":"bad"}', false)).toBeNull();
expect(hydratePersistedState("not-json", false)).toBeNull();
});
it("migrates the legacy default model to the current default", () => {
const payload = JSON.stringify({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.2-codex",
expanded: true,
scripts: [],
},
],
threads: [
{
id: "t-1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.2-codex",
messages: [
{
id: "m-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: true,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, true);
expect(hydrated).not.toBeNull();
expect(hydrated?.projects[0]?.model).toBe(DEFAULT_MODEL);
expect(hydrated?.threads[0]?.model).toBe(DEFAULT_MODEL);
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
expect(hydrated?.runtimeMode).toBe("full-access");
});
it("filters unknown project references and repairs active thread", () => {
const payload = JSON.stringify({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
scripts: [],
},
],
threads: [
{
id: "t-1",
projectId: "p-1",
title: "Valid thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
{
id: "t-2",
projectId: "p-missing",
title: "Dangling thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-2",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated).not.toBeNull();
expect(hydrated?.threads.map((thread) => thread.id)).toEqual(["t-1"]);
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
expect(hydrated?.runtimeMode).toBe("full-access");
});
it("hydrates runtime mode from v3 payload", () => {
const payload = JSON.stringify({
version: 3,
runtimeMode: "approval-required",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
scripts: [],
},
],
threads: [],
activeThreadId: null,
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.runtimeMode).toBe("approval-required");
});
it("hydrates terminal fields from legacy v6 payload", () => {
const payload = JSON.stringify({
version: 6,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
{
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 360,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalLayout: "tabs",
splitTerminalIds: [],
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
lastVisitedAt: "2026-02-08T10:01:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalOpen).toBe(true);
expect(hydrated?.threads[0]?.terminalHeight).toBe(360);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe("term-2");
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z");
});
it("hydrates legacy split layout into a grouped split", () => {
const payload = JSON.stringify({
version: 6,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
{
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 360,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: "term-2",
terminalLayout: "split",
splitTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("defaults terminalHeight when hydrating v5 payloads", () => {
const payload = JSON.stringify({
version: 5,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
{
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("hydrates persisted turn diff summaries as metadata-only entries", () => {
const payload = JSON.stringify({
version: 7,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
codexThreadId: "thr_1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
turnDiffSummaries: [
{
turnId: "turn-1",
completedAt: "2026-02-08T10:05:00.000Z",
checkpointTurnCount: 1,
files: [
{
path: "src/app.ts",
kind: "modified",
additions: 3,
deletions: 1,
},
],
},
],
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([
{
turnId: "turn-1",
completedAt: "2026-02-08T10:05:00.000Z",
checkpointTurnCount: 1,
files: [
{
path: "src/app.ts",
kind: "modified",
additions: 3,
deletions: 1,
},
],
},
]);
});
it("drops malformed persisted turn diff summaries instead of rejecting the whole snapshot", () => {
const payload = JSON.stringify({
version: 7,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
codexThreadId: "thr_1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
turnDiffSummaries: [
{
turnId: "turn-1",
completedAt: "2026-02-08T10:05:00.000Z",
files: [{ path: 123 }],
},
],
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated).not.toBeNull();
expect(hydrated?.threads[0]?.id).toBe("t-1");
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([]);
});
});
describe("toPersistedState", () => {
it("writes v7 payload and strips non-persisted thread fields", () => {
const thread: Thread = {
id: "t-1",
codexThreadId: "thr_1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 320,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
runningTerminalIds: [],
activeTerminalId: "term-2",
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
],
activeTerminalGroupId: "group-term-2",
session: null,
messages: [
{
id: "m-1",
role: "user",
text: "Hi",
attachments: [
{
type: "image",
id: "img-1",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4_096,
previewUrl: "blob:preview-1",
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
events: [],
error: "boom",
createdAt: "2026-02-08T10:00:00.000Z",
lastVisitedAt: "2026-02-08T10:02:00.000Z",
branch: null,
worktreePath: null,
turnDiffSummaries: [
{
turnId: "turn-1",
completedAt: "2026-02-08T10:05:00.000Z",
status: "completed",
checkpointTurnCount: 1,
files: [
{
path: "src/app.ts",
kind: "modified",
additions: 3,
deletions: 1,
},
],
},
],
};
const persisted = toPersistedState({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [thread],
runtimeMode: "full-access",
});
expect(persisted.version).toBe(7);
expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({
id: "t-1",
codexThreadId: "thr_1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 320,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
],
activeTerminalGroupId: "group-term-2",
messages: [
{
id: "m-1",
role: "user",
text: "Hi",
attachments: [
{
type: "image",
id: "img-1",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4_096,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
createdAt: thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: null,
worktreePath: null,
turnDiffSummaries: [
{
turnId: "turn-1",
completedAt: "2026-02-08T10:05:00.000Z",
status: "completed",
checkpointTurnCount: 1,
files: [
{
path: "src/app.ts",
kind: "modified",
additions: 3,
deletions: 1,
},
],
},
],
});
const persistedThread = persisted.threads[0];
expect(persistedThread).toBeDefined();
if (!persistedThread) return;
expect("error" in persistedThread).toBe(false);
expect("session" in persistedThread).toBe(false);
});
});
-399
View File
@@ -1,399 +0,0 @@
import { z } from "zod";
import { projectScriptSchema } from "@t3tools/contracts";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
type ThreadTerminalGroup,
} from "./types";
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
const persistedProjectSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
cwd: z.string().min(1),
model: z.string().min(1),
expanded: z.boolean(),
scripts: z.array(projectScriptSchema).default([]),
});
const persistedMessageSchema = z.object({
id: z.string().min(1),
role: z.enum(["user", "assistant"]),
text: z.string(),
attachments: z
.array(
z.object({
type: z.literal("image"),
id: z.string().min(1),
name: z.string().min(1),
mimeType: z.string().min(1),
sizeBytes: z.number().int().min(1),
}),
)
.optional(),
createdAt: z.string().min(1),
streaming: z.boolean(),
});
const persistedTerminalGroupSchema = z.object({
id: z.string().trim().min(1),
terminalIds: z.array(z.string().trim().min(1)),
});
const persistedTurnDiffFileChangeSchema = z.object({
path: z.string().min(1),
kind: z.string().min(1).optional(),
additions: z.number().int().min(0).optional(),
deletions: z.number().int().min(0).optional(),
});
const persistedTurnDiffSummarySchema = z.object({
turnId: z.string().min(1),
completedAt: z.string().min(1),
status: z.string().min(1).optional(),
files: z.array(persistedTurnDiffFileChangeSchema),
assistantMessageId: z.string().min(1).optional(),
checkpointTurnCount: z.number().int().min(0).optional(),
});
const persistedThreadSchema = z.object({
id: z.string().min(1),
codexThreadId: z.string().min(1).nullable().default(null),
projectId: z.string().min(1),
title: z.string().min(1),
model: z.string().min(1),
terminalOpen: z.boolean().default(false),
terminalHeight: z.number().int().min(120).max(4_096).default(DEFAULT_THREAD_TERMINAL_HEIGHT),
terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]),
activeTerminalId: z.string().trim().min(1).default(DEFAULT_THREAD_TERMINAL_ID),
terminalGroups: z.array(persistedTerminalGroupSchema).default([]),
activeTerminalGroupId: z.string().trim().min(1).optional(),
// Legacy v6 and older fields retained for migration.
terminalLayout: z.enum(["single", "split", "tabs"]).optional(),
splitTerminalIds: z.array(z.string().trim().min(1)).optional(),
messages: z.array(persistedMessageSchema),
createdAt: z.string().min(1),
lastVisitedAt: z.string().min(1).optional(),
branch: z.string().min(1).nullable().optional(),
worktreePath: z.string().min(1).nullable().optional(),
turnDiffSummaries: z.array(persistedTurnDiffSummarySchema).catch([]).default([]),
});
const persistedStateBodySchema = z.object({
projects: z.array(persistedProjectSchema),
threads: z.array(persistedThreadSchema),
activeThreadId: z.string().min(1).nullable().optional(),
});
const runtimeModeSchema = z.enum(["approval-required", "full-access"]);
export const persistedStateV1Schema = persistedStateBodySchema.extend({
version: z.literal(1).optional(),
});
export const persistedStateV2Schema = persistedStateBodySchema.extend({
version: z.literal(2).optional(),
});
export const persistedStateV3Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(3).optional(),
});
export const persistedStateV4Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(4).optional(),
});
export const persistedStateV6Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(6).optional(),
});
export const persistedStateV7Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(7).optional(),
});
export const persistedStateV5Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(5).optional(),
});
const persistedStateSchema = z.union([
persistedStateV7Schema,
persistedStateV6Schema,
persistedStateV5Schema,
persistedStateV4Schema,
persistedStateV3Schema,
persistedStateV2Schema,
persistedStateV1Schema,
]);
export interface PersistedStoreSnapshot {
projects: Project[];
threads: Thread[];
runtimeMode: RuntimeMode;
}
function maybeMigrateLegacyModel(model: string, isLegacyPayload: boolean): string {
if (!isLegacyPayload) {
return model;
}
return model === LEGACY_DEFAULT_MODEL ? DEFAULT_MODEL : model;
}
function hydrateProject(
project: z.infer<typeof persistedProjectSchema>,
isLegacyPayload: boolean,
): Project {
return {
...project,
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
scripts: project.scripts,
};
}
function hydrateThread(
thread: z.infer<typeof persistedThreadSchema>,
isLegacyPayload: boolean,
): Thread {
const terminalIds = [
...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
];
const safeTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const safeTerminalIdSet = new Set(safeTerminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const normalizedGroups: ThreadTerminalGroup[] = [];
const assignUniqueGroupId = (groupId: 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;
};
for (const terminalGroup of thread.terminalGroups) {
const nextTerminalIds = [
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => {
if (!safeTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (nextTerminalIds.length === 0) continue;
for (const terminalId of nextTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
terminalGroup.id.trim().length > 0
? terminalGroup.id.trim()
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
normalizedGroups.push({
id: assignUniqueGroupId(baseGroupId),
terminalIds: nextTerminalIds,
});
}
if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
const splitTerminalIds = [
...new Set(
(thread.splitTerminalIds ?? []).map((id) => id.trim()).filter((id) => id.length > 0),
),
].filter((terminalId) => safeTerminalIdSet.has(terminalId));
if (splitTerminalIds.length >= 2) {
const splitGroupTerminalIds = splitTerminalIds.slice(0, 2);
for (const terminalId of splitGroupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
normalizedGroups.push({
id: assignUniqueGroupId(`group-${splitGroupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`),
terminalIds: splitGroupTerminalIds,
});
}
}
for (const terminalId of safeTerminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
normalizedGroups.push({
id: assignUniqueGroupId(`group-${terminalId}`),
terminalIds: [terminalId],
});
}
const activeGroupIndexFromId = normalizedGroups.findIndex(
(terminalGroup) => terminalGroup.id === thread.activeTerminalGroupId,
);
const activeGroupIndexFromTerminal = normalizedGroups.findIndex((terminalGroup) =>
terminalGroup.terminalIds.includes(activeTerminalId),
);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId =
normalizedGroups[activeGroupIndex]?.id ??
normalizedGroups[0]?.id ??
`group-${DEFAULT_THREAD_TERMINAL_ID}`;
return {
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
terminalOpen: thread.terminalOpen ?? false,
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: safeTerminalIds,
runningTerminalIds: [],
activeTerminalId,
terminalGroups: normalizedGroups,
activeTerminalGroupId,
session: null,
messages: thread.messages.map((message) => {
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
return {
id: message.id,
role: message.role,
text: message.text,
...(hydratedAttachments && hydratedAttachments.length > 0
? { attachments: hydratedAttachments }
: {}),
createdAt: message.createdAt,
streaming: false,
};
}),
events: [],
error: null,
createdAt: thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: thread.branch ?? null,
worktreePath: thread.worktreePath ?? null,
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
turnId: summary.turnId,
completedAt: summary.completedAt,
...(summary.status ? { status: summary.status } : {}),
files: summary.files.map((file) => ({
path: file.path,
...(file.kind ? { kind: file.kind } : {}),
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
})),
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
...(typeof summary.checkpointTurnCount === "number"
? { checkpointTurnCount: summary.checkpointTurnCount }
: {}),
})),
};
}
export function hydratePersistedState(
raw: string,
isLegacyPayload: boolean,
): PersistedStoreSnapshot | null {
let parsedJson: unknown;
try {
parsedJson = JSON.parse(raw);
} catch {
return null;
}
const parsedState = persistedStateSchema.safeParse(parsedJson);
if (!parsedState.success) {
return null;
}
const projects = parsedState.data.projects.map((project) =>
hydrateProject(project, isLegacyPayload),
);
const projectIds = new Set(projects.map((project) => project.id));
const threads = parsedState.data.threads
.map((thread) => hydrateThread(thread, isLegacyPayload))
.filter((thread) => projectIds.has(thread.projectId));
return {
projects,
threads,
runtimeMode:
"runtimeMode" in parsedState.data ? parsedState.data.runtimeMode : DEFAULT_RUNTIME_MODE,
};
}
export function toPersistedState(
state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV7Schema> {
return {
version: 7,
projects: state.projects,
threads: state.threads.map((thread) => ({
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
model: thread.model,
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
terminalIds: thread.terminalIds,
activeTerminalId: thread.activeTerminalId,
terminalGroups: thread.terminalGroups,
activeTerminalGroupId: thread.activeTerminalGroupId,
messages: thread.messages.map((message) => ({
id: message.id,
role: message.role,
text: message.text,
...(message.attachments && message.attachments.length > 0
? {
attachments: message.attachments.map((attachment) => ({
type: attachment.type,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
})),
}
: {}),
createdAt: message.createdAt,
streaming: message.streaming,
})),
createdAt: thread.createdAt,
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
branch: thread.branch,
worktreePath: thread.worktreePath,
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
turnId: summary.turnId,
completedAt: summary.completedAt,
...(summary.status ? { status: summary.status } : {}),
files: summary.files.map((file) => ({
path: file.path,
...(file.kind ? { kind: file.kind } : {}),
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
})),
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
...(typeof summary.checkpointTurnCount === "number"
? { checkpointTurnCount: summary.checkpointTurnCount }
: {}),
})),
})),
runtimeMode: state.runtimeMode,
};
}
+21 -3
View File
@@ -11,6 +11,7 @@
import { Route as rootRouteImport } from './routes/__root'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as ChatSettingsRouteImport } from './routes/_chat.settings'
import { Route as ChatThreadIdRouteImport } from './routes/_chat.$threadId'
const ChatRoute = ChatRouteImport.update({
@@ -22,6 +23,11 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
path: '/',
getParentRoute: () => ChatRoute,
} as any)
const ChatSettingsRoute = ChatSettingsRouteImport.update({
id: '/settings',
path: '/settings',
getParentRoute: () => ChatRoute,
} as any)
const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
id: '/$threadId',
path: '/$threadId',
@@ -31,23 +37,26 @@ const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
'/$threadId': typeof ChatThreadIdRoute
'/settings': typeof ChatSettingsRoute
}
export interface FileRoutesByTo {
'/$threadId': typeof ChatThreadIdRoute
'/settings': typeof ChatSettingsRoute
'/': typeof ChatIndexRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_chat': typeof ChatRouteWithChildren
'/_chat/$threadId': typeof ChatThreadIdRoute
'/_chat/settings': typeof ChatSettingsRoute
'/_chat/': typeof ChatIndexRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/$threadId'
fullPaths: '/' | '/$threadId' | '/settings'
fileRoutesByTo: FileRoutesByTo
to: '/$threadId' | '/'
id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/'
to: '/$threadId' | '/settings' | '/'
id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/settings' | '/_chat/'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
@@ -70,6 +79,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ChatIndexRouteImport
parentRoute: typeof ChatRoute
}
'/_chat/settings': {
id: '/_chat/settings'
path: '/settings'
fullPath: '/settings'
preLoaderRoute: typeof ChatSettingsRouteImport
parentRoute: typeof ChatRoute
}
'/_chat/$threadId': {
id: '/_chat/$threadId'
path: '/$threadId'
@@ -82,11 +98,13 @@ declare module '@tanstack/react-router' {
interface ChatRouteChildren {
ChatThreadIdRoute: typeof ChatThreadIdRoute
ChatSettingsRoute: typeof ChatSettingsRoute
ChatIndexRoute: typeof ChatIndexRoute
}
const ChatRouteChildren: ChatRouteChildren = {
ChatThreadIdRoute: ChatThreadIdRoute,
ChatSettingsRoute: ChatSettingsRoute,
ChatIndexRoute: ChatIndexRoute,
}
+73 -108
View File
@@ -1,31 +1,26 @@
import { Outlet, createRootRouteWithContext, useParams } from "@tanstack/react-router";
import {
Outlet,
createRootRouteWithContext,
type ErrorComponentProps,
useParams,
} from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import { QueryClient, useQueryClient } from "@tanstack/react-query";
import { APP_DISPLAY_NAME } from "../branding";
import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
import { isElectron } from "../env";
import { useNativeApi } from "../hooks/useNativeApi";
import { invalidateGitQueries } from "../lib/gitReactQuery";
import { hydratePersistedState } from "../persistenceSchema";
import { useStore } from "../store";
import { onServerWelcome } from "../wsNativeApi";
const CURRENT_RENDERER_STATE_KEY = "t3code:renderer-state:v7";
const LEGACY_RENDERER_STATE_KEYS = [
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
"t3code:renderer-state:v3",
"codething:renderer-state:v4",
"codething:renderer-state:v3",
"codething:renderer-state:v2",
"codething:renderer-state:v1",
] as const;
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
}>()({
component: RootRouteView,
errorComponent: RootRouteErrorView,
});
function RootRouteView() {
@@ -35,7 +30,9 @@ function RootRouteView() {
return (
<div className="flex h-screen flex-col bg-background text-foreground">
<div className="flex flex-1 items-center justify-center">
<p className="text-sm text-muted-foreground">Connecting to T3 Code server...</p>
<p className="text-sm text-muted-foreground">
Connecting to {APP_DISPLAY_NAME} server...
</p>
</div>
</div>
);
@@ -52,87 +49,74 @@ function RootRouteView() {
);
}
function readLegacyRendererImportPayload() {
if (typeof window === "undefined") {
return null;
}
function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
const message = errorMessage(error);
const details = errorDetails(error);
try {
const rawCurrent = window.localStorage.getItem(CURRENT_RENDERER_STATE_KEY);
const legacyValues = LEGACY_RENDERER_STATE_KEYS.map((key) =>
window.localStorage.getItem(key),
);
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
const raw = rawCurrent ?? rawLegacy;
if (!raw) {
return null;
}
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
if (!hydrated) {
return null;
}
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
<div className="pointer-events-none absolute inset-0 opacity-80">
<div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-red-500)_16%,transparent),transparent)]" />
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
</div>
return {
projects: hydrated.projects.map((project) => ({
id: project.id,
name: project.name,
cwd: project.cwd,
scripts: project.scripts,
})),
threads: hydrated.threads.map((thread) => ({
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
model: thread.model,
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
terminalIds: thread.terminalIds,
activeTerminalId: thread.activeTerminalId,
terminalGroups: thread.terminalGroups,
activeTerminalGroupId: thread.activeTerminalGroupId,
messages: thread.messages.map((message) => ({
id: message.id,
role: message.role,
text: message.text,
...(message.attachments
? {
attachments: message.attachments.map((attachment) => ({
type: attachment.type,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
})),
}
: {}),
createdAt: message.createdAt,
streaming: message.streaming,
})),
createdAt: thread.createdAt,
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
...(thread.branch !== null ? { branch: thread.branch } : {}),
...(thread.worktreePath !== null ? { worktreePath: thread.worktreePath } : {}),
turnDiffSummaries: thread.turnDiffSummaries,
})),
};
} catch {
return null;
}
<section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
{APP_DISPLAY_NAME}
</p>
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
Something went wrong.
</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
<div className="mt-5 flex flex-wrap gap-2">
<Button size="sm" onClick={() => reset()}>
Try again
</Button>
<Button size="sm" variant="outline" onClick={() => window.location.reload()}>
Reload app
</Button>
</div>
<details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
<summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
<span className="group-open:hidden">Show error details</span>
<span className="hidden group-open:inline">Hide error details</span>
</summary>
<pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
{details}
</pre>
</details>
</section>
</div>
);
}
function clearLegacyRendererState(): void {
if (typeof window === "undefined") {
return;
function errorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
if (typeof error === "string" && error.trim().length > 0) {
return error;
}
return "An unexpected router error occurred.";
}
function errorDetails(error: unknown): string {
if (error instanceof Error) {
return error.stack ?? error.message;
}
if (typeof error === "string") {
return error;
}
try {
window.localStorage.removeItem(CURRENT_RENDERER_STATE_KEY);
for (const key of LEGACY_RENDERER_STATE_KEYS) {
window.localStorage.removeItem(key);
}
return JSON.stringify(error, null, 2);
} catch {
// Ignore storage cleanup failures.
return "No additional error details are available.";
}
}
@@ -163,25 +147,6 @@ function StateSyncRouter() {
snapshot,
});
lastStateSeqRef.current = snapshot.lastStateSeq;
const legacyPayload = readLegacyRendererImportPayload();
if (!legacyPayload) {
return;
}
const importResult = await api.state.importLegacyRendererState(legacyPayload);
if (disposed) return;
if (importResult.imported) {
const refreshed = await api.state.bootstrap();
if (disposed) return;
dispatch({
type: "HYDRATE_FROM_SERVER",
snapshot: refreshed,
});
lastStateSeqRef.current = refreshed.lastStateSeq;
}
if (importResult.imported || importResult.alreadyImported) {
clearLegacyRendererState();
}
} catch {
if (disposed) return;
retryTimer = setTimeout(() => {
+76 -2
View File
@@ -1,14 +1,67 @@
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect } from "react";
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
import ChatView from "../components/ChatView";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { useStore } from "../store";
import { Sheet, SheetPopup } from "../components/ui/sheet";
const DiffPanel = lazy(() => import("../components/DiffPanel"));
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
const DiffPanelWrapper = (props: {
children: ReactNode;
sheet: boolean;
diffOpen: boolean;
onCloseDiff: () => void;
}) => {
if (props.sheet) {
return (
<Sheet
open={props.diffOpen}
onOpenChange={(open) => {
if (!open) {
props.onCloseDiff();
}
}}
>
<SheetPopup
side="right"
showCloseButton={false}
keepMounted
className="w-[min(88vw,820px)] max-w-[820px] p-0"
>
{props.children}
</SheetPopup>
</Sheet>
);
}
return (
<aside className={props.diffOpen ? undefined : "hidden"} aria-hidden={!props.diffOpen}>
{props.children}
</aside>
);
};
function ChatThreadRouteView() {
const { state } = useStore();
const navigate = useNavigate();
const { threadId } = Route.useParams();
const search = Route.useSearch();
const threadExists = threadId ? state.threads.some((thread) => thread.id === threadId) : false;
const diffOpen = search.diff === "1";
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
const closeDiff = useCallback(() => {
void navigate({
to: "/$threadId",
params: { threadId },
search: (previous) => {
return stripDiffSearchParams(previous);
},
});
}, [navigate, threadId]);
useEffect(() => {
if (!threadId) {
@@ -30,9 +83,30 @@ function ChatThreadRouteView() {
return null;
}
return <ChatView threadId={threadId} />;
const diffLoadingFallback =
!diffOpen || shouldUseDiffSheet ? (
<div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
Loading diff viewer...
</div>
) : (
<aside className="flex h-full w-[560px] shrink-0 items-center justify-center border-l border-border bg-card px-4 text-center text-xs text-muted-foreground/70">
Loading diff viewer...
</aside>
);
return (
<>
<ChatView threadId={threadId} />
<DiffPanelWrapper sheet={shouldUseDiffSheet} diffOpen={diffOpen} onCloseDiff={closeDiff}>
<Suspense fallback={diffLoadingFallback}>
<DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
</Suspense>
</DiffPanelWrapper>
</>
);
}
export const Route = createFileRoute("/_chat/$threadId")({
validateSearch: (search) => parseDiffRouteSearch(search),
component: ChatThreadRouteView,
});
+259
View File
@@ -0,0 +1,259 @@
import { createFileRoute } from "@tanstack/react-router";
import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { useStore } from "../store";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Switch } from "../components/ui/switch";
const THEME_OPTIONS = [
{
value: "system",
label: "System",
description: "Match your OS appearance setting.",
},
{
value: "light",
label: "Light",
description: "Always use the light theme.",
},
{
value: "dark",
label: "Dark",
description: "Always use the dark theme.",
},
] as const;
const RUNTIME_MODE_OPTIONS = [
{
value: "full-access",
label: "Full access",
description: "Allow commands to run without confirmation prompts.",
},
{
value: "approval-required",
label: "Supervised",
description: "Require approval prompts before command execution.",
},
] as const;
function SettingsRouteView() {
const { theme, setTheme, resolvedTheme } = useTheme();
const { state, dispatch } = useStore();
const { settings, defaults, updateSettings } = useAppSettings();
const codexBinaryPath = settings.codexBinaryPath;
const codexHomePath = settings.codexHomePath;
return (
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
{isElectron && (
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
<span className="text-xs font-medium tracking-wide text-muted-foreground/70">Settings</span>
</div>
)}
<div className="flex-1 overflow-y-auto p-6">
<div className="mx-auto flex w-full max-w-3xl flex-col gap-6">
<header className="space-y-1">
<h1 className="text-2xl font-semibold tracking-tight text-foreground">Settings</h1>
<p className="text-sm text-muted-foreground">
Configure app-level preferences for this device.
</p>
</header>
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4">
<h2 className="text-sm font-medium text-foreground">Appearance</h2>
<p className="mt-1 text-xs text-muted-foreground">
Choose how T3 Code handles light and dark mode.
</p>
</div>
<div className="space-y-2" role="radiogroup" aria-label="Theme preference">
{THEME_OPTIONS.map((option) => {
const selected = theme === option.value;
return (
<button
key={option.value}
type="button"
role="radio"
aria-checked={selected}
className={`flex w-full items-start justify-between rounded-lg border px-3 py-2 text-left transition-colors ${
selected
? "border-primary/60 bg-primary/8 text-foreground"
: "border-border bg-background text-muted-foreground hover:bg-accent"
}`}
onClick={() => setTheme(option.value)}
>
<span className="flex flex-col">
<span className="text-sm font-medium">{option.label}</span>
<span className="text-xs">{option.description}</span>
</span>
{selected ? (
<span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
Selected
</span>
) : null}
</button>
);
})}
</div>
<p className="mt-4 text-xs text-muted-foreground">
Active theme: <span className="font-medium text-foreground">{resolvedTheme}</span>
</p>
</section>
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4">
<h2 className="text-sm font-medium text-foreground">Codex App Server</h2>
<p className="mt-1 text-xs text-muted-foreground">
These overrides apply to new sessions and let you use a non-default Codex install.
</p>
</div>
<div className="space-y-4">
<label className="block space-y-1">
<span className="text-xs font-medium text-foreground">Codex binary path</span>
<Input
value={codexBinaryPath}
onChange={(event) => updateSettings({ codexBinaryPath: event.target.value })}
placeholder="codex"
spellCheck={false}
/>
<span className="text-xs text-muted-foreground">
Leave blank to use <code>codex</code> from your PATH.
</span>
</label>
<label className="block space-y-1">
<span className="text-xs font-medium text-foreground">CODEX_HOME path</span>
<Input
value={codexHomePath}
onChange={(event) => updateSettings({ codexHomePath: event.target.value })}
placeholder="/Users/you/.codex"
spellCheck={false}
/>
<span className="text-xs text-muted-foreground">
Optional custom Codex home/config directory.
</span>
</label>
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
<p>
Binary source: <span className="font-medium text-foreground">{codexBinaryPath || "PATH"}</span>
</p>
<Button
size="xs"
variant="outline"
onClick={() =>
updateSettings({
codexBinaryPath: defaults.codexBinaryPath,
codexHomePath: defaults.codexHomePath,
})
}
>
Reset codex overrides
</Button>
</div>
</div>
</section>
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4">
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
<p className="mt-1 text-xs text-muted-foreground">
Select the default execution policy for this client.
</p>
</div>
<div className="space-y-2" role="radiogroup" aria-label="Runtime mode preference">
{RUNTIME_MODE_OPTIONS.map((option) => {
const selected = state.runtimeMode === option.value;
return (
<button
key={option.value}
type="button"
role="radio"
aria-checked={selected}
className={`flex w-full items-start justify-between rounded-lg border px-3 py-2 text-left transition-colors ${
selected
? "border-primary/60 bg-primary/8 text-foreground"
: "border-border bg-background text-muted-foreground hover:bg-accent"
}`}
onClick={() => {
dispatch({
type: "SET_RUNTIME_MODE",
mode: option.value,
});
}}
>
<span className="flex flex-col">
<span className="text-sm font-medium">{option.label}</span>
<span className="text-xs">{option.description}</span>
</span>
{selected ? (
<span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
Selected
</span>
) : null}
</button>
);
})}
</div>
</section>
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4">
<h2 className="text-sm font-medium text-foreground">Safety</h2>
<p className="mt-1 text-xs text-muted-foreground">
Additional guardrails for destructive local actions.
</p>
</div>
<div className="flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2">
<div>
<p className="text-sm font-medium text-foreground">Confirm thread deletion</p>
<p className="text-xs text-muted-foreground">
Ask for confirmation before deleting a thread and its chat history.
</p>
</div>
<Switch
checked={settings.confirmThreadDelete}
onCheckedChange={(checked) =>
updateSettings({
confirmThreadDelete: Boolean(checked),
})
}
aria-label="Confirm thread deletion"
/>
</div>
{settings.confirmThreadDelete !== defaults.confirmThreadDelete ? (
<div className="mt-3 flex justify-end">
<Button
size="xs"
variant="outline"
onClick={() =>
updateSettings({
confirmThreadDelete: defaults.confirmThreadDelete,
})
}
>
Restore default
</Button>
</div>
) : null}
</section>
</div>
</div>
</div>
);
}
export const Route = createFileRoute("/_chat/settings")({
component: SettingsRouteView,
});
+23 -66
View File
@@ -1,78 +1,34 @@
import { Outlet, createFileRoute } from "@tanstack/react-router";
import { Activity, Suspense, lazy, type ReactNode } from "react";
import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect } from "react";
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
import Sidebar from "../components/Sidebar";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { useStore } from "../store";
import { Sheet, SheetPopup } from "../components/ui/sheet";
const DiffPanel = lazy(() => import("../components/DiffPanel"));
const DiffWorkerPoolProvider = lazy(() =>
import("../components/DiffPanel").then((module) => ({
default: module.DiffWorkerPoolProvider,
})),
);
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
const DiffPanelWrapper = (props: { children: ReactNode; sheet: boolean }) => {
const { state, dispatch } = useStore();
if (props.sheet) {
return (
<Sheet
open={state.diffOpen}
onOpenChange={(open) => {
if (!open) {
dispatch({ type: "CLOSE_DIFF" });
}
}}
>
<SheetPopup
side="right"
showCloseButton={false}
keepMounted
className="w-[min(88vw,820px)] max-w-[820px] p-0"
>
{props.children}
</SheetPopup>
</Sheet>
);
}
return (
<aside className={state.diffOpen ? undefined : "hidden"} aria-hidden={!state.diffOpen}>
{props.children}
</aside>
);
};
function ChatRouteLayout() {
const { state } = useStore();
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
const navigate = useNavigate();
const diffLoadingFallback =
!state.diffOpen || shouldUseDiffSheet ? (
<div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
Loading diff viewer...
</div>
) : (
<aside className="flex h-full w-[560px] shrink-0 items-center justify-center border-l border-border bg-card px-4 text-center text-xs text-muted-foreground/70">
Loading diff viewer...
</aside>
);
useEffect(() => {
const onMenuAction = window.desktopBridge?.onMenuAction;
if (typeof onMenuAction !== "function") {
return;
}
const unsubscribe = onMenuAction((action) => {
if (action !== "open-settings") return;
void navigate({ to: "/settings" });
});
return () => {
unsubscribe?.();
};
}, [navigate]);
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground isolate">
<Sidebar />
<Outlet />
<Activity mode={state.diffOpen ? "visible" : "hidden"}>
<DiffPanelWrapper sheet={shouldUseDiffSheet}>
<Suspense fallback={diffLoadingFallback}>
<DiffWorkerPoolProvider>
<DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
</DiffWorkerPoolProvider>
</Suspense>
</DiffPanelWrapper>
</Activity>
<DiffWorkerPoolProvider>
<Outlet />
</DiffWorkerPoolProvider>
</div>
);
}
@@ -80,3 +36,4 @@ function ChatRouteLayout() {
export const Route = createFileRoute("/_chat")({
component: ChatRouteLayout,
});
+162 -39
View File
@@ -81,10 +81,6 @@ function makeState(thread: Thread): AppState {
threads: [thread],
threadsHydrated: true,
runtimeMode: "full-access",
diffOpen: false,
diffThreadId: null,
diffTurnId: null,
diffFilePath: null,
};
}
@@ -149,21 +145,6 @@ describe("store reducer thread continuity", () => {
expect(next.threads[0]?.terminalOpen).toBe(true);
});
it("opens diff panel with an explicit turn/file target", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "OPEN_DIFF",
threadId: "thread-local-1",
turnId: "turn-1",
filePath: "src/app.ts",
});
expect(next.diffOpen).toBe(true);
expect(next.diffThreadId).toBe("thread-local-1");
expect(next.diffTurnId).toBe("turn-1");
expect(next.diffFilePath).toBe("src/app.ts");
});
it("sets terminal open state per thread", () => {
const state = makeState(makeThread({ terminalOpen: true }));
const next = reducer(state, {
@@ -569,6 +550,168 @@ describe("store reducer thread continuity", () => {
]);
});
it("does not clear persisted turn summaries on thread.upsert snapshots", () => {
const state = makeState(
makeThread({
turnDiffSummaries: [
{
turnId: "turn-1",
completedAt: "2026-02-09T00:00:01.000Z",
files: [{ path: "src/existing.ts", kind: "modified" }],
assistantMessageId: "msg-1",
},
],
}),
);
const next = reducer(state, {
type: "APPLY_STATE_EVENT",
event: {
seq: 1,
eventType: "thread.upsert",
entityId: "thread-local-1",
createdAt: "2026-02-09T00:00:05.000Z",
payload: {
thread: {
id: "thread-local-1",
codexThreadId: "thr-1",
projectId: "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}`,
createdAt: "2026-02-09T00:00:00.000Z",
updatedAt: "2026-02-09T00:00:05.000Z",
lastVisitedAt: "2026-02-09T00:00:05.000Z",
branch: null,
worktreePath: null,
turnDiffSummaries: [],
},
},
},
});
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe("msg-1");
});
it("preserves existing terminal arrays when thread.upsert omits them", () => {
const state = makeState(
makeThread({
terminalOpen: true,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
runningTerminalIds: ["term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{
id: "group-term-2",
terminalIds: ["term-2"],
},
],
activeTerminalGroupId: "group-term-2",
}),
);
const next = reducer(state, {
type: "APPLY_STATE_EVENT",
event: {
seq: 1,
eventType: "thread.upsert",
entityId: "thread-local-1",
createdAt: "2026-02-09T00:00:06.000Z",
payload: {
thread: {
id: "thread-local-1",
codexThreadId: "thr-1",
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
activeTerminalId: "term-2",
activeTerminalGroupId: "group-term-2",
createdAt: "2026-02-09T00:00:00.000Z",
updatedAt: "2026-02-09T00:00:06.000Z",
lastVisitedAt: "2026-02-09T00:00:06.000Z",
branch: null,
worktreePath: null,
turnDiffSummaries: [],
},
},
},
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(next.threads[0]?.runningTerminalIds).toEqual(["term-2"]);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{
id: "group-term-2",
terminalIds: ["term-2"],
},
]);
});
it("uses safe terminal defaults when a new thread.upsert omits terminal arrays", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "APPLY_STATE_EVENT",
event: {
seq: 1,
eventType: "thread.upsert",
entityId: "thread-local-2",
createdAt: "2026-02-09T00:00:06.000Z",
payload: {
thread: {
id: "thread-local-2",
codexThreadId: null,
projectId: "project-1",
title: "Second thread",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
createdAt: "2026-02-09T00:00:01.000Z",
updatedAt: "2026-02-09T00:00:06.000Z",
lastVisitedAt: "2026-02-09T00:00:06.000Z",
branch: null,
worktreePath: null,
turnDiffSummaries: [],
},
},
},
});
const createdThread = next.threads.find((thread) => thread.id === "thread-local-2");
expect(createdThread).toBeDefined();
expect(createdThread?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(createdThread?.runningTerminalIds).toEqual([]);
expect(createdThread?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(createdThread?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
]);
});
it("infers checkpoint turn counts when deriving turn summaries from an empty baseline", () => {
const state = makeState(makeThread({ turnDiffSummaries: [] }));
const next = reducer(state, {
@@ -618,10 +761,6 @@ describe("store reducer thread continuity", () => {
],
threadsHydrated: true,
runtimeMode: "full-access",
diffOpen: true,
diffThreadId: "thread-b",
diffTurnId: "turn-b",
diffFilePath: "src/removed.ts",
};
const next = reducer(state, {
@@ -645,10 +784,6 @@ describe("store reducer thread continuity", () => {
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.id).toBe("thread-a");
expect(next.threads[0]?.projectId).toBe("project-new-a");
expect(next.diffOpen).toBe(false);
expect(next.diffThreadId).toBeNull();
expect(next.diffTurnId).toBeNull();
expect(next.diffFilePath).toBeNull();
});
it("treats empty scripts from sync as authoritative", () => {
@@ -674,10 +809,6 @@ describe("store reducer thread continuity", () => {
threads: [makeThread({ id: "thread-a", projectId: "project-old-a" })],
threadsHydrated: true,
runtimeMode: "full-access",
diffOpen: false,
diffThreadId: null,
diffTurnId: null,
diffFilePath: null,
};
const next = reducer(state, {
@@ -766,10 +897,6 @@ describe("store reducer thread continuity", () => {
],
threadsHydrated: true,
runtimeMode: "full-access",
diffOpen: true,
diffThreadId: "thread-a",
diffTurnId: "turn-a",
diffFilePath: "src/a.ts",
};
const next = reducer(state, {
@@ -781,10 +908,6 @@ describe("store reducer thread continuity", () => {
expect(next.projects[0]?.id).toBe("project-2");
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.id).toBe("thread-b");
expect(next.diffOpen).toBe(false);
expect(next.diffThreadId).toBeNull();
expect(next.diffTurnId).toBeNull();
expect(next.diffFilePath).toBeNull();
});
it("marks completion as seen immediately for the active thread", () => {
+27 -89
View File
@@ -57,20 +57,6 @@ type Action =
| { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "TOGGLE_DIFF" }
| {
type: "OPEN_DIFF";
threadId: string;
turnId?: string;
filePath?: string;
}
| {
type: "SET_DIFF_TARGET";
threadId: string;
turnId?: string;
filePath?: string;
}
| { type: "CLOSE_DIFF" }
| {
type: "APPLY_EVENT";
event: ProviderEvent;
@@ -119,10 +105,6 @@ export interface AppState {
threads: Thread[];
threadsHydrated: boolean;
runtimeMode: RuntimeMode;
diffOpen: boolean;
diffThreadId: string | null;
diffTurnId: string | null;
diffFilePath: string | null;
}
const RUNTIME_MODE_STORAGE_KEY = "t3code:runtime-mode";
@@ -132,10 +114,6 @@ const initialState: AppState = {
threads: [],
threadsHydrated: false,
runtimeMode: DEFAULT_RUNTIME_MODE,
diffOpen: false,
diffThreadId: null,
diffTurnId: null,
diffFilePath: null,
};
// ── Helpers ──────────────────────────────────────────────────────────
@@ -152,10 +130,6 @@ function readPersistedState(): AppState {
return {
...initialState,
runtimeMode,
diffOpen: false,
diffThreadId: null,
diffTurnId: null,
diffFilePath: null,
};
} catch {
return initialState;
@@ -180,32 +154,6 @@ function updateThread(
return threads.map((t) => (t.id === threadId ? updater(t) : t));
}
function resetDiffTargetIfMissing(state: AppState, threads: Thread[]) {
if (!state.diffThreadId) {
return {
diffOpen: state.diffOpen,
diffThreadId: state.diffThreadId,
diffTurnId: state.diffTurnId,
diffFilePath: state.diffFilePath,
};
}
const hasThread = threads.some((thread) => thread.id === state.diffThreadId);
if (hasThread) {
return {
diffOpen: state.diffOpen,
diffThreadId: state.diffThreadId,
diffTurnId: state.diffTurnId,
diffFilePath: state.diffFilePath,
};
}
return {
diffOpen: false,
diffThreadId: null,
diffTurnId: null,
diffFilePath: null,
};
}
function mergeTurnDiffSummaries(
existing: Thread["turnDiffSummaries"],
next: Thread["turnDiffSummaries"],
@@ -585,6 +533,13 @@ function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread>
return {};
}
function resetDiffTargetIfMissing(
_state: AppState,
_threads: Thread[],
): Partial<AppState> {
return {};
}
// ── Reducer ──────────────────────────────────────────────────────────
export function reducer(state: AppState, action: Action): AppState {
@@ -690,13 +645,27 @@ export function reducer(state: AppState, action: Action): AppState {
updatedAt: message.createdAt,
streaming: message.streaming,
})) ?? [];
const payloadTurnDiffSummaries = Array.isArray(threadPayload?.turnDiffSummaries)
? (threadPayload.turnDiffSummaries as Thread["turnDiffSummaries"])
: undefined;
const payloadTerminalIds = Array.isArray(threadPayload?.terminalIds)
? (threadPayload.terminalIds as string[])
: (existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID]);
const payloadRunningTerminalIds = Array.isArray(threadPayload?.runningTerminalIds)
? (threadPayload.runningTerminalIds as string[])
: (existing?.runningTerminalIds ?? []);
const payloadTerminalGroups = Array.isArray(threadPayload?.terminalGroups)
? (threadPayload.terminalGroups as ThreadTerminalGroup[])
: (existing?.terminalGroups ?? []);
const bootstrapThread: StateBootstrapThread = {
...(threadPayload as unknown as Omit<StateBootstrapThread, "messages">),
terminalIds: payloadTerminalIds,
runningTerminalIds: payloadRunningTerminalIds,
terminalGroups: payloadTerminalGroups,
messages: existingStateMessages,
turnDiffSummaries:
(threadPayload?.turnDiffSummaries as Thread["turnDiffSummaries"] | undefined) ??
existing?.turnDiffSummaries ??
[],
turnDiffSummaries: payloadTurnDiffSummaries
? mergeTurnDiffSummaries(existing?.turnDiffSummaries ?? [], payloadTurnDiffSummaries)
: existing?.turnDiffSummaries ?? [],
};
const nextThread = hydrateThreadFromBootstrap(bootstrapThread, existing);
const nextThreads = existing
@@ -878,13 +847,11 @@ export function reducer(state: AppState, action: Action): AppState {
});
})
.filter((thread): thread is Thread => thread !== null);
const diffState = resetDiffTargetIfMissing(state, nextThreads);
return {
...state,
projects: nextProjects,
threads: nextThreads,
...diffState,
};
}
@@ -903,13 +870,11 @@ export function reducer(state: AppState, action: Action): AppState {
}
const threads = state.threads.filter((thread) => thread.projectId !== action.projectId);
const diffState = resetDiffTargetIfMissing(state, threads);
return {
...state,
projects,
threads,
...diffState,
};
}
@@ -1102,29 +1067,6 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
case "TOGGLE_DIFF":
return { ...state, diffOpen: !state.diffOpen };
case "OPEN_DIFF":
return {
...state,
diffOpen: true,
diffThreadId: action.threadId,
diffTurnId: action.turnId ?? null,
diffFilePath: action.filePath ?? null,
};
case "SET_DIFF_TARGET":
return {
...state,
diffThreadId: action.threadId,
diffTurnId: action.turnId ?? null,
diffFilePath: action.filePath ?? null,
};
case "CLOSE_DIFF":
return { ...state, diffOpen: false };
case "APPLY_TERMINAL_EVENT":
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
return state;
@@ -1365,15 +1307,11 @@ export function reducer(state: AppState, action: Action): AppState {
runtimeMode: action.mode,
};
case "DELETE_THREAD": {
const threads = state.threads.filter((t) => t.id !== action.threadId);
const diffState = resetDiffTargetIfMissing(state, threads);
case "DELETE_THREAD":
return {
...state,
threads,
...diffState,
threads: state.threads.filter((t) => t.id !== action.threadId),
};
}
default:
return state;
+1
View File
@@ -8,6 +8,7 @@ interface DesktopBridge {
confirm: (message: string) => Promise<boolean>;
showContextMenu: (items: readonly { id: string; label: string }[]) => Promise<string | null>;
openExternal: (url: string) => Promise<boolean>;
onMenuAction: (listener: (action: string) => void) => () => void;
}
declare global {
+4 -3
View File
@@ -102,14 +102,15 @@ export function createWsNativeApi(): NativeApi {
bootstrap: () => transport.request(WS_METHODS.stateBootstrap),
listMessages: (input) => transport.request(WS_METHODS.stateListMessages, input),
catchUp: (input) => transport.request(WS_METHODS.stateCatchUp, input),
importLegacyRendererState: (input) =>
transport.request(WS_METHODS.stateImportLegacyRendererState, input),
onEvent: (callback) =>
transport.subscribe(WS_CHANNELS.stateEvent, callback as (data: unknown) => void),
},
appSettings: {
get: () => transport.request(WS_METHODS.appSettingsGet),
update: (input) => transport.request(WS_METHODS.appSettingsUpdate, input),
},
threads: {
create: (input) => transport.request(WS_METHODS.threadsCreate, input),
update: (input) => transport.request(WS_METHODS.threadsUpdate, input),
delete: (input) => transport.request(WS_METHODS.threadsDelete, input),
markVisited: (input) => transport.request(WS_METHODS.threadsMarkVisited, input),
updateTerminalState: (input) =>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 MiB

+4
View File
@@ -0,0 +1,4 @@
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 10C0 4.47715 4.47715 0 10 0H118C123.523 0 128 4.47715 128 10V118C128 123.523 123.523 128 118 128H10C4.47715 128 0 123.523 0 118V10Z" fill="black"/>
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 10C0 4.47715 4.47715 0 10 0H118C123.523 0 128 4.47715 128 10V118C128 123.523 123.523 128 118 128H10C4.47715 128 0 123.523 0 118V10Z" fill="black"/>
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

+5 -3
View File
@@ -16,7 +16,7 @@
"name": "@t3tools/desktop",
"version": "0.0.0",
"dependencies": {
"electron": "33.4.11",
"electron": "40.6.0",
},
"devDependencies": {
"@types/node": "^22.10.2",
@@ -687,7 +687,7 @@
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"electron": ["electron@33.4.11", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^20.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-xmdAs5QWRkInC7TpXGNvzo/7exojubk+72jn1oJL7keNeIlw7xNglf8TGtJtkR4rWC5FJq0oXiIXPS9BcK2Irg=="],
"electron": ["electron@40.6.0", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
"electron-to-chromium": ["[email protected]", "", {}, "sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A=="],
@@ -1377,7 +1377,7 @@
"clone-response/mimic-response": ["[email protected]", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],
"electron/@types/node": ["@types/[email protected]9.33", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-Rs1bVAIdBs5gbTIKza/tgpMuG1k3U/UMJLWecIMxNdJFDMzcM5LOiLVRYh3PilWEYDIeUDv7bpiHPLPsbydGcw=="],
"electron/@types/node": ["@types/node@24.10.13", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
"mdast-util-find-and-replace/escape-string-regexp": ["[email protected]", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
@@ -1423,6 +1423,8 @@
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
"electron/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
}
}
+5 -1
View File
@@ -20,6 +20,9 @@
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
"fmt": "oxfmt",
"build:contracts": "turbo run build --filter=@t3tools/contracts",
"dist:desktop:dmg": "node scripts/build-desktop-dmg.mjs",
"dist:desktop:dmg:arm64": "node scripts/build-desktop-dmg.mjs --arch arm64",
"dist:desktop:dmg:x64": "node scripts/build-desktop-dmg.mjs --arch x64",
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo",
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
},
@@ -31,7 +34,8 @@
"vitest": "^4.0.0"
},
"engines": {
"bun": ">=1.3.9"
"bun": "^1.3.9",
"node": "^24.13.1"
},
"packageManager": "[email protected]"
}
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { appSettingsSchema, appSettingsUpdateInputSchema } from "./appSettings";
describe("appSettings schemas", () => {
it("applies defaults for codex paths", () => {
expect(appSettingsSchema.parse({})).toEqual({
codexBinaryPath: "",
codexHomePath: "",
});
});
it("trims codex path overrides in updates", () => {
expect(
appSettingsUpdateInputSchema.parse({
codexBinaryPath: " /opt/codex/bin/codex ",
codexHomePath: " /Users/alice/.codex ",
}),
).toEqual({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "/Users/alice/.codex",
});
});
});
+14
View File
@@ -0,0 +1,14 @@
import { z } from "zod";
export const appSettingsSchema = z.object({
codexBinaryPath: z.string().trim().max(4096).default(""),
codexHomePath: z.string().trim().max(4096).default(""),
});
export const appSettingsUpdateInputSchema = z.object({
codexBinaryPath: z.string().trim().max(4096).optional(),
codexHomePath: z.string().trim().max(4096).optional(),
});
export type AppSettings = z.infer<typeof appSettingsSchema>;
export type AppSettingsUpdateInput = z.input<typeof appSettingsUpdateInputSchema>;
+1
View File
@@ -1,4 +1,5 @@
export * from "./todo";
export * from "./appSettings";
export * from "./ipc";
export * from "./agent";
export * from "./terminal";
+5 -6
View File
@@ -1,4 +1,5 @@
import type { AgentConfig, AgentExit, OutputChunk } from "./agent";
import type { AppSettings, AppSettingsUpdateInput } from "./appSettings";
import type {
GitCheckoutInput,
GitCreateBranchInput,
@@ -47,8 +48,6 @@ import type {
StateCatchUpInput,
StateCatchUpResult,
StateEvent,
StateImportLegacyRendererStateInput,
StateImportLegacyRendererStateResult,
StateListMessagesInput,
StateListMessagesResult,
ThreadsCreateInput,
@@ -128,14 +127,14 @@ export interface NativeApi {
bootstrap: () => Promise<StateBootstrapResult>;
listMessages: (input: StateListMessagesInput) => Promise<StateListMessagesResult>;
catchUp: (input: StateCatchUpInput) => Promise<StateCatchUpResult>;
importLegacyRendererState: (
input: StateImportLegacyRendererStateInput,
) => Promise<StateImportLegacyRendererStateResult>;
onEvent: (callback: (event: StateEvent) => void) => () => void;
};
appSettings: {
get: () => Promise<AppSettings>;
update: (input: AppSettingsUpdateInput) => Promise<AppSettings>;
};
threads: {
create: (input: ThreadsCreateInput) => Promise<ThreadsUpdateResult>;
update: (input: ThreadsUpdateTerminalStateInput) => Promise<ThreadsUpdateResult>;
delete: (input: ThreadsDeleteInput) => Promise<void>;
markVisited: (input: ThreadsMarkVisitedInput) => Promise<ThreadsUpdateResult>;
updateTerminalState: (input: ThreadsUpdateTerminalStateInput) => Promise<ThreadsUpdateResult>;
+22
View File
@@ -39,6 +39,28 @@ describe("providerSessionStartInputSchema", () => {
}),
).toThrow();
});
it("accepts optional codex binary and home path overrides", () => {
const parsed = providerSessionStartInputSchema.parse({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "/Users/theo/.codex",
});
expect(parsed.codexBinaryPath).toBe("/opt/codex/bin/codex");
expect(parsed.codexHomePath).toBe("/Users/theo/.codex");
});
it("rejects blank codex overrides", () => {
expect(() =>
providerSessionStartInputSchema.parse({
codexBinaryPath: " ",
}),
).toThrow();
expect(() =>
providerSessionStartInputSchema.parse({
codexHomePath: " ",
}),
).toThrow();
});
});
describe("providerSendTurnInputSchema", () => {
+2
View File
@@ -51,6 +51,8 @@ export const providerSessionStartInputSchema = z.object({
cwd: z.string().min(1).optional(),
model: z.string().trim().min(1).optional(),
resumeThreadId: z.string().trim().min(1).optional(),
codexBinaryPath: z.string().trim().min(1).optional(),
codexHomePath: z.string().trim().min(1).optional(),
approvalPolicy: providerApprovalPolicySchema.default("never"),
sandboxMode: providerSandboxModeSchema.default("workspace-write"),
});
+1 -26
View File
@@ -3,7 +3,6 @@ import { describe, expect, it } from "vitest";
import {
stateBootstrapResultSchema,
stateCatchUpInputSchema,
stateImportLegacyRendererStateInputSchema,
stateListMessagesInputSchema,
stateListMessagesResultSchema,
stateMessageSchema,
@@ -114,32 +113,8 @@ describe("state schemas", () => {
expect(listInput.limit).toBe(200);
});
it("parses state catch-up and legacy import payloads", () => {
it("parses state catch-up payloads", () => {
const catchUp = stateCatchUpInputSchema.parse({});
expect(catchUp.afterSeq).toBe(0);
const legacyImport = stateImportLegacyRendererStateInputSchema.parse({
projects: [
{
id: "project-1",
name: "repo",
cwd: "/repo",
scripts: [],
createdAt: "2026-02-19T00:00:00.000Z",
updatedAt: "2026-02-19T00:00:00.000Z",
},
],
threads: [
{
id: "thread-1",
projectId: "project-1",
title: "Thread",
model: "gpt-5-codex",
createdAt: "2026-02-19T00:00:00.000Z",
messages: [],
},
],
});
expect(legacyImport.projects).toHaveLength(1);
});
});
-57
View File
@@ -193,57 +193,6 @@ export const threadsUpdateResultSchema = z.object({
thread: stateThreadSchema,
});
export const stateLegacyRendererProjectSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
cwd: z.string().min(1),
scripts: z.array(projectScriptSchema).default([]),
createdAt: z.string().datetime().optional(),
updatedAt: z.string().datetime().optional(),
});
export const stateLegacyRendererMessageSchema = z.object({
id: z.string().min(1),
role: z.enum(["user", "assistant"]),
text: z.string(),
attachments: z.array(stateMessageAttachmentSchema).optional(),
createdAt: z.string().datetime(),
streaming: z.boolean().default(false),
});
export const stateLegacyRendererThreadSchema = z.object({
id: z.string().min(1),
codexThreadId: z.string().min(1).nullable().default(null),
projectId: z.string().min(1),
title: z.string().min(1),
model: z.string().min(1),
terminalOpen: z.boolean().default(false),
terminalHeight: z.number().int().min(120).max(4_096).default(STATE_DEFAULT_TERMINAL_HEIGHT),
terminalIds: z
.array(z.string().trim().min(1))
.max(4)
.default([STATE_DEFAULT_TERMINAL_ID]),
activeTerminalId: z.string().trim().min(1).default(STATE_DEFAULT_TERMINAL_ID),
terminalGroups: z.array(stateThreadTerminalGroupSchema).default([]),
activeTerminalGroupId: z.string().trim().min(1).optional(),
messages: z.array(stateLegacyRendererMessageSchema).default([]),
createdAt: z.string().datetime(),
lastVisitedAt: z.string().datetime().optional(),
branch: z.string().min(1).nullable().optional(),
worktreePath: z.string().min(1).nullable().optional(),
turnDiffSummaries: z.array(stateTurnSummarySchema).default([]),
});
export const stateImportLegacyRendererStateInputSchema = z.object({
projects: z.array(stateLegacyRendererProjectSchema),
threads: z.array(stateLegacyRendererThreadSchema),
});
export const stateImportLegacyRendererStateResultSchema = z.object({
imported: z.boolean(),
alreadyImported: z.boolean(),
});
export type StateThreadTerminalGroup = z.infer<typeof stateThreadTerminalGroupSchema>;
export type StateMessageImageAttachment = z.infer<typeof stateMessageImageAttachmentSchema>;
export type StateMessageAttachment = z.infer<typeof stateMessageAttachmentSchema>;
@@ -267,9 +216,3 @@ export type ThreadsMarkVisitedInput = z.input<typeof threadsMarkVisitedInputSche
export type ThreadsUpdateBranchInput = z.input<typeof threadsUpdateBranchInputSchema>;
export type ThreadsUpdateTerminalStateInput = z.input<typeof threadsUpdateTerminalStateInputSchema>;
export type ThreadsUpdateResult = z.infer<typeof threadsUpdateResultSchema>;
export type StateImportLegacyRendererStateInput = z.input<
typeof stateImportLegacyRendererStateInputSchema
>;
export type StateImportLegacyRendererStateResult = z.infer<
typeof stateImportLegacyRendererStateResultSchema
>;
+10
View File
@@ -0,0 +1,10 @@
import { describe, expect, it } from "vitest";
import { WS_METHODS } from "./ws";
describe("WS thread methods", () => {
it("exposes only canonical terminal state update method", () => {
expect(WS_METHODS.threadsUpdateTerminalState).toBe("threads.updateTerminalState");
expect("threadsUpdate" in WS_METHODS).toBe(false);
});
});
+2 -2
View File
@@ -7,11 +7,11 @@ export const WS_METHODS = {
stateBootstrap: "state.bootstrap",
stateListMessages: "state.listMessages",
stateCatchUp: "state.catchUp",
stateImportLegacyRendererState: "state.importLegacyRendererState",
appSettingsGet: "appSettings.get",
appSettingsUpdate: "appSettings.update",
// Thread methods
threadsCreate: "threads.create",
threadsUpdate: "threads.update",
threadsDelete: "threads.delete",
threadsMarkVisited: "threads.markVisited",
threadsUpdateTerminalState: "threads.updateTerminalState",
+343
View File
@@ -0,0 +1,343 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, "..");
const PRODUCTION_ICON_SOURCE = path.join(repoRoot, "assets/macos-icon-1024.png");
const ARCH_CHOICES = new Set(["arm64", "x64", "universal"]);
function printUsage() {
console.log(`Build a shareable macOS .dmg for T3 Code desktop.
Usage:
node scripts/build-desktop-dmg.mjs [options]
Options:
--arch <arm64|x64|universal> Target arch (default: host arch if supported)
--version <semver> App version in DMG metadata (default: apps/server version)
--output-dir <path> Output folder for final artifacts (default: release)
--skip-build Skip 'bun run build:desktop' (requires existing dist artifacts)
--keep-stage Keep temporary staging directory
--signed Allow automatic code signing discovery
--help Show this message
`);
}
function fail(message) {
console.error(`[desktop-dmg] ${message}`);
process.exit(1);
}
function parseArgs(argv) {
const defaultArch = process.arch === "arm64" || process.arch === "x64" ? process.arch : "arm64";
const options = {
arch: defaultArch,
version: null,
skipBuild: false,
keepStage: false,
signed: false,
outputDir: path.join(repoRoot, "release"),
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === "--help") {
options.help = true;
continue;
}
if (arg === "--skip-build") {
options.skipBuild = true;
continue;
}
if (arg === "--keep-stage") {
options.keepStage = true;
continue;
}
if (arg === "--signed") {
options.signed = true;
continue;
}
if (arg === "--arch" || arg === "--version" || arg === "--output-dir") {
const value = argv[i + 1];
if (!value || value.startsWith("--")) {
fail(`Missing value for ${arg}`);
}
i += 1;
if (arg === "--arch") options.arch = value;
if (arg === "--version") options.version = value;
if (arg === "--output-dir") options.outputDir = path.resolve(repoRoot, value);
continue;
}
fail(`Unknown argument: ${arg}`);
}
if (!ARCH_CHOICES.has(options.arch)) {
fail(`Invalid arch '${options.arch}'. Expected one of: ${Array.from(ARCH_CHOICES).join(", ")}`);
}
return options;
}
async function readJson(filePath) {
const raw = await fs.readFile(filePath, "utf8");
return JSON.parse(raw);
}
async function exists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
function run(command, args, { cwd, env = process.env, stdio = "inherit" } = {}) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
cwd,
env,
stdio,
});
child.on("error", reject);
child.on("exit", (code, signal) => {
if (signal) {
reject(new Error(`${command} exited via signal ${signal}`));
return;
}
if (code !== 0) {
reject(new Error(`${command} exited with code ${code}`));
return;
}
resolve();
});
});
}
async function generateMacIconSet(sourcePng, targetIcns, tmpRoot) {
const iconsetDir = path.join(tmpRoot, "icon.iconset");
await fs.mkdir(iconsetDir, { recursive: true });
const iconSizes = [16, 32, 128, 256, 512];
for (const size of iconSizes) {
await run(
"sips",
["-z", String(size), String(size), sourcePng, "--out", path.join(iconsetDir, `icon_${size}x${size}.png`)],
{ stdio: "ignore" },
);
const retinaSize = size * 2;
await run(
"sips",
[
"-z",
String(retinaSize),
String(retinaSize),
sourcePng,
"--out",
path.join(iconsetDir, `icon_${size}x${size}@2x.png`),
],
{ stdio: "ignore" },
);
}
await run("iconutil", ["-c", "icns", iconsetDir, "-o", targetIcns], { stdio: "ignore" });
}
async function stageProductionIcons(stageResourcesDir) {
if (!(await exists(PRODUCTION_ICON_SOURCE))) {
fail(`Production icon source is missing at ${PRODUCTION_ICON_SOURCE}`);
}
const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "t3code-icon-build-"));
try {
const iconPngPath = path.join(stageResourcesDir, "icon.png");
const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
await run("sips", ["-z", "512", "512", PRODUCTION_ICON_SOURCE, "--out", iconPngPath], {
stdio: "ignore",
});
await generateMacIconSet(PRODUCTION_ICON_SOURCE, iconIcnsPath, tmpRoot);
} finally {
await fs.rm(tmpRoot, { recursive: true, force: true });
}
}
async function validateBundledClientAssets(clientDir) {
const indexPath = path.join(clientDir, "index.html");
const indexHtml = await fs.readFile(indexPath, "utf8");
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map((match) => match[1]);
const missing = [];
for (const ref of refs) {
const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
if (!normalizedRef) continue;
if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
const ext = path.extname(normalizedRef);
if (!ext) continue;
const relativePath = normalizedRef.replace(/^\/+/, "");
const assetPath = path.join(clientDir, relativePath);
if (!(await exists(assetPath))) {
missing.push(normalizedRef);
}
}
if (missing.length > 0) {
const preview = missing.slice(0, 6).join(", ");
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
fail(
`Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
);
}
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
printUsage();
return;
}
if (process.platform !== "darwin") {
fail("This script only builds macOS .dmg artifacts and must run on macOS.");
}
const desktopPkg = await readJson(path.join(repoRoot, "apps/desktop/package.json"));
const serverPkg = await readJson(path.join(repoRoot, "apps/server/package.json"));
const electronVersion = desktopPkg.dependencies?.electron;
if (typeof electronVersion !== "string" || electronVersion.length === 0) {
fail("Could not resolve apps/desktop electron dependency version.");
}
const dependencies = serverPkg.dependencies;
if (!dependencies || Object.keys(dependencies).length === 0) {
fail("Could not resolve production dependencies from apps/server/package.json.");
}
const appVersion = options.version ?? serverPkg.version ?? "0.1.0";
const stageRoot = path.join(os.tmpdir(), "t3code-desktop-dmg-stage");
const stageAppDir = path.join(stageRoot, "app");
const distDirs = {
desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
desktopResources: path.join(repoRoot, "apps/desktop/resources"),
serverDist: path.join(repoRoot, "apps/server/dist"),
};
const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
if (!options.skipBuild) {
console.log("[desktop-dmg] Building desktop/server/web artifacts...");
await run("bun", ["run", "build:desktop"], { cwd: repoRoot });
}
for (const [label, dir] of Object.entries(distDirs)) {
if (!(await exists(dir))) {
fail(`Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`);
}
}
if (!(await exists(bundledClientEntry))) {
fail(
`Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
);
}
await validateBundledClientAssets(path.dirname(bundledClientEntry));
await fs.rm(stageRoot, { recursive: true, force: true });
await fs.mkdir(path.join(stageAppDir, "apps/desktop"), { recursive: true });
await fs.mkdir(path.join(stageAppDir, "apps/server"), { recursive: true });
console.log("[desktop-dmg] Staging release app...");
await fs.cp(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"), {
recursive: true,
});
await fs.cp(distDirs.desktopResources, path.join(stageAppDir, "apps/desktop/resources"), {
recursive: true,
});
await fs.cp(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"), { recursive: true });
await stageProductionIcons(path.join(stageAppDir, "apps/desktop/resources"));
const stagePackageJson = {
name: "t3-code-desktop",
version: appVersion,
private: true,
description: "T3 Code desktop build",
author: "T3 Tools",
main: "apps/desktop/dist-electron/main.js",
build: {
appId: "com.t3tools.t3code",
productName: desktopPkg.productName ?? "T3 Code",
artifactName: "T3-Code-${version}-${arch}.${ext}",
directories: {
buildResources: "apps/desktop/resources",
},
mac: {
target: ["dmg"],
icon: "icon.icns",
category: "public.app-category.developer-tools",
},
},
dependencies,
devDependencies: {
electron: electronVersion,
},
};
await fs.writeFile(
path.join(stageAppDir, "package.json"),
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
"utf8",
);
console.log("[desktop-dmg] Installing staged production dependencies...");
await run("bun", ["install", "--production"], { cwd: stageAppDir });
const buildEnv = {
...process.env,
};
if (!options.signed) {
buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
}
const buildArgs = ["--bun", "electron-builder", "--mac", "dmg", `--${options.arch}`];
console.log(`[desktop-dmg] Building .dmg (arch=${options.arch}, version=${appVersion})...`);
await run("bunx", buildArgs, { cwd: stageAppDir, env: buildEnv });
const stageDistDir = path.join(stageAppDir, "dist");
const stageFiles = await fs.readdir(stageDistDir);
const dmgFiles = stageFiles.filter((file) => file.endsWith(".dmg"));
if (dmgFiles.length === 0) {
fail(`Build completed but no .dmg found in ${stageDistDir}`);
}
await fs.mkdir(options.outputDir, { recursive: true });
const copiedArtifacts = [];
for (const file of stageFiles) {
if (!file.endsWith(".dmg") && !file.endsWith(".dmg.blockmap")) continue;
const from = path.join(stageDistDir, file);
const to = path.join(options.outputDir, file);
await fs.copyFile(from, to);
copiedArtifacts.push(to);
}
if (!options.keepStage) {
await fs.rm(stageRoot, { recursive: true, force: true });
}
console.log("[desktop-dmg] Done. Artifacts:");
for (const artifact of copiedArtifacts) {
console.log(` - ${artifact}`);
}
}
main().catch((error) => {
const message = error instanceof Error ? error.message : String(error);
fail(message);
});