Compare commits

...
Author SHA1 Message Date
Cursor Agent ab955ddbb9 Fix terminal state infinite loop, test ordering assertion, and redundant updateBranch call
- ChatView: Stabilize terminalIds/terminalGroups dependencies by using
  JSON.stringify so React compares by value instead of reference, preventing
  an infinite write loop when normalizeThreadTerminals creates new arrays.
- persistenceService.test: Fix catchUp ordering assertion to compare each
  event's seq against the previous event's seq instead of itself.
- BranchToolbar: Remove redundant api.threads.updateBranch call since the
  useEffect in ChatView already syncs branch changes to the server.
2026-02-20 00:29:10 +00:00
Julius Marminge 384878a3f1 Move app state persistence to centralized SQLite service
- Add server-side `PersistenceService` backed by SQLite with migrations and tests
- Introduce shared state contracts/events and wire WebSocket bootstrap/catch-up flows
- Migrate project/thread/message persistence from renderer-local state to server-managed state
- Store turn diff summaries from checkpoint diffs for faster thread metadata rendering
2026-02-19 16:13:48 -08:00
Julius Marminge bf9f653331 Adopt JSON-first document schema in SQLite persistence plan
- Replace normalized table proposal with a `documents` envelope + `data_json` model
- Update indexing, migration phases, test scope, and done criteria for document-based persistence
- Add schema-versioning and JSON shape drift mitigations
2026-02-19 01:28:02 -08:00
Julius Marminge e7e289f4ba Document centralized SQLite persistence revamp plan
- Add plan 11 detailing migration of core durable state to `~/.t3/state.sqlite`
- Define architecture, schema, migration phases, and testing strategy
- Update `.plans/README.md` to include the new plan entry
2026-02-19 01:10:49 -08:00
27 changed files with 4221 additions and 392 deletions

No files matched your search

