Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge c3975c1b22 Warn when mirror reports unsuccessful state-event writes
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:56:40 +00:00
Cursor AgentandJulius Marminge f0888582cf Remove client-side legacy state-source mode seam
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:54:26 +00:00
Cursor AgentandJulius Marminge 9a56a22dcf Infer strict livestore mode from read-pilot fallback policy
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:51:48 +00:00
Cursor AgentandJulius Marminge 672551f505 Centralize catch-up and list-message parity diff helpers
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:49:46 +00:00
Cursor AgentandJulius Marminge c777aae03d Cover mirror bootstrap replay against real legacy state
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:47:11 +00:00
Cursor AgentandJulius Marminge 0611b8220f Default server config contract to strict livestore mode
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:44:11 +00:00
Cursor AgentandJulius Marminge 7ee0cce572 Restore strict livestore as default after startup hydration hardening
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:43:05 +00:00
Cursor AgentandJulius Marminge 9a6575655c Propagate mirror replay success status during bootstrap
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:41:40 +00:00
Cursor AgentandJulius Marminge 07f4dbf480 Await mirror replay during startup hydration
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:39:17 +00:00
Cursor AgentandJulius Marminge 2dd87351ac Bootstrap LiveStore mirror from persisted catch-up history
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:37:22 +00:00
Cursor AgentandJulius Marminge 93686a84b3 Keep read-pilot as default pending durable mirror bootstrap
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:33:31 +00:00
Cursor AgentandJulius Marminge 842435e622 Promote strict livestore mode to default sync engine
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:30:37 +00:00
Cursor AgentandJulius Marminge e7d37a3643 Add enforce-liveStore startup guard for sync engine mode
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:28:32 +00:00
Cursor AgentandJulius Marminge 8b8ce91e37 Infer sync engine mode from injected state engine
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:26:22 +00:00
Cursor AgentandJulius Marminge bba3afe33b Add read-pilot route metrics and fallback counters
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:23:58 +00:00
Cursor AgentandJulius Marminge 3b20cc7691 Add livestore strict mode and wire mode mapping across stack
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:19:10 +00:00
Cursor AgentandJulius Marminge 04f3546c06 Add contracts coverage for sync engine mode in server config
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:06:37 +00:00
Cursor AgentandJulius Marminge 24dbfa58c9 Add optional shadow catchup and listMessages parity checks
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 12:03:22 +00:00
Cursor AgentandJulius Marminge 75cdd78edb Add websocket coverage for strict read-pilot error mode
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 11:47:34 +00:00
Cursor AgentandJulius Marminge c0c5c8f51a Add strict read-pilot mode without delegate fallback
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 11:40:06 +00:00
Cursor AgentandJulius Marminge 08d4dcbbb8 Add optional shadow bootstrap parity diagnostics
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 11:24:33 +00:00
Cursor AgentandJulius Marminge 6aa5a598b4 Expose sync engine mode in server config and web source selection
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 11:14:21 +00:00
Cursor AgentandJulius Marminge 8a6676cbfb Add optional listMessages parity diagnostics in read pilot
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 11:03:10 +00:00
Cursor AgentandJulius Marminge 09f93f37e9 Extract and test sync engine mode resolution
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:58:04 +00:00
Cursor AgentandJulius Marminge b38812716d Default sync engine mode to read-pilot with fallback
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:52:41 +00:00
Cursor AgentandJulius Marminge c2e35cb01b Add sync-engine migration rollout runbook
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:47:42 +00:00
Cursor AgentandJulius Marminge 1bffbcfb22 Add web state-source mode seam for read-pilot
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:47:04 +00:00
Cursor AgentandJulius Marminge 6513750a9c Add websocket coverage for read-pilot fallback to legacy
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:44:43 +00:00
Cursor AgentandJulius Marminge 5001314519 Add websocket integration coverage for read-pilot ordering
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:40:06 +00:00
Cursor AgentandJulius Marminge 7a9b733368 Add optional catch-up parity diagnostics for read pilot
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:33:55 +00:00
Cursor AgentandJulius Marminge cbfe1e3a57 Add source-labelled read-pilot logging and recovery test
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:26:06 +00:00
Cursor AgentandJulius Marminge fc14fdb569 Expand shadow parity coverage in persistence and ws tests
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:19:38 +00:00
Cursor AgentandJulius Marminge 89e2c73f1f Add shadow engine parity integration coverage
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:05:46 +00:00
Cursor AgentandJulius Marminge 2e2af4cb46 Document sync engine migration runtime flags
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:03:28 +00:00
Cursor AgentandJulius Marminge 38ca95a787 Add bootstrap parity diagnostics for LiveStore read pilot
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 10:02:40 +00:00
Cursor AgentandJulius Marminge 637eae09a4 Add web state source seam for sync provider migration
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 09:58:01 +00:00
Cursor AgentandJulius Marminge 40bb6cb7a7 Add LiveStore read-pilot sync engine with delegate fallback
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 09:54:30 +00:00
Cursor AgentandJulius Marminge dae7ab8359 Project mirrored state events into LiveStore parity snapshot
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 09:49:15 +00:00
Cursor AgentandJulius Marminge fa39092505 Cover message events in shadow sync engine parity test
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 09:43:38 +00:00
Cursor AgentandJulius Marminge ccacb4bcab Add wsServer coverage for injected state sync engine
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 09:42:34 +00:00
Cursor AgentandJulius Marminge 8d0af1f9de Add snapshot parity utility for LiveStore migration
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 09:32:02 +00:00
Cursor AgentandJulius Marminge 262f57d84a Introduce state sync engine seam and LiveStore shadow mirror
Co-authored-by: Julius Marminge <[email protected]>
2026-02-20 09:29:27 +00:00
Julius Marminge e81c2acb78 Harden state persistence and tighten WS thread update API
- Fix persistence edge cases around pagination offsets, assistant message ordering, and checkpoint merge semantics
- Make state DB and sqlite adapter failures safer with better cleanup and runtime errors
- Treat `threads.update` as unsupported, keep `threads.updateTerminalState` canonical, and avoid failing revert RPCs on persistence-write errors
- Add focused server/web/contracts tests for the new failure and compatibility paths
2026-02-20 00:43:30 -08:00
Julius Marminge fda3073e0c Remove legacy renderer state import path and client schema
- drop `stateImportLegacyRendererState` handling from server, WS API, and contracts
- remove legacy renderer import tests and old web persistence schema/tests
- rely on current shared state/bootstrap flow instead of one-time legacy import
2026-02-20 00:22:30 -08:00
Julius Marminge 7214778b64 plan cr fixing 2026-02-20 00:21:31 -08:00
Julius Marminge 27bd9192ad clean 2026-02-19 21:55:12 -08:00
Julius Marminge 0da96d5c93 Merge branch 'main' into codething/48364d50 2026-02-19 21:54:25 -08:00
Julius Marminge 25dbfa7bc7 debug 2026-02-19 21:54:23 -08:00
Julius Marminge 78b7070042 Improve persistence and runtime SQLite compatibility
- add a SQLite adapter that works in both Bun and Node/Electron, with tests
- persist and backfill `assistantMessageId` on turn summaries to keep thread diffs linked
- prevent web state regressions by preserving turn summaries and deduplicating terminal/settings sync updates
2026-02-19 20:49:27 -08:00
Julius Marminge 1332c488ad Add desktop DMG packaging and persisted app settings
- package desktop builds with branded icons, custom app identity, and `t3://app` production loading
- add app settings get/update RPC flow with persistence and tests for Codex binary/home paths
- wire web/desktop settings UX and menu action hooks to open Settings
2026-02-19 18:01:51 -08:00
Julius Marminge 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
95 changed files with 13987 additions and 3955 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?
@@ -0,0 +1,129 @@
# Plan: Remove Legacy localStorage Migration Paths and Resolve CR Feedback Cohesively
## Summary
Delete all runtime migration pathways that ingest legacy browser localStorage state into the new SQLite-backed model, then resolve the remaining code review (CR) findings in grouped workstreams.
This plan intentionally removes migration code instead of improving it. The target is a single canonical state flow: server-backed bootstrap + state events only, with no legacy data import bridge.
## Goals
1. Remove legacy localStorage migration for renderer state completely.
2. Remove dead contracts, RPC methods, server handlers, client callers, and tests tied to that migration.
3. Resolve valid CR findings on the retained architecture.
4. Close review threads with explicit outcomes: fixed, superseded by deletion, or declined with rationale.
## Non-Goals
1. Preserving one-time automatic import of old renderer localStorage data.
2. Refactoring unrelated UX persistence (theme/editor preferences) unless directly required by CR items.
3. Large behavior changes outside correctness/reliability fixes raised in CR.
## Architecture Decision
- Canonical state source remains SQLite + `state.bootstrap` + `state.catchUp` + streamed `stateEvent` updates.
- Legacy renderer-state migration is removed entirely.
- Existing server-side `projects.json` import path is kept unless explicitly removed in a follow-up (it is not localStorage-based).
## Workstream 1: Delete Legacy localStorage Migration End-to-End [COMPLETE]
### 1.1 Contracts and WS protocol cleanup
- Remove `stateImportLegacyRendererState` from `packages/contracts/src/ws.ts`.
- Remove state import input/result schemas and exported types from `packages/contracts/src/state.ts`.
- Remove IPC surface for `state.importLegacyRendererState` in `packages/contracts/src/ipc.ts`.
- Update and prune contracts tests in `packages/contracts/src/state.test.ts` and any IPC/WS tests that reference removed symbols.
### 1.2 Server cleanup
- Remove `PersistenceService.importLegacyRendererState(...)` and associated metadata key/constants used only for this import path.
- Remove WS routing case for `WS_METHODS.stateImportLegacyRendererState` in `apps/server/src/wsServer.ts`.
- Remove server tests that exercise legacy renderer import via RPC and service unit tests.
- Ensure no dead helpers remain (payload mapping, metadata flags, schema imports, etc.).
### 1.3 Web client cleanup
- Remove legacy key constants and helper functions from `apps/web/src/routes/__root.tsx`:
- `CURRENT_RENDERER_STATE_KEY`
- `LEGACY_RENDERER_STATE_KEYS`
- `readLegacyRendererImportPayload`
- `clearLegacyRendererState`
- import-and-refresh bootstrap branch invoking `api.state.importLegacyRendererState(...)`
- Remove `hydratePersistedState` dependency from root route.
- Delete or narrow `apps/web/src/persistenceSchema.ts` to only what is still used. If unused after migration removal, delete file and tests.
- Remove `state.importLegacyRendererState` call path from `apps/web/src/wsNativeApi.ts`.
### 1.4 Dead-code verification pass
- `rg` for: `importLegacyRendererState`, `stateImportLegacyRendererState`, `renderer-state:v`, `hydratePersistedState`, legacy metadata keys.
- Ensure zero references remain in app code, contracts, and tests.
## Workstream 2: Resolve CR Findings in Surviving Code (Grouped by Relevance) [COMPLETE]
### Group A: Data integrity and transactional correctness (highest priority)
- `apps/server/src/persistenceService.ts`
- Fix `listMessages` pagination progress: use fetched row count for `nextOffset`.
- Guard `withTransaction` post-commit event emission so listener exceptions do not surface as transaction failures.
- Preserve `checkpointTurnCount = 0` in turn-summary merge logic.
- Prevent `item/started` from clobbering previously accumulated assistant text when events arrive out of order.
- `apps/server/src/wsServer.ts`
- Wrap/contain `applyCheckpointRevert` persistence update so provider revert success is not falsely returned as failure.
- `apps/server/src/stateDb.ts`
- Close DB when migration initialization fails in constructor.
- Preserve original transaction error if rollback also throws.
### Group B: API/contract clarity and ownership boundaries
- `apps/server/src/wsServer.ts` + `packages/contracts/src/ipc.ts` + `apps/web/src/wsNativeApi.ts`
- Remove ambiguous generic `threads.update` or make it explicit/unsupported (single canonical terminal-state update route).
- Align method names/types with actual handlers.
- `apps/server/src/wsServer.ts`
- Track ownership of injected `persistenceService`; only close internally owned instance in `stop()`.
- `apps/server/src/sqliteAdapter.ts`
- Add explicit guard/error message when `node:sqlite` is unavailable.
### Group C: Client consistency and race prevention
- `apps/web/src/appSettings.ts`
- Add hydration/update sequence guard so hydration cannot overwrite optimistic writes.
- `apps/web/src/store.ts`
- Harden `thread.upsert` normalization to avoid crashes on missing terminal arrays (safe defaults before terminal normalization).
- `apps/web/src/components/Sidebar.tsx`
- Fix no-API thread creation path (do not call API-gated `handleNewThread` in browser-only fallback).
- `apps/web/src/components/BranchToolbar.tsx` + `apps/web/src/components/ChatView.tsx`
- Remove duplicate `updateBranch` network write path.
### Group D: Test reliability and cleanup
- `apps/server/src/persistenceService.test.ts`
- Make timestamp helper deterministic.
- Ensure service instances are always closed via `try/finally`.
- Replace always-true catch-up sequence assertion with monotonic/defined sequence checks.
- Update/add tests for Group A/B/C behavior changes.
## Workstream 3: Review Thread Triage/Closure Strategy
### Threads closed by deletion (Workstream 1)
- Legacy renderer import flow/race concerns in root route.
- Legacy import schemas, WS method concerns, and related service import concerns.
- Any CR comments rooted in the removed migration path.
### Threads closed by fixes (Workstream 2)
- Transaction semantics, pagination correctness, branch update duplication, no-API thread creation, etc.
### Threads closed with rationale (no change)
- Keep concise “not adopted” notes only where behavior is intentional and safe.
## Execution Order
1. Contracts + protocol deletions (Workstream 1.1).
2. Server deletion and compilation fixes (Workstream 1.2).
3. Web deletion and compilation fixes (Workstream 1.3).
4. Dead-code sweep and test pruning (Workstream 1.4).
5. Group A fixes + tests.
6. Group B fixes + tests.
7. Group C fixes + tests.
8. Group D test hardening.
9. Final lint/test pass; prepare review-thread response mapping.
## Validation Matrix
- Lint: `bun run lint`.
- Contracts tests: `bun --cwd packages/contracts test` (or workspace equivalent).
- Server tests (required for backend changes): `bun --cwd apps/server test`.
- Web tests: `bun --cwd apps/web test`.
- Grep-based dead-code validation for removed migration symbols.
## Done Criteria
1. No runtime path exists to import legacy renderer localStorage into server state.
2. No dead symbols remain for removed migration APIs.
3. CR high/medium validity issues in retained code are fixed or explicitly dispositioned.
4. Backend tests and project lint pass.
5. PR discussion can be answered thread-by-thread with: fixed / superseded / intentionally declined.
+2
View File
@@ -10,3 +10,5 @@
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`
12. `12-remove-legacy-localstorage-migrations-and-cr-hardening.md`
+41 -2
View File
@@ -101,17 +101,56 @@ T3 Code has a global runtime mode switch in the chat toolbar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
## Sync engine migration modes
The server supports feature-flagged sync-engine modes while migrating from the legacy in-house state sync pipeline to LiveStore.
- `T3CODE_SYNC_ENGINE_MODE=livestore` (default)
- Uses the LiveStore-backed read path and disables delegate fallback (strict mirror-read mode).
- Mirror state is pre-bootstrapped from persisted catch-up history during server startup.
- `T3CODE_SYNC_ENGINE_MODE=livestore-read-pilot`
- Uses the LiveStore mirror for `state.bootstrap`, `state.catchUp`, and `state.listMessages` reads when available.
- Automatically falls back to legacy reads if the mirror is unavailable or errors.
- `T3CODE_SYNC_ENGINE_MODE=legacy`
- Uses the existing `PersistenceService`-backed state sync engine for reads and writes.
- `T3CODE_SYNC_ENGINE_MODE=shadow`
- Keeps legacy state as canonical, but mirrors committed `state.event` traffic into a LiveStore shadow store for parity validation.
- `T3CODE_LIVESTORE_ENFORCE_MODE=1`
- Disallows `legacy` and `shadow` sync modes at startup.
- Intended for post-cutover environments to prevent accidental rollback to pre-LiveStore modes.
Optional diagnostics:
- `T3CODE_LIVESTORE_BOOTSTRAP_PARITY_CHECK=1`
- In `livestore-read-pilot` mode, compares LiveStore vs legacy `state.bootstrap` snapshots and logs drift diagnostics.
- `T3CODE_LIVESTORE_CATCHUP_PARITY_CHECK=1`
- In `livestore-read-pilot` mode, compares LiveStore vs legacy `state.catchUp` responses and logs drift diagnostics.
- `T3CODE_LIVESTORE_LIST_MESSAGES_PARITY_CHECK=1`
- In `livestore-read-pilot` mode, compares LiveStore vs legacy `state.listMessages` responses and logs drift diagnostics.
- `T3CODE_LIVESTORE_SHADOW_BOOTSTRAP_PARITY_CHECK=1`
- In `shadow` mode, compares mirror vs delegate `state.bootstrap` snapshots and logs drift diagnostics.
- `T3CODE_LIVESTORE_SHADOW_CATCHUP_PARITY_CHECK=1`
- In `shadow` mode, compares mirror vs delegate `state.catchUp` responses and logs drift diagnostics.
- `T3CODE_LIVESTORE_SHADOW_LIST_MESSAGES_PARITY_CHECK=1`
- In `shadow` mode, compares mirror vs delegate `state.listMessages` responses and logs drift diagnostics.
- `T3CODE_LIVESTORE_DISABLE_READ_FALLBACK=1`
- In `livestore-read-pilot` mode, disables delegate read fallback and fails requests when mirror reads fail (strict canary mode).
- Read-source/fallback counters are emitted on shutdown via `livestore read pilot metrics` logs.
Web clients now always consume the server-authoritative `api.state.*` stream, and the server mode fully controls LiveStore vs fallback behavior.
## Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
- **Push events**: `{ type: "push", channel, data }` for streaming provider events
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
+80
View File
@@ -0,0 +1,80 @@
# Sync Engine Migration Runbook
This runbook describes how to operate and verify the LiveStore migration path safely.
## Runtime modes
Server mode is controlled by `T3CODE_SYNC_ENGINE_MODE`:
- `livestore` (default): strict LiveStore read path (delegate read fallback disabled).
- `livestore-read-pilot`: write path remains legacy-backed, but state reads prefer LiveStore mirror with delegate fallback.
- `legacy`: legacy persistence service is canonical for reads/writes.
- `shadow`: legacy remains canonical, and `state.event` writes are mirrored into LiveStore.
Startup behavior:
- when running `shadow`, `livestore-read-pilot`, or `livestore`, the mirror is bootstrapped from persisted catch-up history before serving requests.
Optional safety gate:
- `T3CODE_LIVESTORE_ENFORCE_MODE=1`
- prevents startup in `legacy` or `shadow` mode.
- use in post-cutover environments to block accidental rollback.
## Diagnostics flags
- `T3CODE_LIVESTORE_BOOTSTRAP_PARITY_CHECK=1`
- In read-pilot mode, compares `state.bootstrap` mirror output against delegate output.
- `T3CODE_LIVESTORE_CATCHUP_PARITY_CHECK=1`
- In read-pilot mode, compares `state.catchUp` mirror output against delegate output.
- `T3CODE_LIVESTORE_LIST_MESSAGES_PARITY_CHECK=1`
- In read-pilot mode, compares `state.listMessages` mirror output against delegate output.
- `T3CODE_LIVESTORE_SHADOW_BOOTSTRAP_PARITY_CHECK=1`
- In shadow mode, compares `state.bootstrap` mirror output against delegate output.
- `T3CODE_LIVESTORE_SHADOW_CATCHUP_PARITY_CHECK=1`
- In shadow mode, compares `state.catchUp` mirror output against delegate output.
- `T3CODE_LIVESTORE_SHADOW_LIST_MESSAGES_PARITY_CHECK=1`
- In shadow mode, compares `state.listMessages` mirror output against delegate output.
- `T3CODE_LIVESTORE_DISABLE_READ_FALLBACK=1`
- In read-pilot mode, disables delegate read fallback for strict mirror-read canary validation.
- Web clients consume the server-authoritative `api.state.*` stream directly; server mode now controls fallback behavior.
## Suggested rollout sequence
1. **Baseline**
- Run in `legacy`.
- Ensure no outstanding state-sync regressions in CI.
2. **Shadow validation window**
- Enable `T3CODE_SYNC_ENGINE_MODE=shadow`.
- Watch logs for mirror commit failures.
- Validate parity fixtures and targeted tests.
3. **Read pilot**
- Enable `T3CODE_SYNC_ENGINE_MODE=livestore-read-pilot`.
- Start with parity flags enabled in staging.
- Verify bootstrap/catch-up/list-message fallback behavior under induced mirror failures.
4. **Confidence window**
- Keep parity flags enabled until drift warnings are consistently absent.
- Track fallback frequency (should trend toward zero in healthy conditions).
- Review `livestore read pilot metrics` shutdown logs for route-level source and fallback counts.
## Phase-5 cleanup readiness checklist
Before removing legacy-only sync plumbing:
- [ ] Read-pilot mode has stable production/staging behavior for a full confidence window.
- [ ] Bootstrap and catch-up parity checks show no unexplained drift.
- [ ] Fallback-to-delegate behavior has been exercised and observed as safe.
- [ ] Web client state-source mode seam is present and default behavior remains backwards-compatible.
- [ ] Parity and integration tests cover:
- [ ] project/thread/message lifecycle parity
- [ ] checkpoint revert parity
- [ ] websocket bootstrap/catch-up ordering in read-pilot
- [ ] websocket read fallback under mirror failures
## Final cutover notes
When promoting LiveStore path to default:
- keep legacy fallback for at least one release window;
- remove fallback only after confirming operational metrics and parity diagnostics remain healthy;
- remove legacy-only state sync glue in a dedicated cleanup PR to keep risk isolated and reviewable.
+39 -7
View File
@@ -300,6 +300,42 @@ function backendEnv(): NodeJS.ProcessEnv {
};
}
function resolveBackendLaunch(backendEntry: string): {
command: string;
args: string[];
env: NodeJS.ProcessEnv;
} {
const runtimeOverride = process.env.T3CODE_BACKEND_RUNTIME?.trim();
if (runtimeOverride && runtimeOverride.length > 0) {
if (runtimeOverride === "electron-node") {
return {
command: process.execPath,
args: [backendEntry],
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
};
}
return {
command: runtimeOverride,
args: [backendEntry],
env: backendEnv(),
};
}
// Default to Node-mode execution under Electron in both dev and production.
// This matches main and avoids runtime-specific PTY behavior differences.
return {
command: process.execPath,
args: [backendEntry],
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
};
}
function scheduleBackendRestart(reason: string): void {
if (isQuitting || restartTimer) return;
@@ -322,14 +358,10 @@ function startBackend(): void {
return;
}
const child = spawn(process.execPath, [backendEntry], {
const launch = resolveBackendLaunch(backendEntry);
const child = spawn(launch.command, launch.args, {
cwd: resolveBackendCwd(),
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
env: launch.env,
stdio: "inherit",
});
backendProcess = child;
+4 -6
View File
@@ -17,21 +17,19 @@
"test": "vitest run"
},
"dependencies": {
"@effect/platform-node": "4.0.0-beta.10",
"@effect/sql-sqlite-node": "4.0.0-beta.10",
"effect": "4.0.0-beta.10",
"@livestore/adapter-node": "^0.3.1",
"@livestore/livestore": "^0.3.1",
"@pierre/diffs": "^1.1.0-beta.16",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@effect/vitest": "4.0.0-beta.10",
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0"
"typescript": "^5.7.3"
}
}
+5 -7
View File
@@ -12,13 +12,11 @@ import type {
} from "./coreServices";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
interface ProcessRunner {
(
command: string,
args: readonly string[],
options?: ProcessRunOptions,
): Promise<ProcessRunResult>;
}
type ProcessRunner = (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
+6 -6
View File
@@ -29,7 +29,7 @@ export interface TerminalCommandInput {
maxOutputBytes?: number;
}
export type TerminalCommandResult = ProcessRunResult;
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
upstreamRef: string | null;
@@ -159,7 +159,7 @@ function normalizeGitSpawnError(cwd: string, error: unknown): Error {
return new Error(`Failed to run git command: ${error.message}`);
}
function normalizeGitExecutionError(args: readonly string[], result: ProcessRunResult): Error {
function normalizeGitExecutionError(args: readonly string[], result: TerminalCommandResult): Error {
const stderr = result.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return new Error("Current folder is not a git repository.");
@@ -176,8 +176,8 @@ async function runGitOrThrow(
cwd: string,
args: readonly string[],
options: RunGitOptions = {},
): Promise<ProcessRunResult> {
let result: ProcessRunResult;
): Promise<TerminalCommandResult> {
let result: TerminalCommandResult;
try {
result = await runGit(args, cwd, options.timeoutMs);
} catch (error) {
@@ -197,7 +197,7 @@ async function executeGit(
cwd: string,
args: readonly string[],
options: ExecuteGitOptions = {},
): Promise<ProcessRunResult> {
): Promise<TerminalCommandResult> {
const result = await runGitOrThrow(cwd, args, {
timeoutMs: options.timeoutMs,
allowNonZeroExit: true,
@@ -680,7 +680,7 @@ const defaultGitCoreService = new GitCoreService();
export async function runTerminalCommand(
input: TerminalCommandInput,
): Promise<ProcessRunResult> {
): Promise<TerminalCommandResult> {
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const shellPath =
process.platform === "win32"
+93 -3
View File
@@ -6,6 +6,13 @@ import { fileURLToPath } from "node:url";
import { fixPath } from "./fixPath";
import { createLogger } from "./logger";
import { bootstrapMirrorFromCatchUp } from "./livestore/mirrorBootstrap";
import { LiveStoreStateMirror } from "./livestore/liveStoreEngine";
import { PersistenceService } from "./persistenceService";
import { LegacyStateSyncEngine } from "./stateSyncEngineLegacy";
import { LiveStoreReadPilotStateSyncEngine } from "./stateSyncEngineLiveStoreReadPilot";
import { ShadowStateSyncEngine } from "./stateSyncEngineShadow";
import { assertSyncEngineModeAllowed, resolveSyncEngineMode } from "./syncEngineMode";
import { createServer } from "./wsServer";
fixPath();
@@ -48,6 +55,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();
@@ -100,7 +114,71 @@ 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 legacyStateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
const stateDbPath = resolveStateDbPath(process.env.T3CODE_STATE_DB_PATH);
const syncEngineMode = resolveSyncEngineMode(process.env.T3CODE_SYNC_ENGINE_MODE);
const enforceLiveStoreOnly =
parseBooleanEnv(process.env.T3CODE_LIVESTORE_ENFORCE_MODE) ?? false;
assertSyncEngineModeAllowed(syncEngineMode, {
enforceLiveStoreOnly,
});
const enableLiveStoreBootstrapParityCheck =
parseBooleanEnv(process.env.T3CODE_LIVESTORE_BOOTSTRAP_PARITY_CHECK) ?? false;
const enableLiveStoreCatchUpParityCheck =
parseBooleanEnv(process.env.T3CODE_LIVESTORE_CATCHUP_PARITY_CHECK) ?? false;
const enableLiveStoreListMessagesParityCheck =
parseBooleanEnv(process.env.T3CODE_LIVESTORE_LIST_MESSAGES_PARITY_CHECK) ?? false;
const enableLiveStoreShadowBootstrapParityCheck =
parseBooleanEnv(process.env.T3CODE_LIVESTORE_SHADOW_BOOTSTRAP_PARITY_CHECK) ?? false;
const enableLiveStoreShadowCatchUpParityCheck =
parseBooleanEnv(process.env.T3CODE_LIVESTORE_SHADOW_CATCHUP_PARITY_CHECK) ?? false;
const enableLiveStoreShadowListMessagesParityCheck =
parseBooleanEnv(process.env.T3CODE_LIVESTORE_SHADOW_LIST_MESSAGES_PARITY_CHECK) ?? false;
const disableLiveStoreDelegateReadFallback =
parseBooleanEnv(process.env.T3CODE_LIVESTORE_DISABLE_READ_FALLBACK) ?? false;
const persistenceService = new PersistenceService({
dbPath: stateDbPath,
legacyProjectsJsonPath: path.join(legacyStateDir, "projects.json"),
});
const legacyStateSyncEngine = new LegacyStateSyncEngine({ persistenceService });
const liveStoreMirror = new LiveStoreStateMirror({
storeId: `t3-shadow-${mode}`,
});
const isReadPilotMode = syncEngineMode === "livestore-read-pilot" || syncEngineMode === "livestore";
if (syncEngineMode === "shadow" || isReadPilotMode) {
const bootstrapResult = await bootstrapMirrorFromCatchUp({
source: legacyStateSyncEngine,
mirror: liveStoreMirror,
logger,
failOnError: syncEngineMode === "livestore",
});
logger.info("bootstrapped livestore mirror from persisted catch-up history", {
mirroredCount: bootstrapResult.mirroredCount,
lastStateSeq: bootstrapResult.lastStateSeq,
complete: bootstrapResult.complete,
syncEngineMode,
});
}
const stateSyncEngine =
syncEngineMode === "shadow"
? new ShadowStateSyncEngine({
delegate: legacyStateSyncEngine,
mirror: liveStoreMirror,
enableBootstrapParityCheck: enableLiveStoreShadowBootstrapParityCheck,
enableCatchUpParityCheck: enableLiveStoreShadowCatchUpParityCheck,
enableListMessagesParityCheck: enableLiveStoreShadowListMessagesParityCheck,
})
: isReadPilotMode
? new LiveStoreReadPilotStateSyncEngine({
delegate: legacyStateSyncEngine,
mirror: liveStoreMirror,
enableBootstrapParityCheck: enableLiveStoreBootstrapParityCheck,
enableCatchUpParityCheck: enableLiveStoreCatchUpParityCheck,
enableListMessagesParityCheck: enableLiveStoreListMessagesParityCheck,
disableDelegateReadFallback:
syncEngineMode === "livestore" ? true : disableLiveStoreDelegateReadFallback,
})
: legacyStateSyncEngine;
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;
@@ -116,9 +194,11 @@ async function main() {
port,
host: mode === "desktop" ? "127.0.0.1" : undefined,
cwd,
stateDir,
staticDir,
devUrl,
persistenceService,
stateSyncEngine,
syncEngineMode,
authToken,
});
await server.start();
@@ -128,7 +208,17 @@ async function main() {
url,
cwd,
mode,
stateDir,
stateDbPath,
legacyStateDir,
syncEngineMode,
enforceLiveStoreOnly,
liveStoreBootstrapParityCheck: enableLiveStoreBootstrapParityCheck,
liveStoreCatchUpParityCheck: enableLiveStoreCatchUpParityCheck,
liveStoreListMessagesParityCheck: enableLiveStoreListMessagesParityCheck,
liveStoreShadowBootstrapParityCheck: enableLiveStoreShadowBootstrapParityCheck,
liveStoreShadowCatchUpParityCheck: enableLiveStoreShadowCatchUpParityCheck,
liveStoreShadowListMessagesParityCheck: enableLiveStoreShadowListMessagesParityCheck,
liveStoreDisableReadFallback: disableLiveStoreDelegateReadFallback,
authEnabled: Boolean(authToken),
});
@@ -0,0 +1,197 @@
import { describe, expect, it } from "vitest";
import type { StateBootstrapResult, StateEvent } from "@t3tools/contracts";
import { diffStateSnapshots, isStateSnapshotInParity } from "./parity";
import { LiveStoreStateMirror } from "./liveStoreEngine";
function makeEvent(input: StateEvent): StateEvent {
return input;
}
function makeExpectedSnapshot(): StateBootstrapResult {
return {
projects: [
{
id: "project-1",
cwd: "/workspace/project",
name: "project",
scripts: [],
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:01.000Z",
},
],
threads: [
{
id: "thread-1",
codexThreadId: null,
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:02.000Z",
branch: null,
worktreePath: null,
turnDiffSummaries: [
{
turnId: "turn-1",
completedAt: "2026-02-20T00:00:04.000Z",
files: [],
},
],
messages: [
{
id: "message-1",
threadId: "thread-1",
role: "user",
text: "hello",
createdAt: "2026-02-20T00:00:03.000Z",
updatedAt: "2026-02-20T00:00:03.000Z",
streaming: false,
},
],
},
],
lastStateSeq: 4,
};
}
describe("LiveStoreStateMirror", () => {
it("projects mirrored state events into a parity snapshot", async () => {
const mirror = new LiveStoreStateMirror({ storeId: "shadow-parity-test" });
const events: StateEvent[] = [
makeEvent({
seq: 1,
eventType: "project.upsert",
entityId: "project-1",
createdAt: "2026-02-20T00:00:01.000Z",
payload: {
project: {
id: "project-1",
cwd: "/workspace/project",
name: "project",
scripts: [],
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:01.000Z",
},
},
}),
makeEvent({
seq: 2,
eventType: "thread.upsert",
entityId: "thread-1",
createdAt: "2026-02-20T00:00:02.000Z",
payload: {
thread: {
id: "thread-1",
codexThreadId: null,
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:02.000Z",
branch: null,
worktreePath: null,
},
},
}),
makeEvent({
seq: 3,
eventType: "message.upsert",
entityId: "thread-1:message-1",
createdAt: "2026-02-20T00:00:03.000Z",
payload: {
threadId: "thread-1",
message: {
id: "message-1",
threadId: "thread-1",
role: "user",
text: "hello",
createdAt: "2026-02-20T00:00:03.000Z",
updatedAt: "2026-02-20T00:00:03.000Z",
streaming: false,
},
},
}),
makeEvent({
seq: 4,
eventType: "turn_summary.upsert",
entityId: "thread-1:turn-1",
createdAt: "2026-02-20T00:00:04.000Z",
payload: {
threadId: "thread-1",
turnSummary: {
turnId: "turn-1",
completedAt: "2026-02-20T00:00:04.000Z",
files: [],
},
},
}),
];
try {
for (const event of events) {
await mirror.mirrorStateEvent(event);
}
const expected = makeExpectedSnapshot();
const actual = mirror.debugReadSnapshot();
expect(diffStateSnapshots(expected, actual)).toEqual([]);
expect(isStateSnapshotInParity(expected, actual)).toBe(true);
} finally {
await mirror.dispose();
}
});
it("handles delete events in mirrored projections", async () => {
const mirror = new LiveStoreStateMirror({ storeId: "shadow-delete-test" });
try {
await mirror.mirrorStateEvent(
makeEvent({
seq: 1,
eventType: "project.upsert",
entityId: "project-1",
createdAt: "2026-02-20T00:00:00.000Z",
payload: {
project: {
id: "project-1",
cwd: "/workspace/project",
name: "project",
scripts: [],
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:00.000Z",
},
},
}),
);
await mirror.mirrorStateEvent(
makeEvent({
seq: 2,
eventType: "project.delete",
entityId: "project-1",
createdAt: "2026-02-20T00:00:01.000Z",
payload: { projectId: "project-1" },
}),
);
const snapshot = mirror.debugReadSnapshot();
expect(snapshot.projects).toEqual([]);
expect(snapshot.threads).toEqual([]);
expect(snapshot.lastStateSeq).toBe(2);
} finally {
await mirror.dispose();
}
});
});
@@ -0,0 +1,323 @@
import { makeAdapter } from "@livestore/adapter-node";
import { createStorePromise } from "@livestore/livestore";
import {
stateBootstrapResultSchema,
stateCatchUpResultSchema,
stateListMessagesResultSchema,
stateMessageSchema,
stateProjectSchema,
stateThreadSchema,
stateTurnSummarySchema,
type StateBootstrapResult,
type StateCatchUpResult,
type StateEvent,
type StateListMessagesInput,
type StateListMessagesResult,
} from "@t3tools/contracts";
import { createLogger } from "../logger";
import type { StateEventMirror } from "../stateSyncEngineShadow";
import { liveStoreShadowSchema } from "./materializers";
import { liveStoreShadowEvents } from "./schema";
export interface LiveStoreStateMirrorOptions {
enabled?: boolean;
storeId?: string;
}
interface LiveStoreShadowStore {
commit: (event: unknown) => unknown;
shutdown?: () => unknown;
shutdownPromise?: () => Promise<void>;
}
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" && value.length > 0 ? value : undefined;
}
export class LiveStoreStateMirror implements StateEventMirror {
private readonly enabled: boolean;
private readonly storeId: string;
private readonly logger = createLogger("livestore-shadow");
private store: LiveStoreShadowStore | null = null;
private storePromise: Promise<LiveStoreShadowStore> | null = null;
private lastMirroredSeq = 0;
private disposed = false;
private readonly projectsById = new Map<string, StateBootstrapResult["projects"][number]>();
private readonly threadsById = new Map<string, StateBootstrapResult["threads"][number]>();
private readonly threadMessagesByThreadId = new Map<
string,
Map<string, StateBootstrapResult["threads"][number]["messages"][number]>
>();
private readonly turnSummariesByThreadId = new Map<
string,
Map<string, StateBootstrapResult["threads"][number]["turnDiffSummaries"][number]>
>();
private readonly mirroredEventsBySeq = new Map<number, StateEvent>();
constructor(options: LiveStoreStateMirrorOptions = {}) {
this.enabled = options.enabled ?? true;
this.storeId = options.storeId ?? "t3-shadow-sync";
}
async mirrorStateEvent(event: StateEvent): Promise<boolean> {
if (!this.enabled || this.disposed) {
return false;
}
if (event.seq <= this.lastMirroredSeq) {
return true;
}
const store = await this.getStore();
if (!store) {
return false;
}
try {
store.commit(
liveStoreShadowEvents.stateEventMirrored({
seq: event.seq,
eventType: event.eventType,
entityId: event.entityId,
payloadJson: JSON.stringify(event.payload),
createdAt: event.createdAt,
}, "shadow"),
);
this.applyProjection(event);
this.lastMirroredSeq = event.seq;
return true;
} catch (error) {
this.logger.warn("failed to commit mirrored state event", {
error,
seq: event.seq,
eventType: event.eventType,
});
return false;
}
}
async dispose(): Promise<void> {
if (this.disposed) {
return;
}
this.disposed = true;
const store = this.store;
this.store = null;
this.storePromise = null;
this.lastMirroredSeq = 0;
this.projectsById.clear();
this.threadsById.clear();
this.threadMessagesByThreadId.clear();
this.turnSummariesByThreadId.clear();
this.mirroredEventsBySeq.clear();
if (!store) {
return;
}
try {
if (typeof store.shutdownPromise === "function") {
await store.shutdownPromise();
} else if (typeof store.shutdown === "function") {
const maybeResult = store.shutdown();
if (maybeResult && typeof (maybeResult as PromiseLike<unknown>).then === "function") {
await maybeResult;
}
}
} catch (error) {
this.logger.warn("failed to shutdown livestore shadow store", { error });
}
}
private async getStore(): Promise<LiveStoreShadowStore | null> {
if (!this.enabled || this.disposed) {
return null;
}
if (!this.storePromise) {
const adapter = makeAdapter({
// Shadow mode is intended to validate event parity first.
// Persisted storage can be enabled later during cutover.
storage: { type: "in-memory" },
});
this.storePromise = createStorePromise({
adapter,
schema: liveStoreShadowSchema,
storeId: this.storeId,
})
.then((store) => {
const castStore = store as unknown as LiveStoreShadowStore;
this.store = castStore;
this.logger.info("initialized livestore shadow store", {
storeId: this.storeId,
});
return castStore;
})
.catch((error) => {
this.logger.warn("failed to initialize livestore shadow store", {
error,
storeId: this.storeId,
});
this.storePromise = null;
return Promise.reject(error);
});
}
try {
return await this.storePromise;
} catch {
return null;
}
}
debugReadSnapshot(): StateBootstrapResult {
const projects = Array.from(this.projectsById.values());
const threads = Array.from(this.threadsById.values()).map((thread) => {
const messagesById = this.threadMessagesByThreadId.get(thread.id);
const turnSummariesByTurnId = this.turnSummariesByThreadId.get(thread.id);
return {
...thread,
messages: messagesById
? Array.from(messagesById.values()).toSorted((a, b) => {
if (a.createdAt === b.createdAt) {
return a.id.localeCompare(b.id);
}
return a.createdAt.localeCompare(b.createdAt);
})
: [],
turnDiffSummaries: turnSummariesByTurnId
? Array.from(turnSummariesByTurnId.values()).toSorted((a, b) =>
b.completedAt.localeCompare(a.completedAt),
)
: [],
};
});
return stateBootstrapResultSchema.parse({
projects,
threads,
lastStateSeq: this.lastMirroredSeq,
});
}
debugCatchUp(afterSeq: number): StateCatchUpResult {
const events = Array.from(this.mirroredEventsBySeq.entries())
.filter(([seq]) => seq > afterSeq)
.sort(([a], [b]) => a - b)
.map(([, event]) => event);
return stateCatchUpResultSchema.parse({
events,
lastStateSeq: this.lastMirroredSeq,
});
}
debugListMessages(raw: StateListMessagesInput): StateListMessagesResult {
const snapshot = this.debugReadSnapshot();
const thread = snapshot.threads.find((candidate) => candidate.id === raw.threadId);
const messages = thread?.messages ?? [];
const offset = Math.max(0, Math.floor(raw.offset ?? 0));
const limit = Math.max(1, Math.floor(raw.limit ?? 200));
const paged = messages.slice(offset, offset + limit);
const nextOffset = offset + paged.length;
return stateListMessagesResultSchema.parse({
messages: paged,
total: messages.length,
nextOffset: nextOffset < messages.length ? nextOffset : null,
});
}
private applyProjection(event: StateEvent): void {
this.mirroredEventsBySeq.set(event.seq, event);
const payload = asObject(event.payload);
if (event.eventType === "project.upsert") {
const candidate = stateProjectSchema.safeParse(payload?.project);
if (candidate.success) {
this.projectsById.set(candidate.data.id, candidate.data);
}
return;
}
if (event.eventType === "project.delete") {
const projectId = asString(payload?.projectId) ?? event.entityId;
this.projectsById.delete(projectId);
for (const [threadId, thread] of this.threadsById.entries()) {
if (thread.projectId !== projectId) {
continue;
}
this.threadsById.delete(threadId);
this.threadMessagesByThreadId.delete(threadId);
this.turnSummariesByThreadId.delete(threadId);
}
return;
}
if (event.eventType === "thread.upsert") {
const candidate = stateThreadSchema.safeParse(payload?.thread);
if (!candidate.success) {
return;
}
this.threadsById.set(candidate.data.id, {
...candidate.data,
messages: [],
turnDiffSummaries: [],
});
return;
}
if (event.eventType === "thread.delete") {
const threadId = asString(payload?.threadId) ?? event.entityId;
this.threadsById.delete(threadId);
this.threadMessagesByThreadId.delete(threadId);
this.turnSummariesByThreadId.delete(threadId);
return;
}
if (event.eventType === "message.upsert") {
const threadId = asString(payload?.threadId);
const messageCandidate = stateMessageSchema.safeParse(payload?.message);
if (!threadId || !messageCandidate.success) {
return;
}
const byId = this.threadMessagesByThreadId.get(threadId) ?? new Map();
byId.set(messageCandidate.data.id, messageCandidate.data);
this.threadMessagesByThreadId.set(threadId, byId);
return;
}
if (event.eventType === "message.delete") {
const threadId = asString(payload?.threadId);
const messageId = asString(payload?.messageId);
if (!threadId || !messageId) {
return;
}
this.threadMessagesByThreadId.get(threadId)?.delete(messageId);
return;
}
if (event.eventType === "turn_summary.upsert") {
const threadId = asString(payload?.threadId);
const summaryCandidate = stateTurnSummarySchema.safeParse(payload?.turnSummary);
if (!threadId || !summaryCandidate.success) {
return;
}
const byTurnId = this.turnSummariesByThreadId.get(threadId) ?? new Map();
byTurnId.set(summaryCandidate.data.turnId, summaryCandidate.data);
this.turnSummariesByThreadId.set(threadId, byTurnId);
return;
}
if (event.eventType === "turn_summary.delete") {
const threadId = asString(payload?.threadId);
const turnId = asString(payload?.turnId);
if (!threadId || !turnId) {
return;
}
this.turnSummariesByThreadId.get(threadId)?.delete(turnId);
}
}
}
@@ -0,0 +1,16 @@
import { makeSchema, State } from "@livestore/livestore";
import { liveStoreShadowEvents, shadowMirrorStatus } from "./schema";
export const liveStoreShadowMaterializers = {};
export const liveStoreShadowState = State.SQLite.makeState({
tables: {
shadowMirrorStatus,
},
materializers: liveStoreShadowMaterializers,
});
export const liveStoreShadowSchema = makeSchema({
events: liveStoreShadowEvents,
state: liveStoreShadowState,
});
@@ -0,0 +1,208 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createLogger } from "../logger";
import { PersistenceService } from "../persistenceService";
import { LegacyStateSyncEngine } from "../stateSyncEngineLegacy";
import { bootstrapMirrorFromCatchUp } from "./mirrorBootstrap";
import { LiveStoreStateMirror } from "./liveStoreEngine";
import { diffStateSnapshots } from "./parity";
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("bootstrapMirrorFromCatchUp", () => {
it("mirrors catch-up history into the mirror sink", async () => {
const mirrorStateEvent = vi.fn();
const source = {
catchUp: vi.fn().mockReturnValue({
events: [
{
seq: 1,
entityId: "project-1",
eventType: "project.upsert",
payload: { id: "project-1", name: "Demo", path: "/demo" },
createdAt: new Date().toISOString(),
},
{
seq: 2,
entityId: "thread-1",
eventType: "thread.upsert",
payload: { id: "thread-1", title: "Thread" },
createdAt: new Date().toISOString(),
},
],
lastStateSeq: 2,
}),
};
const result = await bootstrapMirrorFromCatchUp({
source,
mirror: { mirrorStateEvent },
logger: createLogger("mirror-bootstrap-test"),
});
expect(result).toEqual({
mirroredCount: 2,
lastStateSeq: 2,
complete: true,
});
expect(mirrorStateEvent).toHaveBeenCalledTimes(2);
});
it("returns partial progress when non-fatal mirroring errors occur", async () => {
const mirrorStateEvent = vi
.fn()
.mockImplementationOnce(() => {})
.mockImplementationOnce(() => {
throw new Error("mirror write failed");
});
const source = {
catchUp: vi.fn().mockReturnValue({
events: [
{
seq: 1,
entityId: "project-1",
eventType: "project.upsert",
payload: { id: "project-1", name: "Demo", path: "/demo" },
createdAt: new Date().toISOString(),
},
{
seq: 2,
entityId: "thread-1",
eventType: "thread.upsert",
payload: { id: "thread-1", title: "Thread" },
createdAt: new Date().toISOString(),
},
],
lastStateSeq: 2,
}),
};
const result = await bootstrapMirrorFromCatchUp({
source,
mirror: { mirrorStateEvent },
logger: createLogger("mirror-bootstrap-test"),
});
expect(result).toEqual({
mirroredCount: 1,
lastStateSeq: 2,
complete: false,
});
expect(mirrorStateEvent).toHaveBeenCalledTimes(2);
});
it("throws when failOnError is enabled", async () => {
const mirrorStateEvent = vi.fn().mockImplementation(() => {
throw new Error("mirror write failed");
});
const source = {
catchUp: vi.fn().mockReturnValue({
events: [
{
seq: 1,
entityId: "project-1",
eventType: "project.upsert",
payload: { id: "project-1", name: "Demo", path: "/demo" },
createdAt: new Date().toISOString(),
},
],
lastStateSeq: 1,
}),
};
await expect(
bootstrapMirrorFromCatchUp({
source,
mirror: { mirrorStateEvent },
logger: createLogger("mirror-bootstrap-test"),
failOnError: true,
}),
).rejects.toThrow(/failed to bootstrap livestore mirror/i);
});
it("treats mirrorStateEvent false return as a bootstrap failure", async () => {
const source = {
catchUp: vi.fn().mockReturnValue({
events: [
{
seq: 1,
entityId: "project-1",
eventType: "project.upsert",
payload: { id: "project-1", name: "Demo", path: "/demo" },
createdAt: new Date().toISOString(),
},
],
lastStateSeq: 1,
}),
};
const result = await bootstrapMirrorFromCatchUp({
source,
mirror: { mirrorStateEvent: vi.fn().mockResolvedValue(false) },
logger: createLogger("mirror-bootstrap-test"),
});
expect(result).toEqual({
mirroredCount: 0,
lastStateSeq: 1,
complete: false,
});
});
it("replays persisted legacy catch-up history into a real LiveStore mirror", async () => {
const stateDir = makeTempDir("t3code-bootstrap-replay-state-");
const projectDir = makeTempDir("t3code-bootstrap-replay-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
const legacy = new LegacyStateSyncEngine({ persistenceService: service });
const mirror = new LiveStoreStateMirror({ storeId: "bootstrap-replay-parity-test" });
try {
const project = legacy.addProject({ cwd: projectDir }).project;
const thread = legacy.createThread({
projectId: project.id,
title: "Bootstrap replay parity thread",
}).thread;
service.bindSessionToThread("bootstrap-replay-session", thread.id, "runtime-thread-bootstrap");
service.persistUserMessageForTurn({
sessionId: "bootstrap-replay-session",
clientMessageId: "bootstrap-message-1",
clientMessageText: "bootstrap replay parity",
input: "bootstrap replay parity",
attachments: [],
});
const expectedSnapshot = legacy.loadSnapshot();
const bootstrapResult = await bootstrapMirrorFromCatchUp({
source: legacy,
mirror,
logger: createLogger("mirror-bootstrap-test"),
failOnError: true,
});
expect(bootstrapResult.complete).toBe(true);
expect(bootstrapResult.lastStateSeq).toBe(expectedSnapshot.lastStateSeq);
expect(bootstrapResult.mirroredCount).toBeGreaterThan(0);
expect(diffStateSnapshots(expectedSnapshot, mirror.debugReadSnapshot())).toEqual([]);
} finally {
await mirror.dispose();
service.close();
}
});
});
@@ -0,0 +1,60 @@
import type { StateCatchUpResult, StateEvent } from "@t3tools/contracts";
interface CatchUpSource {
catchUp(input: { afterSeq: number }): StateCatchUpResult;
}
interface MirrorSink {
mirrorStateEvent(event: StateEvent): void | boolean | Promise<void | boolean>;
}
interface LoggerLike {
warn(message: string, context?: Record<string, unknown>): void;
}
export interface MirrorBootstrapResult {
mirroredCount: number;
lastStateSeq: number;
complete: boolean;
}
export async function bootstrapMirrorFromCatchUp(options: {
source: CatchUpSource;
mirror: MirrorSink;
logger: LoggerLike;
failOnError?: boolean;
}): Promise<MirrorBootstrapResult> {
const { source, mirror, logger, failOnError = false } = options;
const catchUpResult = source.catchUp({ afterSeq: 0 });
let mirroredCount = 0;
for (const event of catchUpResult.events) {
try {
const mirrorResult = await mirror.mirrorStateEvent(event);
if (mirrorResult === false) {
throw new Error("mirrorStateEvent returned false");
}
mirroredCount += 1;
} catch (error) {
if (failOnError) {
throw new Error("failed to bootstrap livestore mirror from catch-up history", {
cause: error,
});
}
logger.warn("failed to bootstrap livestore mirror event; continuing with partial mirror state", {
error,
eventSeq: event.seq,
mirroredCount,
});
return {
mirroredCount,
lastStateSeq: catchUpResult.lastStateSeq,
complete: false,
};
}
}
return {
mirroredCount,
lastStateSeq: catchUpResult.lastStateSeq,
complete: true,
};
}
+262
View File
@@ -0,0 +1,262 @@
import { describe, expect, it } from "vitest";
import type { StateBootstrapResult } from "@t3tools/contracts";
import {
diffCatchUpResults,
diffListMessagesResults,
diffStateSnapshots,
isStateSnapshotInParity,
} from "./parity";
function makeSnapshot(overrides: Partial<StateBootstrapResult> = {}): StateBootstrapResult {
return {
projects: [],
threads: [],
lastStateSeq: 0,
...overrides,
};
}
describe("diffStateSnapshots", () => {
it("treats snapshots with different ordering as parity-equal", () => {
const projectA = {
id: "project-a",
cwd: "/workspace/a",
name: "A",
scripts: [],
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:00.000Z",
};
const projectB = {
id: "project-b",
cwd: "/workspace/b",
name: "B",
scripts: [],
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:00.000Z",
};
const threadA = {
id: "thread-a",
codexThreadId: null,
projectId: "project-a",
title: "Thread A",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:00.000Z",
branch: null,
worktreePath: null,
turnDiffSummaries: [
{
turnId: "turn-2",
completedAt: "2026-02-20T00:00:02.000Z",
files: [],
},
{
turnId: "turn-1",
completedAt: "2026-02-20T00:00:01.000Z",
files: [],
},
],
messages: [
{
id: "msg-2",
threadId: "thread-a",
role: "assistant" as const,
text: "hello",
createdAt: "2026-02-20T00:00:02.000Z",
updatedAt: "2026-02-20T00:00:02.000Z",
streaming: false,
},
{
id: "msg-1",
threadId: "thread-a",
role: "user" as const,
text: "hi",
createdAt: "2026-02-20T00:00:01.000Z",
updatedAt: "2026-02-20T00:00:01.000Z",
streaming: false,
},
],
};
const expected = makeSnapshot({
projects: [projectA, projectB],
threads: [threadA],
lastStateSeq: 10,
});
const actual = makeSnapshot({
projects: [projectB, projectA],
threads: [
{
...threadA,
turnDiffSummaries: [...threadA.turnDiffSummaries].toReversed(),
messages: [...threadA.messages].toReversed(),
},
],
lastStateSeq: 10,
});
expect(diffStateSnapshots(expected, actual)).toEqual([]);
expect(isStateSnapshotInParity(expected, actual)).toBe(true);
});
it("reports path-qualified diffs when snapshots diverge", () => {
const expected = makeSnapshot({
projects: [
{
id: "project-a",
cwd: "/workspace/a",
name: "Project A",
scripts: [],
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:00.000Z",
},
],
lastStateSeq: 5,
});
const actual = makeSnapshot({
projects: [
{
id: "project-a",
cwd: "/workspace/a",
name: "Project A renamed",
scripts: [],
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:00.000Z",
},
],
lastStateSeq: 7,
});
const diffs = diffStateSnapshots(expected, actual);
expect(diffs).toEqual(
expect.arrayContaining([
expect.objectContaining({
path: "$.lastStateSeq",
expected: 5,
actual: 7,
}),
expect.objectContaining({
path: "$.projects[0].name",
expected: "Project A",
actual: "Project A renamed",
}),
]),
);
expect(isStateSnapshotInParity(expected, actual)).toBe(false);
});
});
describe("diffCatchUpResults", () => {
it("returns empty diff when catch-up payloads are equal", () => {
const catchUp = {
events: [
{
seq: 1,
eventType: "project.upsert" as const,
entityId: "project-1",
payload: { project: { id: "project-1", name: "Demo" } },
createdAt: "2026-02-20T00:00:00.000Z",
},
],
lastStateSeq: 1,
};
expect(diffCatchUpResults(catchUp, catchUp)).toEqual([]);
});
it("returns targeted diffs for catch-up payload drift", () => {
const expected = {
events: [
{
seq: 1,
eventType: "project.upsert" as const,
entityId: "project-1",
payload: { project: { id: "project-1", name: "Demo" } },
createdAt: "2026-02-20T00:00:00.000Z",
},
],
lastStateSeq: 1,
};
const actual = {
events: [
{
seq: 2,
eventType: "project.delete" as const,
entityId: "project-2",
payload: { projectId: "project-2" },
createdAt: "2026-02-20T00:00:00.000Z",
},
],
lastStateSeq: 2,
};
expect(diffCatchUpResults(expected, actual)).toEqual(
expect.arrayContaining([
"lastStateSeq mismatch: expected=1 actual=2",
"events[0].seq mismatch: expected=1 actual=2",
"events[0].eventType mismatch: expected=project.upsert actual=project.delete",
"events[0].entityId mismatch: expected=project-1 actual=project-2",
"events[0].payload mismatch",
]),
);
});
});
describe("diffListMessagesResults", () => {
it("returns empty diff for equivalent list-messages responses", () => {
const result = {
messages: [
{
id: "message-1",
threadId: "thread-1",
role: "user" as const,
text: "hello",
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:00.000Z",
streaming: false,
},
],
total: 1,
nextOffset: null,
};
expect(diffListMessagesResults(result, result)).toEqual([]);
});
it("returns targeted diffs for list-messages drift", () => {
const expected = {
messages: [],
total: 1,
nextOffset: 1,
};
const actual = {
messages: [
{
id: "message-2",
threadId: "thread-1",
role: "assistant" as const,
text: "hi",
createdAt: "2026-02-20T00:00:00.000Z",
updatedAt: "2026-02-20T00:00:00.000Z",
streaming: false,
},
],
total: 2,
nextOffset: null,
};
expect(diffListMessagesResults(expected, actual)).toEqual(
expect.arrayContaining([
"total mismatch: expected=1 actual=2",
"nextOffset mismatch: expected=1 actual=null",
"messages.length mismatch: expected=0 actual=1",
]),
);
});
});
+180
View File
@@ -0,0 +1,180 @@
import type {
StateBootstrapResult,
StateCatchUpResult,
StateListMessagesResult,
} from "@t3tools/contracts";
export interface SnapshotParityDiff {
path: string;
expected: unknown;
actual: unknown;
}
function sortById<T extends { id: string }>(items: readonly T[]): T[] {
return [...items].sort((a, b) => a.id.localeCompare(b.id));
}
function normalizeSnapshot(snapshot: StateBootstrapResult): StateBootstrapResult {
return {
...snapshot,
projects: sortById(snapshot.projects),
threads: sortById(snapshot.threads).map((thread) => ({
...thread,
messages: [...thread.messages].sort((a, b) => {
if (a.id === b.id) {
return a.createdAt.localeCompare(b.createdAt);
}
return a.id.localeCompare(b.id);
}),
turnDiffSummaries: [...thread.turnDiffSummaries].sort((a, b) =>
a.turnId.localeCompare(b.turnId),
),
})),
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function collectDiffs(
expected: unknown,
actual: unknown,
path: string,
diffs: SnapshotParityDiff[],
): void {
if (Object.is(expected, actual)) {
return;
}
if (Array.isArray(expected) || Array.isArray(actual)) {
if (!Array.isArray(expected) || !Array.isArray(actual)) {
diffs.push({ path, expected, actual });
return;
}
if (expected.length !== actual.length) {
diffs.push({
path: `${path}.length`,
expected: expected.length,
actual: actual.length,
});
return;
}
for (let index = 0; index < expected.length; index += 1) {
collectDiffs(expected[index], actual[index], `${path}[${index}]`, diffs);
}
return;
}
if (isRecord(expected) || isRecord(actual)) {
if (!isRecord(expected) || !isRecord(actual)) {
diffs.push({ path, expected, actual });
return;
}
const keys = new Set([...Object.keys(expected), ...Object.keys(actual)]);
for (const key of [...keys].sort((a, b) => a.localeCompare(b))) {
collectDiffs(expected[key], actual[key], `${path}.${key}`, diffs);
}
return;
}
diffs.push({ path, expected, actual });
}
export function diffStateSnapshots(
expectedSnapshot: StateBootstrapResult,
actualSnapshot: StateBootstrapResult,
): SnapshotParityDiff[] {
const expected = normalizeSnapshot(expectedSnapshot);
const actual = normalizeSnapshot(actualSnapshot);
const diffs: SnapshotParityDiff[] = [];
collectDiffs(expected, actual, "$", diffs);
return diffs;
}
export function isStateSnapshotInParity(
expectedSnapshot: StateBootstrapResult,
actualSnapshot: StateBootstrapResult,
): boolean {
return diffStateSnapshots(expectedSnapshot, actualSnapshot).length === 0;
}
export function diffCatchUpResults(expected: StateCatchUpResult, actual: StateCatchUpResult): string[] {
const diffs: string[] = [];
if (expected.lastStateSeq !== actual.lastStateSeq) {
diffs.push(
`lastStateSeq mismatch: expected=${expected.lastStateSeq} actual=${actual.lastStateSeq}`,
);
}
if (expected.events.length !== actual.events.length) {
diffs.push(`events.length mismatch: expected=${expected.events.length} actual=${actual.events.length}`);
}
const minLength = Math.min(expected.events.length, actual.events.length);
for (let index = 0; index < minLength; index += 1) {
const expectedEvent = expected.events[index];
const actualEvent = actual.events[index];
if (!expectedEvent || !actualEvent) {
continue;
}
if (expectedEvent.seq !== actualEvent.seq) {
diffs.push(`events[${index}].seq mismatch: expected=${expectedEvent.seq} actual=${actualEvent.seq}`);
}
if (expectedEvent.eventType !== actualEvent.eventType) {
diffs.push(
`events[${index}].eventType mismatch: expected=${expectedEvent.eventType} actual=${actualEvent.eventType}`,
);
}
if (expectedEvent.entityId !== actualEvent.entityId) {
diffs.push(
`events[${index}].entityId mismatch: expected=${expectedEvent.entityId} actual=${actualEvent.entityId}`,
);
}
const expectedPayload = JSON.stringify(expectedEvent.payload);
const actualPayload = JSON.stringify(actualEvent.payload);
if (expectedPayload !== actualPayload) {
diffs.push(`events[${index}].payload mismatch`);
}
}
return diffs;
}
export function diffListMessagesResults(
expected: StateListMessagesResult,
actual: StateListMessagesResult,
): string[] {
const diffs: string[] = [];
if (expected.total !== actual.total) {
diffs.push(`total mismatch: expected=${expected.total} actual=${actual.total}`);
}
if (expected.nextOffset !== actual.nextOffset) {
diffs.push(
`nextOffset mismatch: expected=${String(expected.nextOffset)} actual=${String(actual.nextOffset)}`,
);
}
if (expected.messages.length !== actual.messages.length) {
diffs.push(
`messages.length mismatch: expected=${expected.messages.length} actual=${actual.messages.length}`,
);
}
const minLength = Math.min(expected.messages.length, actual.messages.length);
for (let index = 0; index < minLength; index += 1) {
const expectedMessage = expected.messages[index];
const actualMessage = actual.messages[index];
if (!expectedMessage || !actualMessage) {
continue;
}
const expectedSerialized = JSON.stringify(expectedMessage);
const actualSerialized = JSON.stringify(actualMessage);
if (expectedSerialized !== actualSerialized) {
diffs.push(`messages[${index}] mismatch`);
}
}
return diffs;
}
+25
View File
@@ -0,0 +1,25 @@
import { Schema, State } from "@livestore/livestore";
export const shadowMirrorStatus = State.SQLite.clientDocument({
name: "shadowMirrorStatus",
schema: Schema.Struct({
seq: Schema.Number,
eventType: Schema.String,
entityId: Schema.String,
payloadJson: Schema.String,
createdAt: Schema.String,
}),
default: {
value: {
seq: 0,
eventType: "",
entityId: "",
payloadJson: "{}",
createdAt: new Date(0).toISOString(),
},
},
});
export const liveStoreShadowEvents = {
stateEventMirrored: shadowMirrorStatus.set,
} as const;
-95
View File
@@ -1,95 +0,0 @@
import { SchemaIssue, Schema } from "effect";
import type { OrchestrationEventRepositoryError } from "../persistence/Errors.ts";
export class OrchestrationCommandJsonParseError extends Schema.TaggedErrorClass<OrchestrationCommandJsonParseError>()(
"OrchestrationCommandJsonParseError",
{
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Invalid orchestration command JSON: ${this.detail}`;
}
}
export class OrchestrationCommandDecodeError extends Schema.TaggedErrorClass<OrchestrationCommandDecodeError>()(
"OrchestrationCommandDecodeError",
{
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Invalid orchestration command payload: ${this.issue}`;
}
}
export class OrchestrationReducerDecodeError extends Schema.TaggedErrorClass<OrchestrationReducerDecodeError>()(
"OrchestrationReducerDecodeError",
{
eventType: Schema.String,
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Reducer decode failed for ${this.eventType}: ${this.issue}`;
}
}
export class OrchestrationListenerCallbackError extends Schema.TaggedErrorClass<OrchestrationListenerCallbackError>()(
"OrchestrationListenerCallbackError",
{
listener: Schema.Literals(["read-model", "domain-event"]),
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Orchestration ${this.listener} listener failed: ${this.detail}`;
}
}
export type OrchestrationDispatchError =
| OrchestrationEventRepositoryError
| OrchestrationReducerDecodeError
| OrchestrationListenerCallbackError;
export type OrchestrationEngineError =
| OrchestrationDispatchError
| OrchestrationCommandJsonParseError
| OrchestrationCommandDecodeError;
export function toOrchestrationCommandDecodeError(error: Schema.SchemaError) {
return new OrchestrationCommandDecodeError({
issue: SchemaIssue.makeFormatterDefault()(error.issue),
cause: error,
});
}
export function toReducerDecodeError(eventType: string) {
return (error: Schema.SchemaError): OrchestrationReducerDecodeError =>
new OrchestrationReducerDecodeError({
eventType,
issue: SchemaIssue.makeFormatterDefault()(error.issue),
cause: error,
});
}
export function toOrchestrationJsonParseError(cause: unknown) {
return new OrchestrationCommandJsonParseError({
detail: `Failed to parse orchestration command JSON: ${cause}`,
cause,
});
}
export function toListenerCallbackError(listener: "read-model" | "domain-event") {
return (cause: unknown): OrchestrationListenerCallbackError =>
new OrchestrationListenerCallbackError({
listener,
detail: `Failed to invoke orchestration ${listener} listener: ${cause}`,
cause,
});
}
-441
View File
@@ -1,441 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { OrchestrationEvent } from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime } from "effect";
import { afterEach, describe, expect, it } from "vitest";
import {
OrchestrationEventRepository,
type OrchestrationEventRepositoryShape,
} from "../persistence/Services/OrchestrationEvents.ts";
import { PersistenceSqlError } from "../persistence/Errors.ts";
import { makeSqlitePersistenceLive } from "../persistence/Layers/Sqlite.ts";
import { OrchestrationEngineLive } from "./Layer.ts";
import { OrchestrationEngineService } from "./Service.ts";
import { OrchestrationEventRepositoryLive } from "../persistence/Layers/OrchestrationEvents.ts";
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 });
}
});
export async function createOrchestrationSystem(stateDir: string) {
const dbPath = path.join(stateDir, "orchestration.sqlite");
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationEventRepositoryLive),
Layer.provide(makeSqlitePersistenceLive(dbPath)),
);
const runtime = ManagedRuntime.make(orchestrationLayer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
return {
engine,
run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
dispose: () => runtime.dispose(),
};
}
describe("OrchestrationEngine", () => {
it("replays to the same deterministic snapshot", async () => {
const stateDir = makeTempDir("t3code-orchestration-");
const createdAt = new Date().toISOString();
const projectId = "project-1";
const threadId = "thread-1";
const firstSystem = await createOrchestrationSystem(stateDir);
const engineA = firstSystem.engine;
await firstSystem.run(
engineA.dispatch({
type: "thread.create",
commandId: "cmd-1",
threadId,
projectId,
title: "Thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt,
}),
);
await firstSystem.run(
engineA.dispatch({
type: "message.send",
commandId: "cmd-3",
threadId,
messageId: "msg-1",
role: "user",
text: "hello",
streaming: false,
createdAt,
}),
);
const snapshotA = await firstSystem.run(engineA.getSnapshot());
await firstSystem.dispose();
const secondSystem = await createOrchestrationSystem(stateDir);
const engineB = secondSystem.engine;
const snapshotB = await secondSystem.run(engineB.getSnapshot());
expect(snapshotB).toEqual(snapshotA);
await secondSystem.dispose();
});
it("fans out read-model updates to subscribers", async () => {
const stateDir = makeTempDir("t3code-orchestration-fanout-");
const system = await createOrchestrationSystem(stateDir);
const engine = system.engine;
const updates: number[] = [];
const unsubscribe = await system.run(
engine.subscribeToReadModel((snapshot) => {
updates.push(snapshot.sequence);
}),
);
await system.run(
engine.dispatch({
type: "thread.create",
commandId: "cmd-thread",
threadId: "thread-2",
projectId: "project-2",
title: "fanout",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: new Date().toISOString(),
}),
);
unsubscribe();
expect(updates.length).toBeGreaterThan(0);
await system.dispose();
});
it("replays append-only events from sequence", async () => {
const stateDir = makeTempDir("t3code-orchestration-replay-");
const system = await createOrchestrationSystem(stateDir);
const engine = system.engine;
await system.run(
engine.dispatch({
type: "thread.create",
commandId: "cmd-a",
threadId: "thread-replay",
projectId: "project-replay",
title: "replay",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: new Date().toISOString(),
}),
);
await system.run(
engine.dispatch({
type: "thread.delete",
commandId: "cmd-b",
threadId: "thread-replay",
createdAt: new Date().toISOString(),
}),
);
const events = await system.run(engine.replayEvents(0));
expect(events.length).toBe(2);
expect(events[0]?.type).toBe("thread.created");
expect(events[1]?.type).toBe("thread.deleted");
await system.dispose();
});
it("stores completed turn summaries even when no files changed", async () => {
const stateDir = makeTempDir("t3code-orchestration-turn-diff-");
const firstSystem = await createOrchestrationSystem(stateDir);
const engine = firstSystem.engine;
const completedAt = new Date().toISOString();
await firstSystem.run(
engine.dispatch({
type: "thread.create",
commandId: "cmd-thread-turn-diff",
threadId: "thread-turn-diff",
projectId: "project-turn-diff",
title: "Turn diff thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: completedAt,
}),
);
await firstSystem.run(
engine.dispatch({
type: "thread.turnDiff.complete",
commandId: "cmd-turn-diff-complete",
threadId: "thread-turn-diff",
turnId: "turn-1",
completedAt,
status: "completed",
files: [],
checkpointTurnCount: 1,
createdAt: completedAt,
}),
);
const firstThread = (await firstSystem.run(engine.getSnapshot())).threads.find(
(thread) => thread.id === "thread-turn-diff",
);
expect(firstThread?.turnDiffSummaries).toEqual([
{
turnId: "turn-1",
completedAt,
status: "completed",
files: [],
checkpointTurnCount: 1,
},
]);
await firstSystem.dispose();
const secondSystem = await createOrchestrationSystem(stateDir);
const restartedEngine = secondSystem.engine;
const restartedThread = (await secondSystem.run(restartedEngine.getSnapshot())).threads.find(
(thread) => thread.id === "thread-turn-diff",
);
expect(restartedThread?.turnDiffSummaries).toEqual([
{
turnId: "turn-1",
completedAt,
status: "completed",
files: [],
checkpointTurnCount: 1,
},
]);
await secondSystem.dispose();
});
it("reverts thread messages and turn summaries to a checkpoint", async () => {
const stateDir = makeTempDir("t3code-orchestration-revert-");
const firstSystem = await createOrchestrationSystem(stateDir);
const engine = firstSystem.engine;
const createdAt = new Date().toISOString();
await firstSystem.run(
engine.dispatch({
type: "thread.create",
commandId: "cmd-thread-revert",
threadId: "thread-revert",
projectId: "project-revert",
title: "Revert thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt,
}),
);
await firstSystem.run(
engine.dispatch({
type: "message.send",
commandId: "cmd-msg-1-user",
threadId: "thread-revert",
messageId: "user-1",
role: "user",
text: "first",
streaming: false,
createdAt,
}),
);
await firstSystem.run(
engine.dispatch({
type: "message.send",
commandId: "cmd-msg-1-assistant",
threadId: "thread-revert",
messageId: "assistant:turn-1",
role: "assistant",
text: "first-response",
streaming: false,
createdAt,
}),
);
await firstSystem.run(
engine.dispatch({
type: "thread.turnDiff.complete",
commandId: "cmd-turn-1-complete",
threadId: "thread-revert",
turnId: "turn-1",
completedAt: createdAt,
status: "completed",
files: [],
assistantMessageId: "assistant:turn-1",
checkpointTurnCount: 1,
createdAt,
}),
);
const createdAtSecond = new Date(Date.now() + 1_000).toISOString();
await firstSystem.run(
engine.dispatch({
type: "message.send",
commandId: "cmd-msg-2-user",
threadId: "thread-revert",
messageId: "user-2",
role: "user",
text: "second",
streaming: false,
createdAt: createdAtSecond,
}),
);
await firstSystem.run(
engine.dispatch({
type: "message.send",
commandId: "cmd-msg-2-assistant",
threadId: "thread-revert",
messageId: "assistant:turn-2",
role: "assistant",
text: "second-response",
streaming: false,
createdAt: createdAtSecond,
}),
);
await firstSystem.run(
engine.dispatch({
type: "thread.turnDiff.complete",
commandId: "cmd-turn-2-complete",
threadId: "thread-revert",
turnId: "turn-2",
completedAt: createdAtSecond,
status: "completed",
files: [],
assistantMessageId: "assistant:turn-2",
checkpointTurnCount: 2,
createdAt: createdAtSecond,
}),
);
await firstSystem.run(
engine.dispatch({
type: "thread.revert",
commandId: "cmd-thread-revert-apply",
threadId: "thread-revert",
turnCount: 1,
messageCount: 2,
createdAt: createdAtSecond,
}),
);
const thread = (await firstSystem.run(engine.getSnapshot())).threads.find(
(entry) => entry.id === "thread-revert",
);
expect(thread?.messages.map((message) => message.id)).toEqual(["user-1", "assistant:turn-1"]);
expect(thread?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
expect(thread?.latestTurnId).toBe("turn-1");
await firstSystem.dispose();
const secondSystem = await createOrchestrationSystem(stateDir);
const restarted = secondSystem.engine;
const restartedThread = (await secondSystem.run(restarted.getSnapshot())).threads.find(
(entry) => entry.id === "thread-revert",
);
expect(restartedThread?.messages.map((message) => message.id)).toEqual([
"user-1",
"assistant:turn-1",
]);
expect(restartedThread?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
await secondSystem.dispose();
});
it("allows stop to be called multiple times", async () => {
const inMemoryStore: OrchestrationEventRepositoryShape = {
append(event) {
return Effect.succeed({ ...event, sequence: 1 });
},
readFromSequence() {
return Effect.succeed([]);
},
readAll() {
return Effect.succeed([]);
},
};
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(Layer.succeed(OrchestrationEventRepository, inMemoryStore)),
),
);
await runtime.runPromise(Effect.service(OrchestrationEngineService));
await runtime.dispose();
await expect(runtime.dispose()).resolves.toBeUndefined();
});
it("keeps processing queued commands after a storage failure", async () => {
const events: OrchestrationEvent[] = [];
let nextSequence = 1;
let shouldFailFirstAppend = true;
const flakyStore: OrchestrationEventRepositoryShape = {
append(event) {
if (shouldFailFirstAppend) {
shouldFailFirstAppend = false;
return Effect.fail(
new PersistenceSqlError({
operation: "test.append",
detail: "append failed",
}),
);
}
const savedEvent = {
...event,
sequence: nextSequence,
} satisfies OrchestrationEvent;
nextSequence += 1;
events.push(savedEvent);
return Effect.succeed(savedEvent);
},
readFromSequence(sequenceExclusive) {
return Effect.succeed(events.filter((event) => event.sequence > sequenceExclusive));
},
readAll() {
return Effect.succeed(events);
},
};
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(Layer.succeed(OrchestrationEventRepository, flakyStore)),
),
);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const createdAt = new Date().toISOString();
await expect(
runtime.runPromise(
engine.dispatch({
type: "thread.create",
commandId: "cmd-flaky-1",
threadId: "thread-flaky-fail",
projectId: "project-flaky",
title: "flaky-fail",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt,
}),
),
).rejects.toThrow("append failed");
const result = await runtime.runPromise(
engine.dispatch({
type: "thread.create",
commandId: "cmd-flaky-2",
threadId: "thread-flaky-ok",
projectId: "project-flaky",
title: "flaky-ok",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt,
}),
);
expect(result.sequence).toBe(1);
expect((await runtime.runPromise(engine.getSnapshot())).sequence).toBe(1);
await runtime.dispose();
});
});
-296
View File
@@ -1,296 +0,0 @@
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
} from "@t3tools/contracts";
import { OrchestrationCommandSchema } from "@t3tools/contracts";
import { Deferred, Effect, Layer, Queue, Schema } from "effect";
import { createLogger } from "../logger.ts";
import { OrchestrationEventRepository } from "../persistence/Services/OrchestrationEvents.ts";
import {
toListenerCallbackError,
toOrchestrationCommandDecodeError,
toOrchestrationJsonParseError,
type OrchestrationDispatchError,
} from "./Errors.ts";
import { createEmptyReadModel, reduceEvent } from "./reducer.ts";
import { OrchestrationEngineService, type OrchestrationEngineShape } from "./Service.ts";
interface CommandEnvelope {
command: OrchestrationCommand;
result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
transient?: boolean | undefined;
}
function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEvent, "sequence"> {
const eventId = crypto.randomUUID();
switch (command.type) {
case "thread.create":
return {
eventId,
type: "thread.created",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.threadId,
projectId: command.projectId,
title: command.title,
model: command.model,
branch: command.branch,
worktreePath: command.worktreePath,
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
};
case "thread.delete":
return {
eventId,
type: "thread.deleted",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.threadId,
deletedAt: command.createdAt,
},
};
case "thread.meta.update":
return {
eventId,
type: "thread.meta-updated",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.branch !== undefined ? { branch: command.branch } : {}),
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
updatedAt: command.createdAt,
},
};
case "message.send":
return {
eventId,
type: "message.sent",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.messageId,
role: command.role,
text: command.text,
threadId: command.threadId,
createdAt: command.createdAt,
streaming: command.streaming === true,
},
};
case "thread.session":
return {
eventId,
type: "thread.session-set",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
session: command.session,
},
};
case "git.readModel.upsert":
return {
eventId,
type: "git.read-model-upsert",
aggregateType: "project",
aggregateId: command.projectId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
projectId: command.projectId,
branch: command.branch,
hasWorkingTreeChanges: command.hasWorkingTreeChanges,
aheadCount: command.aheadCount,
behindCount: command.behindCount,
updatedAt: command.createdAt,
},
};
case "thread.turnDiff.complete":
return {
eventId,
type: "thread.turn-diff-completed",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
turnId: command.turnId,
completedAt: command.completedAt,
...(command.status !== undefined ? { status: command.status } : {}),
files: command.files,
...(command.assistantMessageId !== undefined
? { assistantMessageId: command.assistantMessageId }
: {}),
...(command.checkpointTurnCount !== undefined
? { checkpointTurnCount: command.checkpointTurnCount }
: {}),
},
};
case "thread.revert":
return {
eventId,
type: "thread.reverted",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
turnCount: command.turnCount,
messageCount: command.messageCount,
},
};
}
}
const decodeUnknownCommand = Schema.decodeUnknownEffect(OrchestrationCommandSchema);
const makeOrchestrationEngine = Effect.gen(function* () {
const logger = createLogger("orchestration");
const eventStore = yield* OrchestrationEventRepository;
let readModel = createEmptyReadModel(new Date().toISOString());
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
const readModelListeners = new Set<(snapshot: OrchestrationReadModel) => void>();
const domainEventListeners = new Set<(event: OrchestrationEvent) => void>();
const notifyReadModelListeners = (snapshot: OrchestrationReadModel) =>
Effect.forEach(readModelListeners, (listener) =>
Effect.try({
try: () => listener(snapshot),
catch: toListenerCallbackError("read-model"),
}),
).pipe(Effect.asVoid);
const notifyDomainEventListeners = (event: OrchestrationEvent) =>
Effect.forEach(domainEventListeners, (listener) =>
Effect.try({
try: () => listener(event),
catch: toListenerCallbackError("domain-event"),
}),
).pipe(Effect.asVoid);
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> =>
Effect.gen(function* () {
const eventBase = mapCommandToEvent(envelope.command);
let savedEvent: OrchestrationEvent;
if (envelope.transient) {
savedEvent = { ...eventBase, sequence: readModel.sequence };
} else {
savedEvent = yield* eventStore.append(eventBase);
}
readModel = yield* reduceEvent(readModel, savedEvent);
yield* Deferred.succeed(envelope.result, { sequence: savedEvent.sequence });
const snapshot = readModel;
yield* notifyDomainEventListeners(savedEvent).pipe(
Effect.catch((error) =>
Effect.sync(() => logger.warn("domain event listener failed", { error: String(error) })),
),
);
yield* notifyReadModelListeners(snapshot).pipe(
Effect.catch((error) =>
Effect.sync(() => logger.warn("read model listener failed", { error: String(error) })),
),
);
}).pipe(Effect.catch((error) => Deferred.fail(envelope.result, error).pipe(Effect.asVoid)));
const bootstrapReadModel: Effect.Effect<void, OrchestrationDispatchError> = Effect.gen(
function* () {
const existingEvents = yield* eventStore.readAll();
for (const event of existingEvents) {
readModel = yield* reduceEvent(readModel, event);
}
},
);
yield* bootstrapReadModel;
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
yield* Effect.forkScoped(worker);
logger.info("orchestration engine started", {
sequence: readModel.sequence,
});
const getSnapshot: OrchestrationEngineShape["getSnapshot"] = () =>
Effect.sync((): OrchestrationReadModel => readModel);
const replayEvents: OrchestrationEngineShape["replayEvents"] = (fromSequenceExclusive) =>
eventStore.readFromSequence(fromSequenceExclusive);
const dispatch: OrchestrationEngineShape["dispatch"] = (command, options) =>
Effect.gen(function* () {
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
yield* Queue.offer(commandQueue, { command, result, transient: options?.transient });
return yield* Deferred.await(result);
});
const dispatchUnknown: OrchestrationEngineShape["dispatchUnknown"] = (command) =>
Effect.gen(function* () {
const payload =
typeof command === "string"
? yield* Effect.try({
try: () => JSON.parse(command) as unknown,
catch: toOrchestrationJsonParseError,
})
: command;
const decoded = yield* decodeUnknownCommand(payload).pipe(
Effect.mapError(toOrchestrationCommandDecodeError),
);
return yield* dispatch(decoded);
});
const subscribeToReadModel: OrchestrationEngineShape["subscribeToReadModel"] = (callback) =>
Effect.sync(() => {
readModelListeners.add(callback);
return () => {
readModelListeners.delete(callback);
};
});
const subscribeToDomainEvents: OrchestrationEngineShape["subscribeToDomainEvents"] = (callback) =>
Effect.sync(() => {
domainEventListeners.add(callback);
return () => {
domainEventListeners.delete(callback);
};
});
return {
getSnapshot,
replayEvents,
dispatchUnknown,
dispatch,
subscribeToReadModel,
subscribeToDomainEvents,
} satisfies OrchestrationEngineShape;
});
export const OrchestrationEngineLive = Layer.effect(
OrchestrationEngineService,
makeOrchestrationEngine,
);
-97
View File
@@ -1,97 +0,0 @@
/**
* OrchestrationEngineService - Service interface for orchestration command handling.
*
* Uses Effect `Context.Tag` for dependency injection. Command dispatch,
* replay, and unknown-input decoding all return typed domain errors.
*
* @module OrchestrationEngineService
*/
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { OrchestrationDispatchError, OrchestrationEngineError } from "./Errors.ts";
import type { OrchestrationEventRepositoryError } from "../persistence/Errors.ts";
export interface OrchestrationEngineShape {
/**
* Read the current in-memory orchestration snapshot.
*
* @returns Effect containing the latest read model.
*/
readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel>;
/**
* Replay persisted orchestration events from an exclusive sequence cursor.
*
* @param fromSequenceExclusive - Sequence cursor (exclusive).
* @returns Effect containing ordered events.
*/
readonly replayEvents: (
fromSequenceExclusive: number,
) => Effect.Effect<OrchestrationEvent[], OrchestrationEventRepositoryError>;
/**
* Validate and dispatch an unknown command payload.
*
* Accepts either parsed values or raw JSON strings.
*
* @param command - Unknown command payload.
* @returns Effect containing the sequence of the persisted event.
*/
readonly dispatchUnknown: (
command: unknown,
) => Effect.Effect<{ sequence: number }, OrchestrationEngineError>;
/**
* Dispatch a validated orchestration command.
*
* @param command - Valid orchestration command.
* @param options - Optional dispatch options. Set `transient` to skip persistence.
* @returns Effect containing the sequence of the persisted event.
*/
readonly dispatch: (
command: OrchestrationCommand,
options?: { transient?: boolean | undefined } | undefined,
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError>;
/**
* Subscribe to read model updates.
*
* @param callback - Handler invoked on every read model update.
* @returns Effect containing an unsubscribe function.
*/
readonly subscribeToReadModel: (
callback: (snapshot: OrchestrationReadModel) => void,
) => Effect.Effect<() => void>;
/**
* Subscribe to domain event fan-out.
*
* @param callback - Handler invoked for every persisted domain event.
* @returns Effect containing an unsubscribe function.
*/
readonly subscribeToDomainEvents: (
callback: (event: OrchestrationEvent) => void,
) => Effect.Effect<() => void>;
}
/**
* OrchestrationEngineService - Context tag for orchestration engine access.
*
* @example
* ```ts
* const program = Effect.gen(function* () {
* const engine = yield* OrchestrationEngineService
* return yield* engine.getSnapshot()
* })
* ```
*/
export class OrchestrationEngineService extends ServiceMap.Service<
OrchestrationEngineService,
OrchestrationEngineShape
>()("orchestration/Engine") {}
@@ -1,97 +0,0 @@
import type { OrchestrationEvent } from "@t3tools/contracts";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import { createEmptyReadModel, reduceEvent } from "./reducer.ts";
describe("orchestration reducer", () => {
it("applies thread.created events using runtime schema decoding", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
const event: OrchestrationEvent = {
sequence: 1,
eventId: "event-thread-created",
type: "thread.created",
aggregateType: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-1",
payload: {
id: "thread-1",
projectId: "project-1",
title: "demo",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
};
const next = await Effect.runPromise(reduceEvent(model, event));
expect(next.sequence).toBe(1);
expect(next.threads).toEqual([
{
id: "thread-1",
projectId: "project-1",
title: "demo",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
latestTurnId: null,
latestTurnStartedAt: null,
latestTurnCompletedAt: null,
latestTurnDurationMs: null,
messages: [],
session: null,
turnDiffSummaries: [],
error: null,
},
]);
});
it("fails when event payload cannot be decoded by runtime schema", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
const event: OrchestrationEvent = {
sequence: 1,
eventId: "event-message-invalid",
type: "message.sent",
aggregateType: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-1",
payload: {
id: "message-1",
threadId: "thread-1",
text: "hello",
createdAt: now,
streaming: false,
},
};
await expect(Effect.runPromise(reduceEvent(model, event))).rejects.toBeDefined();
});
it("keeps reducer forward-compatible for unknown event types", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
const event: OrchestrationEvent = {
sequence: 7,
eventId: "event-unknown",
type: "custom.event.ignored",
aggregateType: "unknown",
aggregateId: "aggregate-1",
occurredAt: "2026-01-01T00:00:00.000Z",
commandId: null,
payload: { test: true },
};
const next = await Effect.runPromise(reduceEvent(model, event));
expect(next.sequence).toBe(7);
expect(next.updatedAt).toBe("2026-01-01T00:00:00.000Z");
expect(next.threads).toEqual([]);
});
});
-373
View File
@@ -1,373 +0,0 @@
import type {
OrchestrationEvent,
OrchestrationGitReadModel,
OrchestrationMessage,
OrchestrationReadModel,
OrchestrationSession,
OrchestrationThread,
} from "@t3tools/contracts";
import {
OrchestrationGitReadModelSchema,
OrchestrationMessageSchema,
OrchestrationSessionSchema,
OrchestrationThreadSchema,
OrchestrationTurnDiffFileSchema,
OrchestrationTurnDiffSummarySchema,
} from "@t3tools/contracts";
import { Effect, Schema } from "effect";
import { toReducerDecodeError, type OrchestrationReducerDecodeError } from "./Errors.ts";
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
function updateThread(
threads: ReadonlyArray<OrchestrationThread>,
threadId: string,
patch: ThreadPatch,
): OrchestrationThread[] {
return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));
}
function decodeForEvent<A>(
schema: Schema.Schema<A>,
value: unknown,
eventType: string,
field: string,
): Effect.Effect<A, OrchestrationReducerDecodeError> {
return Schema.decodeUnknownEffect(schema)(value).pipe(
Effect.mapError(toReducerDecodeError(`${eventType}:${field}`)),
) as Effect.Effect<A, OrchestrationReducerDecodeError>;
}
const ThreadCreatedPayloadSchema = Schema.Struct({
id: Schema.String,
projectId: Schema.String,
title: Schema.String,
model: Schema.String,
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
createdAt: Schema.String,
updatedAt: Schema.String,
});
const ThreadMetaUpdatedPayloadSchema = Schema.Struct({
threadId: Schema.String,
title: Schema.optional(Schema.String),
model: Schema.optional(Schema.String),
branch: Schema.optional(Schema.NullOr(Schema.String)),
worktreePath: Schema.optional(Schema.NullOr(Schema.String)),
updatedAt: Schema.String,
});
const MessageSentPayloadSchema = Schema.Struct({
id: Schema.String,
role: Schema.Literals(["user", "assistant"]),
text: Schema.String,
threadId: Schema.String,
createdAt: Schema.String,
streaming: Schema.Boolean,
});
const ThreadSessionSetPayloadSchema = Schema.Struct({
threadId: Schema.String,
session: OrchestrationSessionSchema,
});
const ThreadTurnDiffCompletedPayloadSchema = Schema.Struct({
threadId: Schema.String,
turnId: Schema.String,
completedAt: Schema.String,
status: Schema.optional(Schema.String),
files: Schema.Array(OrchestrationTurnDiffFileSchema),
assistantMessageId: Schema.optional(Schema.String),
checkpointTurnCount: Schema.optional(Schema.Number),
});
const ThreadRevertedPayloadSchema = Schema.Struct({
threadId: Schema.String,
turnCount: Schema.Number,
messageCount: Schema.Number,
});
export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
return {
sequence: 0,
threads: [],
gitByProjectId: {},
updatedAt: nowIso,
};
}
export function reduceEvent(
model: OrchestrationReadModel,
event: OrchestrationEvent,
): Effect.Effect<OrchestrationReadModel, OrchestrationReducerDecodeError> {
const nextBase: OrchestrationReadModel = {
...model,
sequence: event.sequence,
updatedAt: event.occurredAt,
};
switch (event.type) {
case "thread.created":
return Effect.gen(function* () {
const payload = yield* decodeForEvent(
ThreadCreatedPayloadSchema,
event.payload,
event.type,
"payload",
);
const thread: OrchestrationThread = yield* decodeForEvent(
OrchestrationThreadSchema,
{
id: payload.id,
projectId: payload.projectId,
title: payload.title,
model: payload.model,
branch: payload.branch,
worktreePath: payload.worktreePath,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
latestTurnId: null,
latestTurnStartedAt: null,
latestTurnCompletedAt: null,
latestTurnDurationMs: null,
messages: [],
session: null,
turnDiffSummaries: [],
error: null,
},
event.type,
"thread",
);
const existing = nextBase.threads.find((entry) => entry.id === thread.id);
return {
...nextBase,
threads: existing
? nextBase.threads.map((entry) => (entry.id === thread.id ? thread : entry))
: [...nextBase.threads, thread],
};
});
case "thread.deleted":
return Effect.succeed({
...nextBase,
threads: nextBase.threads.filter((thread) => thread.id !== event.aggregateId),
});
case "thread.meta-updated":
return decodeForEvent(
ThreadMetaUpdatedPayloadSchema,
event.payload,
event.type,
"payload",
).pipe(
Effect.map((payload) => {
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...(payload.title !== undefined ? { title: payload.title } : {}),
...(payload.model !== undefined ? { model: payload.model } : {}),
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
updatedAt: payload.updatedAt,
}),
};
}),
);
case "message.sent":
return Effect.gen(function* () {
const payload = yield* decodeForEvent(
MessageSentPayloadSchema,
event.payload,
event.type,
"payload",
);
const targetThread = nextBase.threads.find((thread) => thread.id === payload.threadId);
if (!targetThread) {
return nextBase;
}
const message: OrchestrationMessage = yield* decodeForEvent(
OrchestrationMessageSchema,
{
id: payload.id,
role: payload.role,
text: payload.text,
createdAt: payload.createdAt,
streaming: payload.streaming,
},
event.type,
"message",
);
const existingMessage = targetThread.messages.find((entry) => entry.id === message.id);
const nextMessages = existingMessage
? targetThread.messages.map((entry) =>
entry.id === message.id
? {
...entry,
text: message.streaming
? `${entry.text}${message.text}`
: message.text.length > 0
? message.text
: entry.text,
streaming: message.streaming,
createdAt: message.createdAt,
}
: entry,
)
: [...targetThread.messages, message];
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
messages: nextMessages,
updatedAt: event.occurredAt,
}),
};
});
case "thread.session-set":
return Effect.gen(function* () {
const payload = yield* decodeForEvent(
ThreadSessionSetPayloadSchema,
event.payload,
event.type,
"payload",
);
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
const session: OrchestrationSession = yield* decodeForEvent(
OrchestrationSessionSchema,
{
...payload.session,
threadId: payload.threadId,
},
event.type,
"session",
);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
session,
updatedAt: event.occurredAt,
error: session.lastError,
}),
};
});
case "thread.turn-diff-completed":
return Effect.gen(function* () {
const payload = yield* decodeForEvent(
ThreadTurnDiffCompletedPayloadSchema,
event.payload,
event.type,
"payload",
);
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
const nextSummary = yield* decodeForEvent(
OrchestrationTurnDiffSummarySchema,
{
turnId: payload.turnId,
completedAt: payload.completedAt,
...(payload.status !== undefined ? { status: payload.status } : {}),
files: payload.files,
...(payload.assistantMessageId !== undefined
? { assistantMessageId: payload.assistantMessageId }
: {}),
...(payload.checkpointTurnCount !== undefined
? { checkpointTurnCount: payload.checkpointTurnCount }
: {}),
},
event.type,
"turnDiffSummary",
);
const turnDiffSummaries = [
...thread.turnDiffSummaries.filter((summary) => summary.turnId !== payload.turnId),
nextSummary,
].toSorted((left, right) => left.completedAt.localeCompare(right.completedAt));
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
latestTurnId: payload.turnId,
latestTurnCompletedAt: nextSummary.completedAt,
turnDiffSummaries,
updatedAt: event.occurredAt,
}),
};
});
case "thread.reverted":
return decodeForEvent(ThreadRevertedPayloadSchema, event.payload, event.type, "payload").pipe(
Effect.map((payload) => {
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
const targetTurnCount = Math.max(0, Math.floor(payload.turnCount));
const targetMessageCount = Math.max(0, Math.floor(payload.messageCount));
const sortedSummaries = [...thread.turnDiffSummaries].toSorted((left, right) =>
left.completedAt.localeCompare(right.completedAt),
);
const inferredTurnCountByTurnId = new Map<string, number>();
for (let index = 0; index < sortedSummaries.length; index += 1) {
const summary = sortedSummaries[index];
if (!summary) continue;
inferredTurnCountByTurnId.set(summary.turnId, index + 1);
}
const turnDiffSummaries = thread.turnDiffSummaries
.filter((summary) => {
const checkpointTurnCount =
summary.checkpointTurnCount ?? inferredTurnCountByTurnId.get(summary.turnId) ?? 0;
return checkpointTurnCount <= targetTurnCount;
})
.toSorted((left, right) => left.completedAt.localeCompare(right.completedAt));
const latestSummary =
turnDiffSummaries.length > 0 ? turnDiffSummaries[turnDiffSummaries.length - 1] : null;
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
messages: thread.messages.slice(
0,
Math.min(targetMessageCount, thread.messages.length),
),
turnDiffSummaries,
latestTurnId: latestSummary?.turnId ?? null,
latestTurnStartedAt: null,
latestTurnCompletedAt: latestSummary?.completedAt ?? null,
latestTurnDurationMs: null,
updatedAt: event.occurredAt,
}),
};
}),
);
case "git.read-model-upsert":
return decodeForEvent(
OrchestrationGitReadModelSchema,
event.payload,
event.type,
"payload",
).pipe(
Effect.map((gitReadModel: OrchestrationGitReadModel) => ({
...nextBase,
gitByProjectId: {
...nextBase.gitByProjectId,
[gitReadModel.projectId]: gitReadModel,
},
})),
);
default:
return Effect.succeed(nextBase);
}
}
-126
View File
@@ -1,126 +0,0 @@
import { Schema, SchemaIssue } from "effect";
export class PersistenceSqlError extends Schema.TaggedErrorClass<PersistenceSqlError>()(
"PersistenceSqlError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `SQL error in ${this.operation}: ${this.detail}`;
}
}
export class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceDecodeError>()(
"PersistenceDecodeError",
{
operation: Schema.String,
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Decode error in ${this.operation}: ${this.issue}`;
}
}
export class PersistenceSerializationError extends Schema.TaggedErrorClass<PersistenceSerializationError>()(
"PersistenceSerializationError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Serialization error in ${this.operation}: ${this.detail}`;
}
}
export class ProjectValidationError extends Schema.TaggedErrorClass<ProjectValidationError>()(
"ProjectValidationError",
{
operation: Schema.String,
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Project validation failed in ${this.operation}: ${this.issue}`;
}
}
export class ProjectPathMissingError extends Schema.TaggedErrorClass<ProjectPathMissingError>()(
"ProjectPathMissingError",
{
cwd: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Project path does not exist: ${this.cwd}`;
}
}
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
"ProjectNotFoundError",
{
projectId: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Project not found: ${this.projectId}`;
}
}
export type ProjectRepositoryError =
| PersistenceSqlError
| PersistenceDecodeError
| PersistenceSerializationError
| ProjectValidationError
| ProjectPathMissingError
| ProjectNotFoundError;
export type OrchestrationEventRepositoryError =
| PersistenceSqlError
| PersistenceDecodeError
| PersistenceSerializationError;
export function toPersistenceSqlError(operation: string) {
return (cause: unknown): PersistenceSqlError =>
new PersistenceSqlError({
operation,
detail: `Failed to execute ${operation}`,
cause,
});
}
export function toPersistenceDecodeError(operation: string) {
return (error: Schema.SchemaError): PersistenceDecodeError =>
new PersistenceDecodeError({
operation,
issue: SchemaIssue.makeFormatterDefault()(error.issue),
cause: error,
});
}
export function toPersistenceDecodeCauseError(operation: string) {
return (cause: unknown): PersistenceDecodeError =>
new PersistenceDecodeError({
operation,
issue: `Failed to execute ${operation}`,
cause,
});
}
export function toPersistenceSerializationError(operation: string) {
return (cause: unknown): PersistenceSerializationError =>
new PersistenceSerializationError({
operation,
detail: `Failed to execute ${operation}`,
cause,
});
}
@@ -1,97 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import { ManagedRuntime, Effect } from "effect";
import { afterEach, describe, expect, it } from "vitest";
import { OrchestrationEventRepository } from "../Services/OrchestrationEvents.ts";
import { makeSqliteOrchestrationEventRepositoryLive } from "./OrchestrationEvents.ts";
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("OrchestrationEventRepository", () => {
it("persists and replays events across restarts", async () => {
const stateDir = makeTempDir("t3code-event-store-");
const dbPath = path.join(stateDir, "orchestration.sqlite");
const createdAt = new Date().toISOString();
const firstRuntime = ManagedRuntime.make(makeSqliteOrchestrationEventRepositoryLive(dbPath));
const first = await firstRuntime.runPromise(Effect.service(OrchestrationEventRepository));
const saved = await firstRuntime.runPromise(
first.append({
eventId: "event-1",
type: "thread.created",
aggregateType: "thread",
aggregateId: "thread-1",
occurredAt: createdAt,
commandId: "cmd-1",
payload: { id: "thread-1", projectId: "project-1", title: "demo" },
}),
);
expect(saved.sequence).toBe(1);
await firstRuntime.dispose();
const secondRuntime = ManagedRuntime.make(makeSqliteOrchestrationEventRepositoryLive(dbPath));
const second = await secondRuntime.runPromise(Effect.service(OrchestrationEventRepository));
const replayed = await secondRuntime.runPromise(second.readFromSequence(0));
expect(replayed).toEqual([saved]);
await secondRuntime.dispose();
});
it("creates and reuses the migrator tracking table", async () => {
const stateDir = makeTempDir("t3code-event-store-migrations-");
const dbPath = path.join(stateDir, "orchestration.sqlite");
const firstRuntime = ManagedRuntime.make(makeSqliteOrchestrationEventRepositoryLive(dbPath));
const first = await firstRuntime.runPromise(Effect.service(OrchestrationEventRepository));
await firstRuntime.runPromise(first.readAll());
await firstRuntime.dispose();
const secondRuntime = ManagedRuntime.make(makeSqliteOrchestrationEventRepositoryLive(dbPath));
const second = await secondRuntime.runPromise(Effect.service(OrchestrationEventRepository));
await secondRuntime.runPromise(second.readAll());
await secondRuntime.dispose();
const db = new DatabaseSync(dbPath, { readOnly: true });
const tableRow = db
.prepare(
`
SELECT name
FROM sqlite_master
WHERE type = 'table' AND name IN ('effect_sql_migrations', 'orchestration_sql_migrations')
ORDER BY name ASC
`,
)
.get() as { name: string } | undefined;
expect(tableRow?.name).toBeDefined();
expect(tableRow).toBeDefined();
if (!tableRow) return;
const migrationRows = db
.prepare(
`
SELECT *
FROM ${tableRow.name}
`,
)
.all() as Array<Record<string, unknown>>;
expect(migrationRows.length).toBeGreaterThanOrEqual(1);
expect(Object.values(migrationRows[0] ?? {}).length).toBeGreaterThan(0);
db.close();
});
});
@@ -1,183 +0,0 @@
import type { OrchestrationEvent } from "@t3tools/contracts";
import { OrchestrationEventSchema } from "@t3tools/contracts";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Schema } from "effect";
import {
toPersistenceDecodeCauseError,
toPersistenceDecodeError,
toPersistenceSerializationError,
toPersistenceSqlError,
type OrchestrationEventRepositoryError,
} from "../Errors.ts";
import { makeSqlitePersistenceLive } from "./Sqlite.ts";
import {
OrchestrationEventRepository,
type OrchestrationEventRepositoryShape,
} from "../Services/OrchestrationEvents.ts";
const decodeEvent = Schema.decodeUnknownEffect(OrchestrationEventSchema);
const EventRowSchema = Schema.Struct({
sequence: Schema.Number,
eventId: Schema.String,
type: Schema.String,
aggregateType: Schema.String,
aggregateId: Schema.String,
occurredAt: Schema.String,
commandId: Schema.NullOr(Schema.String),
payloadJson: Schema.String,
});
const AppendEventRequestSchema = Schema.Struct({
eventId: Schema.String,
type: Schema.String,
aggregateType: Schema.String,
aggregateId: Schema.String,
occurredAt: Schema.String,
commandId: Schema.NullOr(Schema.String),
payloadJson: Schema.String,
});
const ReadFromSequenceRequestSchema = Schema.Struct({
sequenceExclusive: Schema.Number,
limit: Schema.Number,
});
function eventRowToOrchestrationEvent(
row: Schema.Schema.Type<typeof EventRowSchema>,
operation: string,
): Effect.Effect<OrchestrationEvent, OrchestrationEventRepositoryError> {
return Effect.try({
try: () => JSON.parse(row.payloadJson) as unknown,
catch: toPersistenceDecodeCauseError(`${operation}:parsePayloadJson`),
}).pipe(
Effect.flatMap((payload) =>
decodeEvent({
sequence: row.sequence,
eventId: row.eventId,
type: row.type,
aggregateType: row.aggregateType,
aggregateId: row.aggregateId,
occurredAt: row.occurredAt,
commandId: row.commandId,
payload,
}).pipe(Effect.mapError(toPersistenceDecodeError(`${operation}:decodeEvent`))),
),
);
}
const makeRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const appendEventRow = SqlSchema.findOne({
Request: AppendEventRequestSchema,
Result: EventRowSchema,
execute: (request) =>
sql`
INSERT INTO orchestration_events (
event_id,
event_type,
aggregate_type,
aggregate_id,
occurred_at,
command_id,
payload_json
)
VALUES (
${request.eventId},
${request.type},
${request.aggregateType},
${request.aggregateId},
${request.occurredAt},
${request.commandId},
${request.payloadJson}
)
RETURNING
sequence,
event_id AS "eventId",
event_type AS "type",
aggregate_type AS "aggregateType",
aggregate_id AS "aggregateId",
occurred_at AS "occurredAt",
command_id AS "commandId",
payload_json AS "payloadJson"
`,
});
const readEventRowsFromSequence = SqlSchema.findAll({
Request: ReadFromSequenceRequestSchema,
Result: EventRowSchema,
execute: (request) =>
sql`
SELECT
sequence,
event_id AS "eventId",
event_type AS "type",
aggregate_type AS "aggregateType",
aggregate_id AS "aggregateId",
occurred_at AS "occurredAt",
command_id AS "commandId",
payload_json AS "payloadJson"
FROM orchestration_events
WHERE sequence > ${request.sequenceExclusive}
ORDER BY sequence ASC
LIMIT ${request.limit}
`,
});
const append: OrchestrationEventRepositoryShape["append"] = (event) =>
Effect.try({
try: () => JSON.stringify(event.payload),
catch: toPersistenceSerializationError("OrchestrationEventRepository.append:encodePayload"),
}).pipe(
Effect.flatMap((payloadJson) =>
appendEventRow({
eventId: event.eventId,
type: event.type,
aggregateType: event.aggregateType,
aggregateId: event.aggregateId,
occurredAt: event.occurredAt,
commandId: event.commandId,
payloadJson,
}).pipe(
Effect.mapError(toPersistenceSqlError("OrchestrationEventRepository.append:insert")),
Effect.flatMap((row) =>
eventRowToOrchestrationEvent(row, "OrchestrationEventRepository.append:rowToEvent"),
),
),
),
);
const readFromSequence: OrchestrationEventRepositoryShape["readFromSequence"] = (
sequenceExclusive,
limit = 1_000,
) =>
readEventRowsFromSequence({ sequenceExclusive, limit }).pipe(
Effect.mapError(toPersistenceSqlError("OrchestrationEventRepository.readFromSequence:query")),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) =>
eventRowToOrchestrationEvent(
row,
"OrchestrationEventRepository.readFromSequence:rowToEvent",
),
),
),
);
return {
append,
readFromSequence,
readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
} satisfies OrchestrationEventRepositoryShape;
});
export const OrchestrationEventRepositoryLive = Layer.effect(
OrchestrationEventRepository,
makeRepository,
);
export function makeSqliteOrchestrationEventRepositoryLive(dbPath: string) {
return OrchestrationEventRepositoryLive.pipe(Layer.provide(makeSqlitePersistenceLive(dbPath)));
}
@@ -1,83 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { Effect, Layer, ManagedRuntime } from "effect";
import { afterEach, describe, expect, it } from "vitest";
import { ProjectRepository } from "../Services/Projects.ts";
import { ProjectRepositoryLive } from "./Projects.ts";
import { makeSqlitePersistenceLive } from "./Sqlite.ts";
function makeProjectRepositoryTest(dbPath: string) {
return ProjectRepositoryLive.pipe(Layer.provide(makeSqlitePersistenceLive(dbPath)));
}
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("ProjectRepository", () => {
it("persists projects and deduplicates adds by cwd", async () => {
const stateDir = makeTempDir("t3code-project-repo-state-");
const projectDir = makeTempDir("t3code-project-repo-project-");
const dbPath = path.join(stateDir, "orchestration.sqlite");
const firstRuntime = ManagedRuntime.make(makeProjectRepositoryTest(dbPath));
const first = await firstRuntime.runPromise(Effect.service(ProjectRepository));
const created = await firstRuntime.runPromise(first.add({ cwd: projectDir }));
expect(created.created).toBe(true);
const duplicate = await firstRuntime.runPromise(first.add({ cwd: projectDir }));
expect(duplicate.created).toBe(false);
expect(duplicate.project.id).toBe(created.project.id);
await firstRuntime.dispose();
const secondRuntime = ManagedRuntime.make(makeProjectRepositoryTest(dbPath));
const second = await secondRuntime.runPromise(Effect.service(ProjectRepository));
const listed = await secondRuntime.runPromise(second.list());
expect(listed).toHaveLength(1);
expect(listed[0]?.cwd).toBe(projectDir);
await secondRuntime.dispose();
});
it("prunes missing project paths", async () => {
const stateDir = makeTempDir("t3code-project-repo-prune-state-");
const existing = makeTempDir("t3code-project-repo-prune-existing-");
const missing = makeTempDir("t3code-project-repo-prune-missing-");
const dbPath = path.join(stateDir, "orchestration.sqlite");
const runtime = ManagedRuntime.make(makeProjectRepositoryTest(dbPath));
const repository = await runtime.runPromise(Effect.service(ProjectRepository));
const existingProject = await runtime.runPromise(repository.add({ cwd: existing }));
const missingProject = await runtime.runPromise(repository.add({ cwd: missing }));
expect(existingProject.created).toBe(true);
expect(missingProject.created).toBe(true);
fs.rmSync(missing, { recursive: true, force: true });
await runtime.runPromise(repository.pruneMissing());
const listed = await runtime.runPromise(repository.list());
expect(listed).toHaveLength(1);
expect(listed[0]?.cwd).toBe(existing);
await runtime.dispose();
});
});
@@ -1,454 +0,0 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import type {
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectRecord,
ProjectScript,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
} from "@t3tools/contracts";
import {
normalizeProjectScripts,
projectAddInputSchema,
projectRecordSchema,
projectRemoveInputSchema,
projectScriptsSchema,
projectUpdateScriptsInputSchema,
} from "@t3tools/contracts";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Option, Schema } from "effect";
import {
PersistenceDecodeError,
ProjectNotFoundError,
ProjectPathMissingError,
ProjectValidationError,
toPersistenceDecodeCauseError,
toPersistenceSerializationError,
toPersistenceSqlError,
type ProjectRepositoryError,
} from "../Errors.ts";
import { ProjectRepository, type ProjectRepositoryShape } from "../Services/Projects.ts";
const ProjectRowSchema = Schema.Struct({
id: Schema.String,
cwd: Schema.String,
name: Schema.String,
scriptsJson: Schema.String,
createdAt: Schema.String,
updatedAt: Schema.String,
});
const FindByIdRequestSchema = Schema.Struct({
id: Schema.String,
});
const FindByCwdRequestSchema = Schema.Struct({
cwd: Schema.String,
});
const InsertProjectRequestSchema = Schema.Struct({
id: Schema.String,
cwd: Schema.String,
name: Schema.String,
scriptsJson: Schema.String,
createdAt: Schema.String,
updatedAt: Schema.String,
});
const UpdateScriptsRequestSchema = Schema.Struct({
id: Schema.String,
scriptsJson: Schema.String,
updatedAt: Schema.String,
});
const DeleteProjectRequestSchema = Schema.Struct({
id: Schema.String,
});
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";
}
function parseProjectScripts(
value: unknown,
operation: string,
): Effect.Effect<ProjectScript[], PersistenceDecodeError> {
const parsed = projectScriptsSchema.safeParse(value);
if (!parsed.success) {
return Effect.fail(
new PersistenceDecodeError({
operation,
issue: parsed.error.message,
cause: (parsed.error as { cause?: unknown }).cause,
}),
);
}
return Effect.succeed(normalizeProjectScripts(parsed.data));
}
function decodeScriptsJson(
raw: string,
operation: string,
): Effect.Effect<ProjectScript[], ProjectRepositoryError> {
return Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: toPersistenceDecodeCauseError(`${operation}:parseScriptsJson`),
}).pipe(Effect.flatMap((value) => parseProjectScripts(value, `${operation}:decodeScripts`)));
}
function rowToProjectRecord(
row: Schema.Schema.Type<typeof ProjectRowSchema>,
operation: string,
): Effect.Effect<ProjectRecord, ProjectRepositoryError> {
return decodeScriptsJson(row.scriptsJson, `${operation}:scripts`).pipe(
Effect.flatMap((scripts) => {
const parsed = projectRecordSchema.safeParse({
id: row.id,
cwd: row.cwd,
name: row.name,
scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
});
if (!parsed.success) {
return Effect.fail(
new PersistenceDecodeError({
operation: `${operation}:projectRecord`,
issue: parsed.error.message,
cause: (parsed.error as { cause?: unknown }).cause,
}),
);
}
return Effect.succeed(parsed.data);
}),
);
}
function decodeAddInput(rawInput: ProjectAddInput) {
const parsed = projectAddInputSchema.safeParse(rawInput);
if (!parsed.success) {
return Effect.fail(
new ProjectValidationError({
operation: "ProjectRepository.add",
issue: parsed.error.message,
cause: (parsed.error as { cause?: unknown }).cause,
}),
);
}
return Effect.succeed(parsed.data);
}
function decodeUpdateScriptsInput(rawInput: ProjectUpdateScriptsInput) {
const parsed = projectUpdateScriptsInputSchema.safeParse(rawInput);
if (!parsed.success) {
return Effect.fail(
new ProjectValidationError({
operation: "ProjectRepository.updateScripts",
issue: parsed.error.message,
cause: (parsed.error as { cause?: unknown }).cause,
}),
);
}
return Effect.succeed(parsed.data);
}
function decodeRemoveInput(rawInput: unknown) {
const parsed = projectRemoveInputSchema.safeParse(rawInput);
if (!parsed.success) {
return Effect.fail(
new ProjectValidationError({
operation: "ProjectRepository.remove",
issue: parsed.error.message,
cause: (parsed.error as { cause?: unknown }).cause,
}),
);
}
return Effect.succeed(parsed.data);
}
const makeRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const listProjectRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectRowSchema,
execute: () =>
sql`
SELECT
id,
cwd,
name,
scripts_json AS "scriptsJson",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projects
ORDER BY created_at DESC
`,
});
const findProjectById = SqlSchema.findOneOption({
Request: FindByIdRequestSchema,
Result: ProjectRowSchema,
execute: ({ id }) =>
sql`
SELECT
id,
cwd,
name,
scripts_json AS "scriptsJson",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projects
WHERE id = ${id}
`,
});
const findProjectByCwd = SqlSchema.findOneOption({
Request: FindByCwdRequestSchema,
Result: ProjectRowSchema,
execute: ({ cwd }) =>
sql`
SELECT
id,
cwd,
name,
scripts_json AS "scriptsJson",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projects
WHERE cwd = ${cwd}
`,
});
const insertProject = SqlSchema.findOne({
Request: InsertProjectRequestSchema,
Result: ProjectRowSchema,
execute: (request) =>
sql`
INSERT INTO projects (
id,
cwd,
name,
scripts_json,
created_at,
updated_at
)
VALUES (
${request.id},
${request.cwd},
${request.name},
${request.scriptsJson},
${request.createdAt},
${request.updatedAt}
)
RETURNING
id,
cwd,
name,
scripts_json AS "scriptsJson",
created_at AS "createdAt",
updated_at AS "updatedAt"
`,
});
const updateProjectScripts = SqlSchema.findOne({
Request: UpdateScriptsRequestSchema,
Result: ProjectRowSchema,
execute: (request) =>
sql`
UPDATE projects
SET
scripts_json = ${request.scriptsJson},
updated_at = ${request.updatedAt}
WHERE id = ${request.id}
RETURNING
id,
cwd,
name,
scripts_json AS "scriptsJson",
created_at AS "createdAt",
updated_at AS "updatedAt"
`,
});
const deleteProject = SqlSchema.void({
Request: DeleteProjectRequestSchema,
execute: ({ id }) => sql`DELETE FROM projects WHERE id = ${id}`,
});
const list: ProjectRepositoryShape["list"] = () =>
listProjectRows(undefined).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.list:query")),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) =>
rowToProjectRecord(row, "ProjectRepository.list:rowToProject"),
),
),
Effect.map(
(projects): ProjectListResult =>
projects.map((project) => ({ ...project, scripts: cloneScripts(project.scripts) })),
),
);
const add: ProjectRepositoryShape["add"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeAddInput(rawInput);
const normalizedCwd = normalizeCwd(input.cwd);
if (!isDirectory(normalizedCwd)) {
return yield* Effect.fail(new ProjectPathMissingError({ cwd: normalizedCwd }));
}
const existing = yield* findProjectByCwd({ cwd: normalizedCwd }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.add:findByCwd")),
);
if (Option.isSome(existing)) {
const project = yield* rowToProjectRecord(existing.value, "ProjectRepository.add:existing");
const result: ProjectAddResult = {
project: {
...project,
scripts: cloneScripts(project.scripts),
},
created: false,
};
return result;
}
const now = new Date().toISOString();
const row = yield* insertProject({
id: randomUUID(),
cwd: normalizedCwd,
name: inferProjectName(normalizedCwd),
scriptsJson: "[]",
createdAt: now,
updatedAt: now,
}).pipe(Effect.mapError(toPersistenceSqlError("ProjectRepository.add:insert")));
const created = yield* rowToProjectRecord(row, "ProjectRepository.add:created");
const result: ProjectAddResult = {
project: {
...created,
scripts: cloneScripts(created.scripts),
},
created: true,
};
return result;
});
const remove: ProjectRepositoryShape["remove"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeRemoveInput(rawInput);
const existing = yield* findProjectById({ id: input.id }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.remove:findById")),
);
if (Option.isNone(existing)) {
return yield* new ProjectNotFoundError({ projectId: input.id });
}
yield* deleteProject({ id: input.id }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.remove:delete")),
);
});
const updateScripts: ProjectRepositoryShape["updateScripts"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeUpdateScriptsInput(rawInput);
const existing = yield* findProjectById({ id: input.id }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.updateScripts:findById")),
);
if (Option.isNone(existing)) {
return yield* new ProjectNotFoundError({ projectId: input.id });
}
const nextScripts = yield* parseProjectScripts(
input.scripts,
"ProjectRepository.updateScripts:decodeScripts",
);
const scriptsJson = yield* Effect.try({
try: () => JSON.stringify(nextScripts),
catch: toPersistenceSerializationError("ProjectRepository.updateScripts:encodeScripts"),
});
const nextUpdatedAt = new Date().toISOString();
const updatedRow = yield* updateProjectScripts({
id: input.id,
scriptsJson,
updatedAt: nextUpdatedAt,
}).pipe(Effect.mapError(toPersistenceSqlError("ProjectRepository.updateScripts:update")));
const updated = yield* rowToProjectRecord(
updatedRow,
"ProjectRepository.updateScripts:updated",
);
const result: ProjectUpdateScriptsResult = {
project: {
...updated,
scripts: cloneScripts(updated.scripts),
},
};
return result;
});
const pruneMissing: ProjectRepositoryShape["pruneMissing"] = () =>
listProjectRows(undefined).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.pruneMissing:query")),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) => {
const normalizedCwd = normalizeCwd(row.cwd);
if (isDirectory(normalizedCwd)) {
return Effect.void;
}
return deleteProject({ id: row.id }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.pruneMissing:delete")),
);
}),
),
Effect.asVoid,
);
return {
list,
add,
remove,
updateScripts,
pruneMissing,
} satisfies ProjectRepositoryShape;
});
export const ProjectRepositoryLive = Layer.effect(ProjectRepository, makeRepository);
@@ -1,41 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqliteClient from "@effect/sql-sqlite-node/SqliteClient";
import { Effect, Layer, ServiceMap } from "effect";
import { runMigrations } from "../Migrations.ts";
export interface PersistenceConfigShape {
readonly dbPath: string;
}
export class PersistenceConfig extends ServiceMap.Service<
PersistenceConfig,
PersistenceConfigShape
>()("persistence/Config") {}
export function makeSqlitePersistenceLive(dbPath: string) {
const SqliteClientLive = Layer.unwrap(
Effect.sync(() => {
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
return SqliteClient.layer({ filename: dbPath });
}),
);
return Layer.effect(
SqlClient.SqlClient,
Effect.gen(function* () {
const sql = yield* SqliteClient.SqliteClient;
yield* sql`PRAGMA journal_mode = WAL;`;
yield* sql`PRAGMA foreign_keys = ON;`;
yield* runMigrations;
return sql;
}),
).pipe(Layer.provide(SqliteClientLive));
}
export const SqlitePersistenceLive = Layer.unwrap(
Effect.map(Effect.service(PersistenceConfig), ({ dbPath }) => makeSqlitePersistenceLive(dbPath)),
);
-68
View File
@@ -1,68 +0,0 @@
/**
* MigrationsLive - Migration runner with inline loader
*
* Uses Migrator.make with fromRecord to define migrations inline.
* All migrations are statically imported - no dynamic file system loading.
*
* Migrations run automatically when the MigrationLayer is provided,
* ensuring the database schema is always up-to-date before the application starts.
*/
import * as Migrator from "effect/unstable/sql/Migrator";
import * as Layer from "effect/Layer";
// Import all migrations statically
import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
import Migration0002 from "./Migrations/002_Projects.ts";
/**
* Migration loader with all migrations defined inline.
*
* Key format: "{id}_{name}" where:
* - id: numeric migration ID (determines execution order)
* - name: descriptive name for the migration
*
* Uses Migrator.fromRecord which parses the key format and
* returns migrations sorted by ID.
*/
const loader = Migrator.fromRecord({
"1_OrchestrationEvents": Migration0001,
"2_Projects": Migration0002,
});
/**
* Migrator run function - no schema dumping needed
* Uses the base Migrator.make without platform dependencies
*/
const run = Migrator.make({});
/**
* Run all pending migrations.
*
* Creates the migrations tracking table (effect_sql_migrations) if it doesn't exist,
* then runs any migrations with ID greater than the latest recorded migration.
*
* Returns array of [id, name] tuples for migrations that were run.
*
* @returns Effect containing array of executed migrations
*/
export const runMigrations = run({ loader });
/**
* Layer that runs migrations when the layer is built.
*
* Use this to ensure migrations run before your application starts.
* Migrations are run automatically - no separate script is needed.
*
* @example
* ```typescript
* import { MigrationsLive } from "@acme/db/Migrations"
* import { SqliteClient } from "@effect/sql-sqlite-node"
*
* // Migrations run automatically when SqliteClient is provided
* const AppLayer = MigrationsLive.pipe(
* Layer.provideMerge(SqliteClient.layer({ filename: "database.sqlite" }))
* )
* ```
*/
export const MigrationsLive = Layer.effectDiscard(runMigrations);
@@ -1,24 +0,0 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE TABLE IF NOT EXISTS orchestration_events (
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT NOT NULL UNIQUE,
event_type TEXT NOT NULL,
aggregate_type TEXT NOT NULL,
aggregate_id TEXT NOT NULL,
occurred_at TEXT NOT NULL,
command_id TEXT,
payload_json TEXT NOT NULL
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_orch_events_aggregate
ON orchestration_events(aggregate_type, aggregate_id, sequence)
`;
});
@@ -1,22 +0,0 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE TABLE IF NOT EXISTS projects (
id TEXT PRIMARY KEY,
cwd TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
scripts_json TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projects_created_at
ON projects(created_at DESC)
`;
});
@@ -1,60 +0,0 @@
/**
* OrchestrationEventRepository - Repository interface for orchestration events.
*
* Uses Effect `Context.Tag` for dependency injection and exposes typed
* persistence/decode errors for event append and replay operations.
*
* @module OrchestrationEventRepository
*/
import type { OrchestrationEvent } from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { OrchestrationEventRepositoryError } from "../Errors.ts";
export interface OrchestrationEventRepositoryShape {
/**
* Persist a new orchestration event.
*
* @param event - Event payload without sequence (assigned by storage).
* @returns Effect containing the stored event with assigned sequence.
*/
readonly append: (
event: Omit<OrchestrationEvent, "sequence">,
) => Effect.Effect<OrchestrationEvent, OrchestrationEventRepositoryError>;
/**
* Replay events after the provided sequence.
*
* @param sequenceExclusive - Sequence cursor (exclusive).
* @param limit - Maximum number of events to return.
* @returns Effect containing ordered events.
*/
readonly readFromSequence: (
sequenceExclusive: number,
limit?: number,
) => Effect.Effect<OrchestrationEvent[], OrchestrationEventRepositoryError>;
/**
* Read all events from the beginning of the stream.
*
* @returns Effect containing all stored events.
*/
readonly readAll: () => Effect.Effect<OrchestrationEvent[], OrchestrationEventRepositoryError>;
}
/**
* OrchestrationEventRepository - Context tag for orchestration event persistence.
*
* @example
* ```ts
* const program = Effect.gen(function* () {
* const events = yield* OrchestrationEventRepository
* return yield* events.readAll()
* })
* ```
*/
export class OrchestrationEventRepository extends ServiceMap.Service<
OrchestrationEventRepository,
OrchestrationEventRepositoryShape
>()("orchestration/EventRepository") {}
@@ -1,78 +0,0 @@
/**
* ProjectRepository - Repository interface for project persistence.
*
* Uses Effect `Context.Tag` for dependency injection and returns typed
* domain errors for all operations.
*
* @module ProjectRepository
*/
import type {
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectRemoveInput,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectRepositoryError } from "../Errors.ts";
export interface ProjectRepositoryShape {
/**
* List all persisted projects.
*
* @returns Effect containing all project records.
*/
readonly list: () => Effect.Effect<ProjectListResult, ProjectRepositoryError>;
/**
* Add a project by cwd, or return the existing project when the cwd already exists.
*
* @param input - Project creation payload.
* @returns Effect containing the project and whether it was newly created.
*/
readonly add: (input: ProjectAddInput) => Effect.Effect<ProjectAddResult, ProjectRepositoryError>;
/**
* Remove a persisted project.
*
* @param input - Project removal payload.
* @returns Effect containing void.
*/
readonly remove: (input: ProjectRemoveInput) => Effect.Effect<void, ProjectRepositoryError>;
/**
* Update the scripts for an existing project.
*
* @param input - Script update payload.
* @returns Effect containing the updated project.
*/
readonly updateScripts: (
input: ProjectUpdateScriptsInput,
) => Effect.Effect<ProjectUpdateScriptsResult, ProjectRepositoryError>;
/**
* Remove projects whose cwd no longer exists on disk.
*
* @returns Effect containing void.
*/
readonly pruneMissing: () => Effect.Effect<void, ProjectRepositoryError>;
}
/**
* ProjectRepository - Context tag for project persistence dependency injection.
*
* @example
* ```ts
* const program = Effect.gen(function* () {
* const projects = yield* ProjectRepository
* return yield* projects.list()
* })
* ```
*/
export class ProjectRepository extends ServiceMap.Service<
ProjectRepository,
ProjectRepositoryShape
>()("persistence/ProjectRepository") {}
+541
View File
@@ -0,0 +1,541 @@
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 { LiveStoreStateMirror } from "./livestore/liveStoreEngine";
import { diffStateSnapshots } from "./livestore/parity";
import { PersistenceService } from "./persistenceService";
import { LegacyStateSyncEngine } from "./stateSyncEngineLegacy";
import { ShadowStateSyncEngine } from "./stateSyncEngineShadow";
const tempDirs: string[] = [];
const ISO_BASE_MS = Date.parse("2026-02-19T00:00:00.000Z");
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
function iso(offsetMs = 0): string {
return new Date(ISO_BASE_MS + offsetMs).toISOString();
}
async function waitForMirrorParity(
readExpected: () => ReturnType<LegacyStateSyncEngine["loadSnapshot"]>,
readMirror: () => ReturnType<LiveStoreStateMirror["debugReadSnapshot"]>,
): Promise<void> {
const maxAttempts = 40;
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
if (diffStateSnapshots(readExpected(), readMirror()).length === 0) {
return;
}
await new Promise((resolve) => setTimeout(resolve, 15));
}
expect(diffStateSnapshots(readExpected(), readMirror())).toEqual([]);
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("PersistenceService", () => {
it("stores app settings in metadata with partial updates", () => {
const stateDir = makeTempDir("t3code-persistence-settings-state-");
const dbPath = path.join(stateDir, "state.sqlite");
const service = new PersistenceService({ dbPath });
try {
expect(service.getAppSettings()).toEqual({
codexBinaryPath: "",
codexHomePath: "",
});
expect(
service.updateAppSettings({
codexBinaryPath: " /opt/codex/bin/codex ",
}),
).toEqual({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "",
});
expect(
service.updateAppSettings({
codexHomePath: " /Users/theo/.codex ",
}),
).toEqual({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "/Users/theo/.codex",
});
} finally {
service.close();
}
const reopened = new PersistenceService({ dbPath });
try {
expect(reopened.getAppSettings()).toEqual({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "/Users/theo/.codex",
});
} finally {
reopened.close();
}
});
it("persists projects/threads/messages and serves bootstrap + catch-up", () => {
const stateDir = makeTempDir("t3code-persistence-state-");
const projectDir = makeTempDir("t3code-persistence-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
try {
const addedProject = service.addProject({ cwd: projectDir });
expect(addedProject.created).toBe(true);
const createdThread = service.createThread({
projectId: addedProject.project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
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");
expect(thread?.turnDiffSummaries[0]?.assistantMessageId).toBe("assistant-msg-1");
const catchUp = service.catchUp({ afterSeq: 0 });
expect(catchUp.events.length).toBeGreaterThan(0);
const sequences = catchUp.events.map((event) => event.seq);
expect(sequences.every((sequence) => Number.isInteger(sequence))).toBe(true);
for (let index = 1; index < sequences.length; index += 1) {
expect(sequences[index]).toBeGreaterThan(sequences[index - 1] ?? Number.NEGATIVE_INFINITY);
}
expect(catchUp.events.some((event) => event.eventType === "project.upsert")).toBe(true);
expect(catchUp.events.some((event) => event.eventType === "thread.upsert")).toBe(true);
expect(catchUp.events.some((event) => event.eventType === "message.upsert")).toBe(true);
} finally {
service.close();
}
});
it("stores turn diff summaries parsed from checkpoint diffs", () => {
const stateDir = makeTempDir("t3code-persistence-diff-state-");
const projectDir = makeTempDir("t3code-persistence-diff-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
try {
const project = service.addProject({ cwd: projectDir }).project;
const thread = service.createThread({
projectId: project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-1", thread.id, "runtime-thread-1");
service.persistTurnDiffSummaryFromCheckpoint({
sessionId: "sess-1",
runtimeThreadId: "runtime-thread-1",
turnId: "turn-1",
checkpointTurnCount: 1,
completedAt: "2026-02-19T00:00:00.000Z",
status: "completed",
diff: [
"diff --git a/src/app.ts b/src/app.ts",
"index 1111111..2222222 100644",
"--- a/src/app.ts",
"+++ b/src/app.ts",
"@@ -1,1 +1,2 @@",
"-console.log('a')",
"+console.log('b')",
"+console.log('c')",
].join("\n"),
});
service.ingestProviderEvent({
id: "evt-agent-msg-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-19T00:00:01.000Z",
method: "item/completed",
turnId: "turn-1",
itemId: "assistant-msg-1",
payload: {
item: {
type: "agentMessage",
id: "assistant-msg-1",
text: "done",
},
threadId: "runtime-thread-1",
turnId: "turn-1",
},
});
const snapshot = service.loadSnapshot();
const summary = snapshot.threads[0]?.turnDiffSummaries[0];
expect(summary?.turnId).toBe("turn-1");
expect(summary?.checkpointTurnCount).toBe(1);
expect(summary?.assistantMessageId).toBe("assistant-msg-1");
expect(summary?.files[0]?.path).toBe("src/app.ts");
expect(summary?.files[0]?.additions).toBe(2);
expect(summary?.files[0]?.deletions).toBe(1);
} finally {
service.close();
}
});
it("advances listMessages.nextOffset by fetched row count even when rows fail to parse", () => {
const stateDir = makeTempDir("t3code-persistence-list-messages-state-");
const projectDir = makeTempDir("t3code-persistence-list-messages-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
try {
const project = service.addProject({ cwd: projectDir }).project;
const thread = service.createThread({
projectId: project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-1", thread.id, "runtime-thread-1");
service.persistUserMessageForTurn({
sessionId: "sess-1",
clientMessageId: "msg-1",
clientMessageText: "first",
input: "first",
attachments: [],
});
service.persistUserMessageForTurn({
sessionId: "sess-1",
clientMessageId: "msg-2",
clientMessageText: "second",
input: "second",
attachments: [],
});
const db = (
service as unknown as {
db: { prepare: (sql: string) => { run: (...params: unknown[]) => unknown } };
}
).db;
db.prepare("UPDATE documents SET data_json = ? WHERE id = ?;").run(
"{bad-json",
`message:${thread.id}:msg-1`,
);
const firstPage = service.listMessages({
threadId: thread.id,
limit: 1,
offset: 0,
});
expect(firstPage.messages).toEqual([]);
expect(firstPage.total).toBe(2);
expect(firstPage.nextOffset).toBe(1);
const secondPage = service.listMessages({
threadId: thread.id,
limit: 1,
offset: firstPage.nextOffset ?? 0,
});
expect(secondPage.messages.map((message) => message.id)).toEqual(["msg-2"]);
expect(secondPage.nextOffset).toBeNull();
} finally {
service.close();
}
});
it("does not throw when state event listeners fail after commit", () => {
const stateDir = makeTempDir("t3code-persistence-state-events-");
const projectDir = makeTempDir("t3code-persistence-state-events-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
try {
service.on("stateEvent", () => {
throw new Error("listener failed");
});
const result = service.addProject({ cwd: projectDir });
expect(result.created).toBe(true);
expect(service.listProjects()).toHaveLength(1);
} finally {
service.close();
}
});
it("preserves checkpointTurnCount=0 when merging turn summaries", () => {
const stateDir = makeTempDir("t3code-persistence-checkpoint-zero-state-");
const projectDir = makeTempDir("t3code-persistence-checkpoint-zero-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
try {
const project = service.addProject({ cwd: projectDir }).project;
const thread = service.createThread({
projectId: project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-1", thread.id, "runtime-thread-1");
service.persistTurnDiffSummaryFromCheckpoint({
sessionId: "sess-1",
runtimeThreadId: "runtime-thread-1",
turnId: "turn-1",
checkpointTurnCount: 0,
completedAt: "2026-02-19T00:00:00.000Z",
diff: "",
});
service.ingestProviderEvent({
id: "evt-assistant-completed",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-19T00:00:01.000Z",
method: "item/completed",
turnId: "turn-1",
payload: {
item: {
type: "agentMessage",
id: "assistant-msg-1",
text: "done",
},
},
});
const snapshot = service.loadSnapshot();
const summary = snapshot.threads[0]?.turnDiffSummaries.find(
(entry) => entry.turnId === "turn-1",
);
expect(summary?.checkpointTurnCount).toBe(0);
expect(summary?.assistantMessageId).toBe("assistant-msg-1");
} finally {
service.close();
}
});
it("does not let out-of-order item/started overwrite accumulated assistant text", () => {
const stateDir = makeTempDir("t3code-persistence-item-order-state-");
const projectDir = makeTempDir("t3code-persistence-item-order-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
try {
const project = service.addProject({ cwd: projectDir }).project;
const thread = service.createThread({
projectId: project.id,
title: "Thread 1",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-1", thread.id, "runtime-thread-1");
service.ingestProviderEvent({
id: "evt-delta",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-19T00:00:02.000Z",
method: "item/agentMessage/delta",
itemId: "assistant-msg-1",
textDelta: "hello",
payload: {
itemId: "assistant-msg-1",
delta: "hello",
},
});
service.ingestProviderEvent({
id: "evt-started-late",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-19T00:00:03.000Z",
method: "item/started",
payload: {
item: {
type: "agentMessage",
id: "assistant-msg-1",
text: "",
},
},
});
const messages = service.listMessages({
threadId: thread.id,
limit: 10,
offset: 0,
}).messages;
const assistantMessage = messages.find((message) => message.id === "assistant-msg-1");
expect(assistantMessage?.text).toBe("hello");
} finally {
service.close();
}
});
it("maintains shadow mirror parity across checkpoint revert effects", async () => {
const stateDir = makeTempDir("t3code-persistence-shadow-parity-state-");
const projectDir = makeTempDir("t3code-persistence-shadow-parity-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
const legacy = new LegacyStateSyncEngine({ persistenceService: service });
const mirror = new LiveStoreStateMirror({ storeId: "persistence-shadow-parity-test" });
const shadow = new ShadowStateSyncEngine({
delegate: legacy,
mirror,
});
try {
const project = shadow.addProject({ cwd: projectDir }).project;
const thread = shadow.createThread({
projectId: project.id,
title: "checkpoint parity thread",
model: "gpt-5.3-codex",
}).thread;
service.bindSessionToThread("sess-shadow", thread.id, "runtime-thread-shadow");
service.persistUserMessageForTurn({
sessionId: "sess-shadow",
clientMessageId: "msg-1",
clientMessageText: "first",
input: "first",
attachments: [],
});
service.persistUserMessageForTurn({
sessionId: "sess-shadow",
clientMessageId: "msg-2",
clientMessageText: "second",
input: "second",
attachments: [],
});
service.persistTurnDiffSummaryFromCheckpoint({
sessionId: "sess-shadow",
runtimeThreadId: "runtime-thread-shadow",
turnId: "turn-1",
checkpointTurnCount: 1,
completedAt: iso(100),
diff: "",
});
service.persistTurnDiffSummaryFromCheckpoint({
sessionId: "sess-shadow",
runtimeThreadId: "runtime-thread-shadow",
turnId: "turn-2",
checkpointTurnCount: 2,
completedAt: iso(200),
diff: "",
});
shadow.applyCheckpointRevert({
sessionId: "sess-shadow",
runtimeThreadId: "runtime-thread-shadow",
turnCount: 1,
messageCount: 1,
});
await waitForMirrorParity(() => legacy.loadSnapshot(), () => mirror.debugReadSnapshot());
const mirrored = mirror.debugReadSnapshot();
expect(mirrored.threads[0]?.messages.map((message) => message.id)).toEqual(["msg-1"]);
expect(mirrored.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
"turn-1",
]);
expect(diffStateSnapshots(legacy.loadSnapshot(), mirrored)).toEqual([]);
} finally {
shadow.close();
}
});
});
File diff suppressed because it is too large. Load diff
+117
View File
@@ -0,0 +1,117 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { ProjectRegistry } from "./projectRegistry";
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("ProjectRegistry scripts", () => {
it("stores and reloads project scripts", () => {
const stateDir = makeTempDir("t3code-project-registry-state-");
const projectDir = makeTempDir("t3code-project-registry-project-");
const registry = new ProjectRegistry(stateDir);
const created = registry.add({ cwd: projectDir }).project;
const updated = registry.updateScripts({
id: created.id,
scripts: [
{
id: "run",
name: "Run",
command: "bun run dev",
icon: "play",
runOnWorktreeCreate: false,
},
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
],
});
expect(updated.project.scripts).toHaveLength(2);
expect(updated.project.scripts[1]?.id).toBe("setup");
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(true);
const reloaded = new ProjectRegistry(stateDir);
const listed = reloaded.list();
expect(listed).toHaveLength(1);
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", () => {
const stateDir = makeTempDir("t3code-project-registry-state-");
const projectDir = makeTempDir("t3code-project-registry-project-");
const registry = new ProjectRegistry(stateDir);
const created = registry.add({ cwd: projectDir }).project;
const updated = registry.updateScripts({
id: created.id,
scripts: [
{
id: "setup",
name: "Setup",
command: "echo setup",
icon: "configure",
runOnWorktreeCreate: true,
},
{
id: "setup",
name: "Setup Duplicate",
command: "echo duplicate",
icon: "configure",
runOnWorktreeCreate: true,
},
{
id: "another",
name: "Another Setup",
command: "echo another",
icon: "play",
runOnWorktreeCreate: true,
},
],
});
expect(updated.project.scripts).toHaveLength(2);
expect(updated.project.scripts[0]?.id).toBe("setup");
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", () => {
const stateDir = makeTempDir("t3code-project-registry-state-");
const registry = new ProjectRegistry(stateDir);
expect(() =>
registry.updateScripts({
id: "missing-project",
scripts: [],
}),
).toThrowError("Project not found");
registry.close();
});
});
+47
View File
@@ -0,0 +1,47 @@
import path from "node:path";
import type {
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectRemoveInput,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
} from "@t3tools/contracts";
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 persistenceService: PersistenceService;
constructor(stateDir: string) {
this.persistenceService = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
});
}
list(): ProjectListResult {
return this.persistenceService.listProjects();
}
add(raw: ProjectAddInput): ProjectAddResult {
return this.persistenceService.addProject(raw);
}
remove(raw: ProjectRemoveInput): void {
this.persistenceService.removeProject(raw);
}
updateScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
return this.persistenceService.updateProjectScripts(raw);
}
close(): void {
this.persistenceService.close();
}
}
+1 -14
View File
@@ -298,14 +298,12 @@ describe("ProviderManager", () => {
it("emits checkpoint/captured after turn completion checkpoint capture", async () => {
const manager = new ProviderManager();
const events: Array<{ method: string; payload?: unknown; threadId?: string; turnId?: string }> =
[];
const events: Array<{ method: string; payload?: unknown; threadId?: string }> = [];
manager.on("event", (event) => {
events.push({
method: event.method,
...(event.payload !== undefined ? { payload: event.payload } : {}),
...(event.threadId ? { threadId: event.threadId } : {}),
...(event.turnId ? { turnId: event.turnId } : {}),
});
});
@@ -318,8 +316,6 @@ describe("ProviderManager", () => {
createdAt: string;
method: string;
threadId: string;
turnId?: string;
payload?: unknown;
}) => void;
codex: {
hasSession: (sessionId: string) => boolean;
@@ -355,12 +351,6 @@ describe("ProviderManager", () => {
createdAt: "2026-02-19T00:00:00.000Z",
method: "turn/completed",
threadId: "thr_1",
turnId: "turn_1",
payload: {
turn: {
status: "completed",
},
},
});
await vi.waitFor(() => {
@@ -374,12 +364,9 @@ describe("ProviderManager", () => {
const checkpointCapturedEvent = events.find((event) => event.method === "checkpoint/captured");
expect(checkpointCapturedEvent?.threadId).toBe("thr_1");
expect(checkpointCapturedEvent?.turnId).toBe("turn_1");
expect(checkpointCapturedEvent?.payload).toEqual({
threadId: "thr_1",
turnCount: 1,
turnId: "turn_1",
status: "completed",
});
manager.dispose();
+81 -32
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];
@@ -130,12 +135,6 @@ function summarizeTurn(turn: CodexThreadTurnSnapshot): {
};
}
function readTurnCompletionStatus(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return asString(turn?.status);
}
function buildCheckpoints(turns: CodexThreadTurnSnapshot[]): ProviderCheckpoint[] {
const checkpoints: ProviderCheckpoint[] = [];
let messageCount = 0;
@@ -169,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>();
@@ -182,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");
@@ -203,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);
@@ -221,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);
}
@@ -245,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);
@@ -481,7 +507,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
return;
}
const turnStatus = readTurnCompletionStatus(event);
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
if (!checkpointCwd) {
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId)
@@ -490,13 +515,8 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
return;
}
const snapshot = await this.codex.readThread(event.sessionId);
this.emitCheckpointCaptured(
event.sessionId,
snapshot.threadId,
snapshot.turns.length,
event.turnId,
turnStatus,
);
await this.persistCheckpointSummaryForTurn(event, initializedCwd, snapshot.threadId, snapshot.turns);
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
})
.catch((error) => {
const message =
@@ -517,26 +537,15 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
this.emitCheckpointCaptured(
event.sessionId,
snapshot.threadId,
snapshot.turns.length,
event.turnId,
turnStatus,
);
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.";
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
});
}
private emitCheckpointCaptured(
sessionId: string,
threadId: string,
turnCount: number,
turnId?: string,
status?: string,
): void {
private emitCheckpointCaptured(sessionId: string, threadId: string, turnCount: number): void {
this.emit("event", {
id: randomUUID(),
kind: "notification",
@@ -545,12 +554,9 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
createdAt: new Date().toISOString(),
method: "checkpoint/captured",
threadId,
...(turnId ? { turnId } : {}),
payload: {
threadId,
turnCount,
...(turnId ? { turnId } : {}),
...(status ? { status } : {}),
},
});
}
@@ -667,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,
});
}
}
+43
View File
@@ -0,0 +1,43 @@
import { describe, expect, it, vi } from "vitest";
import { openSqliteDatabase } from "./sqliteAdapter";
describe("sqliteAdapter", () => {
it("opens a database and runs basic statements", () => {
const db = openSqliteDatabase(":memory:");
db.exec("CREATE TABLE sample (id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT NOT NULL);");
const insertResult = db.prepare("INSERT INTO sample (value) VALUES (?);").run("hello") as {
changes?: number;
lastInsertRowid?: number;
};
expect(insertResult.changes).toBe(1);
const row = db.prepare("SELECT value FROM sample WHERE id = ?;").get(1) as
| { value?: string }
| undefined;
expect(row?.value).toBe("hello");
const rows = db.prepare("SELECT value FROM sample ORDER BY id ASC;").all() as Array<{
value?: string;
}>;
expect(rows.map((entry) => entry.value)).toEqual(["hello"]);
db.close();
});
it("throws a helpful error when node:sqlite is unavailable", () => {
const missingModuleError = new Error("No such built-in module: node:sqlite");
(missingModuleError as NodeJS.ErrnoException).code = "ERR_UNKNOWN_BUILTIN_MODULE";
const requireFn = vi.fn((specifier: string) => {
if (specifier === "node:sqlite") {
throw missingModuleError;
}
throw new Error(`Unexpected module request: ${specifier}`);
});
expect(() => openSqliteDatabase(":memory:", requireFn as never, false)).toThrow(
"node:sqlite is unavailable",
);
});
});
+119
View File
@@ -0,0 +1,119 @@
import { createRequire } from "node:module";
import path from "node:path";
export interface SqliteStatement {
run: (...params: unknown[]) => unknown;
get: (...params: unknown[]) => unknown;
all: (...params: unknown[]) => unknown[];
}
export interface SqliteDatabase {
exec: (sql: string) => void;
prepare: (sql: string) => SqliteStatement;
close: () => void;
}
interface NodeSqliteModule {
DatabaseSync: new (filename: string) => {
exec: (sql: string) => void;
prepare: (sql: string) => SqliteStatement;
close: () => void;
};
}
interface BunSqliteStatement {
run: (...params: unknown[]) => unknown;
get: (...params: unknown[]) => unknown;
all: (...params: unknown[]) => unknown[];
}
interface BunSqliteModule {
Database: new (filename: string) => {
exec: (sql: string) => unknown;
query: (sql: string) => BunSqliteStatement;
close: () => void;
};
}
function isNodeSqliteUnavailableError(error: unknown): boolean {
if (!(error instanceof Error)) {
return false;
}
const code = (error as NodeJS.ErrnoException).code;
if (code === "ERR_UNKNOWN_BUILTIN_MODULE" || code === "MODULE_NOT_FOUND") {
return true;
}
return error.message.includes("node:sqlite");
}
function openNodeSqliteDatabase(
requireFn: ReturnType<typeof createRequire>,
dbPath: string,
): SqliteDatabase {
let nodeSqlite: NodeSqliteModule;
try {
nodeSqlite = requireFn("node:sqlite") as NodeSqliteModule;
} catch (error) {
if (isNodeSqliteUnavailableError(error)) {
throw new Error(
"node:sqlite is unavailable in this runtime. Use Node.js 22+ (or run the server with Bun).",
{ cause: error },
);
}
throw error;
}
if (typeof nodeSqlite.DatabaseSync !== "function") {
throw new Error(
"node:sqlite was loaded but DatabaseSync is missing. Upgrade Node.js or run the server with Bun.",
);
}
const db = new nodeSqlite.DatabaseSync(dbPath);
return {
exec: (sql) => {
db.exec(sql);
},
prepare: (sql) => db.prepare(sql),
close: () => {
db.close();
},
};
}
function openBunSqliteDatabase(
requireFn: ReturnType<typeof createRequire>,
dbPath: string,
): SqliteDatabase {
const bunSqlite = requireFn("bun:sqlite") as BunSqliteModule;
const db = new bunSqlite.Database(dbPath);
return {
exec: (sql) => {
db.exec(sql);
},
prepare: (sql) => {
const statement = db.query(sql);
return {
run: (...params: unknown[]) => statement.run(...params),
get: (...params: unknown[]) => statement.get(...params),
all: (...params: unknown[]) => statement.all(...params),
};
},
close: () => {
db.close();
},
};
}
export function openSqliteDatabase(
dbPath: string,
requireFn: ReturnType<typeof createRequire> = createRequire(
path.join(process.cwd(), "t3code-sqlite-adapter.cjs"),
),
runtimeIsBun = Boolean(process.versions.bun),
): SqliteDatabase {
if (runtimeIsBun) {
// Development mode runs in Bun, so use Bun's SQLite adapter
return openBunSqliteDatabase(requireFn, dbPath);
}
return openNodeSqliteDatabase(requireFn, dbPath);
}
+105
View File
@@ -0,0 +1,105 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { StateDb } from "./stateDb";
import * as sqliteAdapter from "./sqliteAdapter";
import { STATE_DB_SCHEMA_VERSION } from "./stateMigrations";
import * as stateMigrations from "./stateMigrations";
const tempDirs: string[] = [];
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 });
}
vi.restoreAllMocks();
});
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();
});
it("closes the database when migrations fail during construction", () => {
const tempDir = makeTempDir("t3code-state-db-migration-fail-");
const dbPath = path.join(tempDir, "state.sqlite");
const close = vi.fn();
const fakeDb = {
exec: vi.fn(),
prepare: vi.fn(),
close,
};
vi.spyOn(sqliteAdapter, "openSqliteDatabase").mockReturnValue(
fakeDb as unknown as sqliteAdapter.SqliteDatabase,
);
vi.spyOn(stateMigrations, "runStateMigrations").mockImplementation(() => {
throw new Error("migration failed");
});
expect(() => new StateDb({ dbPath })).toThrow("migration failed");
expect(close).toHaveBeenCalledTimes(1);
});
it("preserves the original transaction error when rollback fails", () => {
const tempDir = makeTempDir("t3code-state-db-rollback-fail-");
const dbPath = path.join(tempDir, "state.sqlite");
const rollbackError = new Error("rollback failed");
const exec = vi.fn((sql: string) => {
if (sql === "ROLLBACK;") {
throw rollbackError;
}
});
const fakeDb = {
exec,
prepare: vi.fn(),
close: vi.fn(),
};
vi.spyOn(sqliteAdapter, "openSqliteDatabase").mockReturnValue(
fakeDb as unknown as sqliteAdapter.SqliteDatabase,
);
vi.spyOn(stateMigrations, "runStateMigrations").mockImplementation(() => {});
const stateDb = new StateDb({ dbPath });
const originalError = new Error("operation failed");
let thrown: unknown;
try {
stateDb.transaction(() => {
throw originalError;
});
} catch (error) {
thrown = error;
}
expect(thrown).toBe(originalError);
expect(exec).toHaveBeenCalledWith("ROLLBACK;");
stateDb.close();
});
});
+50
View File
@@ -0,0 +1,50 @@
import fs from "node:fs";
import path from "node:path";
import { openSqliteDatabase, type SqliteDatabase } from "./sqliteAdapter";
import { runStateMigrations } from "./stateMigrations";
export interface StateDbOptions {
dbPath: string;
}
export class StateDb {
readonly dbPath: string;
readonly db: SqliteDatabase;
constructor(options: StateDbOptions) {
this.dbPath = path.resolve(options.dbPath);
fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
this.db = openSqliteDatabase(this.dbPath);
try {
runStateMigrations(this.db);
} catch (error) {
try {
this.db.close();
} catch {
// Best effort close on failed initialization.
}
throw error;
}
}
close(): void {
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) {
try {
this.db.exec("ROLLBACK;");
} catch {
// Preserve the original transactional failure.
}
throw error;
}
}
}
+96
View File
@@ -0,0 +1,96 @@
import type { SqliteDatabase } from "./sqliteAdapter";
export const STATE_DB_SCHEMA_VERSION = 1;
export function applyStateDbPragmas(db: SqliteDatabase): void {
db.exec("PRAGMA journal_mode=WAL;");
db.exec("PRAGMA synchronous=FULL;");
db.exec("PRAGMA busy_timeout=5000;");
db.exec("PRAGMA foreign_keys=ON;");
}
function readUserVersion(db: SqliteDatabase): number {
const row = db.prepare("PRAGMA user_version;").get() as { user_version?: number } | undefined;
const value = row?.user_version;
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
return 0;
}
return value;
}
function migrationV1(db: SqliteDatabase): 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: SqliteDatabase): 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;
}
}
+53
View File
@@ -0,0 +1,53 @@
import type {
AppSettings,
AppSettingsUpdateInput,
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectRemoveInput,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
StateBootstrapResult,
StateCatchUpInput,
StateCatchUpResult,
StateEvent,
StateListMessagesInput,
StateListMessagesResult,
ThreadsCreateInput,
ThreadsDeleteInput,
ThreadsMarkVisitedInput,
ThreadsUpdateBranchInput,
ThreadsUpdateModelInput,
ThreadsUpdateResult,
ThreadsUpdateTerminalStateInput,
ThreadsUpdateTitleInput,
} from "@t3tools/contracts";
export interface ApplyCheckpointRevertInput {
sessionId: string;
runtimeThreadId: string;
turnCount: number;
messageCount: number;
}
export interface StateSyncEngine {
onStateEvent(listener: (event: StateEvent) => void): () => void;
loadSnapshot(): StateBootstrapResult;
listMessages(raw: StateListMessagesInput): StateListMessagesResult;
catchUp(raw: StateCatchUpInput): StateCatchUpResult;
getAppSettings(): AppSettings;
updateAppSettings(raw: AppSettingsUpdateInput): AppSettings;
createThread(raw: ThreadsCreateInput): ThreadsUpdateResult;
updateThreadTerminalState(raw: ThreadsUpdateTerminalStateInput): ThreadsUpdateResult;
updateThreadModel(raw: ThreadsUpdateModelInput): ThreadsUpdateResult;
updateThreadTitle(raw: ThreadsUpdateTitleInput): ThreadsUpdateResult;
updateThreadBranch(raw: ThreadsUpdateBranchInput): ThreadsUpdateResult;
markThreadVisited(raw: ThreadsMarkVisitedInput): ThreadsUpdateResult;
deleteThread(raw: ThreadsDeleteInput): void;
listProjects(): ProjectListResult;
addProject(raw: ProjectAddInput): ProjectAddResult;
removeProject(raw: ProjectRemoveInput): void;
updateProjectScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult;
applyCheckpointRevert(input: ApplyCheckpointRevertInput): void;
close(): void;
}
+117
View File
@@ -0,0 +1,117 @@
import type {
AppSettings,
AppSettingsUpdateInput,
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectRemoveInput,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
StateBootstrapResult,
StateCatchUpInput,
StateCatchUpResult,
StateEvent,
StateListMessagesInput,
StateListMessagesResult,
ThreadsCreateInput,
ThreadsDeleteInput,
ThreadsMarkVisitedInput,
ThreadsUpdateBranchInput,
ThreadsUpdateModelInput,
ThreadsUpdateResult,
ThreadsUpdateTerminalStateInput,
ThreadsUpdateTitleInput,
} from "@t3tools/contracts";
import type { PersistenceService } from "./persistenceService";
import type { ApplyCheckpointRevertInput, StateSyncEngine } from "./stateSyncEngine";
export interface LegacyStateSyncEngineOptions {
persistenceService: PersistenceService;
}
export class LegacyStateSyncEngine implements StateSyncEngine {
private readonly persistenceService: PersistenceService;
constructor(options: LegacyStateSyncEngineOptions) {
this.persistenceService = options.persistenceService;
}
onStateEvent(listener: (event: StateEvent) => void): () => void {
this.persistenceService.on("stateEvent", listener);
return () => {
this.persistenceService.off("stateEvent", listener);
};
}
loadSnapshot(): StateBootstrapResult {
return this.persistenceService.loadSnapshot();
}
listMessages(raw: StateListMessagesInput): StateListMessagesResult {
return this.persistenceService.listMessages(raw);
}
catchUp(raw: StateCatchUpInput): StateCatchUpResult {
return this.persistenceService.catchUp(raw);
}
getAppSettings(): AppSettings {
return this.persistenceService.getAppSettings();
}
updateAppSettings(raw: AppSettingsUpdateInput): AppSettings {
return this.persistenceService.updateAppSettings(raw);
}
createThread(raw: ThreadsCreateInput): ThreadsUpdateResult {
return this.persistenceService.createThread(raw);
}
updateThreadTerminalState(raw: ThreadsUpdateTerminalStateInput): ThreadsUpdateResult {
return this.persistenceService.updateThreadTerminalState(raw);
}
updateThreadModel(raw: ThreadsUpdateModelInput): ThreadsUpdateResult {
return this.persistenceService.updateThreadModel(raw);
}
updateThreadTitle(raw: ThreadsUpdateTitleInput): ThreadsUpdateResult {
return this.persistenceService.updateThreadTitle(raw);
}
updateThreadBranch(raw: ThreadsUpdateBranchInput): ThreadsUpdateResult {
return this.persistenceService.updateThreadBranch(raw);
}
markThreadVisited(raw: ThreadsMarkVisitedInput): ThreadsUpdateResult {
return this.persistenceService.markThreadVisited(raw);
}
deleteThread(raw: ThreadsDeleteInput): void {
this.persistenceService.deleteThread(raw);
}
listProjects(): ProjectListResult {
return this.persistenceService.listProjects();
}
addProject(raw: ProjectAddInput): ProjectAddResult {
return this.persistenceService.addProject(raw);
}
removeProject(raw: ProjectRemoveInput): void {
this.persistenceService.removeProject(raw);
}
updateProjectScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
return this.persistenceService.updateProjectScripts(raw);
}
applyCheckpointRevert(input: ApplyCheckpointRevertInput): void {
this.persistenceService.applyCheckpointRevert(input);
}
close(): void {
// Persistence service lifecycle is owned by server bootstrap.
}
}
@@ -0,0 +1,645 @@
import { EventEmitter } from "node:events";
import { describe, expect, it, vi } from "vitest";
import type {
AppSettings,
AppSettingsUpdateInput,
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectRemoveInput,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
StateBootstrapResult,
StateCatchUpInput,
StateCatchUpResult,
StateEvent,
StateListMessagesInput,
StateListMessagesResult,
ThreadsCreateInput,
ThreadsDeleteInput,
ThreadsMarkVisitedInput,
ThreadsUpdateBranchInput,
ThreadsUpdateModelInput,
ThreadsUpdateResult,
ThreadsUpdateTerminalStateInput,
ThreadsUpdateTitleInput,
} from "@t3tools/contracts";
import type { LiveStoreStateMirror } from "./livestore/liveStoreEngine";
import type { ApplyCheckpointRevertInput, StateSyncEngine } from "./stateSyncEngine";
import { LiveStoreReadPilotStateSyncEngine } from "./stateSyncEngineLiveStoreReadPilot";
class MockDelegateStateSyncEngine extends EventEmitter<{ stateEvent: [event: StateEvent] }>
implements StateSyncEngine
{
readonly loadSnapshotMock = vi.fn<() => StateBootstrapResult>(() => ({
projects: [],
threads: [],
lastStateSeq: 1,
}));
readonly listMessagesMock = vi.fn<(raw: StateListMessagesInput) => StateListMessagesResult>(() => ({
messages: [],
total: 0,
nextOffset: null,
}));
readonly catchUpMock = vi.fn<(raw: StateCatchUpInput) => StateCatchUpResult>(() => ({
events: [],
lastStateSeq: 1,
}));
readonly getAppSettingsMock = vi.fn<() => AppSettings>(() => ({
codexBinaryPath: "",
codexHomePath: "",
}));
readonly updateAppSettingsMock = vi.fn<(raw: AppSettingsUpdateInput) => AppSettings>(() => ({
codexBinaryPath: "",
codexHomePath: "",
}));
readonly createThreadMock = vi.fn<(raw: ThreadsCreateInput) => ThreadsUpdateResult>(() => {
throw new Error("not implemented in test");
});
readonly updateThreadTerminalStateMock = vi.fn<
(raw: ThreadsUpdateTerminalStateInput) => ThreadsUpdateResult
>(() => {
throw new Error("not implemented in test");
});
readonly updateThreadModelMock = vi.fn<(raw: ThreadsUpdateModelInput) => ThreadsUpdateResult>(() => {
throw new Error("not implemented in test");
});
readonly updateThreadTitleMock = vi.fn<(raw: ThreadsUpdateTitleInput) => ThreadsUpdateResult>(() => {
throw new Error("not implemented in test");
});
readonly updateThreadBranchMock = vi.fn<(raw: ThreadsUpdateBranchInput) => ThreadsUpdateResult>(() => {
throw new Error("not implemented in test");
});
readonly markThreadVisitedMock = vi.fn<(raw: ThreadsMarkVisitedInput) => ThreadsUpdateResult>(() => {
throw new Error("not implemented in test");
});
readonly deleteThreadMock = vi.fn<(raw: ThreadsDeleteInput) => void>(() => {});
readonly listProjectsMock = vi.fn<() => ProjectListResult>(() => []);
readonly addProjectMock = vi.fn<(raw: ProjectAddInput) => ProjectAddResult>(() => {
throw new Error("not implemented in test");
});
readonly removeProjectMock = vi.fn<(raw: ProjectRemoveInput) => void>(() => {});
readonly updateProjectScriptsMock = vi.fn<
(raw: ProjectUpdateScriptsInput) => ProjectUpdateScriptsResult
>(() => {
throw new Error("not implemented in test");
});
readonly applyCheckpointRevertMock = vi.fn<(input: ApplyCheckpointRevertInput) => void>(() => {});
readonly closeMock = vi.fn();
onStateEvent(listener: (event: StateEvent) => void): () => void {
this.on("stateEvent", listener);
return () => {
this.off("stateEvent", listener);
};
}
emitStateEvent(event: StateEvent): void {
this.emit("stateEvent", event);
}
loadSnapshot(): StateBootstrapResult {
return this.loadSnapshotMock();
}
listMessages(raw: StateListMessagesInput): StateListMessagesResult {
return this.listMessagesMock(raw);
}
catchUp(raw: StateCatchUpInput): StateCatchUpResult {
return this.catchUpMock(raw);
}
getAppSettings(): AppSettings {
return this.getAppSettingsMock();
}
updateAppSettings(raw: AppSettingsUpdateInput): AppSettings {
return this.updateAppSettingsMock(raw);
}
createThread(raw: ThreadsCreateInput): ThreadsUpdateResult {
return this.createThreadMock(raw);
}
updateThreadTerminalState(raw: ThreadsUpdateTerminalStateInput): ThreadsUpdateResult {
return this.updateThreadTerminalStateMock(raw);
}
updateThreadModel(raw: ThreadsUpdateModelInput): ThreadsUpdateResult {
return this.updateThreadModelMock(raw);
}
updateThreadTitle(raw: ThreadsUpdateTitleInput): ThreadsUpdateResult {
return this.updateThreadTitleMock(raw);
}
updateThreadBranch(raw: ThreadsUpdateBranchInput): ThreadsUpdateResult {
return this.updateThreadBranchMock(raw);
}
markThreadVisited(raw: ThreadsMarkVisitedInput): ThreadsUpdateResult {
return this.markThreadVisitedMock(raw);
}
deleteThread(raw: ThreadsDeleteInput): void {
this.deleteThreadMock(raw);
}
listProjects(): ProjectListResult {
return this.listProjectsMock();
}
addProject(raw: ProjectAddInput): ProjectAddResult {
return this.addProjectMock(raw);
}
removeProject(raw: ProjectRemoveInput): void {
this.removeProjectMock(raw);
}
updateProjectScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
return this.updateProjectScriptsMock(raw);
}
applyCheckpointRevert(input: ApplyCheckpointRevertInput): void {
this.applyCheckpointRevertMock(input);
}
close(): void {
this.closeMock();
}
}
function makeMirrorStub(input: {
snapshot: StateBootstrapResult;
catchUp: StateCatchUpResult;
listMessages: StateListMessagesResult;
}): LiveStoreStateMirror {
return {
mirrorStateEvent: vi.fn(async () => undefined),
dispose: vi.fn(async () => undefined),
debugReadSnapshot: vi.fn(() => input.snapshot),
debugCatchUp: vi.fn(() => input.catchUp),
debugListMessages: vi.fn(() => input.listMessages),
} as unknown as LiveStoreStateMirror;
}
describe("LiveStoreReadPilotStateSyncEngine", () => {
it("serves bootstrap/catchUp/listMessages from mirror when available", () => {
const delegate = new MockDelegateStateSyncEngine();
const mirrorSnapshot: StateBootstrapResult = {
projects: [],
threads: [],
lastStateSeq: 5,
};
const mirrorCatchUp: StateCatchUpResult = {
events: [],
lastStateSeq: 5,
};
const mirrorList: StateListMessagesResult = {
messages: [],
total: 0,
nextOffset: null,
};
const mirror = makeMirrorStub({
snapshot: mirrorSnapshot,
catchUp: mirrorCatchUp,
listMessages: mirrorList,
});
const engine = new LiveStoreReadPilotStateSyncEngine({
delegate,
mirror,
});
try {
expect(engine.loadSnapshot()).toEqual(mirrorSnapshot);
expect(engine.catchUp({ afterSeq: 0 })).toEqual(mirrorCatchUp);
expect(engine.listMessages({ threadId: "thread-1", offset: 0, limit: 10 })).toEqual(mirrorList);
expect(delegate.loadSnapshotMock).not.toHaveBeenCalled();
expect(delegate.catchUpMock).not.toHaveBeenCalled();
expect(delegate.listMessagesMock).not.toHaveBeenCalled();
expect(engine.debugReadMetrics()).toEqual({
routeReadCounts: {
"state.bootstrap": { livestore: 1, delegate: 0 },
"state.catchUp": { livestore: 1, delegate: 0 },
"state.listMessages": { livestore: 1, delegate: 0 },
},
fallbackCounts: {
"state.bootstrap": { "mirror-error": 0, "empty-mirror": 0 },
"state.catchUp": { "mirror-error": 0, "empty-mirror": 0 },
"state.listMessages": { "mirror-error": 0, "empty-mirror": 0 },
},
});
} finally {
engine.close();
}
});
it("falls back to delegate reads when mirror throws", () => {
const delegate = new MockDelegateStateSyncEngine();
const mirror = makeMirrorStub({
snapshot: {
projects: [],
threads: [],
lastStateSeq: 2,
},
catchUp: {
events: [],
lastStateSeq: 2,
},
listMessages: {
messages: [],
total: 0,
nextOffset: null,
},
});
vi.mocked(mirror.debugReadSnapshot).mockImplementationOnce(() => {
throw new Error("mirror bootstrap failure");
});
vi.mocked(mirror.debugCatchUp).mockImplementationOnce(() => {
throw new Error("mirror catch-up failure");
});
vi.mocked(mirror.debugListMessages).mockImplementationOnce(() => {
throw new Error("mirror list failure");
});
const engine = new LiveStoreReadPilotStateSyncEngine({
delegate,
mirror,
});
try {
expect(engine.loadSnapshot()).toEqual({
projects: [],
threads: [],
lastStateSeq: 1,
});
expect(engine.catchUp({ afterSeq: 0 })).toEqual({
events: [],
lastStateSeq: 1,
});
expect(engine.listMessages({ threadId: "thread-1", offset: 0, limit: 10 })).toEqual({
messages: [],
total: 0,
nextOffset: null,
});
expect(delegate.loadSnapshotMock).toHaveBeenCalledTimes(1);
expect(delegate.catchUpMock).toHaveBeenCalledTimes(1);
expect(delegate.listMessagesMock).toHaveBeenCalledTimes(1);
expect(engine.debugReadMetrics()).toEqual({
routeReadCounts: {
"state.bootstrap": { livestore: 0, delegate: 1 },
"state.catchUp": { livestore: 0, delegate: 1 },
"state.listMessages": { livestore: 0, delegate: 1 },
},
fallbackCounts: {
"state.bootstrap": { "mirror-error": 1, "empty-mirror": 0 },
"state.catchUp": { "mirror-error": 1, "empty-mirror": 0 },
"state.listMessages": { "mirror-error": 1, "empty-mirror": 0 },
},
});
} finally {
engine.close();
}
});
it("logs a warning when mirror reports unsuccessful event writes", async () => {
const delegate = new MockDelegateStateSyncEngine();
const mirror = makeMirrorStub({
snapshot: {
projects: [],
threads: [],
lastStateSeq: 1,
},
catchUp: {
events: [],
lastStateSeq: 1,
},
listMessages: {
messages: [],
total: 0,
nextOffset: null,
},
});
vi.mocked(mirror.mirrorStateEvent).mockResolvedValue(false);
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const engine = new LiveStoreReadPilotStateSyncEngine({
delegate,
mirror,
});
try {
delegate.emitStateEvent({
seq: 1,
eventType: "project.upsert",
entityId: "project-1",
payload: {},
createdAt: "2026-02-20T00:00:00.000Z",
});
await Promise.resolve();
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining("mirror state event in read pilot reported unsuccessful write"),
);
} finally {
warnSpy.mockRestore();
engine.close();
}
});
it("runs bootstrap parity check against delegate when enabled", () => {
const delegate = new MockDelegateStateSyncEngine();
delegate.loadSnapshotMock.mockReturnValue({
projects: [],
threads: [],
lastStateSeq: 9,
});
const mirror = makeMirrorStub({
snapshot: {
projects: [],
threads: [],
lastStateSeq: 5,
},
catchUp: {
events: [],
lastStateSeq: 5,
},
listMessages: {
messages: [],
total: 0,
nextOffset: null,
},
});
const engine = new LiveStoreReadPilotStateSyncEngine({
delegate,
mirror,
enableBootstrapParityCheck: true,
});
try {
expect(engine.loadSnapshot()).toEqual({
projects: [],
threads: [],
lastStateSeq: 5,
});
// One call from the parity check path while mirror remains source.
expect(delegate.loadSnapshotMock).toHaveBeenCalledTimes(1);
} finally {
engine.close();
}
});
it("runs catch-up parity check against delegate when enabled", () => {
const delegate = new MockDelegateStateSyncEngine();
delegate.catchUpMock.mockReturnValue({
events: [],
lastStateSeq: 11,
});
const mirror = makeMirrorStub({
snapshot: {
projects: [],
threads: [],
lastStateSeq: 5,
},
catchUp: {
events: [],
lastStateSeq: 7,
},
listMessages: {
messages: [],
total: 0,
nextOffset: null,
},
});
const engine = new LiveStoreReadPilotStateSyncEngine({
delegate,
mirror,
enableCatchUpParityCheck: true,
});
try {
expect(engine.catchUp({ afterSeq: 3 })).toEqual({
events: [],
lastStateSeq: 7,
});
// One call from parity-check comparison path while mirror remains source.
expect(delegate.catchUpMock).toHaveBeenCalledTimes(1);
expect(delegate.catchUpMock).toHaveBeenCalledWith({ afterSeq: 3 });
} finally {
engine.close();
}
});
it("runs list-messages parity check against delegate when enabled", () => {
const delegate = new MockDelegateStateSyncEngine();
delegate.listMessagesMock.mockReturnValue({
messages: [],
total: 2,
nextOffset: 2,
});
const mirror = makeMirrorStub({
snapshot: {
projects: [],
threads: [],
lastStateSeq: 5,
},
catchUp: {
events: [],
lastStateSeq: 5,
},
listMessages: {
messages: [],
total: 1,
nextOffset: null,
},
});
const engine = new LiveStoreReadPilotStateSyncEngine({
delegate,
mirror,
enableListMessagesParityCheck: true,
});
try {
expect(engine.listMessages({ threadId: "thread-1", offset: 0, limit: 10 })).toEqual({
messages: [],
total: 1,
nextOffset: null,
});
// One call from parity-check comparison path while mirror remains source.
expect(delegate.listMessagesMock).toHaveBeenCalledTimes(1);
expect(delegate.listMessagesMock).toHaveBeenCalledWith({
threadId: "thread-1",
offset: 0,
limit: 10,
});
} finally {
engine.close();
}
});
it("can disable delegate read fallback for strict mirror reads", () => {
const delegate = new MockDelegateStateSyncEngine();
const mirror = makeMirrorStub({
snapshot: {
projects: [],
threads: [],
lastStateSeq: 0,
},
catchUp: {
events: [],
lastStateSeq: 0,
},
listMessages: {
messages: [],
total: 0,
nextOffset: null,
},
});
vi.mocked(mirror.debugReadSnapshot).mockImplementationOnce(() => {
throw new Error("strict bootstrap failure");
});
vi.mocked(mirror.debugCatchUp).mockImplementationOnce(() => {
throw new Error("strict catch-up failure");
});
vi.mocked(mirror.debugListMessages).mockImplementationOnce(() => {
throw new Error("strict list failure");
});
const engine = new LiveStoreReadPilotStateSyncEngine({
delegate,
mirror,
disableDelegateReadFallback: true,
});
try {
expect(() => engine.loadSnapshot()).toThrow(/strict bootstrap failure/);
expect(() => engine.catchUp({ afterSeq: 0 })).toThrow(/strict catch-up failure/);
expect(() => engine.listMessages({ threadId: "thread-1", offset: 0, limit: 10 })).toThrow(
/strict list failure/,
);
expect(delegate.loadSnapshotMock).not.toHaveBeenCalled();
expect(delegate.catchUpMock).not.toHaveBeenCalled();
expect(delegate.listMessagesMock).not.toHaveBeenCalled();
} finally {
engine.close();
}
});
it("uses mirror bootstrap even when seq is zero if fallback disabled", () => {
const delegate = new MockDelegateStateSyncEngine();
const mirror = makeMirrorStub({
snapshot: {
projects: [],
threads: [],
lastStateSeq: 0,
},
catchUp: {
events: [],
lastStateSeq: 0,
},
listMessages: {
messages: [],
total: 0,
nextOffset: null,
},
});
const engine = new LiveStoreReadPilotStateSyncEngine({
delegate,
mirror,
disableDelegateReadFallback: true,
});
try {
expect(engine.loadSnapshot()).toEqual({
projects: [],
threads: [],
lastStateSeq: 0,
});
expect(delegate.loadSnapshotMock).not.toHaveBeenCalled();
expect(engine.debugReadMetrics()).toEqual({
routeReadCounts: {
"state.bootstrap": { livestore: 1, delegate: 0 },
"state.catchUp": { livestore: 0, delegate: 0 },
"state.listMessages": { livestore: 0, delegate: 0 },
},
fallbackCounts: {
"state.bootstrap": { "mirror-error": 0, "empty-mirror": 0 },
"state.catchUp": { "mirror-error": 0, "empty-mirror": 0 },
"state.listMessages": { "mirror-error": 0, "empty-mirror": 0 },
},
});
} finally {
engine.close();
}
});
it("returns to mirror reads after transient fallback errors", () => {
const delegate = new MockDelegateStateSyncEngine();
const mirror = makeMirrorStub({
snapshot: {
projects: [],
threads: [],
lastStateSeq: 5,
},
catchUp: {
events: [],
lastStateSeq: 5,
},
listMessages: {
messages: [],
total: 0,
nextOffset: null,
},
});
vi.mocked(mirror.debugCatchUp)
.mockImplementationOnce(() => {
throw new Error("mirror catch-up failure");
})
.mockImplementation(() => ({
events: [],
lastStateSeq: 5,
}));
vi.mocked(mirror.debugListMessages)
.mockImplementationOnce(() => {
throw new Error("mirror list failure");
})
.mockImplementation(() => ({
messages: [],
total: 0,
nextOffset: null,
}));
const engine = new LiveStoreReadPilotStateSyncEngine({
delegate,
mirror,
});
try {
expect(engine.catchUp({ afterSeq: 0 })).toEqual({
events: [],
lastStateSeq: 1,
});
expect(engine.listMessages({ threadId: "thread-1", offset: 0, limit: 10 })).toEqual({
messages: [],
total: 0,
nextOffset: null,
});
expect(delegate.catchUpMock).toHaveBeenCalledTimes(1);
expect(delegate.listMessagesMock).toHaveBeenCalledTimes(1);
expect(engine.catchUp({ afterSeq: 0 })).toEqual({
events: [],
lastStateSeq: 5,
});
expect(engine.listMessages({ threadId: "thread-1", offset: 0, limit: 10 })).toEqual({
messages: [],
total: 0,
nextOffset: null,
});
expect(delegate.catchUpMock).toHaveBeenCalledTimes(1);
expect(delegate.listMessagesMock).toHaveBeenCalledTimes(1);
expect(engine.debugReadMetrics()).toEqual({
routeReadCounts: {
"state.bootstrap": { livestore: 0, delegate: 0 },
"state.catchUp": { livestore: 1, delegate: 1 },
"state.listMessages": { livestore: 1, delegate: 1 },
},
fallbackCounts: {
"state.bootstrap": { "mirror-error": 0, "empty-mirror": 0 },
"state.catchUp": { "mirror-error": 1, "empty-mirror": 0 },
"state.listMessages": { "mirror-error": 1, "empty-mirror": 0 },
},
});
} finally {
engine.close();
}
});
});
@@ -0,0 +1,439 @@
import { EventEmitter } from "node:events";
import type {
AppSettings,
AppSettingsUpdateInput,
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectRemoveInput,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
StateBootstrapResult,
StateCatchUpInput,
StateCatchUpResult,
StateEvent,
StateListMessagesInput,
StateListMessagesResult,
ThreadsCreateInput,
ThreadsDeleteInput,
ThreadsMarkVisitedInput,
ThreadsUpdateBranchInput,
ThreadsUpdateModelInput,
ThreadsUpdateResult,
ThreadsUpdateTerminalStateInput,
ThreadsUpdateTitleInput,
} from "@t3tools/contracts";
import { createLogger } from "./logger";
import type { LiveStoreStateMirror } from "./livestore/liveStoreEngine";
import { diffCatchUpResults, diffListMessagesResults, diffStateSnapshots } from "./livestore/parity";
import type { ApplyCheckpointRevertInput, StateSyncEngine } from "./stateSyncEngine";
interface LiveStoreReadPilotEvents {
stateEvent: [event: StateEvent];
}
type LiveStoreReadSource = "delegate" | "livestore";
type LiveStoreReadRoute = "state.bootstrap" | "state.catchUp" | "state.listMessages";
type LiveStoreFallbackReason = "mirror-error" | "empty-mirror";
export interface LiveStoreReadPilotMetrics {
routeReadCounts: Record<LiveStoreReadRoute, { livestore: number; delegate: number }>;
fallbackCounts: Record<LiveStoreReadRoute, { "mirror-error": number; "empty-mirror": number }>;
}
export interface LiveStoreReadPilotStateSyncEngineOptions {
delegate: StateSyncEngine;
mirror: LiveStoreStateMirror;
enableBootstrapParityCheck?: boolean;
enableCatchUpParityCheck?: boolean;
enableListMessagesParityCheck?: boolean;
disableDelegateReadFallback?: boolean;
}
export class LiveStoreReadPilotStateSyncEngine
extends EventEmitter<LiveStoreReadPilotEvents>
implements StateSyncEngine
{
private readonly delegate: StateSyncEngine;
private readonly mirror: LiveStoreStateMirror;
private readonly logger = createLogger("livestore-read-pilot");
private readonly unsubscribeDelegate: () => void;
private readonly enableBootstrapParityCheck: boolean;
private readonly enableCatchUpParityCheck: boolean;
private readonly enableListMessagesParityCheck: boolean;
private readonly disableDelegateReadFallback: boolean;
private closed = false;
private bootstrapSource: LiveStoreReadSource = "delegate";
private catchUpSource: LiveStoreReadSource = "delegate";
private listMessagesSource: LiveStoreReadSource = "delegate";
private bootstrapParityState: "unknown" | "in-parity" | "drift" = "unknown";
private catchUpParityState: "unknown" | "in-parity" | "drift" = "unknown";
private listMessagesParityState: "unknown" | "in-parity" | "drift" = "unknown";
private readonly metrics: LiveStoreReadPilotMetrics = {
routeReadCounts: {
"state.bootstrap": { livestore: 0, delegate: 0 },
"state.catchUp": { livestore: 0, delegate: 0 },
"state.listMessages": { livestore: 0, delegate: 0 },
},
fallbackCounts: {
"state.bootstrap": { "mirror-error": 0, "empty-mirror": 0 },
"state.catchUp": { "mirror-error": 0, "empty-mirror": 0 },
"state.listMessages": { "mirror-error": 0, "empty-mirror": 0 },
},
};
constructor(options: LiveStoreReadPilotStateSyncEngineOptions) {
super();
this.delegate = options.delegate;
this.mirror = options.mirror;
this.enableBootstrapParityCheck = options.enableBootstrapParityCheck ?? false;
this.enableCatchUpParityCheck = options.enableCatchUpParityCheck ?? false;
this.enableListMessagesParityCheck = options.enableListMessagesParityCheck ?? false;
this.disableDelegateReadFallback = options.disableDelegateReadFallback ?? false;
this.unsubscribeDelegate = this.delegate.onStateEvent((event) => {
this.emit("stateEvent", event);
void this.mirror
.mirrorStateEvent(event)
.then((mirrored) => {
if (mirrored === false) {
this.logger.warn("mirror state event in read pilot reported unsuccessful write", {
seq: event.seq,
});
}
})
.catch((error) => {
this.logger.warn("failed to mirror state event in read pilot", {
error,
seq: event.seq,
});
});
});
}
onStateEvent(listener: (event: StateEvent) => void): () => void {
this.on("stateEvent", listener);
return () => {
this.off("stateEvent", listener);
};
}
loadSnapshot(): StateBootstrapResult {
try {
const snapshot = this.mirror.debugReadSnapshot();
if (this.enableBootstrapParityCheck) {
this.checkBootstrapParity(snapshot);
}
if (snapshot.lastStateSeq === 0 && !this.disableDelegateReadFallback) {
const delegateSnapshot = this.delegate.loadSnapshot();
this.logReadSourceChange("state.bootstrap", this.bootstrapSource, "delegate", {
lastStateSeq: delegateSnapshot.lastStateSeq,
});
this.recordReadRoute("state.bootstrap", "delegate");
this.recordFallback("state.bootstrap", "empty-mirror");
this.bootstrapSource = "delegate";
return delegateSnapshot;
}
this.logReadSourceChange("state.bootstrap", this.bootstrapSource, "livestore", {
lastStateSeq: snapshot.lastStateSeq,
});
this.recordReadRoute("state.bootstrap", "livestore");
this.bootstrapSource = "livestore";
return snapshot;
} catch (error) {
if (this.disableDelegateReadFallback) {
this.logger.error("failed to read bootstrap from livestore mirror with fallback disabled", {
error,
});
throw error;
}
this.logger.warn("failed to read bootstrap from livestore mirror; using delegate", { error });
this.recordFallback("state.bootstrap", "mirror-error");
}
const snapshot = this.delegate.loadSnapshot();
this.logReadSourceChange("state.bootstrap", this.bootstrapSource, "delegate", {
lastStateSeq: snapshot.lastStateSeq,
});
this.recordReadRoute("state.bootstrap", "delegate");
this.bootstrapSource = "delegate";
return snapshot;
}
private checkBootstrapParity(mirrorSnapshot: StateBootstrapResult): void {
let delegateSnapshot: StateBootstrapResult;
try {
delegateSnapshot = this.delegate.loadSnapshot();
} catch (error) {
this.logger.warn("bootstrap parity check failed to read delegate snapshot", { error });
return;
}
const diffs = diffStateSnapshots(delegateSnapshot, mirrorSnapshot);
if (diffs.length === 0) {
if (this.bootstrapParityState !== "in-parity") {
this.bootstrapParityState = "in-parity";
this.logger.info("livestore read pilot bootstrap parity check passed", {
lastStateSeq: mirrorSnapshot.lastStateSeq,
});
}
return;
}
this.bootstrapParityState = "drift";
this.logger.warn("livestore read pilot bootstrap parity drift detected", {
diffCount: diffs.length,
samplePaths: diffs.slice(0, 5).map((diff) => diff.path),
delegateLastStateSeq: delegateSnapshot.lastStateSeq,
mirrorLastStateSeq: mirrorSnapshot.lastStateSeq,
});
}
listMessages(raw: StateListMessagesInput): StateListMessagesResult {
try {
const result = this.mirror.debugListMessages(raw);
if (this.enableListMessagesParityCheck) {
this.checkListMessagesParity(raw, result);
}
this.logReadSourceChange("state.listMessages", this.listMessagesSource, "livestore", {
threadId: raw.threadId,
});
this.recordReadRoute("state.listMessages", "livestore");
this.listMessagesSource = "livestore";
return result;
} catch (error) {
if (this.disableDelegateReadFallback) {
this.logger.error(
"failed to list messages from livestore mirror with fallback disabled",
{
error,
threadId: raw.threadId,
},
);
throw error;
}
this.recordFallback("state.listMessages", "mirror-error");
this.logger.warn("failed to list messages from livestore mirror; using delegate", {
error,
threadId: raw.threadId,
});
const result = this.delegate.listMessages(raw);
this.logReadSourceChange("state.listMessages", this.listMessagesSource, "delegate", {
threadId: raw.threadId,
});
this.recordReadRoute("state.listMessages", "delegate");
this.listMessagesSource = "delegate";
return result;
}
}
private checkListMessagesParity(
raw: StateListMessagesInput,
mirrorResult: StateListMessagesResult,
): void {
let delegateResult: StateListMessagesResult;
try {
delegateResult = this.delegate.listMessages(raw);
} catch (error) {
this.logger.warn("list-messages parity check failed to read delegate listMessages", { error });
return;
}
const diffs = diffListMessagesResults(delegateResult, mirrorResult);
if (diffs.length === 0) {
if (this.listMessagesParityState !== "in-parity") {
this.listMessagesParityState = "in-parity";
this.logger.info("livestore read pilot list-messages parity check passed", {
threadId: raw.threadId,
offset: raw.offset ?? 0,
limit: raw.limit ?? 200,
});
}
return;
}
this.listMessagesParityState = "drift";
this.logger.warn("livestore read pilot list-messages parity drift detected", {
threadId: raw.threadId,
offset: raw.offset ?? 0,
limit: raw.limit ?? 200,
diffCount: diffs.length,
sampleDiffs: diffs.slice(0, 5),
});
}
catchUp(raw: StateCatchUpInput): StateCatchUpResult {
const afterSeq = raw.afterSeq ?? 0;
try {
const result = this.mirror.debugCatchUp(afterSeq);
if (this.enableCatchUpParityCheck) {
this.checkCatchUpParity(raw, result);
}
this.logReadSourceChange("state.catchUp", this.catchUpSource, "livestore", {
afterSeq,
});
this.recordReadRoute("state.catchUp", "livestore");
this.catchUpSource = "livestore";
return result;
} catch (error) {
if (this.disableDelegateReadFallback) {
this.logger.error("failed to catch up from livestore mirror with fallback disabled", {
error,
afterSeq,
});
throw error;
}
this.recordFallback("state.catchUp", "mirror-error");
this.logger.warn("failed to catch up from livestore mirror; using delegate", {
error,
afterSeq,
});
const result = this.delegate.catchUp(raw);
this.logReadSourceChange("state.catchUp", this.catchUpSource, "delegate", {
afterSeq,
});
this.recordReadRoute("state.catchUp", "delegate");
this.catchUpSource = "delegate";
return result;
}
}
debugReadMetrics(): LiveStoreReadPilotMetrics {
return {
routeReadCounts: {
"state.bootstrap": { ...this.metrics.routeReadCounts["state.bootstrap"] },
"state.catchUp": { ...this.metrics.routeReadCounts["state.catchUp"] },
"state.listMessages": { ...this.metrics.routeReadCounts["state.listMessages"] },
},
fallbackCounts: {
"state.bootstrap": { ...this.metrics.fallbackCounts["state.bootstrap"] },
"state.catchUp": { ...this.metrics.fallbackCounts["state.catchUp"] },
"state.listMessages": { ...this.metrics.fallbackCounts["state.listMessages"] },
},
};
}
isReadFallbackDisabled(): boolean {
return this.disableDelegateReadFallback;
}
private checkCatchUpParity(raw: StateCatchUpInput, mirrorResult: StateCatchUpResult): void {
let delegateResult: StateCatchUpResult;
try {
delegateResult = this.delegate.catchUp(raw);
} catch (error) {
this.logger.warn("catch-up parity check failed to read delegate catch-up", { error });
return;
}
const diffs = diffCatchUpResults(delegateResult, mirrorResult);
if (diffs.length === 0) {
if (this.catchUpParityState !== "in-parity") {
this.catchUpParityState = "in-parity";
this.logger.info("livestore read pilot catch-up parity check passed", {
afterSeq: raw.afterSeq ?? 0,
lastStateSeq: mirrorResult.lastStateSeq,
});
}
return;
}
this.catchUpParityState = "drift";
this.logger.warn("livestore read pilot catch-up parity drift detected", {
afterSeq: raw.afterSeq ?? 0,
diffCount: diffs.length,
sampleDiffs: diffs.slice(0, 5),
delegateLastStateSeq: delegateResult.lastStateSeq,
mirrorLastStateSeq: mirrorResult.lastStateSeq,
});
}
private logReadSourceChange(
route: LiveStoreReadRoute,
previous: LiveStoreReadSource,
next: LiveStoreReadSource,
metadata: Record<string, unknown>,
): void {
if (previous === next) {
return;
}
this.logger.info(`serving ${route} from ${next}`, {
source: next,
previousSource: previous,
...metadata,
});
}
private recordReadRoute(route: LiveStoreReadRoute, source: LiveStoreReadSource): void {
this.metrics.routeReadCounts[route][source] += 1;
}
private recordFallback(route: LiveStoreReadRoute, reason: LiveStoreFallbackReason): void {
this.metrics.fallbackCounts[route][reason] += 1;
}
getAppSettings(): AppSettings {
return this.delegate.getAppSettings();
}
updateAppSettings(raw: AppSettingsUpdateInput): AppSettings {
return this.delegate.updateAppSettings(raw);
}
createThread(raw: ThreadsCreateInput): ThreadsUpdateResult {
return this.delegate.createThread(raw);
}
updateThreadTerminalState(raw: ThreadsUpdateTerminalStateInput): ThreadsUpdateResult {
return this.delegate.updateThreadTerminalState(raw);
}
updateThreadModel(raw: ThreadsUpdateModelInput): ThreadsUpdateResult {
return this.delegate.updateThreadModel(raw);
}
updateThreadTitle(raw: ThreadsUpdateTitleInput): ThreadsUpdateResult {
return this.delegate.updateThreadTitle(raw);
}
updateThreadBranch(raw: ThreadsUpdateBranchInput): ThreadsUpdateResult {
return this.delegate.updateThreadBranch(raw);
}
markThreadVisited(raw: ThreadsMarkVisitedInput): ThreadsUpdateResult {
return this.delegate.markThreadVisited(raw);
}
deleteThread(raw: ThreadsDeleteInput): void {
this.delegate.deleteThread(raw);
}
listProjects(): ProjectListResult {
return this.delegate.listProjects();
}
addProject(raw: ProjectAddInput): ProjectAddResult {
return this.delegate.addProject(raw);
}
removeProject(raw: ProjectRemoveInput): void {
this.delegate.removeProject(raw);
}
updateProjectScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
return this.delegate.updateProjectScripts(raw);
}
applyCheckpointRevert(input: ApplyCheckpointRevertInput): void {
this.delegate.applyCheckpointRevert(input);
}
close(): void {
if (this.closed) {
return;
}
this.closed = true;
this.logger.info("livestore read pilot metrics", { metrics: this.metrics });
this.unsubscribeDelegate();
this.removeAllListeners();
void this.mirror.dispose();
}
}
@@ -0,0 +1,303 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { StateEvent } from "@t3tools/contracts";
import { diffStateSnapshots } from "./livestore/parity";
import { LiveStoreStateMirror } from "./livestore/liveStoreEngine";
import { PersistenceService } from "./persistenceService";
import { LegacyStateSyncEngine } from "./stateSyncEngineLegacy";
import type { StateEventMirror } from "./stateSyncEngineShadow";
import { ShadowStateSyncEngine } from "./stateSyncEngineShadow";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
async function waitForParity(
getExpected: () => ReturnType<LegacyStateSyncEngine["loadSnapshot"]>,
getMirrored: () => ReturnType<LiveStoreStateMirror["debugReadSnapshot"]>,
): Promise<void> {
const maxAttempts = 30;
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
if (diffStateSnapshots(getExpected(), getMirrored()).length === 0) {
return;
}
await new Promise((resolve) => setTimeout(resolve, 15));
}
expect(diffStateSnapshots(getExpected(), getMirrored())).toEqual([]);
}
class CapturingMirror implements StateEventMirror {
readonly events: StateEvent[] = [];
disposeCalls = 0;
async mirrorStateEvent(event: StateEvent): Promise<void> {
this.events.push(event);
}
async dispose(): Promise<void> {
this.disposeCalls += 1;
}
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("ShadowStateSyncEngine", () => {
it("delegates durable APIs and mirrors emitted state events", async () => {
const stateDir = makeTempDir("t3code-shadow-state-");
const projectDir = makeTempDir("t3code-shadow-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
const legacy = new LegacyStateSyncEngine({ persistenceService: service });
const mirror = new CapturingMirror();
const shadow = new ShadowStateSyncEngine({
delegate: legacy,
mirror,
});
try {
const observedEvents: StateEvent[] = [];
const unsubscribe = shadow.onStateEvent((event) => {
observedEvents.push(event);
});
const project = shadow.addProject({ cwd: projectDir }).project;
const thread = shadow.createThread({
projectId: project.id,
title: "Shadow thread",
}).thread;
shadow.updateThreadTitle({
threadId: thread.id,
title: "Shadow thread updated",
});
service.bindSessionToThread("shadow-session", thread.id, "runtime-thread-1");
service.persistUserMessageForTurn({
sessionId: "shadow-session",
clientMessageId: "msg-1",
clientMessageText: "hello from shadow",
input: "hello from shadow",
attachments: [],
});
await Promise.resolve();
const snapshot = shadow.loadSnapshot();
expect(snapshot.projects).toHaveLength(1);
expect(snapshot.threads).toHaveLength(1);
expect(snapshot.threads[0]?.title).toBe("Shadow thread updated");
const catchUp = shadow.catchUp({ afterSeq: 0 });
expect(catchUp.events.length).toBeGreaterThan(0);
expect(catchUp.events.map((event) => event.eventType)).toEqual(
expect.arrayContaining(["project.upsert", "thread.upsert"]),
);
expect(mirror.events.map((event) => event.seq)).toEqual(
observedEvents.map((event) => event.seq),
);
expect(mirror.events.some((event) => event.eventType === "message.upsert")).toBe(true);
expect(observedEvents.some((event) => event.eventType === "message.upsert")).toBe(true);
unsubscribe();
} finally {
shadow.close();
service.close();
}
});
it("stops mirroring and disposes once on close", async () => {
const stateDir = makeTempDir("t3code-shadow-close-state-");
const projectDir = makeTempDir("t3code-shadow-close-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
const legacy = new LegacyStateSyncEngine({ persistenceService: service });
const mirror = new CapturingMirror();
const shadow = new ShadowStateSyncEngine({
delegate: legacy,
mirror,
});
try {
shadow.close();
shadow.close();
legacy.addProject({ cwd: projectDir });
await Promise.resolve();
expect(mirror.events).toHaveLength(0);
expect(mirror.disposeCalls).toBe(1);
} finally {
service.close();
}
});
it("logs a warning when mirror reports unsuccessful writes", async () => {
const stateDir = makeTempDir("t3code-shadow-unsuccessful-write-state-");
const projectDir = makeTempDir("t3code-shadow-unsuccessful-write-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
const legacy = new LegacyStateSyncEngine({ persistenceService: service });
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const mirror: StateEventMirror = {
mirrorStateEvent: async () => false,
dispose: async () => undefined,
};
const shadow = new ShadowStateSyncEngine({
delegate: legacy,
mirror,
});
try {
shadow.addProject({ cwd: projectDir });
await Promise.resolve();
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining("livestore shadow mirror reported unsuccessful write"),
);
} finally {
warnSpy.mockRestore();
shadow.close();
service.close();
}
});
it("keeps LiveStore mirror snapshot in parity with delegate writes", async () => {
const stateDir = makeTempDir("t3code-shadow-parity-state-");
const projectDir = makeTempDir("t3code-shadow-parity-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
const legacy = new LegacyStateSyncEngine({ persistenceService: service });
const mirror = new LiveStoreStateMirror({ storeId: "shadow-parity-engine-test" });
const shadow = new ShadowStateSyncEngine({
delegate: legacy,
mirror,
});
try {
const project = shadow.addProject({ cwd: projectDir }).project;
const thread = shadow.createThread({
projectId: project.id,
title: "Parity thread",
}).thread;
service.bindSessionToThread("parity-session", thread.id, "runtime-thread-parity");
service.persistUserMessageForTurn({
sessionId: "parity-session",
clientMessageId: "parity-message-1",
clientMessageText: "hello parity",
input: "hello parity",
attachments: [],
});
await waitForParity(() => legacy.loadSnapshot(), () => mirror.debugReadSnapshot());
} finally {
shadow.close();
service.close();
}
});
it("can run optional bootstrap parity diagnostics without changing read results", () => {
const stateDir = makeTempDir("t3code-shadow-parity-diagnostics-state-");
const projectDir = makeTempDir("t3code-shadow-parity-diagnostics-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
const legacy = new LegacyStateSyncEngine({ persistenceService: service });
const debugReadSnapshot = vi.fn(() => ({
projects: [],
threads: [],
lastStateSeq: 0,
}));
const mirror: StateEventMirror = {
mirrorStateEvent: async () => undefined,
debugReadSnapshot,
dispose: async () => undefined,
};
const shadow = new ShadowStateSyncEngine({
delegate: legacy,
mirror,
enableBootstrapParityCheck: true,
});
try {
legacy.addProject({ cwd: projectDir });
const snapshot = shadow.loadSnapshot();
expect(snapshot.projects).toHaveLength(1);
expect(debugReadSnapshot).toHaveBeenCalledTimes(1);
} finally {
shadow.close();
service.close();
}
});
it("can run optional catch-up and list-messages parity diagnostics", () => {
const stateDir = makeTempDir("t3code-shadow-parity-diagnostics-reads-state-");
const projectDir = makeTempDir("t3code-shadow-parity-diagnostics-reads-project-");
const service = new PersistenceService({
dbPath: path.join(stateDir, "state.sqlite"),
});
const legacy = new LegacyStateSyncEngine({ persistenceService: service });
const debugCatchUp = vi.fn((afterSeq: number) => ({
events: [],
lastStateSeq: afterSeq,
}));
const debugListMessages = vi.fn(() => ({
messages: [],
total: 0,
nextOffset: null,
}));
const mirror: StateEventMirror = {
mirrorStateEvent: async () => undefined,
debugCatchUp,
debugListMessages,
dispose: async () => undefined,
};
const shadow = new ShadowStateSyncEngine({
delegate: legacy,
mirror,
enableCatchUpParityCheck: true,
enableListMessagesParityCheck: true,
});
try {
const project = shadow.addProject({ cwd: projectDir }).project;
const thread = shadow.createThread({
projectId: project.id,
title: "Shadow parity read diagnostics thread",
}).thread;
const catchUp = shadow.catchUp({ afterSeq: 0 });
expect(catchUp.events.length).toBeGreaterThan(0);
const listed = shadow.listMessages({ threadId: thread.id, offset: 0, limit: 10 });
expect(listed).toEqual({
messages: [],
total: 0,
nextOffset: null,
});
expect(debugCatchUp).toHaveBeenCalledTimes(1);
expect(debugCatchUp).toHaveBeenCalledWith(0);
expect(debugListMessages).toHaveBeenCalledTimes(1);
expect(debugListMessages).toHaveBeenCalledWith({
threadId: thread.id,
offset: 0,
limit: 10,
});
} finally {
shadow.close();
service.close();
}
});
});
+296
View File
@@ -0,0 +1,296 @@
import { EventEmitter } from "node:events";
import type {
AppSettings,
AppSettingsUpdateInput,
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectRemoveInput,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
StateBootstrapResult,
StateCatchUpInput,
StateCatchUpResult,
StateEvent,
StateListMessagesInput,
StateListMessagesResult,
ThreadsCreateInput,
ThreadsDeleteInput,
ThreadsMarkVisitedInput,
ThreadsUpdateBranchInput,
ThreadsUpdateModelInput,
ThreadsUpdateResult,
ThreadsUpdateTerminalStateInput,
ThreadsUpdateTitleInput,
} from "@t3tools/contracts";
import { createLogger } from "./logger";
import { diffCatchUpResults, diffListMessagesResults, diffStateSnapshots } from "./livestore/parity";
import type { ApplyCheckpointRevertInput, StateSyncEngine } from "./stateSyncEngine";
interface StateSyncEngineShadowEvents {
stateEvent: [event: StateEvent];
}
export interface StateEventMirror {
mirrorStateEvent(event: StateEvent): Promise<void | boolean>;
debugReadSnapshot?(): StateBootstrapResult;
debugCatchUp?(afterSeq: number): StateCatchUpResult;
debugListMessages?(raw: StateListMessagesInput): StateListMessagesResult;
dispose(): Promise<void> | void;
}
export interface ShadowStateSyncEngineOptions {
delegate: StateSyncEngine;
mirror: StateEventMirror;
enableBootstrapParityCheck?: boolean;
enableCatchUpParityCheck?: boolean;
enableListMessagesParityCheck?: boolean;
}
export class ShadowStateSyncEngine
extends EventEmitter<StateSyncEngineShadowEvents>
implements StateSyncEngine
{
private readonly delegate: StateSyncEngine;
private readonly mirror: StateEventMirror;
private readonly enableBootstrapParityCheck: boolean;
private readonly enableCatchUpParityCheck: boolean;
private readonly enableListMessagesParityCheck: boolean;
private readonly logger = createLogger("shadow-sync-engine");
private readonly unsubscribeDelegate: () => void;
private closed = false;
private bootstrapParityState: "unknown" | "in-parity" | "drift" = "unknown";
private catchUpParityState: "unknown" | "in-parity" | "drift" = "unknown";
private listMessagesParityState: "unknown" | "in-parity" | "drift" = "unknown";
constructor(options: ShadowStateSyncEngineOptions) {
super();
this.delegate = options.delegate;
this.mirror = options.mirror;
this.enableBootstrapParityCheck = options.enableBootstrapParityCheck ?? false;
this.enableCatchUpParityCheck = options.enableCatchUpParityCheck ?? false;
this.enableListMessagesParityCheck = options.enableListMessagesParityCheck ?? false;
this.unsubscribeDelegate = this.delegate.onStateEvent((event) => {
this.emit("stateEvent", event);
void this.mirror
.mirrorStateEvent(event)
.then((mirrored) => {
if (mirrored === false) {
this.logger.warn("livestore shadow mirror reported unsuccessful write", {
seq: event.seq,
});
}
})
.catch((error) => {
this.logger.warn("livestore shadow mirror failed", { error, seq: event.seq });
});
});
}
onStateEvent(listener: (event: StateEvent) => void): () => void {
this.on("stateEvent", listener);
return () => {
this.off("stateEvent", listener);
};
}
loadSnapshot(): StateBootstrapResult {
const snapshot = this.delegate.loadSnapshot();
if (this.enableBootstrapParityCheck) {
this.checkBootstrapParity(snapshot);
}
return snapshot;
}
private checkBootstrapParity(delegateSnapshot: StateBootstrapResult): void {
if (typeof this.mirror.debugReadSnapshot !== "function") {
return;
}
let mirrorSnapshot: StateBootstrapResult;
try {
mirrorSnapshot = this.mirror.debugReadSnapshot();
} catch (error) {
this.logger.warn("shadow bootstrap parity check failed to read mirror snapshot", { error });
return;
}
const diffs = diffStateSnapshots(delegateSnapshot, mirrorSnapshot);
if (diffs.length === 0) {
if (this.bootstrapParityState !== "in-parity") {
this.bootstrapParityState = "in-parity";
this.logger.info("shadow bootstrap parity check passed", {
lastStateSeq: delegateSnapshot.lastStateSeq,
});
}
return;
}
this.bootstrapParityState = "drift";
this.logger.warn("shadow bootstrap parity drift detected", {
diffCount: diffs.length,
samplePaths: diffs.slice(0, 5).map((diff) => diff.path),
delegateLastStateSeq: delegateSnapshot.lastStateSeq,
mirrorLastStateSeq: mirrorSnapshot.lastStateSeq,
});
}
listMessages(raw: StateListMessagesInput): StateListMessagesResult {
const result = this.delegate.listMessages(raw);
if (this.enableListMessagesParityCheck) {
this.checkListMessagesParity(raw, result);
}
return result;
}
catchUp(raw: StateCatchUpInput): StateCatchUpResult {
const result = this.delegate.catchUp(raw);
if (this.enableCatchUpParityCheck) {
this.checkCatchUpParity(raw, result);
}
return result;
}
private checkCatchUpParity(raw: StateCatchUpInput, delegateResult: StateCatchUpResult): void {
if (typeof this.mirror.debugCatchUp !== "function") {
return;
}
const afterSeq = raw.afterSeq ?? 0;
let mirrorResult: StateCatchUpResult;
try {
mirrorResult = this.mirror.debugCatchUp(afterSeq);
} catch (error) {
this.logger.warn("shadow catch-up parity check failed to read mirror catch-up", { error });
return;
}
const diffs = diffCatchUpResults(delegateResult, mirrorResult);
if (diffs.length === 0) {
if (this.catchUpParityState !== "in-parity") {
this.catchUpParityState = "in-parity";
this.logger.info("shadow catch-up parity check passed", {
afterSeq,
lastStateSeq: delegateResult.lastStateSeq,
});
}
return;
}
this.catchUpParityState = "drift";
this.logger.warn("shadow catch-up parity drift detected", {
afterSeq,
diffCount: diffs.length,
sampleDiffs: diffs.slice(0, 5),
delegateLastStateSeq: delegateResult.lastStateSeq,
mirrorLastStateSeq: mirrorResult.lastStateSeq,
});
}
private checkListMessagesParity(
raw: StateListMessagesInput,
delegateResult: StateListMessagesResult,
): void {
if (typeof this.mirror.debugListMessages !== "function") {
return;
}
let mirrorResult: StateListMessagesResult;
try {
mirrorResult = this.mirror.debugListMessages(raw);
} catch (error) {
this.logger.warn("shadow list-messages parity check failed to read mirror listMessages", {
error,
});
return;
}
const diffs = diffListMessagesResults(delegateResult, mirrorResult);
if (diffs.length === 0) {
if (this.listMessagesParityState !== "in-parity") {
this.listMessagesParityState = "in-parity";
this.logger.info("shadow list-messages parity check passed", {
threadId: raw.threadId,
offset: raw.offset ?? 0,
limit: raw.limit ?? 200,
});
}
return;
}
this.listMessagesParityState = "drift";
this.logger.warn("shadow list-messages parity drift detected", {
threadId: raw.threadId,
offset: raw.offset ?? 0,
limit: raw.limit ?? 200,
diffCount: diffs.length,
sampleDiffs: diffs.slice(0, 5),
});
}
getAppSettings(): AppSettings {
return this.delegate.getAppSettings();
}
updateAppSettings(raw: AppSettingsUpdateInput): AppSettings {
return this.delegate.updateAppSettings(raw);
}
createThread(raw: ThreadsCreateInput): ThreadsUpdateResult {
return this.delegate.createThread(raw);
}
updateThreadTerminalState(raw: ThreadsUpdateTerminalStateInput): ThreadsUpdateResult {
return this.delegate.updateThreadTerminalState(raw);
}
updateThreadModel(raw: ThreadsUpdateModelInput): ThreadsUpdateResult {
return this.delegate.updateThreadModel(raw);
}
updateThreadTitle(raw: ThreadsUpdateTitleInput): ThreadsUpdateResult {
return this.delegate.updateThreadTitle(raw);
}
updateThreadBranch(raw: ThreadsUpdateBranchInput): ThreadsUpdateResult {
return this.delegate.updateThreadBranch(raw);
}
markThreadVisited(raw: ThreadsMarkVisitedInput): ThreadsUpdateResult {
return this.delegate.markThreadVisited(raw);
}
deleteThread(raw: ThreadsDeleteInput): void {
this.delegate.deleteThread(raw);
}
listProjects(): ProjectListResult {
return this.delegate.listProjects();
}
addProject(raw: ProjectAddInput): ProjectAddResult {
return this.delegate.addProject(raw);
}
removeProject(raw: ProjectRemoveInput): void {
this.delegate.removeProject(raw);
}
updateProjectScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
return this.delegate.updateProjectScripts(raw);
}
applyCheckpointRevert(input: ApplyCheckpointRevertInput): void {
this.delegate.applyCheckpointRevert(input);
}
close(): void {
if (this.closed) {
return;
}
this.closed = true;
this.unsubscribeDelegate();
this.removeAllListeners();
void this.mirror.dispose();
}
}
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, it } from "vitest";
import { assertSyncEngineModeAllowed, resolveSyncEngineMode } from "./syncEngineMode";
describe("resolveSyncEngineMode", () => {
it("defaults to livestore when env var is missing", () => {
expect(resolveSyncEngineMode(undefined)).toBe("livestore");
expect(resolveSyncEngineMode("")).toBe("livestore");
expect(resolveSyncEngineMode(" ")).toBe("livestore");
});
it("accepts supported mode values case-insensitively", () => {
expect(resolveSyncEngineMode("legacy")).toBe("legacy");
expect(resolveSyncEngineMode("SHADOW")).toBe("shadow");
expect(resolveSyncEngineMode("livestore-read-pilot")).toBe("livestore-read-pilot");
expect(resolveSyncEngineMode("LIVESTORE")).toBe("livestore");
});
it("throws for unsupported values", () => {
expect(() => resolveSyncEngineMode("something-else")).toThrow(
/Invalid T3CODE_SYNC_ENGINE_MODE/i,
);
});
});
describe("assertSyncEngineModeAllowed", () => {
it("allows any mode when enforcement is disabled", () => {
expect(() => assertSyncEngineModeAllowed("legacy")).not.toThrow();
expect(() => assertSyncEngineModeAllowed("shadow")).not.toThrow();
expect(() => assertSyncEngineModeAllowed("livestore-read-pilot")).not.toThrow();
expect(() => assertSyncEngineModeAllowed("livestore")).not.toThrow();
});
it("blocks legacy and shadow when enforceLiveStoreOnly is enabled", () => {
expect(() =>
assertSyncEngineModeAllowed("legacy", { enforceLiveStoreOnly: true }),
).toThrow(/disabled/i);
expect(() =>
assertSyncEngineModeAllowed("shadow", { enforceLiveStoreOnly: true }),
).toThrow(/disabled/i);
});
it("allows livestore modes when enforceLiveStoreOnly is enabled", () => {
expect(() =>
assertSyncEngineModeAllowed("livestore-read-pilot", { enforceLiveStoreOnly: true }),
).not.toThrow();
expect(() =>
assertSyncEngineModeAllowed("livestore", { enforceLiveStoreOnly: true }),
).not.toThrow();
});
});
+35
View File
@@ -0,0 +1,35 @@
export type SyncEngineMode = "legacy" | "shadow" | "livestore-read-pilot" | "livestore";
const VALID_SYNC_ENGINE_MODES: ReadonlySet<SyncEngineMode> = new Set([
"legacy",
"shadow",
"livestore-read-pilot",
"livestore",
]);
export function resolveSyncEngineMode(raw: string | undefined): SyncEngineMode {
if (!raw || raw.trim().length === 0) {
return "livestore";
}
const normalized = raw.trim().toLowerCase();
if (VALID_SYNC_ENGINE_MODES.has(normalized as SyncEngineMode)) {
return normalized as SyncEngineMode;
}
throw new Error(
`Invalid T3CODE_SYNC_ENGINE_MODE: ${raw}. Expected "legacy", "shadow", "livestore-read-pilot", or "livestore".`,
);
}
export function assertSyncEngineModeAllowed(
syncEngineMode: SyncEngineMode,
options: { enforceLiveStoreOnly?: boolean } = {},
): void {
if (!options.enforceLiveStoreOnly) {
return;
}
if (syncEngineMode === "legacy" || syncEngineMode === "shadow") {
throw new Error(
`Sync engine mode "${syncEngineMode}" is disabled because T3CODE_LIVESTORE_ENFORCE_MODE is enabled.`,
);
}
}
+1 -4
View File
@@ -69,10 +69,7 @@ interface ShellCandidate {
args?: string[];
}
interface TerminalStartInput extends TerminalOpenInput {
cols: number;
rows: number
};
type TerminalStartInput = TerminalOpenInput & { cols: number; rows: number };
function defaultShellResolver(): string {
if (process.platform === "win32") {
File diff suppressed because it is too large. Load diff
+177 -396
View File
@@ -7,18 +7,14 @@ import type { Duplex } from "node:stream";
import {
EDITORS,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
WS_CHANNELS,
WS_METHODS,
type OrchestrationReadModelPush,
type TerminalEvent,
type WsPush,
type WsRequest,
type WsResponse,
wsRequestSchema,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime } from "effect";
import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
@@ -36,13 +32,12 @@ import {
import { TerminalManager } from "./terminalManager";
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
import { searchWorkspaceEntries } from "./workspaceEntries";
import { OrchestrationEngineLive } from "./orchestration/Layer";
import { OrchestrationEngineService, type OrchestrationEngineShape } from "./orchestration/Service";
import { ProjectRepositoryLive } from "./persistence/Layers/Projects";
import { makeSqlitePersistenceLive } from "./persistence/Layers/Sqlite";
import { ProjectRepository, type ProjectRepositoryShape } from "./persistence/Services/Projects";
import assert from "node:assert";
import { OrchestrationEventRepositoryLive } from "./persistence/Layers/OrchestrationEvents";
import { PersistenceService } from "./persistenceService";
import type { StateSyncEngine } from "./stateSyncEngine";
import { LegacyStateSyncEngine } from "./stateSyncEngineLegacy";
import { LiveStoreReadPilotStateSyncEngine } from "./stateSyncEngineLiveStoreReadPilot";
import { ShadowStateSyncEngine } from "./stateSyncEngineShadow";
import type { SyncEngineMode } from "./syncEngineMode";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -63,33 +58,16 @@ export interface ServerOptions {
port: number;
host?: string | undefined;
cwd: string;
stateDir?: string | undefined;
staticDir?: string | undefined;
devUrl?: string | undefined;
logWebSocketEvents?: boolean | undefined;
persistenceService?: PersistenceService | undefined;
stateSyncEngine?: StateSyncEngine | undefined;
stateDbPath?: string | undefined;
gitManager?: GitManager | undefined;
terminalManager?: TerminalManager | undefined;
authToken?: string | undefined;
}
const isServerNotRunningError = (error: unknown): boolean => {
if (!(error instanceof Error)) return false;
const maybeCode = (error as NodeJS.ErrnoException).code;
return (
maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running")
);
};
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
socket.write(
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
"Connection: close\r\n" +
"Content-Type: text/plain\r\n" +
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
"\r\n" +
message,
);
socket.destroy();
syncEngineMode?: SyncEngineMode | undefined;
}
function parseBooleanEnv(value: string | undefined): boolean | undefined {
@@ -100,50 +78,40 @@ function parseBooleanEnv(value: string | undefined): boolean | undefined {
return undefined;
}
function asObject(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object") return null;
return value as Record<string, unknown>;
}
function asString(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
function asNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
const noop = () => {};
export function createServer(options: ServerOptions) {
const {
port,
host,
cwd,
stateDir,
staticDir,
devUrl,
logWebSocketEvents: explicitLogWsEvents,
gitManager = new GitManager(),
terminalManager = new TerminalManager(),
persistenceService: providedPersistenceService,
stateSyncEngine: providedStateSyncEngine,
stateDbPath,
gitManager: providedGitManager,
terminalManager: providedTerminalManager,
authToken,
syncEngineMode: providedSyncEngineMode,
} = options;
const providerManager = new ProviderManager();
const resolvedStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
let effectRuntime: ManagedRuntime.ManagedRuntime<
ProjectRepository | OrchestrationEngineService,
unknown
> | null = null;
let projectRepository: ProjectRepositoryShape | null = null;
let orchestrationEngine: OrchestrationEngineShape | null = null;
const persistenceService =
providedPersistenceService ??
new PersistenceService({
dbPath: stateDbPath ?? path.join(os.homedir(), ".t3", "state.sqlite"),
});
const ownsPersistenceService = providedPersistenceService === undefined;
const stateSyncEngine =
providedStateSyncEngine ?? new LegacyStateSyncEngine({ persistenceService });
const syncEngineMode = providedSyncEngineMode ?? inferSyncEngineMode(stateSyncEngine);
const ownsStateSyncEngine = providedStateSyncEngine === undefined;
const providerManager = new ProviderManager({ persistenceService });
const terminalManager = providedTerminalManager ?? new TerminalManager();
const gitManager = providedGitManager ?? new GitManager();
const clients = new Set<WebSocket>();
const logger = createLogger("ws");
const logWebSocketEvents =
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
let unsubscribeReadModel = noop;
let unsubscribeDomainEvents = noop;
function logOutgoingPush(push: WsPush, recipients: number) {
if (!logWebSocketEvents) return;
@@ -154,185 +122,42 @@ export function createServer(options: ServerOptions) {
});
}
const getOrchestrationEngine = () => {
assert(orchestrationEngine, "Orchestration engine is not started");
return orchestrationEngine;
};
const getProjectRepository = () => {
assert(projectRepository, "Project repository is not started");
return projectRepository;
};
const getEffectRuntime = () => {
assert(effectRuntime, "Effect runtime is not started");
return effectRuntime;
};
async function attachOrchestrationSubscriptions(
runtime: ManagedRuntime.ManagedRuntime<ProjectRepository | OrchestrationEngineService, unknown>,
orchestrationEngine: OrchestrationEngineShape,
) {
unsubscribeReadModel = await runtime.runPromise(
orchestrationEngine.subscribeToReadModel((snapshot) => {
const push: WsPush = {
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.readModel,
data: {
sequence: snapshot.sequence,
snapshot,
} satisfies OrchestrationReadModelPush,
};
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);
}),
);
unsubscribeDomainEvents = await runtime.runPromise(
orchestrationEngine.subscribeToDomainEvents((event) => {
const push: WsPush = {
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
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);
}),
);
}
// Forward provider events to all connected WebSocket clients
providerManager.on("event", (event) => {
void (async () => {
const liveOrchestrationEngine = orchestrationEngine;
const runtime = effectRuntime;
if (!liveOrchestrationEngine || !runtime) {
return;
const push: WsPush = {
type: "push",
channel: WS_CHANNELS.providerEvent,
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;
}
const snapshot = await runtime.runPromise(liveOrchestrationEngine.getSnapshot());
const thread = snapshot.threads.find((entry) => entry.session?.sessionId === event.sessionId);
if (!thread) return;
const now = event.createdAt;
if (event.method === "turn/started" || event.method === "turn/completed") {
await runtime.runPromise(
liveOrchestrationEngine.dispatch({
type: "thread.session",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
sessionId: event.sessionId,
provider: event.provider,
status: event.method === "turn/started" ? "running" : "ready",
threadId: thread.id,
activeTurnId: event.method === "turn/started" ? (event.turnId ?? null) : null,
createdAt: thread.session?.createdAt ?? now,
updatedAt: now,
lastError: null,
},
createdAt: now,
}),
);
}
if (event.textDelta && event.textDelta.length > 0) {
const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`;
await runtime.runPromise(
liveOrchestrationEngine.dispatch(
{
type: "message.send",
commandId: crypto.randomUUID(),
threadId: thread.id,
messageId: assistantMessageId,
role: "assistant",
text: event.textDelta,
streaming: true,
createdAt: now,
},
{ transient: true },
),
);
}
if (event.method === "turn/completed") {
const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`;
const latestSnapshot = await runtime.runPromise(liveOrchestrationEngine.getSnapshot());
const latestThread = latestSnapshot.threads.find(
(entry) => entry.session?.sessionId === event.sessionId,
);
const existingMessage = latestThread?.messages.find((m) => m.id === assistantMessageId);
const accumulatedText = existingMessage?.text ?? "";
await runtime.runPromise(
liveOrchestrationEngine.dispatch({
type: "message.send",
commandId: crypto.randomUUID(),
threadId: thread.id,
messageId: assistantMessageId,
role: "assistant",
text: accumulatedText,
streaming: false,
createdAt: now,
}),
);
}
if (event.method === "checkpoint/captured") {
const payload = asObject(event.payload);
const turnId = event.turnId ?? asString(payload?.turnId);
if (turnId) {
await runtime.runPromise(
liveOrchestrationEngine.dispatch({
type: "thread.turnDiff.complete",
commandId: crypto.randomUUID(),
threadId: thread.id,
turnId,
completedAt: now,
...(asString(payload?.status) !== null
? { status: asString(payload?.status) ?? undefined }
: {}),
files: [],
assistantMessageId: `assistant:${turnId}`,
...(asNumber(payload?.turnCount) !== null
? { checkpointTurnCount: asNumber(payload?.turnCount) ?? undefined }
: {}),
createdAt: now,
}),
);
}
}
if (event.kind === "error" && event.message) {
await runtime.runPromise(
liveOrchestrationEngine.dispatch({
type: "thread.session",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
sessionId: event.sessionId,
provider: event.provider,
status: "error",
threadId: thread.id,
activeTurnId: event.turnId ?? null,
createdAt: thread.session?.createdAt ?? now,
updatedAt: now,
lastError: event.message,
},
createdAt: now,
}),
);
}
})().catch(() => undefined);
}
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);
};
const unsubscribeStateEvents = stateSyncEngine.onStateEvent(onStateEvent);
const onTerminalEvent = (event: TerminalEvent) => {
const push: WsPush = {
type: "push",
@@ -410,6 +235,18 @@ export function createServer(options: ServerOptions) {
// WebSocket server — upgrades from the HTTP server
const wss = new WebSocketServer({ noServer: true });
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
socket.write(
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
"Connection: close\r\n" +
"Content-Type: text/plain\r\n" +
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
"\r\n" +
message,
);
socket.destroy();
}
httpServer.on("upgrade", (request, socket, head) => {
if (authToken) {
let providedToken: string | null = null;
@@ -434,8 +271,6 @@ export function createServer(options: ServerOptions) {
wss.on("connection", (ws) => {
clients.add(ws);
const orchestrationEngine = getOrchestrationEngine();
const runtime = getEffectRuntime();
// Send welcome message with project info
const segments = cwd.split(/[/\\]/).filter(Boolean);
@@ -449,25 +284,6 @@ export function createServer(options: ServerOptions) {
logOutgoingPush(welcome, 1);
ws.send(JSON.stringify(welcome));
void runtime
.runPromise(orchestrationEngine.getSnapshot())
.then((snapshot) => {
if (ws.readyState !== ws.OPEN) {
return;
}
const snapshotPush: WsPush = {
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.readModel,
data: {
sequence: snapshot.sequence,
snapshot,
} satisfies OrchestrationReadModelPush,
};
logOutgoingPush(snapshotPush, 1);
ws.send(JSON.stringify(snapshotPush));
})
.catch(() => undefined);
ws.on("message", (raw) => {
void handleMessage(ws, raw);
});
@@ -510,10 +326,6 @@ export function createServer(options: ServerOptions) {
}
async function routeRequest(request: WsRequest): Promise<unknown> {
const orchestrationEngine = getOrchestrationEngine();
const projectRepository = getProjectRepository();
const effectRuntime = getEffectRuntime();
switch (request.method) {
case WS_METHODS.providersStartSession:
return providerManager.startSession(request.params as never);
@@ -532,66 +344,95 @@ export function createServer(options: ServerOptions) {
return undefined;
}
case WS_METHODS.providersListSessions:
return providerManager.listSessions();
case WS_METHODS.providersListCheckpoints:
return providerManager.listCheckpoints(request.params as never);
case WS_METHODS.providersGetCheckpointDiff:
return providerManager.getCheckpointDiff(request.params as never);
case WS_METHODS.providersRevertToCheckpoint: {
const result = await providerManager.revertToCheckpoint(request.params as never);
const params = request.params as { sessionId?: string };
const sessionId = params.sessionId;
if (typeof sessionId === "string") {
const snapshot = await effectRuntime.runPromise(orchestrationEngine.getSnapshot());
const thread = snapshot.threads.find((entry) => entry.session?.sessionId === sessionId);
if (thread) {
const now = new Date().toISOString();
await effectRuntime.runPromise(
orchestrationEngine.dispatch({
type: "thread.revert",
commandId: crypto.randomUUID(),
threadId: thread.id,
turnCount: result.turnCount,
messageCount: result.messageCount,
createdAt: now,
}),
);
if (thread.session) {
await effectRuntime.runPromise(
orchestrationEngine.dispatch({
type: "thread.session",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
...thread.session,
status: "ready",
activeTurnId: null,
updatedAt: now,
lastError: null,
},
createdAt: now,
}),
);
}
case WS_METHODS.providersRevertToCheckpoint:
{
const params = request.params as {
sessionId: string;
turnCount: number;
};
const result = await providerManager.revertToCheckpoint(params as never);
try {
stateSyncEngine.applyCheckpointRevert({
sessionId: params.sessionId,
runtimeThreadId: result.threadId,
turnCount: result.turnCount,
messageCount: result.messageCount,
});
} catch (error) {
logger.warn("failed to persist checkpoint revert", {
sessionId: params.sessionId,
turnCount: params.turnCount,
error,
});
}
return result;
}
return result;
}
case WS_METHODS.stateBootstrap:
return stateSyncEngine.loadSnapshot();
case WS_METHODS.stateListMessages:
return stateSyncEngine.listMessages(request.params as never);
case WS_METHODS.stateCatchUp:
return stateSyncEngine.catchUp(request.params as never);
case WS_METHODS.appSettingsGet:
return stateSyncEngine.getAppSettings();
case WS_METHODS.appSettingsUpdate:
return stateSyncEngine.updateAppSettings((request.params ?? {}) as never);
case WS_METHODS.threadsCreate:
return stateSyncEngine.createThread(request.params as never);
case "threads.update":
throw new Error(
`"threads.update" is unsupported; use ${WS_METHODS.threadsUpdateTerminalState}`,
);
case WS_METHODS.threadsUpdateTerminalState:
return stateSyncEngine.updateThreadTerminalState(request.params as never);
case WS_METHODS.threadsDelete:
stateSyncEngine.deleteThread(request.params as never);
return undefined;
case WS_METHODS.threadsMarkVisited:
return stateSyncEngine.markThreadVisited(request.params as never);
case WS_METHODS.threadsUpdateModel:
return stateSyncEngine.updateThreadModel(request.params as never);
case WS_METHODS.threadsUpdateTitle:
return stateSyncEngine.updateThreadTitle(request.params as never);
case WS_METHODS.threadsUpdateBranch:
return stateSyncEngine.updateThreadBranch(request.params as never);
case WS_METHODS.projectsList:
return effectRuntime.runPromise(projectRepository.list());
return stateSyncEngine.listProjects();
case WS_METHODS.projectsAdd:
return effectRuntime.runPromise(projectRepository.add(request.params as never));
return stateSyncEngine.addProject(request.params as never);
case WS_METHODS.projectsRemove:
return effectRuntime.runPromise(projectRepository.remove(request.params as never));
stateSyncEngine.removeProject(request.params as never);
return undefined;
case WS_METHODS.projectsSearchEntries:
return searchWorkspaceEntries(request.params as never);
case WS_METHODS.projectsUpdateScripts:
return effectRuntime.runPromise(projectRepository.updateScripts(request.params as never));
return stateSyncEngine.updateProjectScripts(request.params as never);
case WS_METHODS.shellOpenInEditor: {
const params = request.params as {
@@ -637,27 +478,8 @@ export function createServer(options: ServerOptions) {
return undefined;
}
case WS_METHODS.gitStatus: {
const params = request.params as { cwd: string };
const status = await gitManager.status(request.params as never);
const projects = await effectRuntime.runPromise(projectRepository.list());
const project = projects.find((entry) => entry.cwd === params.cwd);
if (project) {
await effectRuntime.runPromise(
orchestrationEngine.dispatch({
type: "git.readModel.upsert",
commandId: crypto.randomUUID(),
projectId: project.id,
branch: status.branch,
hasWorkingTreeChanges: status.hasWorkingTreeChanges,
aheadCount: status.aheadCount,
behindCount: status.behindCount,
createdAt: new Date().toISOString(),
}),
);
}
return status;
}
case WS_METHODS.gitStatus:
return gitManager.status(request.params as never);
case WS_METHODS.gitPull:
return pullGitBranch(request.params as never);
@@ -707,6 +529,7 @@ export function createServer(options: ServerOptions) {
case WS_METHODS.serverGetConfig:
return {
cwd,
syncEngineMode,
keybindings: keybindingsConfig,
};
@@ -716,86 +539,16 @@ export function createServer(options: ServerOptions) {
keybindings: keybindingsConfig,
};
case ORCHESTRATION_WS_METHODS.getSnapshot:
return effectRuntime.runPromise(orchestrationEngine.getSnapshot());
case ORCHESTRATION_WS_METHODS.dispatchCommand:
return effectRuntime.runPromise(orchestrationEngine.dispatchUnknown(request.params));
case ORCHESTRATION_WS_METHODS.replayEvents:
return effectRuntime.runPromise(
orchestrationEngine.replayEvents(
Math.max(
0,
Math.floor(
Number(
(request.params as { fromSequenceExclusive?: number } | undefined)
?.fromSequenceExclusive ?? 0,
),
),
),
),
);
default:
throw new Error(`Unknown method: ${request.method}`);
}
}
async function createEffectRuntime() {
const dbPath = path.join(resolvedStateDir, "orchestration.sqlite");
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const orchestrationLayer = Layer.provide(
OrchestrationEngineLive,
OrchestrationEventRepositoryLive,
);
const layer = Layer.mergeAll(orchestrationLayer, ProjectRepositoryLive).pipe(
Layer.provide(persistenceLayer),
);
const runtime = ManagedRuntime.make(layer);
try {
const [nextOrchestrationEngine, repository] = await Promise.all([
runtime.runPromise(Effect.service(OrchestrationEngineService)),
runtime.runPromise(Effect.service(ProjectRepository)),
]);
orchestrationEngine = nextOrchestrationEngine;
projectRepository = repository;
await runtime.runPromise(repository.pruneMissing());
await attachOrchestrationSubscriptions(runtime, nextOrchestrationEngine);
} catch (error) {
await runtime.dispose().catch(() => undefined);
throw error;
}
return runtime;
}
async function disposeEffectRuntime() {
unsubscribeReadModel();
unsubscribeDomainEvents();
unsubscribeReadModel = noop;
unsubscribeDomainEvents = noop;
const runtime = effectRuntime;
effectRuntime = null;
orchestrationEngine = null;
projectRepository = null;
if (!runtime) {
return;
}
await runtime.dispose();
}
async function start() {
effectRuntime = await createEffectRuntime();
function start() {
return new Promise<void>((resolve, reject) => {
const onError = (error: Error) => {
httpServer.off("error", onError);
void disposeEffectRuntime().finally(() => reject(error));
reject(error);
};
httpServer.once("error", onError);
const onListening = () => {
@@ -811,17 +564,32 @@ export function createServer(options: ServerOptions) {
}
async function stop(): Promise<void> {
await disposeEffectRuntime();
terminalManager.off("event", onTerminalEvent);
unsubscribeStateEvents();
providerManager.stopAll();
providerManager.dispose();
terminalManager.dispose();
if (ownsStateSyncEngine) {
stateSyncEngine.close();
}
if (ownsPersistenceService) {
persistenceService.close();
}
for (const client of clients) {
client.close();
}
clients.clear();
const isServerNotRunningError = (error: unknown): boolean => {
if (!(error instanceof Error)) return false;
const maybeCode = (error as NodeJS.ErrnoException).code;
return (
maybeCode === "ERR_SERVER_NOT_RUNNING" ||
error.message.toLowerCase().includes("not running")
);
};
const closeWebSocketServer = new Promise<void>((resolve, reject) => {
wss.close((error) => {
if (error && !isServerNotRunningError(error)) {
@@ -847,3 +615,16 @@ export function createServer(options: ServerOptions) {
return { start, stop, httpServer };
}
function inferSyncEngineMode(stateSyncEngine: StateSyncEngine): SyncEngineMode {
if (stateSyncEngine instanceof LiveStoreReadPilotStateSyncEngine) {
return stateSyncEngine.isReadFallbackDisabled() ? "livestore" : "livestore-read-pilot";
}
if (stateSyncEngine instanceof ShadowStateSyncEngine) {
return "shadow";
}
if (stateSyncEngine instanceof LegacyStateSyncEngine) {
return "legacy";
}
return "legacy";
}
+1 -3
View File
@@ -3,9 +3,7 @@
"compilerOptions": {
"composite": true,
"types": ["node"],
"lib": ["ES2023", "esnext.disposable"],
"noEmit": true,
"allowImportingTsExtensions": true
"lib": ["ES2023", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
}
+159
View File
@@ -0,0 +1,159 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const LOCAL_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:local:v1";
const LEGACY_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
type StorageMap = Map<string, string>;
interface Deferred<T> {
promise: Promise<T>;
resolve: (value: T) => void;
reject: (error?: unknown) => void;
}
function createDeferred<T>(): Deferred<T> {
let resolve!: (value: T) => void;
let reject!: (error?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return {
promise,
resolve,
reject,
};
}
async function flushMicrotasks(times = 3): Promise<void> {
if (times <= 0) return;
await Promise.resolve();
await flushMicrotasks(times - 1);
}
function installWindowMock(initialStorage?: StorageMap): StorageMap {
const storage = initialStorage ?? new Map<string, string>();
const localStorageMock = {
length: 0,
clear: () => {
storage.clear();
localStorageMock.length = 0;
},
getItem: (key: string) => storage.get(key) ?? null,
key: (index: number) => Array.from(storage.keys())[index] ?? null,
removeItem: (key: string) => {
storage.delete(key);
localStorageMock.length = storage.size;
},
setItem: (key: string, value: string) => {
storage.set(key, value);
localStorageMock.length = storage.size;
},
};
localStorageMock.length = storage.size;
const windowMock = {
localStorage: localStorageMock as Storage,
addEventListener: () => undefined,
removeEventListener: () => undefined,
};
Object.defineProperty(globalThis, "window", {
configurable: true,
value: windowMock,
});
return storage;
}
describe("appSettings", () => {
afterEach(() => {
vi.resetModules();
Reflect.deleteProperty(globalThis, "window");
});
it("returns a stable snapshot reference when settings have not changed", async () => {
installWindowMock();
const module = await import("./appSettings");
const first = module.getAppSettingsSnapshot();
const second = module.getAppSettingsSnapshot();
expect(second).toBe(first);
});
it("returns a new snapshot reference when local settings change", async () => {
const storage = installWindowMock();
const module = await import("./appSettings");
const first = module.getAppSettingsSnapshot();
storage.set(LOCAL_APP_SETTINGS_STORAGE_KEY, JSON.stringify({ confirmThreadDelete: false }));
const second = module.getAppSettingsSnapshot();
expect(second).not.toBe(first);
expect(second.confirmThreadDelete).toBe(false);
});
it("prevents hydration from overwriting optimistic backend writes", async () => {
installWindowMock();
const getDeferred = createDeferred<{ codexBinaryPath: string; codexHomePath: string }>();
const updateDeferred = createDeferred<{ codexBinaryPath: string; codexHomePath: string }>();
const get = vi.fn(() => getDeferred.promise);
const update = vi.fn(() => updateDeferred.promise);
window.nativeApi = {
appSettings: {
get,
update,
},
} as unknown as NonNullable<Window["nativeApi"]>;
const module = await import("./appSettings");
const hydration = module.ensureAppSettingsHydrated();
module.updateAppSettings({ codexBinaryPath: "/opt/codex/new" });
getDeferred.resolve({ codexBinaryPath: "/opt/codex/stale", codexHomePath: "" });
await hydration;
expect(module.getAppSettingsSnapshot().codexBinaryPath).toBe("/opt/codex/new");
expect(update).toHaveBeenCalledTimes(1);
updateDeferred.resolve({ codexBinaryPath: "/opt/codex/new", codexHomePath: "" });
await flushMicrotasks();
expect(module.getAppSettingsSnapshot().codexBinaryPath).toBe("/opt/codex/new");
});
it("prevents hydration from overwriting optimistic local writes", async () => {
const storage = installWindowMock(
new Map([
[
LEGACY_APP_SETTINGS_STORAGE_KEY,
JSON.stringify({
confirmThreadDelete: true,
}),
],
]),
);
const getDeferred = createDeferred<{ codexBinaryPath: string; codexHomePath: string }>();
const get = vi.fn(() => getDeferred.promise);
window.nativeApi = {
appSettings: {
get,
update: vi.fn(async () => ({ codexBinaryPath: "", codexHomePath: "" })),
},
} as unknown as NonNullable<Window["nativeApi"]>;
const module = await import("./appSettings");
const hydration = module.ensureAppSettingsHydrated();
module.updateAppSettings({ confirmThreadDelete: false });
getDeferred.resolve({ codexBinaryPath: "", codexHomePath: "" });
await hydration;
expect(module.getAppSettingsSnapshot().confirmThreadDelete).toBe(false);
expect(storage.get(LOCAL_APP_SETTINGS_STORAGE_KEY)).toBe(
JSON.stringify({ confirmThreadDelete: false }),
);
});
});
+249 -39
View File
@@ -1,21 +1,48 @@
import { useCallback, useSyncExternalStore } from "react";
import {
type AppSettings as BackendAppSettings,
appSettingsSchema as backendAppSettingsSchema,
appSettingsUpdateInputSchema,
} from "@t3tools/contracts";
import { useCallback, useEffect, useSyncExternalStore } from "react";
import { z } from "zod";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
import { readNativeApi } from "./session-logic";
const appSettingsSchema = z.object({
codexBinaryPath: z.string().trim().max(4096).default(""),
codexHomePath: z.string().trim().max(4096).default(""),
const LOCAL_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:local:v1";
const LEGACY_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const localAppSettingsSchema = z.object({
confirmThreadDelete: z.boolean().default(true),
});
const legacyAppSettingsSchema = backendAppSettingsSchema.extend({
confirmThreadDelete: z.boolean().default(true),
});
const appSettingsSchema = backendAppSettingsSchema.extend({
confirmThreadDelete: z.boolean().default(true),
});
export type AppSettings = z.infer<typeof appSettingsSchema>;
const DEFAULT_APP_SETTINGS: AppSettings = appSettingsSchema.parse({});
const DEFAULT_BACKEND_APP_SETTINGS: BackendAppSettings = backendAppSettingsSchema.parse({});
const DEFAULT_LOCAL_APP_SETTINGS = localAppSettingsSchema.parse({});
const DEFAULT_APP_SETTINGS: AppSettings = {
...DEFAULT_BACKEND_APP_SETTINGS,
...DEFAULT_LOCAL_APP_SETTINGS,
};
let listeners: Array<() => void> = [];
let cachedRawSettings: string | null | undefined;
let cachedBackendSettings: BackendAppSettings = DEFAULT_BACKEND_APP_SETTINGS;
let cachedBackendCacheKey = JSON.stringify(DEFAULT_BACKEND_APP_SETTINGS);
let cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
let cachedLocalCacheKey: string | undefined;
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
let cachedSnapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
let backendHydrationPromise: Promise<void> | null = null;
let backendHydrated = false;
let backendUpdateSequence = 0;
let optimisticWriteSequence = 0;
function emitChange(): void {
for (const listener of listeners) {
@@ -23,55 +50,240 @@ function emitChange(): void {
}
}
function parsePersistedSettings(value: string | null): AppSettings {
function setCachedBackendSettings(next: BackendAppSettings): void {
cachedBackendSettings = next;
cachedBackendCacheKey = JSON.stringify(next);
}
function parseLegacySettings(value: string | null): z.infer<typeof legacyAppSettingsSchema> | null {
if (!value) {
return DEFAULT_APP_SETTINGS;
return null;
}
try {
const parsed = JSON.parse(value) as unknown;
return appSettingsSchema.parse(parsed);
return legacyAppSettingsSchema.parse(parsed);
} catch {
return DEFAULT_APP_SETTINGS;
return null;
}
}
export function getAppSettingsSnapshot(): AppSettings {
function readLegacySettingsSnapshot(): z.infer<typeof legacyAppSettingsSchema> | null {
if (typeof window === "undefined") {
return DEFAULT_APP_SETTINGS;
return null;
}
const raw = window.localStorage.getItem(APP_SETTINGS_STORAGE_KEY);
if (raw === cachedRawSettings) {
return cachedSnapshot;
}
cachedRawSettings = raw;
cachedSnapshot = parsePersistedSettings(raw);
return cachedSnapshot;
return parseLegacySettings(window.localStorage.getItem(LEGACY_APP_SETTINGS_STORAGE_KEY));
}
function persistSettings(next: AppSettings): void {
function readLocalSettingsSnapshot() {
if (typeof window === "undefined") {
return DEFAULT_LOCAL_APP_SETTINGS;
}
const rawLocal = window.localStorage.getItem(LOCAL_APP_SETTINGS_STORAGE_KEY);
const rawLegacy = rawLocal === null ? window.localStorage.getItem(LEGACY_APP_SETTINGS_STORAGE_KEY) : null;
const cacheKey = rawLocal !== null ? `local:${rawLocal}` : `legacy:${rawLegacy ?? ""}`;
if (cacheKey === cachedLocalCacheKey) {
return cachedLocalSettings;
}
if (rawLocal !== null) {
try {
const parsed = JSON.parse(rawLocal) as unknown;
cachedLocalSettings = localAppSettingsSchema.parse(parsed);
} catch {
cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
}
} else {
const legacySettings = parseLegacySettings(rawLegacy);
cachedLocalSettings = localAppSettingsSchema.parse({
confirmThreadDelete: legacySettings?.confirmThreadDelete ?? DEFAULT_LOCAL_APP_SETTINGS.confirmThreadDelete,
});
}
cachedLocalCacheKey = cacheKey;
return cachedLocalSettings;
}
function persistLocalSettings(next: z.infer<typeof localAppSettingsSchema>): void {
if (typeof window === "undefined") return;
const raw = JSON.stringify(next);
const normalized = localAppSettingsSchema.parse(next);
const raw = JSON.stringify(normalized);
try {
if (raw !== cachedRawSettings) {
window.localStorage.setItem(APP_SETTINGS_STORAGE_KEY, raw);
}
window.localStorage.setItem(LOCAL_APP_SETTINGS_STORAGE_KEY, raw);
} catch {
// Best-effort persistence only.
}
cachedRawSettings = raw;
cachedSnapshot = next;
cachedLocalSettings = normalized;
cachedLocalCacheKey = `local:${raw}`;
}
function normalizeBackendSettings(value: unknown): BackendAppSettings {
const parsed = backendAppSettingsSchema.safeParse(value);
if (parsed.success) {
return parsed.data;
}
return DEFAULT_BACKEND_APP_SETTINGS;
}
async function hydrateBackendSettings(): Promise<void> {
if (typeof window === "undefined" || backendHydrated) {
return;
}
if (backendHydrationPromise) {
await backendHydrationPromise;
return;
}
const hydrationSequence = optimisticWriteSequence;
const hasOptimisticWriteSinceHydration = () => hydrationSequence !== optimisticWriteSequence;
backendHydrationPromise = (async () => {
const api = readNativeApi();
if (!api?.appSettings || typeof api.appSettings.get !== "function") {
backendHydrated = true;
return;
}
const legacySettings = readLegacySettingsSnapshot();
let next = normalizeBackendSettings(await api.appSettings.get());
if (!hasOptimisticWriteSinceHydration()) {
const migrationPatch = appSettingsUpdateInputSchema.parse({
...(next.codexBinaryPath.length === 0 && legacySettings?.codexBinaryPath
? { codexBinaryPath: legacySettings.codexBinaryPath }
: {}),
...(next.codexHomePath.length === 0 && legacySettings?.codexHomePath
? { codexHomePath: legacySettings.codexHomePath }
: {}),
});
const hasMigrationPatch =
migrationPatch.codexBinaryPath !== undefined || migrationPatch.codexHomePath !== undefined;
if (hasMigrationPatch) {
next = normalizeBackendSettings(await api.appSettings.update(migrationPatch));
}
}
if (!hasOptimisticWriteSinceHydration()) {
setCachedBackendSettings(next);
if (legacySettings) {
persistLocalSettings({
confirmThreadDelete: legacySettings.confirmThreadDelete,
});
}
emitChange();
}
backendHydrated = true;
if (legacySettings) {
try {
window.localStorage.removeItem(LEGACY_APP_SETTINGS_STORAGE_KEY);
} catch {
// Best-effort legacy cleanup only.
}
}
})()
.catch(() => undefined)
.finally(() => {
backendHydrationPromise = null;
});
await backendHydrationPromise;
}
export function getAppSettingsSnapshot(): AppSettings {
const localSettings = readLocalSettingsSnapshot();
const snapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
if (snapshotKey === cachedSnapshotKey) {
return cachedSnapshot;
}
cachedSnapshot = appSettingsSchema.parse({
...cachedBackendSettings,
...localSettings,
});
cachedSnapshotKey = snapshotKey;
return cachedSnapshot;
}
export function ensureAppSettingsHydrated(): Promise<void> {
return hydrateBackendSettings();
}
export function updateAppSettings(patch: Partial<AppSettings>): void {
const parsedPatch = appSettingsSchema.partial().parse(patch);
let didChange = false;
let didOptimisticWrite = false;
const markOptimisticWrite = () => {
if (didOptimisticWrite) return;
didOptimisticWrite = true;
optimisticWriteSequence += 1;
};
if (parsedPatch.confirmThreadDelete !== undefined) {
markOptimisticWrite();
persistLocalSettings({
...readLocalSettingsSnapshot(),
confirmThreadDelete: parsedPatch.confirmThreadDelete,
});
didChange = true;
}
const backendPatch = appSettingsUpdateInputSchema.parse({
...(parsedPatch.codexBinaryPath !== undefined
? { codexBinaryPath: parsedPatch.codexBinaryPath }
: {}),
...(parsedPatch.codexHomePath !== undefined ? { codexHomePath: parsedPatch.codexHomePath } : {}),
});
const hasBackendPatch =
backendPatch.codexBinaryPath !== undefined || backendPatch.codexHomePath !== undefined;
if (hasBackendPatch) {
markOptimisticWrite();
const previous = cachedBackendSettings;
const optimisticNext = backendAppSettingsSchema.parse({
...cachedBackendSettings,
...backendPatch,
});
setCachedBackendSettings(optimisticNext);
backendHydrated = true;
didChange = true;
const updateSequence = ++backendUpdateSequence;
const api = readNativeApi();
if (api?.appSettings && typeof api.appSettings.update === "function") {
void api.appSettings
.update(backendPatch)
.then((response) => {
if (updateSequence !== backendUpdateSequence) return;
setCachedBackendSettings(normalizeBackendSettings(response));
emitChange();
})
.catch(() => {
if (updateSequence !== backendUpdateSequence) return;
setCachedBackendSettings(previous);
emitChange();
});
}
}
if (didChange) {
emitChange();
}
}
function subscribe(listener: () => void): () => void {
listeners.push(listener);
const onStorage = (event: StorageEvent) => {
if (event.key === APP_SETTINGS_STORAGE_KEY) {
if (
event.key === null ||
event.key === LOCAL_APP_SETTINGS_STORAGE_KEY ||
event.key === LEGACY_APP_SETTINGS_STORAGE_KEY
) {
emitChange();
}
};
@@ -86,19 +298,17 @@ function subscribe(listener: () => void): () => void {
export function useAppSettings() {
const settings = useSyncExternalStore(subscribe, getAppSettingsSnapshot, () => DEFAULT_APP_SETTINGS);
useEffect(() => {
void ensureAppSettingsHydrated();
}, []);
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
const next = appSettingsSchema.parse({
...getAppSettingsSnapshot(),
...patch,
});
persistSettings(next);
emitChange();
updateAppSettings(patch);
}, []);
const resetSettings = useCallback(() => {
persistSettings(DEFAULT_APP_SETTINGS);
emitChange();
}, []);
updateSettings(DEFAULT_APP_SETTINGS);
}, [updateSettings]);
return {
settings,
+1 -21
View File
@@ -92,23 +92,13 @@ export default function BranchToolbar({
});
if (!activeThreadId || !syncedBranch) return;
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
createdAt: new Date().toISOString(),
});
}
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch, api]);
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
@@ -130,16 +120,6 @@ export default function BranchToolbar({
if (sessionId && worktreePath !== activeWorktreePath) {
void api?.providers.stopSession({ sessionId }).catch(() => undefined);
}
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThreadId,
branch,
worktreePath,
createdAt: new Date().toISOString(),
});
}
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
};
+204 -67
View File
@@ -57,6 +57,7 @@ import {
derivePhase,
deriveTurnDiffFilesFromUnifiedDiff,
deriveTimelineEntries,
type TurnDiffSummary,
type PendingApproval,
deriveWorkLogEntries,
formatDuration,
@@ -71,7 +72,6 @@ import {
MAX_THREAD_TERMINAL_COUNT,
type ChatImageAttachment,
type TurnDiffFileChange,
type TurnDiffSummary,
} from "../types";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
@@ -415,6 +415,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
const checkpointHydrationSessionRequestRef = useRef(new Set<string>());
const checkpointTurnCountSyncFingerprintRef = useRef(new Map<string, string>());
const terminalStateSyncFingerprintRef = useRef(new Map<string, string>());
const activeThread = state.threads.find((t) => t.id === threadId);
const diffSearch = useMemo(
@@ -433,13 +434,28 @@ export default function ChatView({ threadId }: ChatViewProps) {
const phase = derivePhase(activeThread?.session ?? null);
const isWorking = phase === "running" || isSending || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const workLogEntries = useMemo(() => deriveWorkLogEntries([], undefined), []);
const latestTurnWorkEntries = useMemo(
() => deriveWorkLogEntries([], activeThread?.latestTurnId),
[activeThread?.latestTurnId],
const workLogEntries = useMemo(
() => deriveWorkLogEntries(activeThread?.events ?? [], undefined),
[activeThread?.events],
);
const pendingApprovals = useMemo(() => derivePendingApprovals([]), []);
const assistantCompletionByItemId = useMemo(() => new Map<string, string>(), []);
const latestTurnWorkEntries = useMemo(
() => deriveWorkLogEntries(activeThread?.events ?? [], activeThread?.latestTurnId),
[activeThread?.events, activeThread?.latestTurnId],
);
const pendingApprovals = useMemo(
() => derivePendingApprovals(activeThread?.events ?? []),
[activeThread?.events],
);
const assistantCompletionByItemId = useMemo(() => {
const map = new Map<string, string>();
const ordered = [...(activeThread?.events ?? [])].toReversed();
for (const event of ordered) {
if (event.method !== "item/completed") continue;
if (!event.itemId) continue;
map.set(event.itemId, event.createdAt);
}
return map;
}, [activeThread?.events]);
const timelineEntries = useMemo(
() => deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries),
[activeThread?.messages, workLogEntries],
@@ -550,6 +566,36 @@ export default function ChatView({ threadId }: ChatViewProps) {
return byUserMessageId;
}, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
useEffect(() => {
if (!activeThreadId || turnDiffSummaries.length === 0) {
return;
}
const inferredMissingTurnCounts = turnDiffSummaries.reduce<Record<string, number>>(
(acc, summary) => {
if (typeof summary.checkpointTurnCount === "number") {
return acc;
}
const inferredTurnCount = inferredCheckpointTurnCountByTurnId[summary.turnId];
if (typeof inferredTurnCount !== "number") {
return acc;
}
acc[summary.turnId] = inferredTurnCount;
return acc;
},
{},
);
if (Object.keys(inferredMissingTurnCounts).length === 0) {
return;
}
dispatch({
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
threadId: activeThreadId,
checkpointTurnCountByTurnId: inferredMissingTurnCounts,
});
}, [activeThreadId, dispatch, inferredCheckpointTurnCountByTurnId, turnDiffSummaries]);
const completionSummary = useMemo(() => {
if (!activeThread?.latestTurnStartedAt) return null;
if (!activeThread.latestTurnCompletedAt) return null;
@@ -718,6 +764,90 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const hasReachedTerminalLimit =
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
const activeThreadTerminalSyncId = activeThread?.id;
const activeThreadTerminalSyncOpen = activeThread?.terminalOpen;
const activeThreadTerminalSyncHeight = activeThread?.terminalHeight;
const activeThreadTerminalSyncIds = activeThread?.terminalIds;
const activeThreadTerminalSyncActiveId = activeThread?.activeTerminalId;
const activeThreadTerminalSyncGroups = activeThread?.terminalGroups;
const activeThreadTerminalSyncActiveGroupId = activeThread?.activeTerminalGroupId;
useEffect(() => {
if (!api || !activeThread) return;
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]);
useEffect(() => {
if (
!api ||
!activeThreadTerminalSyncId ||
activeThreadTerminalSyncOpen === undefined ||
activeThreadTerminalSyncHeight === undefined ||
activeThreadTerminalSyncIds === undefined ||
activeThreadTerminalSyncActiveId === undefined ||
activeThreadTerminalSyncGroups === undefined
) {
return;
}
const payload = {
threadId: activeThreadTerminalSyncId,
terminalOpen: activeThreadTerminalSyncOpen,
terminalHeight: activeThreadTerminalSyncHeight,
terminalIds: activeThreadTerminalSyncIds,
activeTerminalId: activeThreadTerminalSyncActiveId,
terminalGroups: activeThreadTerminalSyncGroups,
...(activeThreadTerminalSyncActiveGroupId !== undefined
? { activeTerminalGroupId: activeThreadTerminalSyncActiveGroupId }
: {}),
};
const fingerprint = JSON.stringify(payload);
const previousFingerprint = terminalStateSyncFingerprintRef.current.get(payload.threadId);
if (previousFingerprint === fingerprint) return;
terminalStateSyncFingerprintRef.current.set(payload.threadId, fingerprint);
void api.threads
.updateTerminalState(payload)
.catch(() => {
const currentFingerprint = terminalStateSyncFingerprintRef.current.get(payload.threadId);
if (currentFingerprint === fingerprint) {
terminalStateSyncFingerprintRef.current.delete(payload.threadId);
}
});
}, [
api,
activeThreadTerminalSyncId,
activeThreadTerminalSyncOpen,
activeThreadTerminalSyncHeight,
activeThreadTerminalSyncIds,
activeThreadTerminalSyncActiveId,
activeThreadTerminalSyncGroups,
activeThreadTerminalSyncActiveGroupId,
]);
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
for (const image of images) {
@@ -904,7 +1034,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
scripts: input.nextScripts,
});
if (!isElectron || !api) return;
if (!api) return;
let scriptsPersisted = false;
try {
@@ -1428,14 +1558,28 @@ export default function ChatView({ threadId }: ChatViewProps) {
checkpointTurnCountSyncFingerprintRef.current.set(syncKey, turnFingerprint);
try {
await api.providers.listCheckpoints({
const result = await api.providers.listCheckpoints({
sessionId: input.sessionId,
});
const turnIdSet = new Set(turnIds);
const checkpointTurnCountByTurnId = Object.fromEntries(
result.checkpoints
.filter((checkpoint) => checkpoint.turnCount > 0 && turnIdSet.has(checkpoint.id))
.map((checkpoint) => [checkpoint.id, checkpoint.turnCount] as const),
);
if (Object.keys(checkpointTurnCountByTurnId).length === 0) {
return;
}
dispatch({
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
threadId: input.threadId,
checkpointTurnCountByTurnId,
});
} catch {
checkpointTurnCountSyncFingerprintRef.current.delete(syncKey);
}
},
[api, turnDiffSummaries],
[api, dispatch, turnDiffSummaries],
);
const ensureSession = useCallback(
@@ -1466,6 +1610,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,
@@ -1474,21 +1619,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
approvalPolicy: runtimeApprovalPolicy,
sandboxMode: runtimeSandboxMode,
});
await api.orchestration.dispatchCommand({
type: "thread.session",
commandId: crypto.randomUUID(),
dispatch({
type: "UPDATE_SESSION",
threadId: activeThread.id,
session: {
sessionId: session.sessionId,
provider: session.provider,
status: session.status,
threadId: session.threadId ?? activeThread.id,
activeTurnId: session.activeTurnId ?? null,
createdAt: session.createdAt,
updatedAt: session.updatedAt,
lastError: session.lastError ?? null,
},
createdAt: new Date().toISOString(),
session,
});
const resolvedThreadId = session.threadId ?? null;
const continuityState: SessionContinuityState =
@@ -1524,6 +1658,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
api,
codexBinaryPath,
codexHomePath,
dispatch,
runtimeApprovalPolicy,
runtimeSandboxMode,
selectedModel,
@@ -1593,10 +1728,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (!sessionInfo) {
return;
}
await api.providers.revertToCheckpoint({
const result = await api.providers.revertToCheckpoint({
sessionId: sessionInfo.sessionId,
turnCount,
});
dispatch({
type: "REVERT_TO_CHECKPOINT",
threadId: activeThread.id,
sessionId: sessionInfo.sessionId,
threadRuntimeId: result.threadId,
turnCount: result.turnCount,
messageCount: result.messageCount,
});
dispatch({
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
threadId: activeThread.id,
checkpointTurnCountByTurnId: Object.fromEntries(
result.checkpoints
.filter((entry) => entry.turnCount > 0)
.map((entry) => [entry.id, entry.turnCount] as const),
),
});
} catch (err) {
setThreadError(
activeThread.id,
@@ -1643,16 +1795,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
newBranch,
});
sessionCwd = result.worktree.path;
if (api) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThread.id,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
createdAt: new Date().toISOString(),
});
}
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThread.id,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
const setupScript = setupProjectScript(activeProject.scripts);
if (setupScript) {
void runProjectScript(setupScript, {
@@ -1679,15 +1827,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
: "New thread");
const title = truncateTitle(titleSeed);
if (api) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThread.id,
title,
createdAt: new Date().toISOString(),
});
}
dispatch({
type: "SET_THREAD_TITLE",
threadId: activeThread.id,
title,
});
}
setThreadError(activeThread.id, null);
@@ -1699,19 +1843,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
const userMessageId = crypto.randomUUID();
if (api) {
await api.orchestration.dispatchCommand({
type: "message.send",
commandId: crypto.randomUUID(),
threadId: activeThread.id,
messageId: userMessageId,
role: "user",
text: trimmed,
streaming: false,
createdAt: new Date().toISOString(),
});
}
const clientMessageId = crypto.randomUUID();
dispatch({
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: clientMessageId,
text: trimmed,
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
});
const previousMessages = activeThread.messages;
promptRef.current = "";
setPrompt("");
@@ -1748,6 +1887,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,
@@ -1800,18 +1941,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
const onModelSelect = useCallback(
(model: ModelSlug) => {
if (!activeThread) return;
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThread.id,
model: resolveModelSlug(model),
createdAt: new Date().toISOString(),
});
}
dispatch({
type: "SET_THREAD_MODEL",
threadId: activeThread.id,
model: resolveModelSlug(model),
});
scheduleComposerFocus();
},
[activeThread, api, scheduleComposerFocus],
[activeThread, dispatch, scheduleComposerFocus],
);
const onEffortSelect = useCallback(
(effort: ReasoningEffort) => {
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL } from "../model-logic";
import { createLocalThreadForProject } from "./Sidebar.logic";
describe("createLocalThreadForProject", () => {
it("creates a local thread with the project's configured model", () => {
const thread = createLocalThreadForProject({
projectId: "project-1",
projects: [
{
id: "project-1",
name: "Project",
cwd: "/tmp/project",
model: "custom-project-model",
expanded: true,
scripts: [],
},
],
options: {
branch: "feature/test",
worktreePath: "/tmp/project/worktrees/feature-test",
},
});
expect(thread.projectId).toBe("project-1");
expect(thread.model).toBe("custom-project-model");
expect(thread.branch).toBe("feature/test");
expect(thread.worktreePath).toBe("/tmp/project/worktrees/feature-test");
});
it("falls back to the default model when the project is missing", () => {
const thread = createLocalThreadForProject({
projectId: "missing-project",
projects: [],
});
expect(thread.projectId).toBe("missing-project");
expect(thread.model).toBe(DEFAULT_MODEL);
expect(thread.branch).toBeNull();
expect(thread.worktreePath).toBeNull();
});
});
+25
View File
@@ -0,0 +1,25 @@
import { DEFAULT_MODEL } from "../model-logic";
import { createThread } from "../threadFactory";
import type { Project, Thread } from "../types";
interface CreateLocalThreadInput {
projectId: string;
projects: Project[];
options?: {
branch?: string | null;
worktreePath?: string | null;
};
}
export function createLocalThreadForProject({
projectId,
projects,
options,
}: CreateLocalThreadInput): Thread {
const model = projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
return createThread(projectId, {
model,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
});
}
+135 -53
View File
@@ -7,14 +7,16 @@ import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import { type Thread } from "../types";
import { type Project, type Thread } from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { toastManager } from "./ui/toast";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { createLocalThreadForProject } from "./Sidebar.logic";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
@@ -28,6 +30,13 @@ function formatRelativeTime(iso: string): string {
return `${Math.floor(hours / 24)}d ago`;
}
function inferProjectName(cwd: string): string {
const normalized = cwd.replace(/\\/g, "/").replace(/\/+$/, "");
const parts = normalized.split("/");
const last = parts[parts.length - 1];
return last && last.length > 0 ? last : "project";
}
interface ThreadStatusPill {
label: "Working" | "Connecting" | "Completed" | "Awaiting response";
colorClass: string;
@@ -122,7 +131,13 @@ export default function Sidebar() {
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const pendingApprovalByThreadId = useMemo(() => new Map<string, boolean>(), []);
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<string, boolean>();
for (const thread of state.threads) {
map.set(thread.id, derivePendingApprovals(thread.events).length > 0);
}
return map;
}, [state.threads]);
const handleNewThread = useCallback(
(
@@ -132,25 +147,69 @@ export default function Sidebar() {
worktreePath?: string | null;
},
) => {
if (!api) return;
const threadId = crypto.randomUUID();
const createdAt = new Date().toISOString();
const model = state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
void api.orchestration.dispatchCommand({
type: "thread.create",
commandId: crypto.randomUUID(),
threadId,
projectId,
title: "New thread",
model,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
createdAt,
});
void navigate({
to: "/$threadId",
params: { threadId },
});
if (!api) {
const localThread = createLocalThreadForProject({
projectId,
projects: state.projects,
...(options ? { options } : {}),
});
dispatch({
type: "ADD_THREAD",
thread: localThread,
});
void navigate({
to: "/$threadId",
params: { threadId: localThread.id },
});
return;
}
void (async () => {
try {
const result = await api.threads.create({
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.
}
})();
},
[api, dispatch, navigate, state.projects],
);
@@ -181,23 +240,48 @@ export default function Sidebar() {
setIsAddingProject(true);
try {
if (!api) return;
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
if (!api) {
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
}
const name = inferProjectName(cwd);
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: [],
};
dispatch({ type: "ADD_PROJECT", project });
handleNewThread(project.id);
return;
}
const result = await api.projects.add({ cwd });
const projects = await api.projects.list();
dispatch({ type: "SYNC_PROJECTS", projects });
const hasThread = state.threads.some((thread) => thread.projectId === result.project.id);
if (hasThread) {
focusMostRecentThreadForProject(result.project.id);
return;
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);
}
handleNewThread(result.project.id);
} finally {
setIsAddingProject(false);
setNewCwd("");
@@ -211,7 +295,6 @@ export default function Sidebar() {
handleNewThread,
isAddingProject,
state.projects,
state.threads,
],
);
@@ -289,12 +372,8 @@ export default function Sidebar() {
const shouldNavigateToFallback = routeThreadId === threadId;
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: crypto.randomUUID(),
threadId,
createdAt: new Date().toISOString(),
});
void api.threads.delete({ threadId }).catch(() => undefined);
dispatch({ type: "DELETE_THREAD", threadId });
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
void navigate({
@@ -368,20 +447,23 @@ export default function Sidebar() {
);
if (!confirmed) return;
try {
await api.projects.remove({ id: projectId });
const projects = await api.projects.list();
dispatch({ type: "SYNC_PROJECTS", projects });
} catch (error) {
const message =
error instanceof Error ? error.message : "Unknown error deleting project.";
console.error("Failed to remove project", { projectId, error });
toastManager.add({
type: "error",
title: `Failed to delete "${project.name}"`,
description: message,
});
if (isElectron) {
try {
await api.projects.remove({ id: projectId });
} catch (error) {
const message =
error instanceof Error ? error.message : "Unknown error deleting project.";
console.error("Failed to remove project", { projectId, error });
toastManager.add({
type: "error",
title: `Failed to delete "${project.name}"`,
description: message,
});
return;
}
}
dispatch({ type: "DELETE_PROJECT", projectId });
},
[api, dispatch, state.projects, state.threads],
);
@@ -252,6 +252,7 @@ function TerminalViewport({
),
);
});
let didReceiveRenderableEventSinceOpen = false;
const themeObserver = new MutationObserver(() => {
const activeTerminal = terminalRef.current;
@@ -279,9 +280,14 @@ function TerminalViewport({
...(runtimeEnv ? { env: runtimeEnv } : {}),
});
if (disposed) return;
activeTerminal.write("\u001bc");
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
const shouldHydrateFromSnapshot =
snapshot.history.length > 0 || !didReceiveRenderableEventSinceOpen;
if (shouldHydrateFromSnapshot) {
// Avoid clearing output that arrived before open() resolved.
activeTerminal.write("\u001bc");
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
}
}
if (autoFocus) {
window.requestAnimationFrame(() => {
@@ -302,6 +308,10 @@ function TerminalViewport({
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
if (event.type !== "activity") {
didReceiveRenderableEventSinceOpen = true;
}
if (event.type === "output") {
activeTerminal.write(event.data);
return;
+1 -1
View File
@@ -1,5 +1,5 @@
import { useMemo } from "react";
import { readNativeApi } from "../nativeApi";
import { readNativeApi } from "../session-logic";
export function useNativeApi() {
return useMemo(() => readNativeApi(), []);
+18 -2
View File
@@ -1,13 +1,29 @@
import type { ProviderEvent } from "@t3tools/contracts";
import { useMemo } from "react";
import { inferCheckpointTurnCountByTurnId } from "../session-logic";
import { deriveTurnDiffSummaries, inferCheckpointTurnCountByTurnId } from "../session-logic";
import type { Thread, TurnDiffSummary } from "../types";
const derivedTurnDiffSummaryCache = new WeakMap<readonly ProviderEvent[], TurnDiffSummary[]>();
function deriveTurnDiffSummariesCached(events: ProviderEvent[]): TurnDiffSummary[] {
const cached = derivedTurnDiffSummaryCache.get(events);
if (cached) {
return cached;
}
const derived = deriveTurnDiffSummaries(events);
derivedTurnDiffSummaryCache.set(events, derived);
return derived;
}
export function useTurnDiffSummaries(activeThread: Thread | undefined) {
const turnDiffSummaries = useMemo(() => {
if (!activeThread) {
return [];
}
return activeThread.turnDiffSummaries;
if (activeThread.turnDiffSummaries.length > 0) {
return activeThread.turnDiffSummaries;
}
return deriveTurnDiffSummariesCached(activeThread.events);
}, [activeThread]);
const inferredCheckpointTurnCountByTurnId = useMemo(
-18
View File
@@ -1,18 +0,0 @@
import type { NativeApi } from "@t3tools/contracts";
import { createWsNativeApi } from "./wsNativeApi";
let cachedApi: NativeApi | undefined;
export function readNativeApi(): NativeApi | undefined {
if (typeof window === "undefined") return undefined;
if (cachedApi) return cachedApi;
if (window.nativeApi) {
cachedApi = window.nativeApi;
return cachedApi;
}
cachedApi = createWsNativeApi();
return cachedApi;
}
+148 -61
View File
@@ -2,16 +2,18 @@ import {
Outlet,
createRootRouteWithContext,
type ErrorComponentProps,
useParams,
} from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import { QueryClient } from "@tanstack/react-query";
import { useEffect, useMemo, useRef } from "react";
import { QueryClient, useQueryClient } from "@tanstack/react-query";
import { APP_DISPLAY_NAME } from "../branding";
import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
import { isElectron } from "../env";
import { useNativeApi } from "../hooks/useNativeApi";
import { DEFAULT_MODEL } from "../model-logic";
import { invalidateGitQueries } from "../lib/gitReactQuery";
import { createStateSource } from "../stateSource";
import { useStore } from "../store";
import { onServerWelcome } from "../wsNativeApi";
@@ -40,9 +42,8 @@ function RootRouteView() {
return (
<ToastProvider>
<AnchoredToastProvider>
<EventRouter />
<AutoProjectBootstrap />
<DesktopProjectBootstrap />
<StateSyncRouter />
<BrowserDefaultProjectBootstrap />
<Outlet />
</AnchoredToastProvider>
</ToastProvider>
@@ -120,84 +121,170 @@ function errorDetails(error: unknown): string {
}
}
function EventRouter() {
function StateSyncRouter() {
const api = useNativeApi();
const { dispatch } = useStore();
const queryClient = useQueryClient();
const activeAssistantItemRef = useRef<string | null>(null);
const activeThreadId = useParams({
strict: false,
select: (params) => params.threadId,
});
const lastStateSeqRef = useRef(0);
const stateQueueRef = useRef(Promise.resolve());
const stateSource = useMemo(() => (api ? createStateSource(api) : null), [api]);
useEffect(() => {
if (!api || !stateSource) return;
let disposed = false;
let retryDelayMs = 500;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const bootstrap = async () => {
try {
const snapshot = await stateSource.bootstrap();
if (disposed) return;
dispatch({
type: "HYDRATE_FROM_SERVER",
snapshot,
});
lastStateSeqRef.current = snapshot.lastStateSeq;
} 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, stateSource]);
useEffect(() => {
if (!api || !stateSource) return;
return stateSource.onEvent((event) => {
stateQueueRef.current = stateQueueRef.current
.then(async () => {
if (event.seq <= lastStateSeqRef.current) {
return;
}
if (event.seq > lastStateSeqRef.current + 1) {
const catchUp = await stateSource.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, stateSource]);
useEffect(() => {
if (!api) return;
void Promise.all([api.projects.list(), api.orchestration.getSnapshot()])
.then(([projects, snapshot]) => {
dispatch({ type: "SYNC_PROJECTS", projects });
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
return api.providers.onEvent((event) => {
if (event.method === "turn/completed") {
void invalidateGitQueries(queryClient);
}
if (event.method === "checkpoint/captured") {
const payload = event.payload as { turnCount?: number } | undefined;
const turnCount = payload?.turnCount;
void queryClient.invalidateQueries({
queryKey: ["providers", "checkpointDiff"] as const,
predicate: (query) => {
if (typeof turnCount !== "number") return true;
return query.queryKey[5] === turnCount;
},
});
}
if (!activeThreadId) return;
dispatch({
type: "APPLY_EVENT",
event,
activeAssistantItemRef,
activeThreadId,
});
});
}, [activeThreadId, api, dispatch, queryClient]);
useEffect(() => {
if (!api || !activeThreadId) return;
const visitedAt = new Date().toISOString();
dispatch({
type: "MARK_THREAD_VISITED",
threadId: activeThreadId,
visitedAt,
});
void api.threads
.markVisited({
threadId: activeThreadId,
visitedAt,
})
.catch(() => undefined);
const unsubReadModel = api.orchestration.onReadModel((snapshot) => {
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
}, [activeThreadId, api, dispatch]);
useEffect(() => {
if (!api) return;
return api.terminal.onEvent((event) => {
dispatch({
type: "APPLY_TERMINAL_EVENT",
event,
});
});
return () => {
unsubReadModel();
};
}, [api, dispatch]);
return null;
}
function AutoProjectBootstrap() {
function BrowserDefaultProjectBootstrap() {
const api = useNativeApi();
const { state, dispatch } = useStore();
const bootstrappedRef = useRef(false);
const { state } = useStore();
const createdRef = useRef(false);
useEffect(() => {
if (!api) return;
// Browser mode auto-adds the current cwd project via server welcome.
// Desktop skips this because projects are already loaded from the repository.
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 now = new Date().toISOString();
void api.projects
.add({ cwd: payload.cwd })
.then(async (result) => {
const projects = await api.projects.list();
dispatch({ type: "SYNC_PROJECTS", projects });
const existing = state.projects.find((project) => project.cwd === payload.cwd);
if (existing) {
createdRef.current = true;
return;
}
const hasThread = state.threads.some((thread) => thread.projectId === result.project.id);
if (hasThread) {
return;
}
return api.orchestration.dispatchCommand({
type: "thread.create",
commandId: crypto.randomUUID(),
threadId: crypto.randomUUID(),
projectId: result.project.id,
title: "New thread",
model: DEFAULT_MODEL,
branch: null,
worktreePath: null,
createdAt: now,
});
})
.catch(() => undefined);
createdRef.current = true;
void api.projects.add({ cwd: payload.cwd }).catch(() => {
createdRef.current = false;
});
});
}, [api, state.projects, state.threads, dispatch]);
}, [api, state.projects, state.threadsHydrated]);
return null;
}
function DesktopProjectBootstrap() {
// Desktop hydration runs through EventRouter project + orchestration sync.
return null;
}
+935
View File
@@ -0,0 +1,935 @@
import { describe, expect, it } from "vitest";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
derivePendingApprovals,
deriveTurnDiffFilesFromUnifiedDiff,
deriveTurnDiffSummaries,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
} from "./session-logic";
import type { ChatMessage } from "./types";
function makeEvent(overrides: Partial<ProviderEvent>): ProviderEvent {
return {
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-08T10:00:00.000Z",
method: "noop",
...overrides,
};
}
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
provider: "codex",
status: "ready",
createdAt: "2026-02-08T09:59:00.000Z",
updatedAt: "2026-02-08T09:59:00.000Z",
...overrides,
};
}
describe("deriveTimelineEntries", () => {
it("interleaves messages and work entries by timestamp", () => {
const messages: ChatMessage[] = [
{
id: "m-user",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
{
id: "m-assistant",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:05:00.000Z",
streaming: false,
},
];
const workEntries: WorkLogEntry[] = [
{
id: "w-1",
label: "Tool call",
createdAt: "2026-02-08T10:02:00.000Z",
tone: "tool",
},
{
id: "w-2",
label: "Preamble",
createdAt: "2026-02-08T10:03:00.000Z",
tone: "thinking",
},
];
const timeline = deriveTimelineEntries(messages, workEntries);
expect(timeline.map((entry) => entry.id)).toEqual([
"message:m-user",
"work:w-1",
"work:w-2",
"message:m-assistant",
]);
});
it("prefers work entries when timestamps are equal", () => {
const messages: ChatMessage[] = [
{
id: "m-1",
role: "assistant",
text: "Done",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
];
const workEntries: WorkLogEntry[] = [
{
id: "w-1",
label: "Tool call",
createdAt: "2026-02-08T10:00:00.000Z",
tone: "tool",
},
];
const timeline = deriveTimelineEntries(messages, workEntries);
expect(timeline.map((entry) => entry.id)).toEqual(["work:w-1", "message:m-1"]);
});
});
describe("deriveWorkLogEntries", () => {
it("drops preamble/work events from the visible work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-1",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { item: { type: "preamble", text: "thinking" } },
}),
makeEvent({
id: "evt-2",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { item: { type: "work", text: "planning" } },
}),
makeEvent({
id: "evt-3",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: { item: { type: "tool_call", command: "ls -la" } },
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
});
it("does not surface successful turn completion as a work-log row", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:10.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
],
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("shows failed turn completion in the work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:10.000Z",
payload: {
turn: {
id: "turn-1",
status: "failed",
error: { message: "sandbox denied" },
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Turn failed");
expect(entries[0]?.detail).toBe("sandbox denied");
});
it("hides reasoning and agent-message noise from the visible work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-summary-part",
method: "item/reasoning/summaryPartAdded",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-summary-delta",
method: "item/reasoning/summaryTextDelta",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
}),
makeEvent({
id: "evt-agent-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
item: { id: "item-msg", type: "agentMessage", text: "Working..." },
},
}),
makeEvent({
id: "evt-agent-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:04.000Z",
payload: {
item: {
id: "item-msg",
type: "agentMessage",
text: "Done response",
},
},
}),
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
},
}),
makeEvent({
id: "evt-tool-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:06.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
},
}),
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:08.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
],
"turn-1",
);
expect(entries.map((entry) => entry.label)).toEqual(["Tool call"]);
});
it("coalesces command start/completed lifecycle into one entry", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-command-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
makeEvent({
id: "evt-command-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Command run");
expect(entries[0]?.detail).toBe("git status --short");
});
it("preserves full tool-call detail text without data truncation", () => {
const longCommand =
'node ./scripts/sync.js --project ct-round-5 --mode dry-run --include "very long argument with lots of detail and metadata to verify there is no hard truncation in session logic"';
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: longCommand },
},
}),
],
"turn-1",
);
expect(entries[0]?.detail).toBe(longCommand);
});
it("hides generic tool-call rows that have no identifying detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call" },
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("includes collab tool-call rows with tool name detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-collab-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: {
id: "item-collab",
type: "collabAgentToolCall",
tool: "spawnAgent",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
expect(entries[0]?.detail).toBe("spawnAgent");
});
it("can derive work-log entries across all turns when not scoped", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-turn-1-tool",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { item: { type: "tool_call", command: "ls -la" } },
}),
makeEvent({
id: "evt-turn-2-tool",
method: "item/started",
turnId: "turn-2",
createdAt: "2026-02-08T10:00:02.000Z",
payload: { item: { type: "tool_call", command: "pwd" } },
}),
],
undefined,
);
expect(entries).toHaveLength(2);
expect(entries.map((entry) => entry.detail)).toEqual(["pwd", "ls -la"]);
});
});
describe("deriveTurnDiffSummaries", () => {
it("tracks completed turns and links them to assistant message completion", () => {
const summaries = deriveTurnDiffSummaries([
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-file-change",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
item: {
id: "item-file-change",
type: "fileChange",
status: "completed",
changes: [
{
path: "src/a.ts",
kind: "modified",
diff: "diff --git a/src/a.ts b/src/a.ts\n@@ -1 +1 @@\n-old\n+new\n",
},
],
},
},
}),
makeEvent({
id: "evt-turn-diff-updated",
method: "turn/diff/updated",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
threadId: "thr-1",
turnId: "turn-1",
diff: [
"diff --git a/src/a.ts b/src/a.ts",
"@@ -1 +1 @@",
"-old",
"+new",
"diff --git a/src/b.ts b/src/b.ts",
"@@ -0,0 +1 @@",
"+created",
].join("\n"),
},
}),
makeEvent({
id: "evt-agent-msg",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
item: {
id: "msg-1",
type: "agentMessage",
text: "Done",
},
},
}),
makeEvent({
id: "evt-turn-completed",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:04.000Z",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
}),
makeEvent({
id: "evt-turn-2-file-change",
method: "item/completed",
turnId: "turn-2",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: {
id: "item-file-change-2",
type: "fileChange",
status: "completed",
changes: [
{
path: "src/unfinished.ts",
kind: "modified",
diff: "diff --git a/src/unfinished.ts b/src/unfinished.ts",
},
],
},
},
}),
]);
expect(summaries).toHaveLength(1);
expect(summaries[0]?.turnId).toBe("turn-1");
expect(summaries[0]?.assistantMessageId).toBe("msg-1");
expect(summaries[0]?.files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
expect(summaries[0]?.files[0]?.kind).toBe("modified");
expect(summaries[0]?.files[0]?.additions).toBe(1);
expect(summaries[0]?.files[0]?.deletions).toBe(1);
expect(summaries[0]).not.toHaveProperty("unifiedDiff");
});
it("includes completed turns even when no fileChange tool events were emitted", () => {
const summaries = deriveTurnDiffSummaries([
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-turn-completed",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
}),
]);
expect(summaries).toHaveLength(1);
expect(summaries[0]?.turnId).toBe("turn-1");
expect(summaries[0]?.files).toEqual([]);
});
it("keeps newest diff data when older events provide stale values", () => {
const summaries = deriveTurnDiffSummaries([
makeEvent({
id: "evt-turn-diff-old",
method: "turn/diff/updated",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
diff: [
"diff --git a/src/example.ts b/src/example.ts",
"@@ -1 +1,2 @@",
"-old",
"+older",
"+extra",
].join("\n"),
},
}),
makeEvent({
id: "evt-turn-diff-new",
method: "turn/diff/updated",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
diff: [
"diff --git a/src/example.ts b/src/example.ts",
"@@ -1 +1 @@",
"-old",
"+newest",
].join("\n"),
},
}),
makeEvent({
id: "evt-turn-completed",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
}),
]);
expect(summaries).toHaveLength(1);
expect(summaries[0]?.files[0]?.path).toBe("src/example.ts");
expect(summaries[0]?.files[0]?.additions).toBe(1);
expect(summaries[0]?.files[0]?.deletions).toBe(1);
});
});
describe("deriveTurnDiffFilesFromUnifiedDiff", () => {
it("splits a multi-file patch into sorted per-file entries", () => {
const files = deriveTurnDiffFilesFromUnifiedDiff(
[
"diff --git a/src/b.ts b/src/b.ts",
"@@ -1 +1 @@",
"-old-b",
"+new-b",
"diff --git a/src/a.ts b/src/a.ts",
"@@ -1 +1 @@",
"-old-a",
"+new-a",
].join("\n"),
);
expect(files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
expect(files[0]?.additions).toBe(1);
expect(files[0]?.deletions).toBe(1);
});
it("parses git headers when file paths include ` b/`", () => {
const files = deriveTurnDiffFilesFromUnifiedDiff(
[
"diff --git a/subdir b/example.ts b/subdir b/example.ts",
"--- a/subdir b/example.ts",
"+++ b/subdir b/example.ts",
"@@ -1 +1 @@",
"-old",
"+new",
].join("\n"),
);
expect(files).toHaveLength(1);
expect(files[0]?.path).toBe("subdir b/example.ts");
});
it("parses git header fallback for binary diffs with ` b/` in path", () => {
const files = deriveTurnDiffFilesFromUnifiedDiff(
[
"diff --git a/subdir b/image.png b/subdir b/image.png",
"Binary files a/subdir b/image.png and b/subdir b/image.png differ",
].join("\n"),
);
expect(files).toHaveLength(1);
expect(files[0]?.path).toBe("subdir b/image.png");
});
});
describe("derivePendingApprovals", () => {
it("returns pending command/file-change approvals", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { command: "git commit -m 'msg'" },
}),
]);
expect(approvals).toEqual([
{
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
detail: "git commit -m 'msg'",
},
]);
});
it("removes approvals after a decision event", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-decision",
method: "item/requestApproval/decision",
requestId: "req-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/fileChange/requestApproval",
requestId: "req-1",
requestKind: "file-change",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
it("clears pending approvals after turn completion", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
});
describe("evolveSession", () => {
it("updates thread id when thread starts", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
method: "thread/started",
createdAt: "2026-02-08T10:01:00.000Z",
payload: { thread: { id: "thread-1" } },
}),
);
expect(next.threadId).toBe("thread-1");
expect(next.updatedAt).toBe("2026-02-08T10:01:00.000Z");
});
it("moves to running and records active turn on turn start", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:02:00.000Z",
}),
);
expect(next.status).toBe("running");
expect(next.activeTurnId).toBe("turn-1");
expect(next.updatedAt).toBe("2026-02-08T10:02:00.000Z");
});
it("returns to ready and clears active turn on successful completion", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
lastError: "older error",
});
const next = evolveSession(
previous,
makeEvent({
method: "turn/completed",
createdAt: "2026-02-08T10:03:00.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
);
expect(next.status).toBe("ready");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("older error");
});
it("marks session as error when turn fails", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
});
const next = evolveSession(
previous,
makeEvent({
method: "turn/completed",
createdAt: "2026-02-08T10:03:00.000Z",
payload: {
turn: { id: "turn-1", status: "failed", error: { message: "boom" } },
},
}),
);
expect(next.status).toBe("error");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("boom");
});
it("moves to error on runtime error events", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
kind: "error",
method: "runtime/error",
createdAt: "2026-02-08T10:04:00.000Z",
message: "runtime failure",
}),
);
expect(next.status).toBe("error");
expect(next.lastError).toBe("runtime failure");
});
it("closes session on close lifecycle events", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
});
const next = evolveSession(
previous,
makeEvent({
method: "session/closed",
createdAt: "2026-02-08T10:05:00.000Z",
message: "closed",
}),
);
expect(next.status).toBe("closed");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("closed");
});
});
describe("applyEventToMessages", () => {
it("handles start/delta/completed flow for assistant messages", () => {
const activeAssistantItemRef = { current: null as string | null };
const started = applyEventToMessages(
[],
makeEvent({
method: "item/started",
createdAt: "2026-02-08T10:00:00.000Z",
payload: {
item: {
id: "item-1",
type: "agentMessage",
text: "Hello",
},
},
}),
activeAssistantItemRef,
);
expect(started).toEqual([
{
id: "item-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: true,
},
]);
expect(activeAssistantItemRef.current).toBe("item-1");
const withDelta = applyEventToMessages(
started,
makeEvent({
method: "item/agentMessage/delta",
createdAt: "2026-02-08T10:00:01.000Z",
itemId: "item-1",
textDelta: " world",
}),
activeAssistantItemRef,
);
expect(withDelta[0]?.text).toBe("Hello world");
expect(withDelta[0]?.streaming).toBe(true);
const completed = applyEventToMessages(
withDelta,
makeEvent({
method: "item/completed",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-1",
type: "agentMessage",
text: "Hello world!",
},
},
}),
activeAssistantItemRef,
);
expect(completed[0]?.text).toBe("Hello world!");
expect(completed[0]?.streaming).toBe(false);
expect(activeAssistantItemRef.current).toBeNull();
});
it("supports out-of-order delta before started/completed", () => {
const activeAssistantItemRef = { current: null as string | null };
const withDelta = applyEventToMessages(
[],
makeEvent({
method: "item/agentMessage/delta",
createdAt: "2026-02-08T10:00:01.000Z",
itemId: "item-2",
textDelta: "Partial",
}),
activeAssistantItemRef,
);
expect(withDelta[0]?.id).toBe("item-2");
expect(withDelta[0]?.text).toBe("Partial");
expect(withDelta[0]?.streaming).toBe(true);
expect(activeAssistantItemRef.current).toBe("item-2");
const completed = applyEventToMessages(
withDelta,
makeEvent({
method: "item/completed",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-2",
type: "agentMessage",
text: "Partial + final",
},
},
}),
activeAssistantItemRef,
);
expect(completed[0]?.text).toBe("Partial + final");
expect(completed[0]?.streaming).toBe(false);
});
it("clears all streaming flags when turn completes", () => {
const previous: ChatMessage[] = [
{
id: "m-user",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
{
id: "m-assistant",
role: "assistant",
text: "Typing",
createdAt: "2026-02-08T10:00:01.000Z",
streaming: true,
},
];
const next = applyEventToMessages(
previous,
makeEvent({
method: "turn/completed",
}),
{ current: null },
);
expect(next.every((entry) => entry.streaming === false)).toBe(true);
});
});
+881 -69
View File
@@ -1,6 +1,6 @@
import type { ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { ChatMessage, SessionPhase, TurnDiffFileChange, TurnDiffSummary } from "./types";
import { createWsNativeApi } from "./wsNativeApi";
export const PROVIDER_OPTIONS: Array<{
value: ProviderKind;
@@ -11,6 +11,73 @@ export const PROVIDER_OPTIONS: Array<{
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
];
let cachedApi: NativeApi | undefined;
export function readNativeApi(): NativeApi | undefined {
if (typeof window === "undefined") return undefined;
if (cachedApi) return cachedApi;
// Prefer Electron preload bridge if available
if (window.nativeApi) {
cachedApi = window.nativeApi;
return cachedApi;
}
// Fall back to WebSocket transport
cachedApi = createWsNativeApi();
return cachedApi;
}
export function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") return undefined;
return value as Record<string, unknown>;
}
function asArray(value: unknown): unknown[] | undefined {
return Array.isArray(value) ? value : undefined;
}
export function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
export function formatTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
second: "2-digit",
}).format(new Date(isoDate));
}
export function formatDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1_000);
if (seconds === 0) return `${minutes}m`;
if (seconds === 60) return `${minutes + 1}m`;
return `${minutes}m ${seconds}s`;
}
export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
if (!endIso) return null;
const startedAt = Date.parse(startIso);
const endedAt = Date.parse(endIso);
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
return null;
}
return formatDuration(endedAt - startedAt);
}
export interface WorkLogEntry {
id: string;
createdAt: string;
@@ -40,94 +107,680 @@ export type TimelineEntry =
entry: WorkLogEntry;
};
export function formatTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
second: "2-digit",
}).format(new Date(isoDate));
export type { TurnDiffFileChange, TurnDiffSummary } from "./types";
function normalizeDetail(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
export function formatDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1_000);
if (seconds === 0) return `${minutes}m`;
if (seconds === 60) return `${minutes + 1}m`;
return `${minutes}m ${seconds}s`;
function approvalDetail(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const command = asString(payload?.command);
if (command) return command;
return asString(payload?.reason);
}
export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
if (!endIso) return null;
const startedAt = Date.parse(startIso);
const endedAt = Date.parse(endIso);
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
export function derivePendingApprovals(events: ProviderEvent[]): PendingApproval[] {
const pending = new Map<string, PendingApproval>();
const ordered = [...events].toReversed();
for (const event of ordered) {
if (
event.method === "session/closed" ||
event.method === "session/exited" ||
event.method === "turn/completed"
) {
pending.clear();
continue;
}
const requestId = event.requestId ?? asString(asObject(event.payload)?.requestId);
if (!requestId) continue;
if (
event.kind === "request" &&
(event.requestKind === "command" || event.requestKind === "file-change")
) {
const detail = approvalDetail(event);
pending.set(requestId, {
requestId,
requestKind: event.requestKind,
createdAt: event.createdAt,
...(detail ? { detail } : {}),
});
continue;
}
if (event.method === "item/requestApproval/decision") {
pending.delete(requestId);
}
}
return Array.from(pending.values());
}
function normalizeItemType(raw: string | undefined): string {
if (!raw) return "item";
return raw
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[._/-]/g, " ")
.replace(/\s+/g, " ")
.trim()
.toLowerCase();
}
function shouldDropItemType(type: string): boolean {
if (type.includes("preamble") || type.includes("reasoning") || type.includes("thought")) {
return true;
}
return type === "work" || type.startsWith("work ");
}
function shouldShowItemLifecycle(type: string): boolean {
return type.includes("tool") || type.includes("command") || type.includes("file change");
}
function shouldDropMethod(method: string): boolean {
return /(^|\/)(preamble|work|reasoning|thought)(\/|$)/i.test(method);
}
function itemTypeMeta(type: string): {
label: string;
tone: WorkLogEntry["tone"];
} {
if (type.includes("command")) {
return { label: "Command run", tone: "tool" };
}
if (type.includes("file change")) {
return { label: "File change", tone: "tool" };
}
if (type.includes("tool")) {
return { label: "Tool call", tone: "tool" };
}
return { label: "Work item", tone: "info" };
}
interface ItemLifecycleCandidate {
id: string;
itemId?: string;
createdAt: string;
label: string;
detail?: string;
tone: WorkLogEntry["tone"];
phase: "started" | "completed";
}
function extractDetail(
payload: Record<string, unknown> | undefined,
item: Record<string, unknown> | undefined,
): string | undefined {
const candidates = [
asString(item?.command),
asString(item?.tool),
asString(item?.name),
asString(item?.title),
asString(item?.summary),
asString(item?.text),
asString(item?.prompt),
asString(payload?.message),
asString(payload?.prompt),
asString(payload?.command),
];
for (const candidate of candidates) {
const detail = normalizeDetail(candidate);
if (detail) return detail;
}
return undefined;
}
function lifecycleCandidateFromItemEvent(event: ProviderEvent): ItemLifecycleCandidate | null {
const payload = asObject(event.payload);
const item = asObject(payload?.item);
const normalizedType = normalizeItemType(asString(item?.type));
if (shouldDropItemType(normalizedType) || shouldDropMethod(event.method)) {
return null;
}
return formatDuration(endedAt - startedAt);
if (!shouldShowItemLifecycle(normalizedType)) {
return null;
}
const meta = itemTypeMeta(normalizedType);
const isStarted = event.method === "item/started";
const isCompleted = event.method === "item/completed";
if (!isStarted && !isCompleted) {
return null;
}
const detail = extractDetail(payload, item);
const itemId = event.itemId ?? asString(item?.id);
return {
id: event.id,
...(itemId ? { itemId } : {}),
createdAt: event.createdAt,
label: meta.label,
...(detail ? { detail } : {}),
tone: meta.tone,
phase: isCompleted ? "completed" : "started",
};
}
export function derivePendingApprovals(_events: unknown[]): PendingApproval[] {
return [];
function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "request") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method.includes("commandExecution")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "Command approval requested",
tone: "tool",
};
}
if (event.method.includes("fileChange")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "File-change approval requested",
tone: "tool",
};
}
if (event.method.includes("requestUserInput")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "Tool requested user input",
tone: "tool",
};
}
return {
id: event.id,
createdAt: event.createdAt,
label: `Request: ${event.method}`,
tone: "info",
};
}
function entryFromNotification(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "notification") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method === "item/agentMessage/delta") return null;
if (event.method === "turn/started") {
return null;
}
if (event.method === "thread/started") return null;
if (event.method === "turn/completed") {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
if (status !== "failed") {
return null;
}
const turnError = asObject(turn?.error);
const turnErrorMessage = asString(turnError?.message);
const turnErrorDetail = normalizeDetail(turnErrorMessage);
return {
id: event.id,
createdAt: event.createdAt,
label: "Turn failed",
...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
tone: "error",
};
}
if (event.method.startsWith("item/")) return null;
return null;
}
function entryFromError(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "error") return null;
if (shouldDropMethod(event.method)) return null;
const detail = normalizeDetail(event.message);
return {
id: event.id,
createdAt: event.createdAt,
label: "Runtime error",
...(detail ? { detail } : {}),
tone: "error",
};
}
function eventTurnId(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return event.turnId ?? asString(turn?.id);
}
export function deriveWorkLogEntries(
_events: unknown[],
_latestTurnId: string | undefined,
events: ProviderEvent[],
turnId: string | undefined,
): WorkLogEntry[] {
return [];
const ordered = [...events].toReversed();
const entries: WorkLogEntry[] = [];
const turnStartedAtIso = turnId
? ordered.find((event) => {
if (event.method !== "turn/started") return false;
return eventTurnId(event) === turnId;
})?.createdAt
: undefined;
const turnStartedAt = turnStartedAtIso ? Date.parse(turnStartedAtIso) : Number.NaN;
const shouldIncludeEvent = (event: ProviderEvent): boolean => {
if (!turnId) return true;
const scopedTurnId = eventTurnId(event);
if (scopedTurnId && scopedTurnId !== turnId) {
return false;
}
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
const eventAt = Date.parse(event.createdAt);
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
return false;
}
}
return true;
};
const completedLifecycleItemIds = new Set<string>();
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const candidate = lifecycleCandidateFromItemEvent(event);
if (candidate?.phase === "completed" && candidate.itemId) {
completedLifecycleItemIds.add(candidate.itemId);
}
}
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const lifecycleCandidate = lifecycleCandidateFromItemEvent(event);
if (lifecycleCandidate) {
if (
lifecycleCandidate.phase === "started" &&
lifecycleCandidate.itemId &&
completedLifecycleItemIds.has(lifecycleCandidate.itemId)
) {
continue;
}
if (lifecycleCandidate.label === "Tool call" && !lifecycleCandidate.detail) {
continue;
}
entries.push({
id: lifecycleCandidate.id,
createdAt: lifecycleCandidate.createdAt,
label: lifecycleCandidate.label,
...(lifecycleCandidate.detail ? { detail: lifecycleCandidate.detail } : {}),
tone: lifecycleCandidate.tone,
});
continue;
}
const fromRequest = entryFromRequest(event);
if (fromRequest) {
entries.push(fromRequest);
continue;
}
const fromNotification = entryFromNotification(event);
if (fromNotification) {
entries.push(fromNotification);
continue;
}
const fromError = entryFromError(event);
if (fromError) {
entries.push(fromError);
}
}
return entries;
}
interface MutableTurnDiffSummary {
turnId: string;
completedAt: string | undefined;
status: string | undefined;
assistantMessageId: string | undefined;
hasTurnDiffUpdate: boolean;
filesByPath: Map<string, TurnDiffFileChange>;
}
function parseFileChangeEntriesFromEvent(event: ProviderEvent): TurnDiffFileChange[] {
if (event.method !== "item/completed") {
return [];
}
const item = asObject(asObject(event.payload)?.item);
const itemType = normalizeItemType(asString(item?.type));
if (itemType !== "file change") {
return [];
}
const changes = asArray(item?.changes) ?? [];
const parsed: TurnDiffFileChange[] = [];
for (const rawChange of changes) {
const change = asObject(rawChange);
if (!change) continue;
const diff = normalizeDetail(asString(change.diff));
const path = normalizeDetail(asString(change.path)) ?? (diff ? parsePathFromDiff(diff) : undefined);
if (!path) continue;
const additions = asNumber(change.additions);
const deletions = asNumber(change.deletions);
const stat = additions !== undefined && deletions !== undefined ? null : diff ? countDiffStat(diff) : null;
const kind = normalizeDetail(asString(change.kind));
parsed.push({
path,
...(kind ? { kind } : {}),
...(additions !== undefined ? { additions } : stat ? { additions: stat.additions } : {}),
...(deletions !== undefined ? { deletions } : stat ? { deletions: stat.deletions } : {}),
});
}
return parsed;
}
function mergeTurnDiffFileChange(
byPath: Map<string, TurnDiffFileChange>,
incoming: TurnDiffFileChange,
): void {
const existing = byPath.get(incoming.path);
if (!existing) {
byPath.set(incoming.path, incoming);
return;
}
if (existing.kind === undefined && incoming.kind !== undefined) {
existing.kind = incoming.kind;
}
if (existing.additions === undefined && incoming.additions !== undefined) {
existing.additions = incoming.additions;
}
if (existing.deletions === undefined && incoming.deletions !== undefined) {
existing.deletions = incoming.deletions;
}
}
function parsePathFromDiff(diff: string): string | undefined {
const normalized = diff.replace(/\r\n/g, "\n");
const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m);
if (bPath && bPath[1]) return bPath[1];
const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m);
if (gitHeader && gitHeader[1]) return gitHeader[1];
const direct = normalized.match(/^\+\+\+ (.+)$/m);
if (!direct || !direct[1] || direct[1] === "/dev/null") {
return undefined;
}
return direct[1];
}
export function splitUnifiedDiffByFile(diff: string): Map<string, string> {
const normalized = diff.replace(/\r\n/g, "\n");
const byPath = new Map<string, string>();
const headerMatches = [...normalized.matchAll(/^diff --git .+$/gm)];
if (headerMatches.length === 0) {
const path = parsePathFromDiff(normalized);
if (path) {
byPath.set(path, normalized.trim());
}
return byPath;
}
for (let index = 0; index < headerMatches.length; index += 1) {
const match = headerMatches[index];
if (!match) continue;
const start = match.index ?? 0;
const nextStart = headerMatches[index + 1]?.index ?? normalized.length;
const segment = normalized.slice(start, nextStart).trim();
const path = parsePathFromDiff(segment);
if (!path || segment.length === 0) continue;
byPath.set(path, segment);
}
return byPath;
}
export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileChange[] {
const fileDiffsByPath = splitUnifiedDiffByFile(diff);
return Array.from(fileDiffsByPath.entries())
.map(([path, fileDiff]) => {
const stat = countDiffStat(fileDiff);
return {
path,
additions: stat.additions,
deletions: stat.deletions,
};
})
.toSorted((a, b) => a.path.localeCompare(b.path));
}
export function inferCheckpointTurnCountByTurnId(
summaries: TurnDiffSummary[],
): Record<string, number> {
if (summaries.length === 0) {
return {};
}
const sorted = [...summaries].toSorted((a, b) => {
const aTime = Date.parse(a.completedAt);
const bTime = Date.parse(b.completedAt);
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
return a.completedAt.localeCompare(b.completedAt);
}
return aTime - bTime;
});
const next: Record<string, number> = {};
let fallbackTurnCount = 1;
for (const summary of sorted) {
if (typeof summary.checkpointTurnCount === "number") {
next[summary.turnId] = summary.checkpointTurnCount;
fallbackTurnCount = Math.max(fallbackTurnCount, summary.checkpointTurnCount + 1);
continue;
}
next[summary.turnId] = fallbackTurnCount;
fallbackTurnCount += 1;
}
return next;
}
export function countDiffStat(patch: string | undefined): { additions: number; deletions: number } {
if (!patch) {
return { additions: 0, deletions: 0 };
}
let additions = 0;
let deletions = 0;
for (const line of patch.replace(/\r\n/g, "\n").split("\n")) {
if (line.startsWith("+++ ") || line.startsWith("--- ")) continue;
if (line.startsWith("+")) {
additions += 1;
continue;
}
if (line.startsWith("-")) {
deletions += 1;
}
}
return { additions, deletions };
}
export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummary[] {
const firstEventAt = Date.parse(events[0]?.createdAt ?? "");
const lastEventAt = Date.parse(events.at(-1)?.createdAt ?? "");
const ordered =
events.length < 2 ||
Number.isNaN(firstEventAt) ||
Number.isNaN(lastEventAt) ||
firstEventAt >= lastEventAt
? events
: [...events].toReversed();
const byTurnId = new Map<string, MutableTurnDiffSummary>();
const ensureSummary = (turnId: string): MutableTurnDiffSummary => {
const existing = byTurnId.get(turnId);
if (existing) return existing;
const next: MutableTurnDiffSummary = {
turnId,
completedAt: undefined,
status: undefined,
assistantMessageId: undefined,
hasTurnDiffUpdate: false,
filesByPath: new Map<string, TurnDiffFileChange>(),
};
byTurnId.set(turnId, next);
return next;
};
for (const event of ordered) {
const turnId = eventTurnId(event);
if (!turnId) continue;
const summary = ensureSummary(turnId);
if (event.method === "turn/completed") {
if (summary.completedAt === undefined) {
summary.completedAt = event.createdAt;
}
const turn = asObject(asObject(event.payload)?.turn);
if (summary.status === undefined) {
summary.status = normalizeDetail(asString(turn?.status));
}
}
if (event.method === "item/completed") {
const item = asObject(asObject(event.payload)?.item);
if (asString(item?.type) === "agentMessage") {
const itemId = normalizeDetail(asString(item?.id));
if (itemId && summary.assistantMessageId === undefined) {
summary.assistantMessageId = itemId;
}
}
}
if (event.method === "turn/diff/updated" && !summary.hasTurnDiffUpdate) {
summary.hasTurnDiffUpdate = true;
const diff = normalizeDetail(asString(asObject(event.payload)?.diff));
if (diff) {
for (const file of deriveTurnDiffFilesFromUnifiedDiff(diff)) {
mergeTurnDiffFileChange(summary.filesByPath, file);
}
}
}
for (const file of parseFileChangeEntriesFromEvent(event)) {
mergeTurnDiffFileChange(summary.filesByPath, file);
}
}
const summaries: TurnDiffSummary[] = [];
for (const summary of byTurnId.values()) {
if (!summary.completedAt) continue;
summaries.push({
turnId: summary.turnId,
completedAt: summary.completedAt,
...(summary.status ? { status: summary.status } : {}),
files: Array.from(summary.filesByPath.values()).toSorted((a, b) =>
a.path.localeCompare(b.path),
),
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
});
}
summaries.sort((a, b) => {
const aTime = Date.parse(a.completedAt);
const bTime = Date.parse(b.completedAt);
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
return b.completedAt.localeCompare(a.completedAt);
}
return bTime - aTime;
});
return summaries;
}
function toTimestamp(isoDate: string): number {
const parsed = Date.parse(isoDate);
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
}
export function deriveTimelineEntries(
messages: ChatMessage[],
workEntries: WorkLogEntry[],
): TimelineEntry[] {
const messageRows: TimelineEntry[] = messages.map((message) => ({
id: message.id,
kind: "message",
createdAt: message.createdAt,
message,
}));
const workRows: TimelineEntry[] = workEntries.map((entry) => ({
id: entry.id,
kind: "work",
createdAt: entry.createdAt,
entry,
}));
return [...messageRows, ...workRows].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
}
const timeline: TimelineEntry[] = [];
let messageIndex = 0;
let workIndex = 0;
export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileChange[] {
const files: TurnDiffFileChange[] = [];
const lines = diff.split("\n");
for (const line of lines) {
if (!line.startsWith("diff --git ")) continue;
const match = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
const filePath = match?.[2] ?? match?.[1];
if (!filePath) continue;
files.push({ path: filePath });
while (messageIndex < messages.length || workIndex < workEntries.length) {
const message = messages[messageIndex];
const workEntry = workEntries[workIndex];
if (!message && workEntry) {
timeline.push({
id: `work:${workEntry.id}`,
kind: "work",
createdAt: workEntry.createdAt,
entry: workEntry,
});
workIndex += 1;
continue;
}
if (!workEntry && message) {
timeline.push({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
});
messageIndex += 1;
continue;
}
if (!message || !workEntry) {
break;
}
const messageAt = toTimestamp(message.createdAt);
const workAt = toTimestamp(workEntry.createdAt);
if (workAt <= messageAt) {
timeline.push({
id: `work:${workEntry.id}`,
kind: "work",
createdAt: workEntry.createdAt,
entry: workEntry,
});
workIndex += 1;
continue;
}
timeline.push({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
});
messageIndex += 1;
}
return files;
}
export function inferCheckpointTurnCountByTurnId(
summaries: TurnDiffSummary[],
): Record<string, number> {
const sorted = [...summaries].sort((a, b) => a.completedAt.localeCompare(b.completedAt));
const result: Record<string, number> = {};
for (let index = 0; index < sorted.length; index += 1) {
const summary = sorted[index];
if (!summary) continue;
result[summary.turnId] = index + 1;
}
return result;
}
export function deriveTurnDiffSummaries(_events: unknown[]): TurnDiffSummary[] {
return [];
return timeline;
}
export function derivePhase(session: ProviderSession | null): SessionPhase {
@@ -136,3 +789,162 @@ export function derivePhase(session: ProviderSession | null): SessionPhase {
if (session.status === "running") return "running";
return "ready";
}
export function evolveSession(previous: ProviderSession, event: ProviderEvent): ProviderSession {
const payload = asObject(event.payload);
if (event.method === "thread/started") {
const thread = asObject(payload?.thread);
return {
...previous,
threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/started") {
const turn = asObject(payload?.turn);
return {
...previous,
status: "running",
activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/completed") {
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
const turnError = asObject(turn?.error);
return {
...previous,
status: status === "failed" ? "error" : "ready",
activeTurnId: undefined,
lastError: asString(turnError?.message) ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.kind === "error") {
return {
...previous,
status: "error",
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.method === "session/closed" || event.method === "session/exited") {
return {
...previous,
status: "closed",
activeTurnId: undefined,
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
return { ...previous, updatedAt: event.createdAt };
}
export function applyEventToMessages(
previous: ChatMessage[],
event: ProviderEvent,
activeAssistantItemRef: { current: string | null },
): ChatMessage[] {
const payload = asObject(event.payload);
if (event.method === "item/started") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return previous;
const itemId = asString(item?.id);
if (!itemId) return previous;
activeAssistantItemRef.current = itemId;
const seedText = asString(item?.text) ?? "";
const filtered = previous.filter((entry) => entry.id !== itemId);
return [
...filtered,
{
id: itemId,
role: "assistant",
text: seedText,
createdAt: event.createdAt,
streaming: true,
},
];
}
if (event.method === "item/agentMessage/delta") {
const itemId = event.itemId ?? asString(payload?.itemId);
const delta = event.textDelta ?? asString(payload?.delta) ?? "";
if (!itemId || !delta) return previous;
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
if (existingIndex === -1) {
activeAssistantItemRef.current = itemId;
return [
...previous,
{
id: itemId,
role: "assistant",
text: delta,
createdAt: event.createdAt,
streaming: true,
},
];
}
const updated = [...previous];
const existing = updated[existingIndex];
if (!existing) return previous;
updated[existingIndex] = {
...existing,
text: `${existing.text}${delta}`,
streaming: true,
};
return updated;
}
if (event.method === "item/completed") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return previous;
const itemId = asString(item?.id);
if (!itemId) return previous;
const fullText = asString(item?.text);
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
if (existingIndex === -1) {
return [
...previous,
{
id: itemId,
role: "assistant",
text: fullText ?? "",
createdAt: event.createdAt,
streaming: false,
},
];
}
const updated = [...previous];
const existing = updated[existingIndex];
if (!existing) return previous;
updated[existingIndex] = {
...existing,
text: fullText ?? existing.text,
streaming: false,
};
if (activeAssistantItemRef.current === itemId) {
activeAssistantItemRef.current = null;
}
return updated;
}
if (event.method === "turn/completed") {
return previous.map((entry) => ({ ...entry, streaming: false }));
}
return previous;
}
+198
View File
@@ -0,0 +1,198 @@
import { describe, expect, it, vi } from "vitest";
import type { NativeApi, StateEvent } from "@t3tools/contracts";
import { createStateSource } from "./stateSource";
function makeApi(): NativeApi {
const onStateEvent = vi.fn<(callback: (event: StateEvent) => void) => () => void>((callback) => {
callback({
seq: 1,
eventType: "project.upsert",
entityId: "project-1",
payload: {},
createdAt: "2026-02-20T00:00:00.000Z",
});
return () => undefined;
});
return {
todos: {
list: async () => [],
add: async () => [],
toggle: async () => [],
remove: async () => [],
},
dialogs: {
pickFolder: async () => null,
confirm: async () => true,
},
terminal: {
open: vi.fn(async () => {
throw new Error("not implemented");
}),
write: vi.fn(async () => undefined),
resize: vi.fn(async () => undefined),
clear: vi.fn(async () => undefined),
restart: vi.fn(async () => {
throw new Error("not implemented");
}),
close: vi.fn(async () => undefined),
onEvent: vi.fn(() => () => undefined),
},
agent: {
spawn: vi.fn(async () => ""),
kill: vi.fn(async () => undefined),
write: vi.fn(async () => undefined),
onOutput: vi.fn(() => () => undefined),
onExit: vi.fn(() => () => undefined),
},
providers: {
startSession: vi.fn(async () => {
throw new Error("not implemented");
}),
sendTurn: vi.fn(async () => {
throw new Error("not implemented");
}),
interruptTurn: vi.fn(async () => undefined),
respondToRequest: vi.fn(async () => undefined),
stopSession: vi.fn(async () => undefined),
listSessions: vi.fn(async () => []),
listCheckpoints: vi.fn(async () => {
throw new Error("not implemented");
}),
getCheckpointDiff: vi.fn(async () => {
throw new Error("not implemented");
}),
revertToCheckpoint: vi.fn(async () => {
throw new Error("not implemented");
}),
onEvent: vi.fn(() => () => undefined),
},
state: {
bootstrap: vi.fn(async () => ({
projects: [],
threads: [],
lastStateSeq: 3,
})),
listMessages: vi.fn(async () => ({
messages: [],
total: 0,
nextOffset: null,
})),
catchUp: vi.fn(async () => ({
events: [],
lastStateSeq: 3,
})),
onEvent: onStateEvent,
},
appSettings: {
get: vi.fn(async () => ({ codexBinaryPath: "", codexHomePath: "" })),
update: vi.fn(async () => ({ codexBinaryPath: "", codexHomePath: "" })),
},
threads: {
create: vi.fn(async () => {
throw new Error("not implemented");
}),
delete: vi.fn(async () => undefined),
markVisited: vi.fn(async () => {
throw new Error("not implemented");
}),
updateTerminalState: vi.fn(async () => {
throw new Error("not implemented");
}),
updateModel: vi.fn(async () => {
throw new Error("not implemented");
}),
updateTitle: vi.fn(async () => {
throw new Error("not implemented");
}),
updateBranch: vi.fn(async () => {
throw new Error("not implemented");
}),
},
projects: {
list: vi.fn(async () => []),
add: vi.fn(async () => {
throw new Error("not implemented");
}),
remove: vi.fn(async () => undefined),
searchEntries: vi.fn(async () => ({ entries: [], truncated: false })),
updateScripts: vi.fn(async () => {
throw new Error("not implemented");
}),
},
shell: {
openInEditor: vi.fn(async () => undefined),
openExternal: vi.fn(async () => undefined),
},
git: {
pull: vi.fn(async () => {
throw new Error("not implemented");
}),
status: vi.fn(async () => {
throw new Error("not implemented");
}),
runStackedAction: vi.fn(async () => {
throw new Error("not implemented");
}),
listBranches: vi.fn(async () => {
throw new Error("not implemented");
}),
createWorktree: vi.fn(async () => {
throw new Error("not implemented");
}),
removeWorktree: vi.fn(async () => undefined),
createBranch: vi.fn(async () => undefined),
checkout: vi.fn(async () => undefined),
init: vi.fn(async () => undefined),
},
contextMenu: {
show: vi.fn(async () => null),
},
server: {
getConfig: vi.fn(async () => ({
cwd: "/workspace",
syncEngineMode: "legacy" as const,
keybindings: [],
})),
upsertKeybinding: vi.fn(async () => ({
keybindings: [],
})),
},
};
}
describe("createStateSource", () => {
it("delegates bootstrap/catchUp/onEvent to api.state", async () => {
const api = makeApi();
const source = createStateSource(api);
await expect(source.bootstrap()).resolves.toEqual({
projects: [],
threads: [],
lastStateSeq: 3,
});
await expect(source.catchUp({ afterSeq: 1 })).resolves.toEqual({
events: [],
lastStateSeq: 3,
});
const received: StateEvent[] = [];
const unsubscribe = source.onEvent((event) => {
received.push(event);
});
expect(received).toEqual([
{
seq: 1,
eventType: "project.upsert",
entityId: "project-1",
payload: {},
createdAt: "2026-02-20T00:00:00.000Z",
},
]);
unsubscribe();
expect(api.state.bootstrap).toHaveBeenCalledTimes(1);
expect(api.state.catchUp).toHaveBeenCalledWith({ afterSeq: 1 });
expect(api.state.onEvent).toHaveBeenCalledTimes(1);
});
});
+21
View File
@@ -0,0 +1,21 @@
import type {
NativeApi,
StateBootstrapResult,
StateCatchUpInput,
StateCatchUpResult,
StateEvent,
} from "@t3tools/contracts";
export interface StateSource {
bootstrap(): Promise<StateBootstrapResult>;
catchUp(input: StateCatchUpInput): Promise<StateCatchUpResult>;
onEvent(listener: (event: StateEvent) => void): () => void;
}
export function createStateSource(api: NativeApi): StateSource {
return {
bootstrap: () => api.state.bootstrap(),
catchUp: (input) => api.state.catchUp(input),
onEvent: (listener) => api.state.onEvent(listener),
};
}
File diff suppressed because it is too large. Load diff
+788 -115
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -32,6 +32,7 @@ export function createThread(projectId: string, options: CreateThreadOptions = {
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
events: [],
turnDiffSummaries: [],
error: null,
createdAt,
+2
View File
@@ -1,5 +1,6 @@
import type {
ProjectScript as ContractProjectScript,
ProviderEvent,
ProviderSession,
} from "@t3tools/contracts";
@@ -76,6 +77,7 @@ export interface Thread {
activeTerminalGroupId: string;
session: ProviderSession | null;
messages: ChatMessage[];
events: ProviderEvent[];
error: string | null;
createdAt: string;
latestTurnId?: string | undefined;
+1
View File
@@ -24,6 +24,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
events: [],
turnDiffSummaries: [],
error: null,
createdAt: "2026-02-13T00:00:00.000Z",
+25 -30
View File
@@ -1,13 +1,4 @@
import {
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
type NativeApi,
WS_CHANNELS,
WS_METHODS,
type OrchestrationEvent,
type OrchestrationReadModel,
type WsWelcomePayload,
} from "@t3tools/contracts";
import { type NativeApi, WS_CHANNELS, WS_METHODS, type WsWelcomePayload } from "@t3tools/contracts";
import { showContextMenuFallback } from "./contextMenuFallback";
import { WsTransport } from "./wsTransport";
@@ -99,10 +90,34 @@ export function createWsNativeApi(): NativeApi {
interruptTurn: (input) => transport.request(WS_METHODS.providersInterruptTurn, input),
respondToRequest: (input) => transport.request(WS_METHODS.providersRespondToRequest, input),
stopSession: (input) => transport.request(WS_METHODS.providersStopSession, input),
listSessions: () => transport.request(WS_METHODS.providersListSessions),
listCheckpoints: (input) => transport.request(WS_METHODS.providersListCheckpoints, input),
getCheckpointDiff: (input) => transport.request(WS_METHODS.providersGetCheckpointDiff, input),
revertToCheckpoint: (input) =>
transport.request(WS_METHODS.providersRevertToCheckpoint, input),
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),
onEvent: (callback) =>
transport.subscribe(WS_CHANNELS.stateEvent, callback as (data: unknown) => void),
},
appSettings: {
get: () => transport.request(WS_METHODS.appSettingsGet),
update: (input) => transport.request(WS_METHODS.appSettingsUpdate, input),
},
threads: {
create: (input) => transport.request(WS_METHODS.threadsCreate, input),
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),
@@ -155,26 +170,6 @@ export function createWsNativeApi(): NativeApi {
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
},
orchestration: {
getSnapshot: () => transport.request(ORCHESTRATION_WS_METHODS.getSnapshot),
dispatchCommand: (command) =>
transport.request(ORCHESTRATION_WS_METHODS.dispatchCommand, command),
replayEvents: (fromSequenceExclusive) =>
transport.request(ORCHESTRATION_WS_METHODS.replayEvents, { fromSequenceExclusive }),
onReadModel: (callback) =>
transport.subscribe(
ORCHESTRATION_WS_CHANNELS.readModel,
(data: unknown) => {
const payload = data as { snapshot: OrchestrationReadModel };
callback(payload.snapshot);
},
),
onDomainEvent: (callback) =>
transport.subscribe(
ORCHESTRATION_WS_CHANNELS.domainEvent,
callback as (data: unknown) => void,
),
},
};
instance = { api, transport };
+168 -93
View File
@@ -34,22 +34,20 @@
"t3": "./dist/index.mjs",
},
"dependencies": {
"@effect/platform-node": "4.0.0-beta.10",
"@effect/sql-sqlite-node": "4.0.0-beta.10",
"effect": "4.0.0-beta.10",
"@livestore/adapter-node": "^0.3.1",
"@livestore/livestore": "^0.3.1",
"@pierre/diffs": "^1.1.0-beta.16",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0",
},
"devDependencies": {
"@effect/vitest": "4.0.0-beta.10",
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
},
},
"apps/web": {
@@ -92,7 +90,6 @@
"name": "@t3tools/contracts",
"version": "0.0.0",
"dependencies": {
"effect": "4.0.0-beta.10",
"zod": "^3.24.1",
},
"devDependencies": {
@@ -150,13 +147,33 @@
"@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.28.6", "@floating-ui/utils": "^0.2.10", "reselect": "^5.1.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-oYC7w0gp76RI5MxprlGLV0wze0SErZaRl3AAkeP3OnNB/UBMb6RqNf6ZSIlxOc9Qp68Ab3C2VOcJQyRs7Xc7Vw=="],
"@effect/platform-node": ["@effect/[email protected]", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.10", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.10", "ioredis": "^5.7.0" } }, "sha512-ikZ/uyos5okYAHE+wWOwZkHgriFUTY3aY8Kdqbj/ro8xw0z9YXWN4fbyQAZUWkBcieDKS36N+QfHRMPG4fEWRA=="],
"@effect/cli": ["@effect/[email protected]", "", { "dependencies": { "ini": "^4.1.3", "toml": "^3.0.0", "yaml": "^2.5.0" }, "peerDependencies": { "@effect/platform": "^0.82.8", "@effect/printer": "^0.43.4", "@effect/printer-ansi": "^0.43.4", "effect": "^3.15.4" } }, "sha512-CRdzBUW3SkjsL1Og5bnh7nt1VN0JwNLyfnjlzTWwtIm07WFFdcZXUXquFJfmU++eTP5Kfp8JbZYvsHwmzg/q1w=="],
"@effect/platform-node-shared": ["@effect/[email protected]", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.10" } }, "sha512-gBSeOG2bfchXFdgdi5oipHKynOzSd7BlzTy5QcjFOoCUTtLP9igqohPB9hTkV3a6seWE2JJqsgsQ79VuLb7fAg=="],
"@effect/cluster": ["@effect/[email protected]", "", { "peerDependencies": { "@effect/platform": "^0.82.8", "@effect/rpc": "^0.59.9", "@effect/sql": "^0.35.8", "effect": "^3.15.4" } }, "sha512-QlXfP8sTTijyw0XQdMFmjIVywqhrbrIuQ64RIazuNdiHkBMLGqkXPerFXdQwaeDeCb8iWy4vAUZSPqThCeHIdw=="],
"@effect/sql-sqlite-node": ["@effect/[email protected]", "", { "dependencies": { "better-sqlite3": "^12.6.2" }, "peerDependencies": { "effect": "^4.0.0-beta.10" } }, "sha512-oQl+gF31HaVM9R8YEpf96CIJypP1Roa5z1VPj8s7ZP+3aCtRVor1K+eMxYNAb8ph7R68Tz0LpmVkefq0mEI3CA=="],
"@effect/experimental": ["@effect/[email protected]", "", { "dependencies": { "uuid": "^11.0.3" }, "peerDependencies": { "@effect/platform": "^0.82.8", "effect": "^3.15.4", "ioredis": "^5", "lmdb": "^3" }, "optionalPeers": ["ioredis", "lmdb"] }, "sha512-2XasqFLQZFy2PGybFdBjgflXFfPuorc/6DMxogeTDHknZa0RH4KoJQQlWaCngbKMsZrZcv0jV+Zi4aDZsVGl7g=="],
"@effect/vitest": ["@effect/[email protected]", "", { "peerDependencies": { "effect": "^4.0.0-beta.10", "vitest": "^3.0.0" } }, "sha512-WmE8vCNw+eDoAq9CwwymrAdIBw1f+8hDP3AUF7jyC7/Cj/kyAYOFwkbtKmDXIFaTlf7G/2fmulEXeCO5W8j0kQ=="],
"@effect/opentelemetry": ["@effect/[email protected]", "", { "peerDependencies": { "@effect/platform": "^0.82.8", "@opentelemetry/api": "^1.9", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/sdk-metrics": "^2.0.0", "@opentelemetry/sdk-trace-base": "^2.0.0", "@opentelemetry/sdk-trace-node": "^2.0.0", "@opentelemetry/sdk-trace-web": "^2.0.0", "@opentelemetry/semantic-conventions": "^1.33.0", "effect": "^3.15.4" }, "optionalPeers": ["@opentelemetry/api", "@opentelemetry/resources", "@opentelemetry/sdk-metrics", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-trace-node", "@opentelemetry/sdk-trace-web"] }, "sha512-ZULA3TSLVx3ylcWcmwg5wHiDIMc+LWPxUQVEqE5I+PgqNcPuhk11DjLO+ZYPWbQ2nF7NsawMactNOVCZLMQa7Q=="],
"@effect/platform": ["@effect/[email protected]", "", { "dependencies": { "find-my-way-ts": "^0.1.5", "msgpackr": "^1.11.4", "multipasta": "^0.2.5" }, "peerDependencies": { "effect": "^3.15.4" } }, "sha512-JEnIACWM2CfyKbf31dPzC903iF11SfiAk74Xs43Ez+n1ieQz2Ew2S/99KBbuesIKkDScLtn8PI23EBFMQiL0Ow=="],
"@effect/platform-browser": ["@effect/[email protected]", "", { "dependencies": { "multipasta": "^0.2.5" }, "peerDependencies": { "@effect/platform": "^0.82.8", "effect": "^3.15.4" } }, "sha512-xMLpEOrQcZnqZH/DIBjZdYo6W2gtFPgbrt8uxKhDg/GrEXPLJW/yxuKh7JCO/yuQWWZf6o/qhgEVHB406ppwYg=="],
"@effect/platform-bun": ["@effect/[email protected]", "", { "dependencies": { "@effect/platform-node-shared": "^0.35.5", "multipasta": "^0.2.5" }, "peerDependencies": { "@effect/cluster": "^0.34.5", "@effect/platform": "^0.82.8", "@effect/rpc": "^0.59.9", "@effect/sql": "^0.35.8", "effect": "^3.15.4" } }, "sha512-XAbcJ9UbyCHzEWrUg2kGrZBAnQgVR6MRva1NWf7oU9+Q7SgDuMriNhvIOm9OTjS5KWrwTlzYa8Lr0gmCNEkewQ=="],
"@effect/platform-node": ["@effect/[email protected]", "", { "dependencies": { "@effect/platform-node-shared": "^0.35.5", "mime": "^3.0.0", "undici": "^7.10.0", "ws": "^8.18.2" }, "peerDependencies": { "@effect/cluster": "^0.34.5", "@effect/platform": "^0.82.8", "@effect/rpc": "^0.59.9", "@effect/sql": "^0.35.8", "effect": "^3.15.4" } }, "sha512-iRJolgh/DWjs6LjhDY38XtWwxI42sXfdKYD25syl2I1sUm4j/+NBaMOA4OPyf6DNKHIYU82nVyXEGNtrBlFWww=="],
"@effect/platform-node-shared": ["@effect/[email protected]", "", { "dependencies": { "@parcel/watcher": "^2.5.1", "multipasta": "^0.2.5", "ws": "^8.18.2" }, "peerDependencies": { "@effect/cluster": "^0.34.5", "@effect/platform": "^0.82.8", "@effect/rpc": "^0.59.9", "@effect/sql": "^0.35.8", "effect": "^3.15.4" } }, "sha512-F0Hh+aueRxOw2vqo9LNqWh31ch5WBhz0Hp0vYQ8jntjLOsvN5oX/0JbGO4E5BNsMZV5HCraP6I4ACjP3KUnvCQ=="],
"@effect/printer": ["@effect/[email protected]", "", { "peerDependencies": { "@effect/typeclass": "^0.34.5", "effect": "^3.15.5" } }, "sha512-0e+GlRzP1EMFlkkNozjvlNGq2T5VgstO6BDffY+MSqic6OZyd3nyM83CCHOCOT0+0legzr7qaHtY4WdCb0GdLA=="],
"@effect/printer-ansi": ["@effect/[email protected]", "", { "dependencies": { "@effect/printer": "^0.43.5" }, "peerDependencies": { "@effect/typeclass": "^0.34.5", "effect": "^3.15.5" } }, "sha512-EQXEKevlBIZPoVGhUi1gybkMrJc9zBKr8SiCN+xVvf2qW6K0I/oOGw58lqWXA3gKfughZBX8MkCVfqWDJlrpmw=="],
"@effect/rpc": ["@effect/[email protected]", "", { "peerDependencies": { "@effect/platform": "^0.82.8", "effect": "^3.15.4" } }, "sha512-9Nw6YRBbTgsCyVb7/AMCTML7cE6v38cN0I7tP05XAlvKdmCroifaNopDCO7w1C3EPeNBG42nYuYnwU6L0Atnhg=="],
"@effect/sql": ["@effect/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.33.0", "uuid": "^11.0.3" }, "peerDependencies": { "@effect/experimental": "^0.46.8", "@effect/platform": "^0.82.8", "effect": "^3.15.4" } }, "sha512-M1x6XMWkIHMY7iHbZgHVpq1jhhX+oFBN5LcL7Oc7cy3h2rtWf9VH2WvC2ivc2gscoKSpITlxEhGNHDFy9YrCSw=="],
"@effect/typeclass": ["@effect/[email protected]", "", { "peerDependencies": { "effect": "^3.15.5" } }, "sha512-nC00DQoD2Tx7EMC1B1UvgPLr7QsG5Ck2nHn94LZl5ddteDNQLPAVkAWSKM+BE5ILyE1eMTblQ+EcomPW2rtUdg=="],
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
@@ -248,8 +265,6 @@
"@inquirer/type": ["@inquirer/[email protected]", "", { "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-BvziSRxfz5Ov8ch0z/n3oijRSEcEsHnhggm4xFZe93DHcUCTlutlq9Ox4SVENAfcRD22UQq7T/atg9Wr3k09eA=="],
"@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-eUgLqrMf8nJkZxT24JvVRrQya1vZkQh8BBeYNwGDqa5I0VUi8ACx7uFvAaLxintokpTenkK6DASvo/bvNbBGow=="],
"@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
@@ -260,6 +275,26 @@
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@livestore/adapter-node": ["@livestore/[email protected]", "", { "dependencies": { "@livestore/common": "0.3.1", "@livestore/devtools-vite": "0.3.1", "@livestore/sqlite-wasm": "0.3.1", "@livestore/utils": "0.3.1", "@livestore/webmesh": "0.3.1", "@opentelemetry/api": "1.9.0", "vite": "6.3.4" } }, "sha512-qP6nGY8du3r+4aS4yJ2YgaDVp/KzE/qBzOzleFTBR9DEM0faeLI9EXzwVq9A/k8pbxm5heF78l0ConExxxl42Q=="],
"@livestore/adapter-web": ["@livestore/[email protected]", "", { "dependencies": { "@livestore/common": "0.3.1", "@livestore/devtools-web-common": "0.3.1", "@livestore/sqlite-wasm": "0.3.1", "@livestore/utils": "0.3.1", "@livestore/webmesh": "0.3.1", "@opentelemetry/api": "1.9.0" } }, "sha512-0ZKTam+C3KeG5qiiTLFOgoMhdUBCENmuaMwxoj7WOtA2c4eKyqIy+P/1zga+az0XqaMJoG5FVszWhWMUMzNjtQ=="],
"@livestore/common": ["@livestore/[email protected]", "", { "dependencies": { "@livestore/utils": "0.3.1", "@livestore/webmesh": "0.3.1", "@opentelemetry/api": "1.9.0", "graphology": "0.26.0-alpha1", "graphology-dag": "0.4.1", "graphology-types": "0.24.8" } }, "sha512-D44ia+zVH8EF0TWGUp0GQnCVvCsGKgKD/ryFl+kx607/l7GDUSagNnWkRmMwhhshJSJblQwouhA9fwjDNTBB2g=="],
"@livestore/devtools-vite": ["@livestore/[email protected]", "", { "dependencies": { "@livestore/adapter-web": "0.3.1", "@livestore/utils": "0.3.1", "vite": "*" } }, "sha512-7d4dxI1jkNtMRNxfnj7WVFIg+z5+M1FxTCUw4XrtHYeJGd7qy3GOJ/75D0lU12OQ7EbY/qSVnoU7++SkSEjMFA=="],
"@livestore/devtools-web-common": ["@livestore/[email protected]", "", { "dependencies": { "@livestore/common": "0.3.1", "@livestore/utils": "0.3.1", "@livestore/webmesh": "0.3.1" } }, "sha512-jU7IvebelTtvSTQ2zKNzSm5qZodwUiPsNsDURsY5Yw0DXpafcfpRobs/WYd+Wd4Q1E4oFaK05hPfWZGbVFdw7Q=="],
"@livestore/livestore": ["@livestore/[email protected]", "", { "dependencies": { "@livestore/common": "0.3.1", "@livestore/utils": "0.3.1", "@opentelemetry/api": "1.9.0" } }, "sha512-imw1JK5i82yTmSC4PRoZ1gUiG39jasR49c5TPQI/MCIFSbgqcKS0x1IPoB8js6tlPoVm+iH7p4JTAQKYC2q3Pg=="],
"@livestore/sqlite-wasm": ["@livestore/[email protected]", "", { "dependencies": { "@livestore/common": "0.3.1", "@livestore/utils": "0.3.1", "@livestore/wa-sqlite": "1.0.5-dev.2" } }, "sha512-+JLIwpd2N214LmwlUX6arYnJ5IhvSi4Fn3Jk6E6fNfuUU4tczcL1PtgfIX2IoiPhn9QDG0YJVdJBT6KYi1uMyg=="],
"@livestore/utils": ["@livestore/[email protected]", "", { "dependencies": { "@standard-schema/spec": "1.0.0", "msgpackr": "1.11.2", "nanoid": "5.1.3", "pretty-bytes": "6.1.1" }, "peerDependencies": { "@effect/cli": "~0.61.4", "@effect/cluster": "~0.34.1", "@effect/experimental": "~0.46.4", "@effect/opentelemetry": "~0.48.4", "@effect/platform": "~0.82.4", "@effect/platform-browser": "~0.62.4", "@effect/platform-bun": "~0.65.1", "@effect/platform-node": "~0.81.1", "@effect/printer": "~0.43.2", "@effect/printer-ansi": "~0.43.2", "@effect/rpc": "~0.59.5", "@effect/sql": "~0.35.4", "@effect/typeclass": "~0.34.2", "@opentelemetry/api": "~1.9.0", "@opentelemetry/resources": "~2.0.0", "effect": "~3.15.2" } }, "sha512-DFgrKpVIu/Nn9GE0QG2uitrFLF63aIiV5rencAk3kigNPzq4iBao05wvT/JVqgRxxiM7F1SuAZYogwM4QdpcDA=="],
"@livestore/wa-sqlite": ["@livestore/[email protected]", "", {}, "sha512-i7tKFEp0m3+4tGLV9Z5eAr/3RZPuNOyuf4NaQ/ygF2KwzlHc3TnqouPuE2sMH06r3soXIilWYND/x0eT8x6D6Q=="],
"@livestore/webmesh": ["@livestore/[email protected]", "", { "dependencies": { "@livestore/utils": "0.3.1" } }, "sha512-JLYFgiOf1r7xqN7SkwdHNZdZ+geQlEdC9rg81DeC839vqqshA5TEhh045dhEkeyVJZqeg44vX5adUX6FOkhTfg=="],
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="],
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="],
@@ -282,6 +317,14 @@
"@open-draft/until": ["@open-draft/[email protected]", "", {}, "sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg=="],
"@opentelemetry/api": ["@opentelemetry/[email protected]", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
"@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
"@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
"@opentelemetry/semantic-conventions": ["@opentelemetry/[email protected]", "", {}, "sha512-R5R9tb2AXs2IRLNKLBJDynhkfmx7mX0vi8NkhZb3gUkPWHn6HXk5J8iQ/dql0U3ApfWym4kXXmBDRGO+oeOfjg=="],
"@oxc-project/runtime": ["@oxc-project/[email protected]", "", {}, "sha512-4vYtWXMnXM6EaweCxbJ6bISAhkNHeN33SihvuX3wrpqaSJA4ZEoW35i9mSvE74+GDf1yTeVE+aEHA+WBpjDk/g=="],
"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-m6RebKHIRsax2iCwVpYW2ErQwa4ywHJrE4sCK3/8JK8ZZAWOKXaRJFl/uP51gaVyyXlaS4+chU1nSCdzYf6QqQ=="],
@@ -340,6 +383,34 @@
"@oxlint/binding-win32-x64-msvc": ["@oxlint/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-DJbQsSJUr4KSi9uU0QqOgI7PX2C+fKGZX+YDprt3vM2sC0dWZsgVTLoN2vtkNyEWJSY2mnvRFUshWXT3bmo0Ug=="],
"@parcel/watcher": ["@parcel/[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3", "is-glob": "^4.0.3", "node-addon-api": "^7.0.0", "picomatch": "^4.0.3" }, "optionalDependencies": { "@parcel/watcher-android-arm64": "2.5.6", "@parcel/watcher-darwin-arm64": "2.5.6", "@parcel/watcher-darwin-x64": "2.5.6", "@parcel/watcher-freebsd-x64": "2.5.6", "@parcel/watcher-linux-arm-glibc": "2.5.6", "@parcel/watcher-linux-arm-musl": "2.5.6", "@parcel/watcher-linux-arm64-glibc": "2.5.6", "@parcel/watcher-linux-arm64-musl": "2.5.6", "@parcel/watcher-linux-x64-glibc": "2.5.6", "@parcel/watcher-linux-x64-musl": "2.5.6", "@parcel/watcher-win32-arm64": "2.5.6", "@parcel/watcher-win32-ia32": "2.5.6", "@parcel/watcher-win32-x64": "2.5.6" } }, "sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ=="],
"@parcel/watcher-android-arm64": ["@parcel/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-YQxSS34tPF/6ZG7r/Ih9xy+kP/WwediEUsqmtf0cuCV5TPPKw/PQHRhueUo6JdeFJaqV3pyjm0GdYjZotbRt/A=="],
"@parcel/watcher-darwin-arm64": ["@parcel/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Z2ZdrnwyXvvvdtRHLmM4knydIdU9adO3D4n/0cVipF3rRiwP+3/sfzpAwA/qKFL6i1ModaabkU7IbpeMBgiVEA=="],
"@parcel/watcher-darwin-x64": ["@parcel/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-HgvOf3W9dhithcwOWX9uDZyn1lW9R+7tPZ4sug+NGrGIo4Rk1hAXLEbcH1TQSqxts0NYXXlOWqVpvS1SFS4fRg=="],
"@parcel/watcher-freebsd-x64": ["@parcel/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-vJVi8yd/qzJxEKHkeemh7w3YAn6RJCtYlE4HPMoVnCpIXEzSrxErBW5SJBgKLbXU3WdIpkjBTeUNtyBVn8TRng=="],
"@parcel/watcher-linux-arm-glibc": ["@parcel/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-9JiYfB6h6BgV50CCfasfLf/uvOcJskMSwcdH1PHH9rvS1IrNy8zad6IUVPVUfmXr+u+Km9IxcfMLzgdOudz9EQ=="],
"@parcel/watcher-linux-arm-musl": ["@parcel/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg=="],
"@parcel/watcher-linux-arm64-glibc": ["@parcel/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA=="],
"@parcel/watcher-linux-arm64-musl": ["@parcel/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA=="],
"@parcel/watcher-linux-x64-glibc": ["@parcel/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ=="],
"@parcel/watcher-linux-x64-musl": ["@parcel/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg=="],
"@parcel/watcher-win32-arm64": ["@parcel/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-3ukyebjc6eGlw9yRt678DxVF7rjXatWiHvTXqphZLvo7aC5NdEgFufVwjFfY51ijYEWpXbqF5jtrK275z52D4Q=="],
"@parcel/watcher-win32-ia32": ["@parcel/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-k35yLp1ZMwwee3Ez/pxBi5cf4AoBKYXj00CZ80jUz5h8prpiaQsiRPKQMxoLstNuqe2vR4RNPEAEcjEFzhEz/g=="],
"@parcel/watcher-win32-x64": ["@parcel/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-hbQlYcCq5dlAX9Qx+kFb0FHue6vbjlf0FrNzSKdYK2APUf7tGfGxQCk2ihEREmbR6ZMc0MVAD5RIX/41gpUzTw=="],
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-McjTuEPuacSIcXdoI2O9W6VSHIOs9ApEHnEUwONKZnKqIo2GGv1vNg9Pr8tgBOL7lgBWNEHX5ROJ5z1X74sENQ=="],
"@quansync/fs": ["@quansync/[email protected]", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
@@ -610,28 +681,18 @@
"bail": ["[email protected]", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
"base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg=="],
"better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-8VYKM3MjCa9WcaSAI3hzwhmyHVlH8tiGFwf0RlTsZPWJ1I5MkzjiudCo4KC4DxOaL/53A5B1sI/IbldNFDbsKA=="],
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
"bindings": ["[email protected]", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="],
"birpc": ["[email protected]", "", {}, "sha512-LShSxJP0KTmd101b6DRyGBj57LZxSDYWKitQNW/mi8GRMvZb078Uf9+pveax1DrVL89vm7mWe+TovdI/UDOuPw=="],
"bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
"boolean": ["[email protected]", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
"braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA=="],
"buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
"buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
@@ -662,8 +723,6 @@
"chokidar": ["[email protected]", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="],
"chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
"cli-width": ["[email protected]", "", {}, "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ=="],
@@ -674,8 +733,6 @@
"clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
"cluster-key-slot": ["[email protected]", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="],
"color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
"color-name": ["[email protected]", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
@@ -698,8 +755,6 @@
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
"deep-extend": ["[email protected]", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="],
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
@@ -716,8 +771,6 @@
"delayed-stream": ["[email protected]", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="],
"denque": ["[email protected]", "", {}, "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw=="],
"dequal": ["[email protected]", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="],
"detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
@@ -732,7 +785,7 @@
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"effect": ["effect@4.0.0-beta.10", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-UvxWmT0uzWZqNmQODfW7y1zb0LMlH3xtSn/UESpck2Wvv6SogxibYPWKKNcUsRMm5wwprOoW2IwItYLQyZpe8Q=="],
"effect": ["effect@3.15.5", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "fast-check": "^3.23.1" } }, "sha512-9IA4xu9niyDIuWkS/whroDj3u2nbccw+9fQ9sKCzaEtuwTV5SSoNvp8XOozeSF/0Nwnh+mx2+ShYYgSueOTmMw=="],
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
@@ -774,7 +827,7 @@
"estree-walker": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],
"expand-template": ["[email protected]", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
"events": ["[email protected]", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="],
"expect-type": ["[email protected]", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],
@@ -782,14 +835,12 @@
"extract-zip": ["[email protected]", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="],
"fast-check": ["fast-check@4.5.3", "", { "dependencies": { "pure-rand": "^7.0.0" } }, "sha512-IE9csY7lnhxBnA8g/WI5eg/hygA6MGWJMSNfFRrBlXUciADEhS1EDB0SIsMSvzubzIlOBbVITSsypCsW717poA=="],
"fast-check": ["fast-check@3.23.2", "", { "dependencies": { "pure-rand": "^6.1.0" } }, "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A=="],
"fd-slicer": ["[email protected]", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="],
"fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"file-uri-to-path": ["[email protected]", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="],
"fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
"find-my-way-ts": ["[email protected]", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="],
@@ -798,8 +849,6 @@
"form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
"fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
@@ -818,8 +867,6 @@
"get-tsconfig": ["[email protected]", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="],
"github-from-package": ["[email protected]", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
"glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
"global-agent": ["[email protected]", "", { "dependencies": { "boolean": "^3.0.1", "es6-error": "^4.1.1", "matcher": "^3.0.0", "roarr": "^2.15.3", "semver": "^7.3.2", "serialize-error": "^7.0.1" } }, "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q=="],
@@ -832,6 +879,14 @@
"graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
"graphology": ["[email protected]", "", { "dependencies": { "events": "^3.3.0", "obliterator": "^2.0.2" }, "peerDependencies": { "graphology-types": ">=0.24.0" } }, "sha512-XQ3b+P3Vvljq/mF+O15R5PlR8kVpRL8K8vhJWW9Enh2+iGNn5c3WZNpXP2OaAacfNV3a9gV3Ia6+Qz6do2JZ8w=="],
"graphology-dag": ["[email protected]", "", { "dependencies": { "graphology-utils": "^2.4.1", "mnemonist": "^0.39.0" }, "peerDependencies": { "graphology-types": ">=0.19.0" } }, "sha512-3ch9oOAnHZDoT043vyg7ukmSkKJ505nFzaHaYOn0IF2PgGo5VtIavyVK4UpbIa4tli3hhGm1ZTdBsubTmaxu/w=="],
"graphology-types": ["[email protected]", "", {}, "sha512-hDRKYXa8TsoZHjgEaysSRyPdT6uB78Ci8WnjgbStlQysz7xR52PInxNsmnB7IBOM1BhikxkNyCVEFgmPKnpx3Q=="],
"graphology-utils": ["[email protected]", "", { "peerDependencies": { "graphology-types": ">=0.23.0" } }, "sha512-ckHg8MXrXJkOARk56ZaSCM1g1Wihe2d6iTmz1enGOz4W/l831MBCKSayeFQfowgF8wd+PQ4rlch/56Vs/VZLDQ=="],
"graphql": ["[email protected]", "", {}, "sha512-DKKrynuQRne0PNpEbzuEdHlYOMksHSUI8Zc9Unei5gTsMNA2/vMpoMz/yKba50pejK56qj98qM0SjYxAKi13gQ=="],
"has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
@@ -868,20 +923,14 @@
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
"ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"import-from": ["[email protected]", "", { "dependencies": { "resolve-from": "^5.0.0" } }, "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ=="],
"import-without-cache": ["[email protected]", "", {}, "sha512-B6Lc2s6yApwnD2/pMzFh/d5AVjdsDXjgkeJ766FmFuJELIGHNycKRj+l3A39yZPM4CchqNCB4RITEAYB1KUM6A=="],
"inherits": ["in[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
"ini": ["[email protected]", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="],
"ini": ["in[email protected]", "", {}, "sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg=="],
"inline-style-parser": ["[email protected]", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
"ioredis": ["[email protected]", "", { "dependencies": { "@ioredis/commands": "1.5.0", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-VI5tMCdeoxZWU5vjHWsiE/Su76JGhBvWF1MJnV9ZtGltHk9BmD48oDq8Tj8haZ85aceXZMxLNDQZRVo5QKNgXA=="],
"is-alphabetical": ["[email protected]", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
"is-alphanumerical": ["[email protected]", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="],
@@ -930,8 +979,6 @@
"keyv": ["[email protected]", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
"kubernetes-types": ["[email protected]", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="],
"lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.31.1", "lightningcss-darwin-arm64": "1.31.1", "lightningcss-darwin-x64": "1.31.1", "lightningcss-freebsd-x64": "1.31.1", "lightningcss-linux-arm-gnueabihf": "1.31.1", "lightningcss-linux-arm64-gnu": "1.31.1", "lightningcss-linux-arm64-musl": "1.31.1", "lightningcss-linux-x64-gnu": "1.31.1", "lightningcss-linux-x64-musl": "1.31.1", "lightningcss-win32-arm64-msvc": "1.31.1", "lightningcss-win32-x64-msvc": "1.31.1" } }, "sha512-l51N2r93WmGUye3WuFoN5k10zyvrVs0qfKBhyC5ogUQ6Ew6JUSswh78mbSO+IU3nTWsyOArqPCcShdQSadghBQ=="],
"lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-HXJF3x8w9nQ4jbXRiNppBCqeZPIAfUo8zE/kOEGbW5NZvGc/K7nMxbhIr+YlFlHW5mpbg/YFPdbnCh1wAXCKFg=="],
@@ -958,12 +1005,8 @@
"lodash": ["[email protected]", "", {}, "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w=="],
"lodash.defaults": ["[email protected]", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="],
"lodash.difference": ["[email protected]", "", {}, "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA=="],
"lodash.isarguments": ["[email protected]", "", {}, "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg=="],
"longest-streak": ["[email protected]", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="],
"lowercase-keys": ["[email protected]", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="],
@@ -1072,7 +1115,7 @@
"micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
"mime": ["mime@4.1.0", "", { "bin": { "mime": "bin/cli.js" } }, "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw=="],
"mime": ["mime@3.0.0", "", { "bin": { "mime": "cli.js" } }, "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A=="],
"mime-db": ["[email protected]", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
@@ -1082,11 +1125,11 @@
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
"mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
"mnemonist": ["[email protected]", "", { "dependencies": { "obliterator": "^2.0.1" } }, "sha512-vyWo2K3fjrUw8YeeZ1zF0fy6Mu59RHokURlld8ymdUPjMlD9EC9ov1/YPqTgqRvUN9nTr3Gqfz29LYAmu0PHPQ=="],
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"msgpackr": ["[email protected].8", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
"msgpackr": ["[email protected].2", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-F9UngXRlPyWCDEASDpTf6c9uNhGPTqnTeLVt7bN+bU1eajoR/8V9ys2BRaV5C/e5ihE6sJ9uPIKaYt6bFuO32g=="],
"msgpackr-extract": ["[email protected]", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA=="],
@@ -1098,10 +1141,6 @@
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
"napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-+CGM1L1CgmtheLcBuleyYOn7NWPVu0s0EJH2C4puxgEZb9h8QpR9G2dBfZJOAUhi7VQxuBPMd0hiISWcTyiYyQ=="],
"node-addon-api": ["[email protected]", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
"node-gyp-build-optional-packages": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="],
@@ -1116,6 +1155,8 @@
"object-keys": ["[email protected]", "", {}, "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="],
"obliterator": ["[email protected]", "", {}, "sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw=="],
"obug": ["[email protected]", "", {}, "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ=="],
"once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
@@ -1150,10 +1191,10 @@
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
"pretty-bytes": ["[email protected]", "", {}, "sha512-mQUvGU6aUFQ+rNvTIAcZuWGRT9a6f6Yrg9bHs4ImKF+HZCEK+plBvnAZYSIQztknZF2qnzNtr6F8s0+IuptdlQ=="],
"progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
"property-information": ["[email protected]", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="],
@@ -1162,14 +1203,12 @@
"pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA=="],
"pure-rand": ["pure-rand@7.0.1", "", {}, "sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ=="],
"pure-rand": ["pure-rand@6.1.0", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
"quansync": ["[email protected]", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="],
"quick-lru": ["[email protected]", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="],
"rc": ["[email protected]", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
"react": ["[email protected]", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
"react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
@@ -1178,16 +1217,10 @@
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
"readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"readdirp": ["[email protected]", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
"recast": ["[email protected]", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA=="],
"redis-errors": ["[email protected]", "", {}, "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w=="],
"redis-parser": ["[email protected]", "", { "dependencies": { "redis-errors": "^1.0.0" } }, "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A=="],
"regex": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg=="],
"regex-recursion": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg=="],
@@ -1234,8 +1267,6 @@
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
"safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
@@ -1254,10 +1285,6 @@
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
"simple-concat": ["[email protected]", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
"simple-get": ["[email protected]", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
@@ -1268,8 +1295,6 @@
"stackback": ["[email protected]", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],
"standard-as-callback": ["[email protected]", "", {}, "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A=="],
"statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"std-env": ["[email protected]", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
@@ -1278,14 +1303,10 @@
"string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
"stringify-entities": ["[email protected]", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
"strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"strip-json-comments": ["[email protected]", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
"style-to-js": ["[email protected]", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
"style-to-object": ["[email protected]", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="],
@@ -1306,10 +1327,6 @@
"tapable": ["[email protected]", "", {}, "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg=="],
"tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ=="],
"tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
"tiny-warning": ["[email protected]", "", {}, "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="],
@@ -1346,8 +1363,6 @@
"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
"tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
"turbo": ["[email protected]", "", { "optionalDependencies": { "turbo-darwin-64": "2.8.7", "turbo-darwin-arm64": "2.8.7", "turbo-linux-64": "2.8.7", "turbo-linux-arm64": "2.8.7", "turbo-windows-64": "2.8.7", "turbo-windows-arm64": "2.8.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-RBLh5caMAu1kFdTK1jgH2gH/z+jFsvX5rGbhgJ9nlIAWXSvxlzwId05uDlBA1+pBd3wO/UaKYzaQZQBXDd7kcA=="],
"turbo-darwin-64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Xr4TO/oDDwoozbDtBvunb66g//WK8uHRygl72vUthuwzmiw48pil4IuoG/QbMHd9RE8aBnVmzC0WZEWk/WWt3A=="],
@@ -1400,9 +1415,7 @@
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"uuid": ["[email protected]", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w=="],
"uuid": ["uuid@11.1.0", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A=="],
"vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
@@ -1470,8 +1483,18 @@
"@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
"@effect/platform/msgpackr": ["[email protected]", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
"@electron/get/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"@livestore/adapter-node/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-BiReIiMS2fyFqbqNT/Qqt4CVITDU9M9vE+DKcVAsB+ZV0wvTKd+3hMbkpxz1b+NmEDMegpVbisKiAZOnvO92Sw=="],
"@livestore/devtools-vite/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
"@livestore/utils/@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA=="],
"@livestore/utils/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-zAbEOEr7u2CbxwoMRlz/pNSpRP0FdAU4pRaYunCdEezWohXFs+a0Xw7RfkKaezMsmSM1vttcLthJtwRnVtOfHQ=="],
"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.30.2", "lightningcss-darwin-arm64": "1.30.2", "lightningcss-darwin-x64": "1.30.2", "lightningcss-freebsd-x64": "1.30.2", "lightningcss-linux-arm-gnueabihf": "1.30.2", "lightningcss-linux-arm64-gnu": "1.30.2", "lightningcss-linux-arm64-musl": "1.30.2", "lightningcss-linux-x64-gnu": "1.30.2", "lightningcss-linux-x64-musl": "1.30.2", "lightningcss-win32-arm64-msvc": "1.30.2", "lightningcss-win32-x64-msvc": "1.30.2" } }, "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" }, "bundled": true }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
@@ -1514,8 +1537,6 @@
"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
"rc/ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
"readdirp/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
"recast/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
@@ -1532,6 +1553,8 @@
"@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
"@livestore/adapter-node/vite/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],
"@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A=="],
"@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA=="],
@@ -1557,5 +1580,57 @@
"electron/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/android-arm64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/android-x64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "x64" }, "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/darwin-arm64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/darwin-x64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/freebsd-arm64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/freebsd-x64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/linux-arm": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/linux-arm64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/linux-ia32": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ia32" }, "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/linux-loong64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/linux-mips64el": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/linux-ppc64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/linux-riscv64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/linux-s390x": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/linux-x64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/netbsd-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/netbsd-x64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/openbsd-arm64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/openbsd-x64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/openharmony-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/sunos-x64": ["@esbuild/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/win32-arm64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/win32-ia32": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ=="],
"@livestore/adapter-node/vite/esbuild/@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="],
}
}
-1
View File
@@ -23,7 +23,6 @@
"test": "vitest run"
},
"dependencies": {
"effect": "4.0.0-beta.10",
"zod": "^3.24.1"
},
"devDependencies": {
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { appSettingsSchema, appSettingsUpdateInputSchema } from "./appSettings";
describe("appSettings schemas", () => {
it("applies defaults for codex paths", () => {
expect(appSettingsSchema.parse({})).toEqual({
codexBinaryPath: "",
codexHomePath: "",
});
});
it("trims codex path overrides in updates", () => {
expect(
appSettingsUpdateInputSchema.parse({
codexBinaryPath: " /opt/codex/bin/codex ",
codexHomePath: " /Users/alice/.codex ",
}),
).toEqual({
codexBinaryPath: "/opt/codex/bin/codex",
codexHomePath: "/Users/alice/.codex",
});
});
});
+14
View File
@@ -0,0 +1,14 @@
import { z } from "zod";
export const appSettingsSchema = z.object({
codexBinaryPath: z.string().trim().max(4096).default(""),
codexHomePath: z.string().trim().max(4096).default(""),
});
export const appSettingsUpdateInputSchema = z.object({
codexBinaryPath: z.string().trim().max(4096).optional(),
codexHomePath: z.string().trim().max(4096).optional(),
});
export type AppSettings = z.infer<typeof appSettingsSchema>;
export type AppSettingsUpdateInput = z.input<typeof appSettingsUpdateInputSchema>;
+2 -1
View File
@@ -1,4 +1,5 @@
export * from "./todo";
export * from "./appSettings";
export * from "./ipc";
export * from "./agent";
export * from "./terminal";
@@ -9,4 +10,4 @@ export * from "./keybindings";
export * from "./server";
export * from "./project";
export * from "./git";
export * from "./orchestration";
export * from "./state";
+39 -12
View File
@@ -1,4 +1,5 @@
import type { AgentConfig, AgentExit, OutputChunk } from "./agent";
import type { AppSettings, AppSettingsUpdateInput } from "./appSettings";
import type {
GitCheckoutInput,
GitCreateBranchInput,
@@ -16,6 +17,7 @@ import type {
GitStatusResult,
} from "./git";
import type {
ProviderEvent,
ProviderGetCheckpointDiffInput,
ProviderGetCheckpointDiffResult,
ProviderInterruptTurnInput,
@@ -41,6 +43,22 @@ import type {
ProjectUpdateScriptsResult,
} from "./project";
import type { ServerConfig } from "./server";
import type {
StateBootstrapResult,
StateCatchUpInput,
StateCatchUpResult,
StateEvent,
StateListMessagesInput,
StateListMessagesResult,
ThreadsCreateInput,
ThreadsDeleteInput,
ThreadsMarkVisitedInput,
ThreadsUpdateBranchInput,
ThreadsUpdateModelInput,
ThreadsUpdateResult,
ThreadsUpdateTerminalStateInput,
ThreadsUpdateTitleInput,
} from "./state";
import type {
TerminalClearInput,
TerminalCloseInput,
@@ -52,11 +70,6 @@ import type {
} from "./terminal";
import type { NewTodoInput, Todo } from "./todo";
import type { ServerUpsertKeybindingInput, ServerUpsertKeybindingResult } from "./server";
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
} from "./orchestration";
export const EDITORS = [
{ id: "cursor", label: "Cursor", command: "cursor" },
@@ -98,6 +111,7 @@ export interface NativeApi {
interruptTurn: (input: ProviderInterruptTurnInput) => Promise<void>;
respondToRequest: (input: ProviderRespondToRequestInput) => Promise<void>;
stopSession: (input: ProviderStopSessionInput) => Promise<void>;
listSessions: () => Promise<ProviderSession[]>;
listCheckpoints: (
input: ProviderListCheckpointsInput,
) => Promise<ProviderListCheckpointsResult>;
@@ -107,6 +121,26 @@ export interface NativeApi {
revertToCheckpoint: (
input: ProviderRevertToCheckpointInput,
) => Promise<ProviderRevertToCheckpointResult>;
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
};
state: {
bootstrap: () => Promise<StateBootstrapResult>;
listMessages: (input: StateListMessagesInput) => Promise<StateListMessagesResult>;
catchUp: (input: StateCatchUpInput) => Promise<StateCatchUpResult>;
onEvent: (callback: (event: StateEvent) => void) => () => void;
};
appSettings: {
get: () => Promise<AppSettings>;
update: (input: AppSettingsUpdateInput) => Promise<AppSettings>;
};
threads: {
create: (input: ThreadsCreateInput) => 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>;
@@ -142,11 +176,4 @@ export interface NativeApi {
getConfig: () => Promise<ServerConfig>;
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
};
orchestration: {
getSnapshot: () => Promise<OrchestrationReadModel>;
dispatchCommand: (command: OrchestrationCommand) => Promise<{ sequence: number }>;
replayEvents: (fromSequenceExclusive: number) => Promise<OrchestrationEvent[]>;
onReadModel: (callback: (snapshot: OrchestrationReadModel) => void) => () => void;
onDomainEvent: (callback: (event: OrchestrationEvent) => void) => () => void;
};
}
-216
View File
@@ -1,216 +0,0 @@
import { Schema } from "effect";
export const ORCHESTRATION_WS_METHODS = {
getSnapshot: "orchestration.getSnapshot",
dispatchCommand: "orchestration.dispatchCommand",
replayEvents: "orchestration.replayEvents",
} as const;
export const ORCHESTRATION_WS_CHANNELS = {
readModel: "orchestration.readModel",
domainEvent: "orchestration.domainEvent",
} as const;
const IsoDateTimeSchema = Schema.String;
const IdSchema = Schema.String;
export const OrchestrationMessageSchema = Schema.Struct({
id: IdSchema,
role: Schema.Literals(["user", "assistant"]),
text: Schema.String,
createdAt: IsoDateTimeSchema,
streaming: Schema.Boolean,
});
export type OrchestrationMessage = Schema.Schema.Type<typeof OrchestrationMessageSchema>;
export const OrchestrationSessionSchema = Schema.Struct({
sessionId: IdSchema,
status: Schema.Literals(["connecting", "ready", "running", "error", "closed"]),
provider: Schema.Literals(["codex", "claudeCode"]),
threadId: IdSchema,
activeTurnId: Schema.NullOr(Schema.String),
createdAt: IsoDateTimeSchema,
updatedAt: IsoDateTimeSchema,
lastError: Schema.NullOr(Schema.String),
});
export type OrchestrationSession = Schema.Schema.Type<typeof OrchestrationSessionSchema>;
export const OrchestrationTurnDiffFileSchema = Schema.Struct({
path: Schema.String,
kind: Schema.optional(Schema.String),
additions: Schema.optional(Schema.Number),
deletions: Schema.optional(Schema.Number),
});
export type OrchestrationTurnDiffFile = Schema.Schema.Type<typeof OrchestrationTurnDiffFileSchema>;
export const OrchestrationTurnDiffSummarySchema = Schema.Struct({
turnId: IdSchema,
completedAt: IsoDateTimeSchema,
status: Schema.optional(Schema.String),
files: Schema.Array(OrchestrationTurnDiffFileSchema),
assistantMessageId: Schema.optional(Schema.String),
checkpointTurnCount: Schema.optional(Schema.Number),
});
export type OrchestrationTurnDiffSummary = Schema.Schema.Type<
typeof OrchestrationTurnDiffSummarySchema
>;
export const OrchestrationThreadSchema = Schema.Struct({
id: IdSchema,
projectId: IdSchema,
title: Schema.String,
model: Schema.String,
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
createdAt: IsoDateTimeSchema,
updatedAt: IsoDateTimeSchema,
latestTurnId: Schema.NullOr(Schema.String),
latestTurnStartedAt: Schema.NullOr(Schema.String),
latestTurnCompletedAt: Schema.NullOr(Schema.String),
latestTurnDurationMs: Schema.NullOr(Schema.Number),
messages: Schema.Array(OrchestrationMessageSchema),
session: Schema.NullOr(OrchestrationSessionSchema),
turnDiffSummaries: Schema.Array(OrchestrationTurnDiffSummarySchema),
error: Schema.NullOr(Schema.String),
});
export type OrchestrationThread = Schema.Schema.Type<typeof OrchestrationThreadSchema>;
export const OrchestrationGitReadModelSchema = Schema.Struct({
projectId: IdSchema,
branch: Schema.NullOr(Schema.String),
hasWorkingTreeChanges: Schema.Boolean,
aheadCount: Schema.Number,
behindCount: Schema.Number,
updatedAt: IsoDateTimeSchema,
});
export type OrchestrationGitReadModel = Schema.Schema.Type<typeof OrchestrationGitReadModelSchema>;
export const OrchestrationReadModelSchema = Schema.Struct({
sequence: Schema.Number,
threads: Schema.Array(OrchestrationThreadSchema),
gitByProjectId: Schema.Record( Schema.String, OrchestrationGitReadModelSchema),
updatedAt: IsoDateTimeSchema,
});
export type OrchestrationReadModel = Schema.Schema.Type<typeof OrchestrationReadModelSchema>;
export const CreateThreadCommandSchema = Schema.Struct({
type: Schema.Literal("thread.create"),
commandId: IdSchema,
threadId: IdSchema,
projectId: IdSchema,
title: Schema.String,
model: Schema.String,
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
createdAt: IsoDateTimeSchema,
});
export const DeleteThreadCommandSchema = Schema.Struct({
type: Schema.Literal("thread.delete"),
commandId: IdSchema,
threadId: IdSchema,
createdAt: IsoDateTimeSchema,
});
export const UpdateThreadMetaCommandSchema = Schema.Struct({
type: Schema.Literal("thread.meta.update"),
commandId: IdSchema,
threadId: IdSchema,
title: Schema.optional(Schema.String),
model: Schema.optional(Schema.String),
branch: Schema.optional(Schema.NullOr(Schema.String)),
worktreePath: Schema.optional(Schema.NullOr(Schema.String)),
createdAt: IsoDateTimeSchema,
});
export const SendMessageCommandSchema = Schema.Struct({
type: Schema.Literal("message.send"),
commandId: IdSchema,
threadId: IdSchema,
messageId: IdSchema,
role: Schema.Literals(["user", "assistant"]),
text: Schema.String,
streaming: Schema.optional(Schema.Boolean),
createdAt: IsoDateTimeSchema,
});
export const SetThreadSessionSchema = Schema.Struct({
type: Schema.Literal("thread.session"),
commandId: IdSchema,
threadId: IdSchema,
session: OrchestrationSessionSchema,
createdAt: IsoDateTimeSchema,
});
export const UpsertGitReadModelCommandSchema = Schema.Struct({
type: Schema.Literal("git.readModel.upsert"),
commandId: IdSchema,
projectId: IdSchema,
branch: Schema.NullOr(Schema.String),
hasWorkingTreeChanges: Schema.Boolean,
aheadCount: Schema.Number,
behindCount: Schema.Number,
createdAt: IsoDateTimeSchema,
});
export const CompleteThreadTurnDiffCommandSchema = Schema.Struct({
type: Schema.Literal("thread.turnDiff.complete"),
commandId: IdSchema,
threadId: IdSchema,
turnId: IdSchema,
completedAt: IsoDateTimeSchema,
status: Schema.optional(Schema.String),
files: Schema.Array(OrchestrationTurnDiffFileSchema),
assistantMessageId: Schema.optional(Schema.String),
checkpointTurnCount: Schema.optional(Schema.Number),
createdAt: IsoDateTimeSchema,
});
export const RevertThreadCommandSchema = Schema.Struct({
type: Schema.Literal("thread.revert"),
commandId: IdSchema,
threadId: IdSchema,
turnCount: Schema.Number,
messageCount: Schema.Number,
createdAt: IsoDateTimeSchema,
});
export const OrchestrationCommandSchema = Schema.Union([
CreateThreadCommandSchema,
DeleteThreadCommandSchema,
UpdateThreadMetaCommandSchema,
SendMessageCommandSchema,
SetThreadSessionSchema,
UpsertGitReadModelCommandSchema,
CompleteThreadTurnDiffCommandSchema,
RevertThreadCommandSchema,]
);
export type OrchestrationCommand = Schema.Schema.Type<typeof OrchestrationCommandSchema>;
export const OrchestrationEventSchema = Schema.Struct({
sequence: Schema.Number,
eventId: IdSchema,
type: Schema.String,
aggregateType: Schema.String,
aggregateId: Schema.String,
occurredAt: IsoDateTimeSchema,
commandId: Schema.NullOr(Schema.String),
payload: Schema.Unknown,
});
export type OrchestrationEvent = Schema.Schema.Type<typeof OrchestrationEventSchema>;
export const OrchestrationReadModelPushSchema = Schema.Struct({
sequence: Schema.Number,
snapshot: OrchestrationReadModelSchema,
});
export type OrchestrationReadModelPush = Schema.Schema.Type<typeof OrchestrationReadModelPushSchema>;
+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");
});
@@ -78,6 +80,8 @@ describe("providerSendTurnInputSchema", () => {
it("accepts image-only turns", () => {
const parsed = providerSendTurnInputSchema.parse({
sessionId: "sess_1",
clientMessageId: "msg_1",
clientMessageText: "",
attachments: [
{
type: "image",
@@ -89,6 +93,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(),
@@ -81,6 +82,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)
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { serverConfigSchema } from "./server";
describe("serverConfigSchema", () => {
it("defaults syncEngineMode to livestore when omitted", () => {
expect(
serverConfigSchema.parse({
cwd: "/workspace",
keybindings: [],
}),
).toEqual({
cwd: "/workspace",
syncEngineMode: "livestore",
keybindings: [],
});
});
it("accepts supported sync engine modes", () => {
expect(
serverConfigSchema.parse({
cwd: "/workspace",
syncEngineMode: "livestore-read-pilot",
keybindings: [],
}).syncEngineMode,
).toBe("livestore-read-pilot");
expect(
serverConfigSchema.parse({
cwd: "/workspace",
syncEngineMode: "shadow",
keybindings: [],
}).syncEngineMode,
).toBe("shadow");
expect(
serverConfigSchema.parse({
cwd: "/workspace",
syncEngineMode: "livestore",
keybindings: [],
}).syncEngineMode,
).toBe("livestore");
});
it("rejects unsupported sync engine mode values", () => {
expect(() =>
serverConfigSchema.parse({
cwd: "/workspace",
syncEngineMode: "something-else",
keybindings: [],
}),
).toThrow();
});
});
+3
View File
@@ -3,6 +3,9 @@ import { keybindingRuleSchema, resolvedKeybindingsConfigSchema } from "./keybind
export const serverConfigSchema = z.object({
cwd: z.string().min(1),
syncEngineMode: z
.enum(["legacy", "shadow", "livestore-read-pilot", "livestore"])
.default("livestore"),
keybindings: resolvedKeybindingsConfigSchema.default([]),
});
+120
View File
@@ -0,0 +1,120 @@
import { describe, expect, it } from "vitest";
import {
stateBootstrapResultSchema,
stateCatchUpInputSchema,
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 payloads", () => {
const catchUp = stateCatchUpInputSchema.parse({});
expect(catchUp.afterSeq).toBe(0);
});
});
+218
View File
@@ -0,0 +1,218 @@
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 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>;
+10
View File
@@ -0,0 +1,10 @@
import { describe, expect, it } from "vitest";
import { WS_METHODS } from "./ws";
describe("WS thread methods", () => {
it("exposes only canonical terminal state update method", () => {
expect(WS_METHODS.threadsUpdateTerminalState).toBe("threads.updateTerminalState");
expect("threadsUpdate" in WS_METHODS).toBe(false);
});
});
+19
View File
@@ -3,12 +3,29 @@ import { z } from "zod";
// ── WebSocket RPC Method Names ───────────────────────────────────────
export const WS_METHODS = {
// State methods
stateBootstrap: "state.bootstrap",
stateListMessages: "state.listMessages",
stateCatchUp: "state.catchUp",
appSettingsGet: "appSettings.get",
appSettingsUpdate: "appSettings.update",
// Thread methods
threadsCreate: "threads.create",
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",
providersInterruptTurn: "providers.interruptTurn",
providersRespondToRequest: "providers.respondToRequest",
providersStopSession: "providers.stopSession",
providersListSessions: "providers.listSessions",
providersListCheckpoints: "providers.listCheckpoints",
providersGetCheckpointDiff: "providers.getCheckpointDiff",
providersRevertToCheckpoint: "providers.revertToCheckpoint",
@@ -50,6 +67,8 @@ export const WS_METHODS = {
// ── Push Event Channels ──────────────────────────────────────────────
export const WS_CHANNELS = {
providerEvent: "providers.event",
stateEvent: "state.event",
terminalEvent: "terminal.event",
serverWelcome: "server.welcome",
} as const;