@@ -0,0 +1,482 @@
# Plan: Centralize Core Persistence in SQLite (`~/.t3/state.sqlite`)
## Summary
Move durable core app state out of renderer `localStorage` and into a centralized SQLite database at `~/.t3/state.sqlite`, while keeping machine-level editable config in JSON (keybindings) and browser UX preferences in browser-scoped state by default.
This plan preserves existing checkpoint patch storage in Git (`refs/t3/checkpoints/...`) and adds optional checkpoint diff summaries in SQLite (parsed via `@pierre/diffs`) for fast UI metadata rendering.
Core migration goals:
1. Data persistence scalability.
2. Move as much logic and state control as possible to the server, keeping the frontend simple.
## Why This Revamp
Current persistence is split across multiple stores:
- Renderer core state in `apps/web/src/store.ts` (`localStorage`, key `t3code:renderer-state:v7`)
- Server project registry in `~/.t3/userdata/projects.json` (`apps/server/src/projectRegistry.ts`)
- Provider thread event logs in `.logs/threads/*.events.ndjson` (`apps/server/src/providerManager.ts`)
- Terminal history in `.logs/terminals/*.log` (`apps/server/src/terminalManager.ts`)
- Keybindings in `~/.t3/keybindings.json` (`apps/server/src/keybindings.ts`)
This produces a split-brain model (client-local canonical thread/message state, server-local provider runtime state), weak multi-window consistency, and fragile reconnect/restart behavior.
## Goals
1. Make SQLite the canonical durable store for core app entities:
- projects
- threads
- messages
- turn/checkpoint diff metadata (summary only)
2. Keep checkpoint patch contents in Git only.
3. Keep machine-level editable config in JSON files (keybindings), and keep browser UX preferences browser-scoped by default.
4. Make server authoritative for durable state; client becomes a cache/subscriber.
5. Support reliable reconnect/catch-up without `localStorage`.
## Non-Goals
1. Replacing Git checkpoint storage with DB blob storage.
2. Persisting raw terminal output into SQLite (keep file-based terminal history for now).
3. Supporting provider implementations beyond current Codex flow in this revamp.
4. Full event-sourcing rewrite of all UI state in v1.
## Data Classification and Storage Policy
| Data class | Examples | Store | Notes |
| --- | --- | --- | --- |
| Core durable app data | projects, threads, messages, thread metadata, turn summaries | SQLite (`~/.t3/state.sqlite`) | Canonical source of truth |
| Checkpoint patch content | unified diff between checkpoints | Git refs (`refs/t3/checkpoints/...`) | Existing `FilesystemCheckpointStore` remains |
| Checkpoint metadata | changed files, +/- per file, checkpoint turn mapping | SQLite | Derived from Git diff + `@pierre/diffs` |
| Machine-level editable config | keybindings | `~/.t3/keybindings.json` | Existing behavior, stays human-editable |
| Browser-scoped UX preferences | theme, preferred editor, last-invoked script by project | Browser storage (currently `localStorage`) | Not canonical app data; per-browser behavior |
| Volatile runtime state | active websocket connections, in-flight turn status, pending approvals | Memory | Rebuilt from runtime/provider events |
## Preference Scope Clarification
1. `project.scripts` belongs to core app data and is persisted in SQLite with the project record.
2. `script preference` means UX memory only, specifically the current `t3code:last-invoked-script-by-project` map used to preselect/run convenience actions.
3. Theme/editor/script-preference keys are per-browser UX and are intentionally separate from shared project/thread/message data.
4. Runtime mode default (`full-access` vs `approval-required`) should be treated as UX preference by default unless we explicitly decide it is a machine policy.
## Current vs Target Architecture
### Current (simplified)
```mermaid
flowchart LR
UI[apps/web] -->|ws rpc + push| WS[apps/server/wsServer]
UI -->|localStorage| LS[(Browser localStorage)]
WS --> PR[ProjectRegistry]
PR --> PJ[projects.json]
WS --> PM[ProviderManager]
PM --> CASM[CodexAppServerManager]
CASM --> C[codex app-server]
PM --> TL[thread .ndjson logs]
PM --> FCS[FilesystemCheckpointStore]
FCS --> GIT[(Git refs/t3/checkpoints)]
```
### Target
```mermaid
flowchart LR
UI[apps/web] -->|ws rpc + push| WS[apps/server/wsServer]
WS --> PS[PersistenceService]
PS --> DB[(~/.t3/state.sqlite)]
WS --> CFG[Keybinding Config]
CFG --> JSON[(~/.t3/keybindings.json)]
UI --> BSTATE[(Browser UX prefs)]
WS --> PM[ProviderManager]
PM --> CASM[CodexAppServerManager]
CASM --> C[codex app-server]
PM --> FCS[FilesystemCheckpointStore]
FCS --> GIT[(Git refs/t3/checkpoints)]
PM --> PS
PS -->|state push| WS
```
Provider remains the runtime execution engine. PersistenceService becomes the durable state authority and broadcaster.
## Core Domain Model (SQLite)
Use strict schema + migrations (e.g. `PRAGMA user_version` or migration table), WAL mode, and transactional writes.
### JSON-first (iteration-friendly) schema
Use a document-style core table with a minimal indexed envelope. Put evolving entity fields in `data_json`.
1. `documents`
- `id TEXT PRIMARY KEY`
- examples: `project:<uuid>`, `thread:<uuid>`, `message:<uuid>`, `turn_summary:<threadId>:<turnId>`
- `kind TEXT NOT NULL`
- `project` | `thread` | `message` | `turn_summary`
- `project_id TEXT NULL`
- `thread_id TEXT NULL`
- `sort_key INTEGER NULL`
- message order, thread ordering hints, summary ordering, etc.
- `schema_version INTEGER NOT NULL DEFAULT 1`
- `created_at TEXT NOT NULL`
- `updated_at TEXT NOT NULL`
- `data_json TEXT NOT NULL`
2. `provider_events`
- `seq INTEGER PRIMARY KEY AUTOINCREMENT`
- `id TEXT NOT NULL UNIQUE`
- `session_id TEXT NOT NULL`
- `provider TEXT NOT NULL`
- `kind TEXT NOT NULL`
- `method TEXT NOT NULL`
- `thread_id TEXT NULL`
- `turn_id TEXT NULL`
- `item_id TEXT NULL`
- `request_id TEXT NULL`
- `request_kind TEXT NULL`
- `text_delta TEXT NULL`
- `message TEXT NULL`
- `payload_json TEXT NULL`
- `created_at TEXT NOT NULL`
3. `state_events`
- `seq INTEGER PRIMARY KEY AUTOINCREMENT`
- `event_type TEXT NOT NULL` (e.g. `project.upsert`, `thread.delete`, `message.upsert`)
- `entity_id TEXT NOT NULL`
- `payload_json TEXT NOT NULL`
- `created_at TEXT NOT NULL`
4. `metadata`
- `key TEXT PRIMARY KEY`
- `value_json TEXT NOT NULL`
- for one-time migrations/import markers
### Envelope indexes
- `documents(kind)`
- `documents(project_id, kind)`
- `documents(thread_id, kind, sort_key)`
- `documents(kind, updated_at DESC)`
- `provider_events(session_id, seq)`
- `provider_events(thread_id, seq)`
- `state_events(seq)`
### Document conventions
1. Validate each `kind` with Zod before writes and after reads.
2. Keep envelope fields stable (`kind`, `project_id`, `thread_id`, `sort_key`) for fast list/filter queries.
3. Put fast-changing/evolving structure in `data_json`:
- project: name/cwd/model/expanded/scripts
- thread: title/model/codex thread id/terminal layout/branch/worktree
- message: role/text/attachments/streaming/provider ids
- turn_summary: completed/status/checkpoint turn count/file +/- summary
4. Use `schema_version` per document to support incremental document migrations without global table churn.
### Normalization runway (later, optional)
When model shapes stabilize, we can materialize normalized tables from `documents` without changing the external protocol:
1. Add typed read models (`projects_v2`, `messages_v2`, etc.).
2. Backfill from `documents`.
3. Switch read paths gradually.
## Streaming Protocol and Synchronization
Keep current WS request/response envelope and push model. Extend with state snapshot + patch stream.
### New/extended WS methods
1. `state.bootstrap`
- returns complete durable snapshot for initial render:
- projects (+scripts)
- threads (+terminal metadata + turn summaries)
- messages (+attachments), optionally capped per thread then paged
- `lastStateSeq`
2. `state.listMessages` (paged)
- for large threads and virtualized history
3. `threads.create`
4. `threads.update`
5. `threads.delete`
6. `threads.markVisited`
7. `threads.updateTerminalState`
8. `threads.updateModel`
9. `threads.updateTitle`
10. `state.catchUp`
- input: `afterSeq`
- returns ordered `state_events` for reconnect recovery
Existing `projects.*`, `providers.*`, `terminal.*`, `git.*`, `server.*` remain; they route through persistence-aware services.
### Push channels
1. Keep `providers.event` for raw runtime/provider telemetry.
2. Add `state.event` for canonical persisted mutations (`seq` ordered).
3. Keep `terminal.event` and `server.welcome`.
### Ordering guarantees
- Every durable mutation writes `state_events` in the same DB transaction as row changes.
- Server broadcasts `state.event` after commit.
- Clients apply events strictly by `seq`.
- Reconnect uses `state.catchUp(afterSeq)` to fill gaps.
## Core App Flows
### 1) Startup + hydration
```mermaid
sequenceDiagram
participant UI as Web Client
participant WS as wsServer
participant PS as PersistenceService
participant DB as SQLite
UI->>WS: connect websocket
WS-->>UI: push server.welcome
UI->>WS: state.bootstrap()
WS->>PS: loadSnapshot()
PS->>DB: SELECT projects/threads/messages/metadata
DB-->>PS: snapshot + lastStateSeq
PS-->>WS: bootstrap payload
WS-->>UI: response(snapshot)
UI->>WS: subscribe state.event/providers.event
```
### 2) Create thread
```mermaid
sequenceDiagram
participant UI
participant WS
participant PS
participant DB
UI->>WS: threads.create(projectId, model, title, branch,...)
WS->>PS: createThread(...)
PS->>DB: INSERT thread + terminal defaults + state_event
DB-->>PS: committed row + seq
PS-->>WS: thread
WS-->>UI: response(thread)
WS-->>UI: push state.event(thread.upsert, seq)
```
### 3) Send turn + stream + persist
```mermaid
sequenceDiagram
participant UI
participant WS
participant PM as ProviderManager
participant CASM as CodexAppServerManager
participant Codex as codex app-server
participant PS as PersistenceService
participant DB as SQLite
UI->>WS: providers.startSession(threadId, resumeThreadId?)
WS->>PM: startSession(...)
PM->>CASM: thread/start or thread/resume
CASM->>Codex: JSON-RPC
Codex-->>CASM: notifications/events
CASM-->>PM: ProviderEvent
PM-->>PS: ingestProviderEvent(event)
PS->>DB: INSERT provider_events + projection updates + state_event
DB-->>PS: seq
PM-->>WS: provider event
WS-->>UI: push providers.event
WS-->>UI: push state.event
UI->>WS: providers.sendTurn(sessionId, input, attachments)
WS->>PM: sendTurn(...)
PM->>CASM: turn/start
CASM->>Codex: JSON-RPC
```
### 4) Checkpoint capture + diff summary
```mermaid
sequenceDiagram
participant PM as ProviderManager
participant FCS as FilesystemCheckpointStore
participant G as Git refs/t3/checkpoints
participant PS as PersistenceService
participant DB as SQLite
participant WS as wsServer
participant UI as Web Client
PM->>FCS: captureCheckpoint(threadId, turnCount)
FCS->>G: update-ref refs/t3/checkpoints/...
PM->>FCS: diffCheckpoints(turnCount-1, turnCount)
FCS-->>PM: unified patch
PM->>PS: persistTurnDiffSummary(turnId, patch)
PS->>PS: parse patch with @pierre/diffs
PS->>DB: upsert thread_turn_summaries + thread_turn_diff_files + state_event
DB-->>PS: seq
PS-->>WS: state.event(turn summary upsert)
WS-->>UI: push state.event
```
## Provider Role in the New Model
Provider components are unchanged in purpose, but persistence boundaries become explicit:
1. `CodexAppServerManager`
- runtime bridge to `codex app-server`
- emits provider events
- no direct durability ownership
2. `ProviderManager`
- session lifecycle + checkpoint orchestration
- forwards provider events to:
- websocket push (`providers.event`)
- persistence projection (`PersistenceService`)
3. `PersistenceService` (new)
- canonicalizes thread/message state
- stores provider event log
- stores turn summary metadata
- emits `state.event` patches
This cleanly separates runtime execution concerns from durable conversation state.
## Client Data Flow (Server -> Client)
### Current issue
- Web client computes and persists canonical messages/thread state locally (`reducer`, `applyEventToMessages`, `deriveTurnDiffSummaries`), so reconnect and multi-window consistency rely on localStorage.
### New flow
1. Client bootstraps from server (`state.bootstrap`) instead of localStorage hydration.
2. Client uses `state.event` as authoritative mutation stream.
3. Client may still use optimistic UI for latency, but server-issued canonical IDs/rows win.
4. `providers.event` remains for live UX details (in-progress deltas, approvals, lifecycle).
## Migration Plan
### A) Server-side source migrations
1. Introduce DB migration runner.
2. On startup, import `projects.json` into SQLite if present and not yet imported.
3. Preserve `projects.json` as backup:
- rename to `projects.json.bak.<timestamp>`
4. Keep keybindings migration path untouched (`~/.t3/keybindings.json` remains canonical).
### B) Client-side legacy state migration
1. Detect legacy localStorage keys:
- `t3code:renderer-state:v7` and legacy list in `apps/web/src/store.ts`
2. Add one-time method `state.importLegacyRendererState(payload)`.
3. Server validates and sanitizes payload with shared schema (port from `apps/web/src/persistenceSchema.ts` to contracts/server module).
4. Server upserts projects/threads/messages/terminal metadata into SQLite.
5. Server writes `metadata` marker to prevent duplicate imports.
6. Client clears legacy localStorage keys after successful import.
### C) Browser UX preference boundary
Default behavior: keep these browser-scoped and do not move them into SQLite or `~/.t3/*.json`:
- `t3code:theme`
- `t3code:last-editor`
- `t3code:last-invoked-script-by-project`
Optional future mode (not required for this revamp):
- Add server-backed preferences storage for users who want zero browser persistence.
## Implementation Phases
### Phase 0: Foundation
1. Add SQLite dependency and persistence modules:
- `apps/server/src/stateDb.ts`
- `apps/server/src/stateMigrations.ts`
- `apps/server/src/persistenceService.ts`
2. Add migration boot in `apps/server/src/index.ts`.
3. Update default state path to `~/.t3/state.sqlite` (with env override).
### Phase 1: Document store cut-in (projects + threads first)
1. Replace `ProjectRegistry` JSON backend with DB-backed document repository.
2. Add `threads.*` methods to server routes.
3. Keep web reducer but stop writing to localStorage for these entities.
### Phase 2: Message + turn document persistence
1. Ingest provider events into DB (`provider_events`).
2. Project events into `documents` rows for `message` and `turn_summary` kinds.
3. Add `state.event` push and `state.catchUp`.
### Phase 3: Web client cutover
1. Replace `readPersistedState()` boot path with `state.bootstrap`.
2. Remove `persistState()` localStorage writes for core state.
3. Keep only in-memory reducer/cache for volatile UI fields.
### Phase 4: Preference boundary hardening
1. Keep `~/.t3/keybindings.json` as the only required JSON config in this revamp.
2. Keep `theme` / `last-editor` / `last-invoked-script-by-project` browser-scoped (explicitly non-canonical).
3. Ensure no core entity (`projects`, `threads`, `messages`, turn summaries) is read from or written to browser storage.
### Phase 5: Cleanup + compatibility
1. Remove deprecated localStorage/persistence schema paths once migration is stable.
2. Keep temporary migration fallback for one release window.
3. (Optional) add a follow-up normalization milestone when schemas settle.
## Streaming/Projection Design Notes
1. Durable append:
- always append raw provider events first.
2. Projection:
- update message/thread projections in the same transaction when practical.
- if expensive, queue projection jobs but keep deterministic ordering by provider event `seq`.
3. Backpressure:
- avoid heavyweight diff parsing on hot delta path.
- compute checkpoint diff summaries only on checkpoint/turn completion.
## Reliability and Performance Settings
1. SQLite pragmas:
- `journal_mode=WAL`
- `synchronous=FULL` (or `NORMAL` only if validated under load)
- `busy_timeout=5000`
- `foreign_keys=ON`
2. Prepared statements for hot paths.
3. Batch/paginate message retrieval for large threads.
4. Add caps/retention for `provider_events` if DB growth becomes material.
## Testing Plan
Backend changes require new tests and runtime validation.
### Unit tests
1. DB schema + migrations
2. Document repository CRUD (`project`/`thread`/`message`/`turn_summary`)
3. Provider event projection logic
4. Checkpoint summary parser (`@pierre/diffs` integration and malformed diff fallback)
5. Keybindings JSON behavior remains unchanged (read/write + malformed-file handling)
### Integration tests (`wsServer`)
1. `state.bootstrap` returns canonical snapshot
2. `state.event` emits ordered `seq`
3. reconnect + `state.catchUp` replays missing events
4. `providers.event` + `state.event` coherence on a streamed turn
5. localStorage import endpoint idempotence
### Migration tests
1. `projects.json` import -> DB rows
2. localStorage v7 import -> DB rows
3. legacy payload rejection safety
### Frontend tests
1. store boot without localStorage core snapshot
2. reducer handling of `state.event` patches
3. fallback behavior when server unavailable
## Risks and Mitigations
1. Risk: Split writes between provider stream and DB create race conditions.
- Mitigation: single persistence ingestion queue per session/thread, transactional writes, monotonic `seq`.
2. Risk: Message duplication with optimistic UI.
- Mitigation: client-supplied message IDs echoed by server; idempotent upserts.
3. Risk: DB write amplification on text deltas.
- Mitigation: append-only provider event log + projection throttling/finalization.
4. Risk: migration corruption from malformed local data.
- Mitigation: strict schema validation + partial-row rejection + migration markers + backups.
5. Risk: checkpoint summary parsing overhead.
- Mitigation: parse only finalized checkpoint ranges and fallback to lightweight stat extraction.
6. Risk: JSON shape drift across fast iterations.
- Mitigation: per-kind Zod schemas + `schema_version` in documents + migration tests for older payloads.
## Done Criteria
1. No core durable app data depends on renderer localStorage.
2. Projects/threads/messages/turn summaries persist in `~/.t3/state.sqlite` via JSON-first documents.
3. Checkpoint patch content remains Git-backed; optional summaries are in DB.
4. Keybindings remain JSON-backed at `~/.t3/keybindings.json`.
5. Theme/editor/last-invoked-script remain browser-scoped (or explicitly migrated in a separate opt-in feature).
6. App reload/reconnect reconstructs state from server snapshot + event catch-up.
7. Lint/typecheck/tests pass across server/web/contracts.
## Concrete File Impact (Expected)
### Server
- `apps/server/src/index.ts` (state db path + bootstrap)
- `apps/server/src/wsServer.ts` (new state/thread routes + push channel)
- `apps/server/src/providerManager.ts` (persist event hooks + checkpoint summary writes)
- `apps/server/src/projectRegistry.ts` (replace or wrap with document-backed repo)
- new persistence modules (`stateDb`, migrations, document repository, persistence service)
### Web
- `apps/web/src/store.ts` (remove localStorage core persistence)
- `apps/web/src/persistenceSchema.ts` (migration-only use then eventual removal)
- `apps/web/src/routes/__root.tsx` (state bootstrap and catch-up wiring)
- `apps/web/src/wsNativeApi.ts` / contracts (new methods/channels)
- preference callsites remain browser-scoped by default (`useTheme`, editor/script preference keys)
### Contracts
- `packages/contracts/src/ws.ts` (new methods/channels)
- `packages/contracts/src/ipc.ts` (new NativeApi sections for state/threads)
- new schemas for thread/message/state-event payloads
## Open Questions
1. Should runtime mode (`full-access` vs `approval-required`) remain browser-scoped UX state, or be elevated to machine policy?
2. Should terminal panel layout/state be in SQLite (shared) or stay browser-scoped UX state?
3. Do we need provider event retention limits from day one?
4. Do we keep `.logs/threads/*.events.ndjson` as debug mirror after DB event log is live?
5. For non-desktop/browser mode, should state still centralize to `~/.t3/state.sqlite` or support workspace-local override by default?
+1
View File
@@ -10,3 +10,4 @@
8. `08-precommit-format-and-lint.md`
9. `09-event-state-test-expansion.md`
10. `10-unify-process-session-abstraction.md`
11. `11-centralized-sqlite-persistence-revamp.md`
+1
View File
@@ -17,6 +17,7 @@
"test": "vitest run"
},
"dependencies": {
"@pierre/diffs": "^1.1.0-beta.16",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
+17 -5
View File
@@ -6,7 +6,7 @@ import { fileURLToPath } from "node:url";
import { fixPath } from "./fixPath";
import { createLogger } from "./logger";
import { ProjectRegistry } from "./projectRegistry";
import { PersistenceService } from "./persistenceService";
import { createServer } from "./wsServer";
fixPath();
@@ -49,6 +49,13 @@ function resolveStateDir(raw: string | undefined): string {
return path.resolve(expandHomePath(raw.trim()));
}
function resolveStateDbPath(raw: string | undefined): string {
if (!raw || raw.trim().length === 0) {
return path.join(os.homedir(), ".t3", "state.sqlite");
}
return path.resolve(expandHomePath(raw.trim()));
}
async function findAvailablePort(preferred: number): Promise<number> {
return new Promise((resolve, reject) => {
const server = net.createServer();
@@ -101,8 +108,12 @@ async function main() {
const requestedPort = parsePort(process.env.T3CODE_PORT);
const port =
requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
const projectRegistry = new ProjectRegistry(stateDir);
const legacyStateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
const stateDbPath = resolveStateDbPath(process.env.T3CODE_STATE_DB_PATH);
const persistenceService = new PersistenceService({
dbPath: stateDbPath,
legacyProjectsJsonPath: path.join(legacyStateDir, "projects.json"),
});
const devUrl = process.env.VITE_DEV_SERVER_URL;
const noBrowser = parseBooleanEnv(process.env.T3CODE_NO_BROWSER) ?? mode === "desktop";
const authToken = process.env.T3CODE_AUTH_TOKEN;
@@ -120,7 +131,7 @@ async function main() {
cwd,
staticDir,
devUrl,
projectRegistry,
persistenceService,
authToken,
});
await server.start();
@@ -130,7 +141,8 @@ async function main() {
url,
cwd,
mode,
stateDir,
stateDbPath,
legacyStateDir,
authEnabled: Boolean(authToken),
});
+241
View File
@@ -0,0 +1,241 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import type { ProviderEvent } from "@t3tools/contracts";
import { PersistenceService } from "./persistenceService";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
function iso(offsetMs = 0): string {
return new Date(Date.now() + offsetMs).toISOString();
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("PersistenceService", () => {
it("persists projects/threads/messages and serves bootstrap + catch-up", () => {
const stateDir = makeTempDir("t3code-persistence-state-");
const projectDir = makeTempDir("t3code-persistence-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
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;
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",
};
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: {
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",
},
},
});
service.ingestProviderEvent({
...baseEvent,
id: "evt-4",
createdAt: iso(40),
method: "turn/completed",
turnId: "turn-1",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
});
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");
const catchUp = service.catchUp({ afterSeq: 0 });
expect(catchUp.events.length).toBeGreaterThan(0);
expect(
catchUp.events.every(
(event, index, events) => index === 0 || event.seq > events[index - 1]!.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);
service.close();
});
it("stores turn diff summaries parsed from checkpoint diffs", () => {
const stateDir = makeTempDir("t3code-persistence-diff-state-");
const projectDir = makeTempDir("t3code-persistence-diff-project-");
const service = new 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");
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.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-");
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,
});
const secondImport = service.importLegacyRendererState({
projects: [],
threads: [],
});
expect(secondImport).toEqual({
imported: false,
alreadyImported: true,
});
const snapshot = service.loadSnapshot();
expect(snapshot.projects).toHaveLength(1);
expect(snapshot.threads).toHaveLength(1);
expect(snapshot.threads[0]?.messages).toHaveLength(1);
service.close();
});
});
File diff suppressed because it is too large. Load diff
+4
View File
@@ -57,6 +57,8 @@ describe("ProjectRegistry scripts", () => {
expect(listed[0]?.scripts).toHaveLength(2);
expect(listed[0]?.scripts[0]?.id).toBe("run");
expect(listed[0]?.scripts[1]?.id).toBe("setup");
registry.close();
reloaded.close();
});
it("deduplicates script ids and allows only one setup script", () => {
@@ -97,6 +99,7 @@ describe("ProjectRegistry scripts", () => {
expect(updated.project.scripts[0]?.runOnWorktreeCreate).toBe(true);
expect(updated.project.scripts[1]?.id).toBe("another");
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(false);
registry.close();
});
it("throws when updating scripts for an unknown project id", () => {
@@ -109,5 +112,6 @@ describe("ProjectRegistry scripts", () => {
scripts: [],
}),
).toThrowError("Project not found");
registry.close();
});
});
+23 -211
View File
@@ -1,235 +1,47 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import {
type ProjectAddInput,
type ProjectAddResult,
type ProjectListResult,
type ProjectRecord,
type ProjectRemoveInput,
type ProjectScript,
type ProjectUpdateScriptsInput,
type ProjectUpdateScriptsResult,
normalizeProjectScripts,
projectAddInputSchema,
projectRecordSchema,
projectRemoveInputSchema,
projectScriptsSchema,
projectUpdateScriptsInputSchema,
import type {
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectRemoveInput,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
} from "@t3tools/contracts";
function cloneScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
const cloned: ProjectScript[] = [];
for (const script of scripts) {
cloned.push({
id: script.id,
name: script.name,
command: script.command,
icon: script.icon,
runOnWorktreeCreate: script.runOnWorktreeCreate,
});
}
return cloned;
}
function normalizeCwd(rawCwd: string): string {
const resolved = path.resolve(rawCwd.trim());
const normalized = path.normalize(resolved);
if (process.platform === "win32") {
return normalized.toLowerCase();
}
return normalized;
}
function isDirectory(cwd: string): boolean {
try {
return fs.statSync(cwd).isDirectory();
} catch {
return false;
}
}
function inferProjectName(cwd: string): string {
const name = path.basename(cwd);
return name.length > 0 ? name : "project";
}
import { PersistenceService } from "./persistenceService";
/**
* Backward-compatible wrapper retained for tests and legacy callsites.
* Core storage now lives in SQLite through PersistenceService.
*/
export class ProjectRegistry {
private readonly stateDir: string;
private readonly filePath: string;
private projects: ProjectRecord[];
private readonly persistenceService: PersistenceService;
constructor(stateDir: string) {
this.stateDir = stateDir;
this.filePath = path.join(this.stateDir, "projects.json");
fs.mkdirSync(this.stateDir, { recursive: true });
this.projects = this.loadFromDisk();
this.persistenceService = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
});
}
list(): ProjectListResult {
return this.projects.map((project) => ({
...project,
scripts: cloneScripts(project.scripts),
}));
return this.persistenceService.listProjects();
}
add(raw: ProjectAddInput): ProjectAddResult {
const input = projectAddInputSchema.parse(raw);
const normalizedCwd = normalizeCwd(input.cwd);
if (!isDirectory(normalizedCwd)) {
throw new Error(`Project path does not exist: ${normalizedCwd}`);
}
const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd);
if (existing) {
return {
project: {
...existing,
scripts: cloneScripts(existing.scripts),
},
created: false,
};
}
const now = new Date().toISOString();
const project: ProjectRecord = {
id: randomUUID(),
cwd: normalizedCwd,
name: inferProjectName(normalizedCwd),
scripts: [],
createdAt: now,
updatedAt: now,
};
this.projects = [project, ...this.projects];
this.persist();
return {
project: {
...project,
scripts: cloneScripts(project.scripts),
},
created: true,
};
return this.persistenceService.addProject(raw);
}
remove(raw: ProjectRemoveInput): void {
const input = projectRemoveInputSchema.parse(raw);
const next = this.projects.filter((project) => project.id !== input.id);
if (next.length === this.projects.length) {
return;
}
this.projects = next;
this.persist();
this.persistenceService.removeProject(raw);
}
updateScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
const input = projectUpdateScriptsInputSchema.parse(raw);
const index = this.projects.findIndex((project) => project.id === input.id);
if (index < 0) {
throw new Error(`Project not found: ${input.id}`);
}
const nextScripts = normalizeProjectScripts(projectScriptsSchema.parse(input.scripts));
const nextUpdatedAt = new Date().toISOString();
const nextProject: ProjectRecord = {
...this.projects[index]!,
scripts: nextScripts,
updatedAt: nextUpdatedAt,
};
const nextProjects = [...this.projects];
nextProjects[index] = nextProject;
this.projects = nextProjects;
this.persist();
return {
project: { ...nextProject, scripts: cloneScripts(nextProject.scripts) },
};
return this.persistenceService.updateProjectScripts(raw);
}
private loadFromDisk(): ProjectRecord[] {
const loaded = this.readPersistedProjects();
const deduped = new Map<string, ProjectRecord>();
const normalizedProjects: ProjectRecord[] = [];
for (const project of loaded) {
const normalizedCwd = normalizeCwd(project.cwd);
if (!isDirectory(normalizedCwd)) {
continue;
}
if (deduped.has(normalizedCwd)) {
continue;
}
const normalizedProject: ProjectRecord = {
...project,
cwd: normalizedCwd,
name:
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
scripts: normalizeProjectScripts(project.scripts),
};
deduped.set(normalizedCwd, normalizedProject);
normalizedProjects.push(normalizedProject);
}
const changed =
normalizedProjects.length !== loaded.length ||
normalizedProjects.some((project, index) => {
const source = loaded[index];
if (!source) return true;
return (
source.id !== project.id ||
source.cwd !== project.cwd ||
source.name !== project.name ||
JSON.stringify(source.scripts) !== JSON.stringify(project.scripts) ||
source.createdAt !== project.createdAt ||
source.updatedAt !== project.updatedAt
);
});
if (changed) {
this.projects = normalizedProjects;
this.persist();
}
return normalizedProjects;
}
private readPersistedProjects(): ProjectRecord[] {
try {
const raw = fs.readFileSync(this.filePath, "utf8");
const parsed = JSON.parse(raw) as { projects?: unknown };
if (!parsed || !Array.isArray(parsed.projects)) {
return [];
}
const projects: ProjectRecord[] = [];
for (const candidate of parsed.projects) {
const row = projectRecordSchema.safeParse(candidate);
if (!row.success) {
continue;
}
projects.push(row.data);
}
return projects;
} catch {
return [];
}
}
private persist(): void {
const payload = JSON.stringify(
{
version: 1,
projects: this.projects,
},
null,
2,
);
const tempFile = `${this.filePath}.tmp-${process.pid}-${Date.now()}`;
fs.writeFileSync(tempFile, payload);
fs.renameSync(tempFile, this.filePath);
close(): void {
this.persistenceService.close();
}
}
+78 -1
View File
@@ -31,6 +31,11 @@ import {
import type { CodexThreadTurnSnapshot } from "./codexAppServerManager";
import { CodexAppServerManager } from "./codexAppServerManager";
import { FilesystemCheckpointStore } from "./filesystemCheckpointStore";
import type { PersistenceService } from "./persistenceService";
export interface ProviderManagerOptions {
persistenceService?: PersistenceService | undefined;
}
export interface ProviderManagerEvents {
event: [event: ProviderEvent];
@@ -163,6 +168,7 @@ function buildCheckpoints(turns: CodexThreadTurnSnapshot[]): ProviderCheckpoint[
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
private readonly codex = new CodexAppServerManager();
private readonly filesystemCheckpointStore = new FilesystemCheckpointStore();
private readonly persistenceService: PersistenceService | undefined;
private readonly threadLogsDir: string;
private readonly threadLogStreams = new Map<string, fs.WriteStream>();
private readonly sessionThreadIds = new Map<string, string>();
@@ -176,12 +182,21 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
}
this.routeEventToThreadLog(event);
try {
this.persistenceService?.ingestProviderEvent(event);
} catch {
// Persistence failures should not break provider streaming.
}
if (event.method === "session/closed" || event.method === "session/exited") {
this.persistenceService?.unbindSession(event.sessionId);
}
this.emit("event", event);
this.maybeCaptureFilesystemCheckpoint(event);
};
constructor() {
constructor(options: ProviderManagerOptions = {}) {
super();
this.persistenceService = options.persistenceService;
const logsDir = path.resolve(process.cwd(), ".logs");
this.threadLogsDir = path.join(logsDir, "threads");
@@ -197,6 +212,17 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
}
const session = await this.codex.startSession(input);
if (input.threadId) {
try {
this.persistenceService?.bindSessionToThread(
session.sessionId,
input.threadId,
session.threadId ?? null,
);
} catch {
// Runtime session establishment should proceed even if persistence fails.
}
}
if (session.threadId) {
this.sessionThreadIds.set(session.sessionId, session.threadId);
this.flushPendingSessionEvents(session.sessionId, session.threadId);
@@ -215,6 +241,11 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
try {
this.persistenceService?.persistUserMessageForTurn(input);
} catch {
// User turn persistence is best-effort on runtime send.
}
return this.codex.sendTurn(input);
}
@@ -239,6 +270,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
stopSession(raw: ProviderStopSessionInput): void {
const input = providerStopSessionInputSchema.parse(raw);
this.codex.stopSession(input.sessionId);
this.persistenceService?.unbindSession(input.sessionId);
this.sessionThreadIds.delete(input.sessionId);
this.pendingEventsBySession.delete(input.sessionId);
this.sessionCheckpointCwds.delete(input.sessionId);
@@ -483,6 +515,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
return;
}
const snapshot = await this.codex.readThread(event.sessionId);
await this.persistCheckpointSummaryForTurn(event, initializedCwd, snapshot.threadId, snapshot.turns);
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
})
.catch((error) => {
@@ -504,6 +537,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
await this.persistCheckpointSummaryForTurn(event, checkpointCwd, snapshot.threadId, snapshot.turns);
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
}).catch((error) => {
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
@@ -639,4 +673,47 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
this.threadLogStreams.set(threadId, stream);
return stream;
}
private async persistCheckpointSummaryForTurn(
event: ProviderEvent,
cwd: string,
runtimeThreadId: string,
turns: CodexThreadTurnSnapshot[],
): Promise<void> {
if (!this.persistenceService) {
return;
}
if (turns.length === 0) {
return;
}
const toTurnCount = turns.length;
const fromTurnCount = Math.max(0, toTurnCount - 1);
let diff = "";
try {
diff = await this.filesystemCheckpointStore.diffCheckpoints({
cwd,
threadId: runtimeThreadId,
fromTurnCount,
toTurnCount,
});
} catch {
return;
}
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
const latestTurn = turns[toTurnCount - 1];
const turnId = asString(turn?.id) ?? latestTurn?.id ?? null;
const status = asString(turn?.status);
this.persistenceService.persistTurnDiffSummaryFromCheckpoint({
sessionId: event.sessionId,
runtimeThreadId,
turnId,
checkpointTurnCount: toTurnCount,
completedAt: event.createdAt,
...(status ? { status } : {}),
diff,
});
}
}
+46
View File
@@ -0,0 +1,46 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { StateDb } from "./stateDb";
import { STATE_DB_SCHEMA_VERSION } from "./stateMigrations";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("StateDb", () => {
it("creates the SQLite schema and applies migrations", () => {
const tempDir = makeTempDir("t3code-state-db-");
const dbPath = path.join(tempDir, "state.sqlite");
const stateDb = new StateDb({ dbPath });
const tables = stateDb.db
.prepare("SELECT name FROM sqlite_master WHERE type = 'table';")
.all() as Array<{ name: string }>;
const tableNames = new Set(tables.map((table) => table.name));
expect(tableNames.has("documents")).toBe(true);
expect(tableNames.has("provider_events")).toBe(true);
expect(tableNames.has("state_events")).toBe(true);
expect(tableNames.has("metadata")).toBe(true);
const userVersion = stateDb.db
.prepare("PRAGMA user_version;")
.get() as { user_version: number } | undefined;
expect(userVersion?.user_version).toBe(STATE_DB_SCHEMA_VERSION);
stateDb.close();
});
});
+37
View File
@@ -0,0 +1,37 @@
import fs from "node:fs";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import { runStateMigrations } from "./stateMigrations";
export interface StateDbOptions {
dbPath: string;
}
export class StateDb {
readonly dbPath: string;
readonly db: DatabaseSync;
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);
}
close(): void {
this.db.close();
}
transaction<T>(fn: () => T): T {
this.db.exec("BEGIN IMMEDIATE;");
try {
const result = fn();
this.db.exec("COMMIT;");
return result;
} catch (error) {
this.db.exec("ROLLBACK;");
throw error;
}
}
}
+96
View File
@@ -0,0 +1,96 @@
import type { DatabaseSync } from "node:sqlite";
export const STATE_DB_SCHEMA_VERSION = 1;
export function applyStateDbPragmas(db: DatabaseSync): 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 {
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) {
return 0;
}
return value;
}
function migrationV1(db: DatabaseSync): void {
db.exec(`
CREATE TABLE IF NOT EXISTS documents (
id TEXT PRIMARY KEY,
kind TEXT NOT NULL,
project_id TEXT NULL,
thread_id TEXT NULL,
sort_key INTEGER NULL,
schema_version INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
data_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS provider_events (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
id TEXT NOT NULL UNIQUE,
session_id TEXT NOT NULL,
provider TEXT NOT NULL,
kind TEXT NOT NULL,
method TEXT NOT NULL,
thread_id TEXT NULL,
turn_id TEXT NULL,
item_id TEXT NULL,
request_id TEXT NULL,
request_kind TEXT NULL,
text_delta TEXT NULL,
message TEXT NULL,
payload_json TEXT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS state_events (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
event_type TEXT NOT NULL,
entity_id TEXT NOT NULL,
payload_json TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS metadata (
key TEXT PRIMARY KEY,
value_json TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_documents_kind ON documents(kind);
CREATE INDEX IF NOT EXISTS idx_documents_project_kind ON documents(project_id, kind);
CREATE INDEX IF NOT EXISTS idx_documents_thread_kind_sort ON documents(thread_id, kind, sort_key);
CREATE INDEX IF NOT EXISTS idx_documents_kind_updated ON documents(kind, updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_provider_events_session_seq ON provider_events(session_id, seq);
CREATE INDEX IF NOT EXISTS idx_provider_events_thread_seq ON provider_events(thread_id, seq);
CREATE INDEX IF NOT EXISTS idx_state_events_seq ON state_events(seq);
`);
}
export function runStateMigrations(db: DatabaseSync): void {
applyStateDbPragmas(db);
const userVersion = readUserVersion(db);
if (userVersion >= STATE_DB_SCHEMA_VERSION) {
return;
}
db.exec("BEGIN IMMEDIATE;");
try {
if (userVersion < 1) {
migrationV1(db);
}
db.exec(`PRAGMA user_version=${STATE_DB_SCHEMA_VERSION};`);
db.exec("COMMIT;");
} catch (error) {
db.exec("ROLLBACK;");
throw error;
}
}
+176 -2
View File
@@ -13,10 +13,10 @@ import {
WS_METHODS,
type KeybindingsConfig,
type ResolvedKeybindingsConfig,
type StateEvent,
type WsPush,
type WsResponse,
} from "@t3tools/contracts";
import { ProjectRegistry } from "./projectRegistry";
import { compileResolvedKeybindingRule, DEFAULT_KEYBINDINGS } from "./keybindings";
import type {
TerminalClearInput,
@@ -28,6 +28,7 @@ import type {
TerminalWriteInput,
} from "@t3tools/contracts";
import type { TerminalManager } from "./terminalManager";
import { PersistenceService } from "./persistenceService";
interface PendingMessages {
queue: unknown[];
@@ -207,6 +208,15 @@ function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsCon
return resolved;
}
async function waitForPush(ws: WebSocket, channel: string): Promise<WsPush> {
while (true) {
const message = (await waitForMessage(ws)) as WsPush;
if (message.type === "push" && message.channel === channel) {
return message;
}
}
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
function mergeWithDefaultsForTest(custom: KeybindingsConfig): ResolvedKeybindingsConfig {
@@ -246,12 +256,16 @@ describe("WebSocket Server", () => {
} = {},
): 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"),
});
return createServer({
port: 0,
cwd: options.cwd ?? "/test/project",
...(options.devUrl ? { devUrl: options.devUrl } : {}),
...(options.authToken ? { authToken: options.authToken } : {}),
projectRegistry: new ProjectRegistry(stateDir),
persistenceService,
...(options.gitManager ? { gitManager: options.gitManager as never } : {}),
...(options.terminalManager ? { terminalManager: options.terminalManager } : {}),
});
@@ -646,6 +660,166 @@ describe("WebSocket Server", () => {
expect(response.result).toEqual([]);
});
it("supports state bootstrap and ordered catch-up events", async () => {
const stateDir = makeTempDir("t3code-ws-state-bootstrap-");
const projectCwd = makeTempDir("t3code-ws-state-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: "My Thread",
model: "gpt-5.3-codex",
});
expect(createdThread.error).toBeUndefined();
const threadId = (createdThread.result as { thread: { id: string } }).thread.id;
const updatedThread = await sendRequest(ws, WS_METHODS.threadsUpdateTitle, {
threadId,
title: "Updated Thread Title",
});
expect(updatedThread.error).toBeUndefined();
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; title: string }>;
lastStateSeq: number;
};
expect(snapshot.projects).toHaveLength(1);
expect(snapshot.threads).toHaveLength(1);
expect(snapshot.threads[0]?.title).toBe("Updated Thread Title");
expect(snapshot.lastStateSeq).toBeGreaterThan(0);
const catchUp = await sendRequest(ws, WS_METHODS.stateCatchUp, { afterSeq: 0 });
expect(catchUp.error).toBeUndefined();
const events = (catchUp.result as { events: StateEvent[] }).events;
expect(events.length).toBeGreaterThanOrEqual(3);
for (let index = 1; index < events.length; index += 1) {
const previous = events[index - 1];
const current = events[index];
expect(previous).toBeDefined();
expect(current).toBeDefined();
if (!previous || !current) continue;
expect(current.seq).toBeGreaterThan(previous.seq);
}
expect(events.some((event) => event.eventType === "project.upsert")).toBe(true);
expect(events.some((event) => event.eventType === "thread.upsert")).toBe(true);
});
it("broadcasts ordered state.event pushes", async () => {
const stateDir = makeTempDir("t3code-ws-state-events-");
const projectCwd = makeTempDir("t3code-ws-state-events-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 writerWs = await connectWs(port);
connections.push(writerWs);
await waitForMessage(writerWs);
const observerWs = await connectWs(port);
connections.push(observerWs);
await waitForMessage(observerWs);
const addedProject = await sendRequest(writerWs, WS_METHODS.projectsAdd, { cwd: projectCwd });
expect(addedProject.error).toBeUndefined();
const firstStatePush = await waitForPush(observerWs, WS_CHANNELS.stateEvent);
const firstEvent = firstStatePush.data as StateEvent;
expect(firstEvent.eventType).toBe("project.upsert");
const projectId = (addedProject.result as { project: { id: string } }).project.id;
const createdThread = await sendRequest(writerWs, WS_METHODS.threadsCreate, {
projectId,
title: "State Event Thread",
model: "gpt-5.3-codex",
});
expect(createdThread.error).toBeUndefined();
const secondStatePush = await waitForPush(observerWs, WS_CHANNELS.stateEvent);
const secondEvent = secondStatePush.data as StateEvent;
expect(secondEvent.eventType).toBe("thread.upsert");
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();
+84 -11
View File
@@ -18,7 +18,6 @@ import {
import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
import { ProjectRegistry } from "./projectRegistry";
import { ProviderManager } from "./providerManager";
import { GitManager } from "./gitManager";
import {
@@ -33,6 +32,7 @@ import {
import { TerminalManager } from "./terminalManager";
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
import { searchWorkspaceEntries } from "./workspaceEntries";
import { PersistenceService } from "./persistenceService";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -56,7 +56,8 @@ export interface ServerOptions {
staticDir?: string | undefined;
devUrl?: string | undefined;
logWebSocketEvents?: boolean | undefined;
projectRegistry?: ProjectRegistry | undefined;
persistenceService?: PersistenceService | undefined;
stateDbPath?: string | undefined;
gitManager?: GitManager | undefined;
terminalManager?: TerminalManager | undefined;
authToken?: string | undefined;
@@ -78,15 +79,19 @@ export function createServer(options: ServerOptions) {
staticDir,
devUrl,
logWebSocketEvents: explicitLogWsEvents,
projectRegistry: providedRegistry,
persistenceService: providedPersistenceService,
stateDbPath,
gitManager: providedGitManager,
terminalManager: providedTerminalManager,
authToken,
} = options;
const providerManager = new ProviderManager();
const persistenceService =
providedPersistenceService ??
new PersistenceService({
dbPath: stateDbPath ?? path.join(os.homedir(), ".t3", "state.sqlite"),
});
const providerManager = new ProviderManager({ persistenceService });
const terminalManager = providedTerminalManager ?? new TerminalManager();
const projectRegistry =
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
const gitManager = providedGitManager ?? new GitManager();
const clients = new Set<WebSocket>();
const logger = createLogger("ws");
@@ -121,6 +126,24 @@ export function createServer(options: ServerOptions) {
logOutgoingPush(push, recipients);
});
const onStateEvent = (event: unknown) => {
const push: WsPush = {
type: "push",
channel: WS_CHANNELS.stateEvent,
data: event,
};
const message = JSON.stringify(push);
let recipients = 0;
for (const client of clients) {
if (client.readyState === client.OPEN) {
client.send(message);
recipients += 1;
}
}
logOutgoingPush(push, recipients);
};
persistenceService.on("stateEvent", onStateEvent);
const onTerminalEvent = (event: TerminalEvent) => {
const push: WsPush = {
type: "push",
@@ -317,22 +340,70 @@ export function createServer(options: ServerOptions) {
return providerManager.getCheckpointDiff(request.params as never);
case WS_METHODS.providersRevertToCheckpoint:
return providerManager.revertToCheckpoint(request.params as never);
{
const params = request.params as {
sessionId: string;
turnCount: number;
};
const result = await providerManager.revertToCheckpoint(params as never);
persistenceService.applyCheckpointRevert({
sessionId: params.sessionId,
runtimeThreadId: result.threadId,
turnCount: result.turnCount,
messageCount: result.messageCount,
});
return result;
}
case WS_METHODS.stateBootstrap:
return persistenceService.loadSnapshot();
case WS_METHODS.stateListMessages:
return persistenceService.listMessages(request.params as never);
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.threadsCreate:
return persistenceService.createThread(request.params as never);
case WS_METHODS.threadsUpdate:
case WS_METHODS.threadsUpdateTerminalState:
return persistenceService.updateThreadTerminalState(request.params as never);
case WS_METHODS.threadsDelete:
persistenceService.deleteThread(request.params as never);
return undefined;
case WS_METHODS.threadsMarkVisited:
return persistenceService.markThreadVisited(request.params as never);
case WS_METHODS.threadsUpdateModel:
return persistenceService.updateThreadModel(request.params as never);
case WS_METHODS.threadsUpdateTitle:
return persistenceService.updateThreadTitle(request.params as never);
case WS_METHODS.threadsUpdateBranch:
return persistenceService.updateThreadBranch(request.params as never);
case WS_METHODS.projectsList:
return projectRegistry.list();
return persistenceService.listProjects();
case WS_METHODS.projectsAdd:
return projectRegistry.add(request.params as never);
return persistenceService.addProject(request.params as never);
case WS_METHODS.projectsRemove:
projectRegistry.remove(request.params as never);
persistenceService.removeProject(request.params as never);
return undefined;
case WS_METHODS.projectsSearchEntries:
return searchWorkspaceEntries(request.params as never);
case WS_METHODS.projectsUpdateScripts:
return projectRegistry.updateScripts(request.params as never);
return persistenceService.updateProjectScripts(request.params as never);
case WS_METHODS.shellOpenInEditor: {
const params = request.params as {
@@ -464,9 +535,11 @@ export function createServer(options: ServerOptions) {
async function stop(): Promise<void> {
terminalManager.off("event", onTerminalEvent);
persistenceService.off("stateEvent", onStateEvent);
providerManager.stopAll();
providerManager.dispose();
terminalManager.dispose();
persistenceService.close();
for (const client of clients) {
client.close();
+65 -2
View File
@@ -751,6 +751,65 @@ export default function ChatView({ threadId }: ChatViewProps) {
const hasReachedTerminalLimit =
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
useEffect(() => {
if (!api || !activeThread) return;
void api.threads
.updateTitle({
threadId: activeThread.id,
title: activeThread.title,
})
.catch(() => undefined);
}, [activeThread?.id, activeThread?.title, api]);
useEffect(() => {
if (!api || !activeThread) return;
void api.threads
.updateModel({
threadId: activeThread.id,
model: activeThread.model,
})
.catch(() => undefined);
}, [activeThread?.id, activeThread?.model, api]);
useEffect(() => {
if (!api || !activeThread) return;
void api.threads
.updateBranch({
threadId: activeThread.id,
branch: activeThread.branch,
worktreePath: activeThread.worktreePath,
})
.catch(() => undefined);
}, [activeThread?.id, activeThread?.branch, activeThread?.worktreePath, api]);
const terminalIdsKey = JSON.stringify(activeThread?.terminalIds ?? null);
const terminalGroupsKey = JSON.stringify(activeThread?.terminalGroups ?? null);
useEffect(() => {
if (!api || !activeThread) return;
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);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
activeThread?.id,
activeThread?.terminalOpen,
activeThread?.terminalHeight,
terminalIdsKey,
activeThread?.activeTerminalId,
terminalGroupsKey,
activeThread?.activeTerminalGroupId,
api,
]);
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
for (const image of images) {
if (!image.previewUrl) continue;
@@ -936,7 +995,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
scripts: input.nextScripts,
});
if (!isElectron || !api) return;
if (!api) return;
let scriptsPersisted = false;
try {
@@ -1512,6 +1571,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
try {
const session = await api.providers.startSession({
provider: "codex",
threadId: activeThread.id,
cwd: cwdOverride ?? activeThread.worktreePath ?? activeProject.cwd,
model: selectedModel || undefined,
resumeThreadId: priorCodexThreadId ?? undefined,
@@ -1740,10 +1800,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
const clientMessageId = crypto.randomUUID();
dispatch({
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: crypto.randomUUID(),
id: clientMessageId,
text: trimmed,
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
});
@@ -1783,6 +1844,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
: trimmed || undefined;
await api.providers.sendTurn({
sessionId: sessionInfo.sessionId,
clientMessageId,
clientMessageText: trimmed,
...(input ? { input } : {}),
...(turnAttachments.length > 0 ? { attachments: turnAttachments } : {}),
model: selectedModel || undefined,
+74 -38
View File
@@ -15,7 +15,6 @@ import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { toastManager } from "./ui/toast";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { createThread } from "../threadFactory";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
@@ -147,21 +146,56 @@ export default function Sidebar() {
worktreePath?: string | null;
},
) => {
const thread = createThread(projectId, {
model: state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
});
dispatch({
type: "ADD_THREAD",
thread,
});
void navigate({
to: "/$threadId",
params: { threadId: thread.id },
});
if (!api) return;
void (async () => {
try {
const result = await api.threads.create({
projectId,
model:
state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
});
dispatch({
type: "ADD_THREAD",
thread: {
id: result.thread.id,
codexThreadId: result.thread.codexThreadId,
projectId: result.thread.projectId,
title: result.thread.title,
model: result.thread.model,
terminalOpen: result.thread.terminalOpen,
terminalHeight: result.thread.terminalHeight,
terminalIds: result.thread.terminalIds,
runningTerminalIds: result.thread.runningTerminalIds,
activeTerminalId: result.thread.activeTerminalId,
terminalGroups: result.thread.terminalGroups,
activeTerminalGroupId: result.thread.activeTerminalGroupId,
session: null,
messages: [],
events: [],
error: null,
createdAt: result.thread.createdAt,
latestTurnId: result.thread.latestTurnId,
latestTurnStartedAt: result.thread.latestTurnStartedAt,
latestTurnCompletedAt: result.thread.latestTurnCompletedAt,
latestTurnDurationMs: result.thread.latestTurnDurationMs,
lastVisitedAt: result.thread.lastVisitedAt,
branch: result.thread.branch,
worktreePath: result.thread.worktreePath,
turnDiffSummaries: result.thread.turnDiffSummaries ?? [],
},
});
void navigate({
to: "/$threadId",
params: { threadId: result.thread.id },
});
} catch {
// Ignore thread creation errors here; caller surfaces project-level failures.
}
})();
},
[dispatch, navigate, state.projects],
[api, dispatch, navigate, state.projects],
);
const focusMostRecentThreadForProject = useCallback(
@@ -190,29 +224,7 @@ export default function Sidebar() {
setIsAddingProject(true);
try {
if (isElectron && api) {
const result = await api.projects.add({ cwd });
const project: Project = {
id: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: result.project.scripts,
};
const existingById = state.projects.find((p) => p.id === project.id);
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
if (!existingById && !existingByCwd) {
dispatch({ type: "ADD_PROJECT", project });
}
const resolvedProjectId = existingByCwd?.id ?? project.id;
if (result.created) {
handleNewThread(resolvedProjectId);
} else {
focusMostRecentThreadForProject(resolvedProjectId);
}
} else {
if (!api) {
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
@@ -230,6 +242,29 @@ export default function Sidebar() {
};
dispatch({ type: "ADD_PROJECT", project });
handleNewThread(project.id);
return;
}
const result = await api.projects.add({ cwd });
const project: Project = {
id: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: result.project.scripts,
};
const existingById = state.projects.find((p) => p.id === project.id);
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
if (!existingById && !existingByCwd) {
dispatch({ type: "ADD_PROJECT", project });
}
const resolvedProjectId = existingByCwd?.id ?? project.id;
if (result.created) {
handleNewThread(resolvedProjectId);
} else {
focusMostRecentThreadForProject(resolvedProjectId);
}
} finally {
setIsAddingProject(false);
@@ -310,6 +345,7 @@ export default function Sidebar() {
const shouldNavigateToFallback = routeThreadId === threadId;
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
void api.threads.delete({ threadId }).catch(() => undefined);
dispatch({ type: "DELETE_THREAD", threadId });
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
+216 -88
View File
@@ -6,10 +6,22 @@ import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
import { isElectron } from "../env";
import { useNativeApi } from "../hooks/useNativeApi";
import { invalidateGitQueries } from "../lib/gitReactQuery";
import { DEFAULT_MODEL } from "../model-logic";
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;
}>()({
@@ -32,16 +44,99 @@ function RootRouteView() {
return (
<ToastProvider>
<AnchoredToastProvider>
<EventRouter />
<AutoProjectBootstrap />
<DesktopProjectBootstrap />
<StateSyncRouter />
<BrowserDefaultProjectBootstrap />
<Outlet />
</AnchoredToastProvider>
</ToastProvider>
);
}
function EventRouter() {
function readLegacyRendererImportPayload() {
if (typeof window === "undefined") {
return null;
}
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 {
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;
}
}
function clearLegacyRendererState(): void {
if (typeof window === "undefined") {
return;
}
try {
window.localStorage.removeItem(CURRENT_RENDERER_STATE_KEY);
for (const key of LEGACY_RENDERER_STATE_KEYS) {
window.localStorage.removeItem(key);
}
} catch {
// Ignore storage cleanup failures.
}
}
function StateSyncRouter() {
const api = useNativeApi();
const { dispatch } = useStore();
const queryClient = useQueryClient();
@@ -50,6 +145,95 @@ function EventRouter() {
strict: false,
select: (params) => params.threadId,
});
const lastStateSeqRef = useRef(0);
const stateQueueRef = useRef(Promise.resolve());
useEffect(() => {
if (!api) return;
let disposed = false;
let retryDelayMs = 500;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const bootstrap = async () => {
try {
const snapshot = await api.state.bootstrap();
if (disposed) return;
dispatch({
type: "HYDRATE_FROM_SERVER",
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(() => {
retryTimer = null;
void bootstrap();
}, retryDelayMs);
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
}
};
void bootstrap();
return () => {
disposed = true;
if (retryTimer) {
clearTimeout(retryTimer);
}
};
}, [api, dispatch]);
useEffect(() => {
if (!api) return;
return api.state.onEvent((event) => {
stateQueueRef.current = stateQueueRef.current
.then(async () => {
if (event.seq <= lastStateSeqRef.current) {
return;
}
if (event.seq > lastStateSeqRef.current + 1) {
const catchUp = await api.state.catchUp({ afterSeq: lastStateSeqRef.current });
for (const missingEvent of catchUp.events) {
if (missingEvent.seq <= lastStateSeqRef.current) continue;
dispatch({
type: "APPLY_STATE_EVENT",
event: missingEvent,
});
lastStateSeqRef.current = missingEvent.seq;
}
}
if (event.seq > lastStateSeqRef.current) {
dispatch({
type: "APPLY_STATE_EVENT",
event,
});
lastStateSeqRef.current = event.seq;
}
})
.catch(() => undefined);
});
}, [api, dispatch]);
useEffect(() => {
if (!api) return;
@@ -79,13 +263,20 @@ function EventRouter() {
}, [activeThreadId, api, dispatch, queryClient]);
useEffect(() => {
if (!activeThreadId) return;
if (!api || !activeThreadId) return;
const visitedAt = new Date().toISOString();
dispatch({
type: "MARK_THREAD_VISITED",
threadId: activeThreadId,
visitedAt: new Date().toISOString(),
visitedAt,
});
}, [activeThreadId, dispatch]);
void api.threads
.markVisited({
threadId: activeThreadId,
visitedAt,
})
.catch(() => undefined);
}, [activeThreadId, api, dispatch]);
useEffect(() => {
if (!api) return;
@@ -100,96 +291,33 @@ function EventRouter() {
return null;
}
function AutoProjectBootstrap() {
const { state, dispatch } = useStore();
const bootstrappedRef = useRef(false);
function BrowserDefaultProjectBootstrap() {
const api = useNativeApi();
const { state } = useStore();
const createdRef = useRef(false);
useEffect(() => {
// Browser mode bootstraps from server welcome.
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
if (isElectron) return;
if (isElectron || !api || !state.threadsHydrated) {
return;
}
return onServerWelcome((payload) => {
if (bootstrappedRef.current) return;
// Don't create duplicate projects for the same cwd
const existing = state.projects.find((project) => project.cwd === payload.cwd);
if (existing) {
bootstrappedRef.current = true;
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
if (createdRef.current) {
return;
}
bootstrappedRef.current = true;
const existing = state.projects.find((project) => project.cwd === payload.cwd);
if (existing) {
createdRef.current = true;
return;
}
// Create project + thread from server cwd
const projectId = crypto.randomUUID();
dispatch({
type: "ADD_PROJECT",
project: {
id: projectId,
name: payload.projectName,
cwd: payload.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: [],
},
createdRef.current = true;
void api.projects.add({ cwd: payload.cwd }).catch(() => {
createdRef.current = false;
});
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
});
}, [state.projects, dispatch]);
return null;
}
function DesktopProjectBootstrap() {
const api = useNativeApi();
const { dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
if (!isElectron || !api || bootstrappedRef.current) return;
let disposed = false;
let retryDelayMs = 500;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const attemptBootstrap = async () => {
try {
const projects = await api.projects.list();
if (disposed) return;
dispatch({
type: "SYNC_PROJECTS",
projects: projects.map((project) => ({
id: project.id,
name: project.name,
cwd: project.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: project.scripts,
})),
});
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
bootstrappedRef.current = true;
} catch {
if (disposed) return;
retryTimer = setTimeout(() => {
retryTimer = null;
void attemptBootstrap();
}, retryDelayMs);
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
}
};
void attemptBootstrap();
return () => {
disposed = true;
if (retryTimer) {
clearTimeout(retryTimer);
}
};
}, [api, dispatch]);
}, [api, state.projects, state.threadsHydrated]);
return null;
}
+306 -34
View File
@@ -8,9 +8,16 @@ import {
useReducer,
} from "react";
import { type ProviderEvent, type ProviderSession, type TerminalEvent, normalizeProjectScripts } from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import {
type ProviderEvent,
type ProviderSession,
type StateBootstrapResult,
type StateBootstrapThread,
type StateEvent,
type TerminalEvent,
normalizeProjectScripts,
} from "@t3tools/contracts";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import {
applyEventToMessages,
asObject,
@@ -34,6 +41,8 @@ import {
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "HYDRATE_FROM_SERVER"; snapshot: StateBootstrapResult }
| { type: "APPLY_STATE_EVENT"; event: StateEvent }
| { type: "ADD_PROJECT"; project: Project }
| { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
| { type: "SYNC_PROJECTS"; projects: Project[] }
@@ -116,17 +125,7 @@ export interface AppState {
diffFilePath: string | null;
}
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
const LEGACY_PERSISTED_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;
const RUNTIME_MODE_STORAGE_KEY = "t3code:runtime-mode";
const initialState: AppState = {
projects: [],
@@ -145,21 +144,14 @@ function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
const raw = rawCurrent ?? rawLegacy;
if (!raw) return initialState;
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
if (!hydrated) return initialState;
const threads = hydrated.threads.map((thread) => normalizeThreadTerminals(thread));
const rawRuntimeMode = window.localStorage.getItem(RUNTIME_MODE_STORAGE_KEY);
const runtimeMode =
rawRuntimeMode === "approval-required" || rawRuntimeMode === "full-access"
? rawRuntimeMode
: DEFAULT_RUNTIME_MODE;
return {
...hydrated,
threads,
threadsHydrated: threads.length > 0,
...initialState,
runtimeMode,
diffOpen: false,
diffThreadId: null,
diffTurnId: null,
@@ -174,12 +166,9 @@ function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
window.localStorage.setItem(RUNTIME_MODE_STORAGE_KEY, state.runtimeMode);
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
// Ignore storage failures to avoid breaking chat UX.
}
}
@@ -275,6 +264,58 @@ function mergeTurnDiffSummaries(
);
}
function hydrateThreadFromBootstrap(
thread: StateBootstrapThread,
existing: Thread | undefined,
): Thread {
return normalizeThreadTerminals({
id: thread.id,
codexThreadId: thread.codexThreadId ?? null,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(thread.model),
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
terminalIds: thread.terminalIds,
runningTerminalIds: thread.runningTerminalIds,
activeTerminalId: thread.activeTerminalId,
terminalGroups: thread.terminalGroups,
activeTerminalGroupId: thread.activeTerminalGroupId,
session: existing?.session ?? null,
messages: thread.messages.map((message) => ({
id: message.id,
role: message.role,
text: message.text,
...(message.attachments
? { attachments: message.attachments.map((attachment) => ({ ...attachment })) }
: {}),
createdAt: message.createdAt,
streaming: message.streaming,
})),
events: existing?.events ?? [],
error: existing?.error ?? null,
createdAt: thread.createdAt,
latestTurnId: thread.latestTurnId,
latestTurnStartedAt: thread.latestTurnStartedAt,
latestTurnCompletedAt: thread.latestTurnCompletedAt,
latestTurnDurationMs: thread.latestTurnDurationMs,
lastVisitedAt: thread.lastVisitedAt ?? thread.createdAt,
branch: thread.branch ?? null,
worktreePath: thread.worktreePath ?? null,
turnDiffSummaries: thread.turnDiffSummaries ?? [],
});
}
function upsertThreadMessage(messages: Thread["messages"], message: Thread["messages"][number]) {
const index = messages.findIndex((entry) => entry.id === message.id);
if (index < 0) {
return [...messages, message];
}
const next = [...messages];
next[index] = message;
return next;
}
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
@@ -548,6 +589,228 @@ function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread>
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "HYDRATE_FROM_SERVER": {
const previousProjectById = new Map(
state.projects.map((project) => [project.id, project] as const),
);
const nextProjects = action.snapshot.projects.map((project) => {
const previous = previousProjectById.get(project.id);
return {
id: project.id,
name: project.name,
cwd: project.cwd,
model: resolveModelSlug(previous?.model ?? DEFAULT_MODEL),
expanded: previous?.expanded ?? true,
scripts: normalizeProjectScripts(project.scripts),
};
});
const nextProjectIdSet = new Set(nextProjects.map((project) => project.id));
const previousThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const));
const nextThreads = action.snapshot.threads
.filter((thread) => nextProjectIdSet.has(thread.projectId))
.map((thread) => hydrateThreadFromBootstrap(thread, previousThreadById.get(thread.id)));
const diffState = resetDiffTargetIfMissing(state, nextThreads);
return {
...state,
projects: nextProjects,
threads: nextThreads,
threadsHydrated: true,
...diffState,
};
}
case "APPLY_STATE_EVENT": {
const payload = asObject(action.event.payload);
const eventType = action.event.eventType;
if (eventType === "project.upsert") {
const project = asObject(payload?.project);
const id = asString(project?.id);
const name = asString(project?.name);
const cwd = asString(project?.cwd);
const scripts = Array.isArray(project?.scripts) ? (project.scripts as ProjectScript[]) : [];
if (!id || !name || !cwd) {
return state;
}
const previous = state.projects.find((entry) => entry.id === id);
const nextProject: Project = {
id,
name,
cwd,
model: resolveModelSlug(previous?.model ?? DEFAULT_MODEL),
expanded: previous?.expanded ?? true,
scripts: normalizeProjectScripts(scripts),
};
const nextProjects = previous
? state.projects.map((entry) => (entry.id === id ? nextProject : entry))
: [...state.projects, nextProject];
return {
...state,
projects: nextProjects,
};
}
if (eventType === "project.delete") {
const projectId = asString(payload?.projectId) ?? action.event.entityId;
const projects = state.projects.filter((project) => project.id !== projectId);
const threads = state.threads.filter((thread) => thread.projectId !== projectId);
const diffState = resetDiffTargetIfMissing(state, threads);
return {
...state,
projects,
threads,
...diffState,
};
}
if (eventType === "thread.upsert") {
const threadPayload = asObject(payload?.thread);
const threadId = asString(threadPayload?.id);
const projectId = asString(threadPayload?.projectId);
if (!threadId || !projectId) {
return state;
}
if (!state.projects.some((project) => project.id === projectId)) {
return state;
}
const existing = state.threads.find((thread) => thread.id === threadId);
const existingStateMessages =
existing?.messages.map((message) => ({
id: message.id,
threadId,
role: message.role,
text: message.text,
...(message.attachments
? {
attachments: message.attachments.map((attachment) => ({ ...attachment })),
}
: {}),
createdAt: message.createdAt,
updatedAt: message.createdAt,
streaming: message.streaming,
})) ?? [];
const bootstrapThread: StateBootstrapThread = {
...(threadPayload as unknown as Omit<StateBootstrapThread, "messages">),
messages: existingStateMessages,
turnDiffSummaries:
(threadPayload?.turnDiffSummaries as Thread["turnDiffSummaries"] | undefined) ??
existing?.turnDiffSummaries ??
[],
};
const nextThread = hydrateThreadFromBootstrap(bootstrapThread, existing);
const nextThreads = existing
? state.threads.map((thread) => (thread.id === nextThread.id ? nextThread : thread))
: [...state.threads, nextThread];
return {
...state,
threads: nextThreads,
};
}
if (eventType === "thread.delete") {
const threadId = asString(payload?.threadId) ?? action.event.entityId;
const nextThreads = state.threads.filter((thread) => thread.id !== threadId);
const diffState = resetDiffTargetIfMissing(state, nextThreads);
return {
...state,
threads: nextThreads,
...diffState,
};
}
if (eventType === "message.upsert") {
const threadId = asString(payload?.threadId);
const messagePayload = asObject(payload?.message);
const messageId = asString(messagePayload?.id);
const role = messagePayload?.role === "assistant" ? "assistant" : "user";
const text = typeof messagePayload?.text === "string" ? messagePayload.text : "";
const createdAt = asString(messagePayload?.createdAt);
if (!threadId || !messageId || !createdAt) {
return state;
}
const attachments = Array.isArray(messagePayload?.attachments)
? (messagePayload.attachments as Thread["messages"][number]["attachments"])
: undefined;
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
messages: upsertThreadMessage(thread.messages, {
id: messageId,
role,
text,
...(attachments ? { attachments } : {}),
createdAt,
streaming: messagePayload?.streaming === true,
}),
})),
};
}
if (eventType === "message.delete") {
const threadId = asString(payload?.threadId);
const messageId = asString(payload?.messageId);
if (!threadId || !messageId) {
return state;
}
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
messages: thread.messages.filter((message) => message.id !== messageId),
})),
};
}
if (eventType === "turn_summary.upsert") {
const threadId = asString(payload?.threadId);
const summaryPayload = asObject(payload?.turnSummary);
const turnId = asString(summaryPayload?.turnId);
const completedAt = asString(summaryPayload?.completedAt);
if (!threadId || !turnId || !completedAt) {
return state;
}
const summary: Thread["turnDiffSummaries"][number] = {
turnId,
completedAt,
status: asString(summaryPayload?.status),
files: Array.isArray(summaryPayload?.files)
? (summaryPayload.files as Thread["turnDiffSummaries"][number]["files"])
: [],
assistantMessageId: asString(summaryPayload?.assistantMessageId),
checkpointTurnCount:
typeof summaryPayload?.checkpointTurnCount === "number"
? summaryPayload.checkpointTurnCount
: undefined,
};
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
turnDiffSummaries: mergeTurnDiffSummaries(thread.turnDiffSummaries, [summary]),
})),
};
}
if (eventType === "turn_summary.delete") {
const threadId = asString(payload?.threadId);
const turnId = asString(payload?.turnId);
if (!threadId || !turnId) {
return state;
}
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
turnDiffSummaries: thread.turnDiffSummaries.filter((summary) => summary.turnId !== turnId),
})),
};
}
return state;
}
case "ADD_PROJECT":
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
return state;
@@ -657,6 +920,15 @@ export function reducer(state: AppState, action: Action): AppState {
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
turnDiffSummaries: action.thread.turnDiffSummaries ?? [],
});
const existingIndex = state.threads.findIndex((thread) => thread.id === nextThread.id);
if (existingIndex >= 0) {
const nextThreads = [...state.threads];
nextThreads[existingIndex] = nextThread;
return {
...state,
threads: nextThreads,
};
}
return {
...state,
threads: [...state.threads, nextThread],
@@ -1120,7 +1392,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
useEffect(() => {
persistState(state);
}, [state]);
}, [state.runtimeMode]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
+20
View File
@@ -98,6 +98,26 @@ export function createWsNativeApi(): NativeApi {
onEvent: (callback) =>
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
},
state: {
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),
},
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) =>
transport.request(WS_METHODS.threadsUpdateTerminalState, input),
updateModel: (input) => transport.request(WS_METHODS.threadsUpdateModel, input),
updateTitle: (input) => transport.request(WS_METHODS.threadsUpdateTitle, input),
updateBranch: (input) => transport.request(WS_METHODS.threadsUpdateBranch, input),
},
projects: {
list: () => transport.request(WS_METHODS.projectsList),
add: (input) => transport.request(WS_METHODS.projectsAdd, input),
+1
View File
@@ -34,6 +34,7 @@
"t3": "./dist/index.mjs",
},
"dependencies": {
"@pierre/diffs": "^1.1.0-beta.16",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0",
+1
View File
@@ -9,3 +9,4 @@ export * from "./keybindings";
export * from "./server";
export * from "./project";
export * from "./git";
export * from "./state";
+37
View File
@@ -42,6 +42,24 @@ import type {
ProjectUpdateScriptsResult,
} from "./project";
import type { ServerConfig } from "./server";
import type {
StateBootstrapResult,
StateCatchUpInput,
StateCatchUpResult,
StateEvent,
StateImportLegacyRendererStateInput,
StateImportLegacyRendererStateResult,
StateListMessagesInput,
StateListMessagesResult,
ThreadsCreateInput,
ThreadsDeleteInput,
ThreadsMarkVisitedInput,
ThreadsUpdateBranchInput,
ThreadsUpdateModelInput,
ThreadsUpdateResult,
ThreadsUpdateTerminalStateInput,
ThreadsUpdateTitleInput,
} from "./state";
import type {
TerminalClearInput,
TerminalCloseInput,
@@ -106,6 +124,25 @@ export interface NativeApi {
) => Promise<ProviderRevertToCheckpointResult>;
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
};
state: {
bootstrap: () => Promise<StateBootstrapResult>;
listMessages: (input: StateListMessagesInput) => Promise<StateListMessagesResult>;
catchUp: (input: StateCatchUpInput) => Promise<StateCatchUpResult>;
importLegacyRendererState: (
input: StateImportLegacyRendererStateInput,
) => Promise<StateImportLegacyRendererStateResult>;
onEvent: (callback: (event: StateEvent) => void) => () => void;
};
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>;
updateModel: (input: ThreadsUpdateModelInput) => Promise<ThreadsUpdateResult>;
updateTitle: (input: ThreadsUpdateTitleInput) => Promise<ThreadsUpdateResult>;
updateBranch: (input: ThreadsUpdateBranchInput) => Promise<ThreadsUpdateResult>;
};
projects: {
list: () => Promise<ProjectListResult>;
add: (input: ProjectAddInput) => Promise<ProjectAddResult>;
+6
View File
@@ -25,8 +25,10 @@ describe("providerSessionStartInputSchema", () => {
it("accepts optional resumeThreadId", () => {
const parsed = providerSessionStartInputSchema.parse({
threadId: "thread-local-1",
resumeThreadId: "thread_123",
});
expect(parsed.threadId).toBe("thread-local-1");
expect(parsed.resumeThreadId).toBe("thread_123");
});
@@ -56,6 +58,8 @@ describe("providerSendTurnInputSchema", () => {
it("accepts image-only turns", () => {
const parsed = providerSendTurnInputSchema.parse({
sessionId: "sess_1",
clientMessageId: "msg_1",
clientMessageText: "",
attachments: [
{
type: "image",
@@ -67,6 +71,8 @@ describe("providerSendTurnInputSchema", () => {
],
});
expect(parsed.input).toBeUndefined();
expect(parsed.clientMessageId).toBe("msg_1");
expect(parsed.clientMessageText).toBe("");
expect(parsed.attachments).toHaveLength(1);
});
+3
View File
@@ -47,6 +47,7 @@ export const providerSessionSchema = z.object({
export const providerSessionStartInputSchema = z.object({
provider: providerKindSchema.default("codex"),
threadId: z.string().trim().min(1).optional(),
cwd: z.string().min(1).optional(),
model: z.string().trim().min(1).optional(),
resumeThreadId: z.string().trim().min(1).optional(),
@@ -79,6 +80,8 @@ export const providerSendTurnAttachmentInputSchema = z.discriminatedUnion("type"
export const providerSendTurnInputSchema = z
.object({
sessionId: z.string().min(1),
clientMessageId: z.string().trim().min(1).optional(),
clientMessageText: z.string().max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS).optional(),
input: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS).optional(),
attachments: z
.array(providerSendTurnAttachmentInputSchema)
+145
View File
@@ -0,0 +1,145 @@
import { describe, expect, it } from "vitest";
import {
stateBootstrapResultSchema,
stateCatchUpInputSchema,
stateImportLegacyRendererStateInputSchema,
stateListMessagesInputSchema,
stateListMessagesResultSchema,
stateMessageSchema,
stateThreadSchema,
threadsCreateInputSchema,
threadsUpdateTerminalStateInputSchema,
threadsUpdateTitleInputSchema,
} from "./state";
describe("state schemas", () => {
it("applies defaults for state thread records", () => {
const parsed = stateThreadSchema.parse({
id: "thread-1",
projectId: "project-1",
title: "Thread",
model: "gpt-5-codex",
createdAt: "2026-02-19T00:00:00.000Z",
updatedAt: "2026-02-19T00:00:00.000Z",
});
expect(parsed.codexThreadId).toBeNull();
expect(parsed.terminalIds).toEqual(["default"]);
expect(parsed.activeTerminalId).toBe("default");
expect(parsed.turnDiffSummaries).toEqual([]);
});
it("validates bootstrap payloads", () => {
const parsed = stateBootstrapResultSchema.parse({
projects: [
{
id: "project-1",
cwd: "/repo",
name: "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",
updatedAt: "2026-02-19T00:00:00.000Z",
messages: [],
},
],
lastStateSeq: 12,
});
expect(parsed.lastStateSeq).toBe(12);
expect(parsed.threads[0]?.messages).toEqual([]);
});
it("validates message pagination result payloads", () => {
const message = stateMessageSchema.parse({
id: "msg-1",
threadId: "thread-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-19T00:00:00.000Z",
updatedAt: "2026-02-19T00:00:00.000Z",
streaming: false,
});
const result = stateListMessagesResultSchema.parse({
messages: [message],
total: 1,
nextOffset: null,
});
expect(result.total).toBe(1);
expect(result.nextOffset).toBeNull();
});
it("enforces at least one terminal field on terminal updates", () => {
expect(() =>
threadsUpdateTerminalStateInputSchema.parse({
threadId: "thread-1",
}),
).toThrow();
const parsed = threadsUpdateTerminalStateInputSchema.parse({
threadId: "thread-1",
terminalOpen: true,
});
expect(parsed.terminalOpen).toBe(true);
});
it("parses thread create/title inputs and state pagination defaults", () => {
const created = threadsCreateInputSchema.parse({
projectId: "project-1",
});
expect(created.projectId).toBe("project-1");
const titled = threadsUpdateTitleInputSchema.parse({
threadId: "thread-1",
title: "New title",
});
expect(titled.title).toBe("New title");
const listInput = stateListMessagesInputSchema.parse({
threadId: "thread-1",
});
expect(listInput.offset).toBe(0);
expect(listInput.limit).toBe(200);
});
it("parses state catch-up and legacy import 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);
});
});
+275
View File
@@ -0,0 +1,275 @@
import { z } from "zod";
import { projectScriptSchema } from "./project";
export const STATE_DEFAULT_TERMINAL_ID = "default";
export const STATE_DEFAULT_TERMINAL_HEIGHT = 280;
export const stateThreadTerminalGroupSchema = z.object({
id: z.string().trim().min(1),
terminalIds: z.array(z.string().trim().min(1)).min(1).max(4),
});
export const stateMessageImageAttachmentSchema = 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),
});
export const stateMessageAttachmentSchema = z.discriminatedUnion("type", [
stateMessageImageAttachmentSchema,
]);
export const stateMessageSchema = z.object({
id: z.string().min(1),
threadId: z.string().min(1),
role: z.enum(["user", "assistant"]),
text: z.string(),
attachments: z.array(stateMessageAttachmentSchema).optional(),
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
streaming: z.boolean().default(false),
});
export const stateTurnDiffFileChangeSchema = 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(),
});
export const stateTurnSummarySchema = z.object({
turnId: z.string().min(1),
completedAt: z.string().datetime(),
status: z.string().min(1).optional(),
files: z.array(stateTurnDiffFileChangeSchema).default([]),
assistantMessageId: z.string().min(1).optional(),
checkpointTurnCount: z.number().int().min(0).optional(),
});
export const stateProjectSchema = z.object({
id: z.string().min(1),
cwd: z.string().min(1),
name: z.string().min(1),
scripts: z.array(projectScriptSchema).default([]),
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
});
export const stateThreadSchema = 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]),
runningTerminalIds: z.array(z.string().trim().min(1)).max(4).default([]),
activeTerminalId: z.string().trim().min(1).default(STATE_DEFAULT_TERMINAL_ID),
terminalGroups: z.array(stateThreadTerminalGroupSchema).default([]),
activeTerminalGroupId: z
.string()
.trim()
.min(1)
.default(`group-${STATE_DEFAULT_TERMINAL_ID}`),
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
lastVisitedAt: z.string().datetime().optional(),
latestTurnId: z.string().min(1).optional(),
latestTurnStartedAt: z.string().datetime().optional(),
latestTurnCompletedAt: z.string().datetime().optional(),
latestTurnDurationMs: z.number().int().min(0).optional(),
branch: z.string().min(1).nullable().default(null),
worktreePath: z.string().min(1).nullable().default(null),
turnDiffSummaries: z.array(stateTurnSummarySchema).default([]),
});
export const stateBootstrapThreadSchema = stateThreadSchema.extend({
messages: z.array(stateMessageSchema).default([]),
});
export const stateBootstrapResultSchema = z.object({
projects: z.array(stateProjectSchema),
threads: z.array(stateBootstrapThreadSchema),
lastStateSeq: z.number().int().min(0),
});
export const stateCatchUpInputSchema = z.object({
afterSeq: z.number().int().min(0).default(0),
});
export const stateEventSchema = z.object({
seq: z.number().int().positive(),
eventType: z.string().min(1),
entityId: z.string().min(1),
payload: z.unknown(),
createdAt: z.string().datetime(),
});
export const stateCatchUpResultSchema = z.object({
events: z.array(stateEventSchema),
lastStateSeq: z.number().int().min(0),
});
export const stateListMessagesInputSchema = z.object({
threadId: z.string().min(1),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(500).default(200),
});
export const stateListMessagesResultSchema = z.object({
messages: z.array(stateMessageSchema),
total: z.number().int().min(0),
nextOffset: z.number().int().min(0).nullable(),
});
export const threadsCreateInputSchema = z.object({
projectId: z.string().min(1),
title: z.string().trim().min(1).optional(),
model: z.string().trim().min(1).optional(),
branch: z.string().trim().min(1).nullable().optional(),
worktreePath: z.string().trim().min(1).nullable().optional(),
terminalOpen: z.boolean().optional(),
terminalHeight: z.number().int().min(120).max(4_096).optional(),
terminalIds: z.array(z.string().trim().min(1)).max(4).optional(),
activeTerminalId: z.string().trim().min(1).optional(),
terminalGroups: z.array(stateThreadTerminalGroupSchema).optional(),
activeTerminalGroupId: z.string().trim().min(1).optional(),
});
export const threadsUpdateTitleInputSchema = z.object({
threadId: z.string().min(1),
title: z.string().trim().min(1),
});
export const threadsUpdateModelInputSchema = z.object({
threadId: z.string().min(1),
model: z.string().trim().min(1),
});
export const threadsDeleteInputSchema = z.object({
threadId: z.string().min(1),
});
export const threadsMarkVisitedInputSchema = z.object({
threadId: z.string().min(1),
visitedAt: z.string().datetime().optional(),
});
export const threadsUpdateBranchInputSchema = z.object({
threadId: z.string().min(1),
branch: z.string().trim().min(1).nullable(),
worktreePath: z.string().trim().min(1).nullable(),
});
export const threadsUpdateTerminalStateInputSchema = z
.object({
threadId: z.string().min(1),
terminalOpen: z.boolean().optional(),
terminalHeight: z.number().int().min(120).max(4_096).optional(),
terminalIds: z.array(z.string().trim().min(1)).max(4).optional(),
runningTerminalIds: z.array(z.string().trim().min(1)).max(4).optional(),
activeTerminalId: z.string().trim().min(1).optional(),
terminalGroups: z.array(stateThreadTerminalGroupSchema).optional(),
activeTerminalGroupId: z.string().trim().min(1).optional(),
})
.superRefine((value, ctx) => {
const hasAnyUpdate = Object.keys(value).some((key) => key !== "threadId");
if (!hasAnyUpdate) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "At least one terminal field must be provided",
path: ["threadId"],
});
}
});
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>;
export type StateMessage = z.infer<typeof stateMessageSchema>;
export type StateTurnDiffFileChange = z.infer<typeof stateTurnDiffFileChangeSchema>;
export type StateTurnSummary = z.infer<typeof stateTurnSummarySchema>;
export type StateProject = z.infer<typeof stateProjectSchema>;
export type StateThread = z.infer<typeof stateThreadSchema>;
export type StateBootstrapThread = z.infer<typeof stateBootstrapThreadSchema>;
export type StateBootstrapResult = z.infer<typeof stateBootstrapResultSchema>;
export type StateCatchUpInput = z.input<typeof stateCatchUpInputSchema>;
export type StateEvent = z.infer<typeof stateEventSchema>;
export type StateCatchUpResult = z.infer<typeof stateCatchUpResultSchema>;
export type StateListMessagesInput = z.input<typeof stateListMessagesInputSchema>;
export type StateListMessagesResult = z.infer<typeof stateListMessagesResultSchema>;
export type ThreadsCreateInput = z.input<typeof threadsCreateInputSchema>;
export type ThreadsUpdateTitleInput = z.input<typeof threadsUpdateTitleInputSchema>;
export type ThreadsUpdateModelInput = z.input<typeof threadsUpdateModelInputSchema>;
export type ThreadsDeleteInput = z.input<typeof threadsDeleteInputSchema>;
export type ThreadsMarkVisitedInput = z.input<typeof threadsMarkVisitedInputSchema>;
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
>;
+17
View File
@@ -3,6 +3,22 @@ import { z } from "zod";
// ── WebSocket RPC Method Names ───────────────────────────────────────
export const WS_METHODS = {
// State methods
stateBootstrap: "state.bootstrap",
stateListMessages: "state.listMessages",
stateCatchUp: "state.catchUp",
stateImportLegacyRendererState: "state.importLegacyRendererState",
// Thread methods
threadsCreate: "threads.create",
threadsUpdate: "threads.update",
threadsDelete: "threads.delete",
threadsMarkVisited: "threads.markVisited",
threadsUpdateTerminalState: "threads.updateTerminalState",
threadsUpdateModel: "threads.updateModel",
threadsUpdateTitle: "threads.updateTitle",
threadsUpdateBranch: "threads.updateBranch",
// Provider methods (mirrors NativeApi.providers)
providersStartSession: "providers.startSession",
providersSendTurn: "providers.sendTurn",
@@ -52,6 +68,7 @@ export const WS_METHODS = {
export const WS_CHANNELS = {
providerEvent: "providers.event",
stateEvent: "state.event",
terminalEvent: "terminal.event",
serverWelcome: "server.welcome",
} as const;