Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
470cabc110 | ||
|
|
5817848a17 | ||
|
|
30309855b0 | ||
|
|
6e7a8b92b0 | ||
|
|
ebd49ac5db | ||
|
|
c0158cb444 |
No files matched your search
@@ -10,4 +10,3 @@ packages/*/dist
|
||||
.env.local
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
@@ -1,482 +0,0 @@
|
||||
# Plan: Centralize Core Persistence in SQLite (`~/.t3/state.sqlite`)
|
||||
|
||||
## Summary
|
||||
Move durable core app state out of renderer `localStorage` and into a centralized SQLite database at `~/.t3/state.sqlite`, while keeping machine-level editable config in JSON (keybindings) and browser UX preferences in browser-scoped state by default.
|
||||
|
||||
This plan preserves existing checkpoint patch storage in Git (`refs/t3/checkpoints/...`) and adds optional checkpoint diff summaries in SQLite (parsed via `@pierre/diffs`) for fast UI metadata rendering.
|
||||
|
||||
Core migration goals:
|
||||
1. Data persistence scalability.
|
||||
2. Move as much logic and state control as possible to the server, keeping the frontend simple.
|
||||
|
||||
## Why This Revamp
|
||||
Current persistence is split across multiple stores:
|
||||
|
||||
- Renderer core state in `apps/web/src/store.ts` (`localStorage`, key `t3code:renderer-state:v7`)
|
||||
- Server project registry in `~/.t3/userdata/projects.json` (`apps/server/src/projectRegistry.ts`)
|
||||
- Provider thread event logs in `.logs/threads/*.events.ndjson` (`apps/server/src/providerManager.ts`)
|
||||
- Terminal history in `.logs/terminals/*.log` (`apps/server/src/terminalManager.ts`)
|
||||
- Keybindings in `~/.t3/keybindings.json` (`apps/server/src/keybindings.ts`)
|
||||
|
||||
This produces a split-brain model (client-local canonical thread/message state, server-local provider runtime state), weak multi-window consistency, and fragile reconnect/restart behavior.
|
||||
|
||||
## Goals
|
||||
1. Make SQLite the canonical durable store for core app entities:
|
||||
- projects
|
||||
- threads
|
||||
- messages
|
||||
- turn/checkpoint diff metadata (summary only)
|
||||
2. Keep checkpoint patch contents in Git only.
|
||||
3. Keep machine-level editable config in JSON files (keybindings), and keep browser UX preferences browser-scoped by default.
|
||||
4. Make server authoritative for durable state; client becomes a cache/subscriber.
|
||||
5. Support reliable reconnect/catch-up without `localStorage`.
|
||||
|
||||
## Non-Goals
|
||||
1. Replacing Git checkpoint storage with DB blob storage.
|
||||
2. Persisting raw terminal output into SQLite (keep file-based terminal history for now).
|
||||
3. Supporting provider implementations beyond current Codex flow in this revamp.
|
||||
4. Full event-sourcing rewrite of all UI state in v1.
|
||||
|
||||
## Data Classification and Storage Policy
|
||||
| Data class | Examples | Store | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| Core durable app data | projects, threads, messages, thread metadata, turn summaries | SQLite (`~/.t3/state.sqlite`) | Canonical source of truth |
|
||||
| Checkpoint patch content | unified diff between checkpoints | Git refs (`refs/t3/checkpoints/...`) | Existing `FilesystemCheckpointStore` remains |
|
||||
| Checkpoint metadata | changed files, +/- per file, checkpoint turn mapping | SQLite | Derived from Git diff + `@pierre/diffs` |
|
||||
| Machine-level editable config | keybindings | `~/.t3/keybindings.json` | Existing behavior, stays human-editable |
|
||||
| Browser-scoped UX preferences | theme, preferred editor, last-invoked script by project | Browser storage (currently `localStorage`) | Not canonical app data; per-browser behavior |
|
||||
| Volatile runtime state | active websocket connections, in-flight turn status, pending approvals | Memory | Rebuilt from runtime/provider events |
|
||||
|
||||
## Preference Scope Clarification
|
||||
1. `project.scripts` belongs to core app data and is persisted in SQLite with the project record.
|
||||
2. `script preference` means UX memory only, specifically the current `t3code:last-invoked-script-by-project` map used to preselect/run convenience actions.
|
||||
3. Theme/editor/script-preference keys are per-browser UX and are intentionally separate from shared project/thread/message data.
|
||||
4. Runtime mode default (`full-access` vs `approval-required`) should be treated as UX preference by default unless we explicitly decide it is a machine policy.
|
||||
|
||||
## Current vs Target Architecture
|
||||
### Current (simplified)
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI[apps/web] -->|ws rpc + push| WS[apps/server/wsServer]
|
||||
UI -->|localStorage| LS[(Browser localStorage)]
|
||||
WS --> PR[ProjectRegistry]
|
||||
PR --> PJ[projects.json]
|
||||
WS --> PM[ProviderManager]
|
||||
PM --> CASM[CodexAppServerManager]
|
||||
CASM --> C[codex app-server]
|
||||
PM --> TL[thread .ndjson logs]
|
||||
PM --> FCS[FilesystemCheckpointStore]
|
||||
FCS --> GIT[(Git refs/t3/checkpoints)]
|
||||
```
|
||||
|
||||
### Target
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI[apps/web] -->|ws rpc + push| WS[apps/server/wsServer]
|
||||
WS --> PS[PersistenceService]
|
||||
PS --> DB[(~/.t3/state.sqlite)]
|
||||
WS --> CFG[Keybinding Config]
|
||||
CFG --> JSON[(~/.t3/keybindings.json)]
|
||||
UI --> BSTATE[(Browser UX prefs)]
|
||||
WS --> PM[ProviderManager]
|
||||
PM --> CASM[CodexAppServerManager]
|
||||
CASM --> C[codex app-server]
|
||||
PM --> FCS[FilesystemCheckpointStore]
|
||||
FCS --> GIT[(Git refs/t3/checkpoints)]
|
||||
PM --> PS
|
||||
PS -->|state push| WS
|
||||
```
|
||||
|
||||
Provider remains the runtime execution engine. PersistenceService becomes the durable state authority and broadcaster.
|
||||
|
||||
## Core Domain Model (SQLite)
|
||||
Use strict schema + migrations (e.g. `PRAGMA user_version` or migration table), WAL mode, and transactional writes.
|
||||
|
||||
### JSON-first (iteration-friendly) schema
|
||||
Use a document-style core table with a minimal indexed envelope. Put evolving entity fields in `data_json`.
|
||||
|
||||
1. `documents`
|
||||
- `id TEXT PRIMARY KEY`
|
||||
- examples: `project:<uuid>`, `thread:<uuid>`, `message:<uuid>`, `turn_summary:<threadId>:<turnId>`
|
||||
- `kind TEXT NOT NULL`
|
||||
- `project` | `thread` | `message` | `turn_summary`
|
||||
- `project_id TEXT NULL`
|
||||
- `thread_id TEXT NULL`
|
||||
- `sort_key INTEGER NULL`
|
||||
- message order, thread ordering hints, summary ordering, etc.
|
||||
- `schema_version INTEGER NOT NULL DEFAULT 1`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- `data_json TEXT NOT NULL`
|
||||
|
||||
2. `provider_events`
|
||||
- `seq INTEGER PRIMARY KEY AUTOINCREMENT`
|
||||
- `id TEXT NOT NULL UNIQUE`
|
||||
- `session_id TEXT NOT NULL`
|
||||
- `provider TEXT NOT NULL`
|
||||
- `kind TEXT NOT NULL`
|
||||
- `method TEXT NOT NULL`
|
||||
- `thread_id TEXT NULL`
|
||||
- `turn_id TEXT NULL`
|
||||
- `item_id TEXT NULL`
|
||||
- `request_id TEXT NULL`
|
||||
- `request_kind TEXT NULL`
|
||||
- `text_delta TEXT NULL`
|
||||
- `message TEXT NULL`
|
||||
- `payload_json TEXT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
|
||||
3. `state_events`
|
||||
- `seq INTEGER PRIMARY KEY AUTOINCREMENT`
|
||||
- `event_type TEXT NOT NULL` (e.g. `project.upsert`, `thread.delete`, `message.upsert`)
|
||||
- `entity_id TEXT NOT NULL`
|
||||
- `payload_json TEXT NOT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
|
||||
4. `metadata`
|
||||
- `key TEXT PRIMARY KEY`
|
||||
- `value_json TEXT NOT NULL`
|
||||
- for one-time migrations/import markers
|
||||
|
||||
### Envelope indexes
|
||||
- `documents(kind)`
|
||||
- `documents(project_id, kind)`
|
||||
- `documents(thread_id, kind, sort_key)`
|
||||
- `documents(kind, updated_at DESC)`
|
||||
- `provider_events(session_id, seq)`
|
||||
- `provider_events(thread_id, seq)`
|
||||
- `state_events(seq)`
|
||||
|
||||
### Document conventions
|
||||
1. Validate each `kind` with Zod before writes and after reads.
|
||||
2. Keep envelope fields stable (`kind`, `project_id`, `thread_id`, `sort_key`) for fast list/filter queries.
|
||||
3. Put fast-changing/evolving structure in `data_json`:
|
||||
- project: name/cwd/model/expanded/scripts
|
||||
- thread: title/model/codex thread id/terminal layout/branch/worktree
|
||||
- message: role/text/attachments/streaming/provider ids
|
||||
- turn_summary: completed/status/checkpoint turn count/file +/- summary
|
||||
4. Use `schema_version` per document to support incremental document migrations without global table churn.
|
||||
|
||||
### Normalization runway (later, optional)
|
||||
When model shapes stabilize, we can materialize normalized tables from `documents` without changing the external protocol:
|
||||
1. Add typed read models (`projects_v2`, `messages_v2`, etc.).
|
||||
2. Backfill from `documents`.
|
||||
3. Switch read paths gradually.
|
||||
|
||||
## Streaming Protocol and Synchronization
|
||||
Keep current WS request/response envelope and push model. Extend with state snapshot + patch stream.
|
||||
|
||||
### New/extended WS methods
|
||||
1. `state.bootstrap`
|
||||
- returns complete durable snapshot for initial render:
|
||||
- projects (+scripts)
|
||||
- threads (+terminal metadata + turn summaries)
|
||||
- messages (+attachments), optionally capped per thread then paged
|
||||
- `lastStateSeq`
|
||||
|
||||
2. `state.listMessages` (paged)
|
||||
- for large threads and virtualized history
|
||||
|
||||
3. `threads.create`
|
||||
4. `threads.update`
|
||||
5. `threads.delete`
|
||||
6. `threads.markVisited`
|
||||
7. `threads.updateTerminalState`
|
||||
8. `threads.updateModel`
|
||||
9. `threads.updateTitle`
|
||||
|
||||
10. `state.catchUp`
|
||||
- input: `afterSeq`
|
||||
- returns ordered `state_events` for reconnect recovery
|
||||
|
||||
Existing `projects.*`, `providers.*`, `terminal.*`, `git.*`, `server.*` remain; they route through persistence-aware services.
|
||||
|
||||
### Push channels
|
||||
1. Keep `providers.event` for raw runtime/provider telemetry.
|
||||
2. Add `state.event` for canonical persisted mutations (`seq` ordered).
|
||||
3. Keep `terminal.event` and `server.welcome`.
|
||||
|
||||
### Ordering guarantees
|
||||
- Every durable mutation writes `state_events` in the same DB transaction as row changes.
|
||||
- Server broadcasts `state.event` after commit.
|
||||
- Clients apply events strictly by `seq`.
|
||||
- Reconnect uses `state.catchUp(afterSeq)` to fill gaps.
|
||||
|
||||
## Core App Flows
|
||||
### 1) Startup + hydration
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Web Client
|
||||
participant WS as wsServer
|
||||
participant PS as PersistenceService
|
||||
participant DB as SQLite
|
||||
|
||||
UI->>WS: connect websocket
|
||||
WS-->>UI: push server.welcome
|
||||
UI->>WS: state.bootstrap()
|
||||
WS->>PS: loadSnapshot()
|
||||
PS->>DB: SELECT projects/threads/messages/metadata
|
||||
DB-->>PS: snapshot + lastStateSeq
|
||||
PS-->>WS: bootstrap payload
|
||||
WS-->>UI: response(snapshot)
|
||||
UI->>WS: subscribe state.event/providers.event
|
||||
```
|
||||
|
||||
### 2) Create thread
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI
|
||||
participant WS
|
||||
participant PS
|
||||
participant DB
|
||||
|
||||
UI->>WS: threads.create(projectId, model, title, branch,...)
|
||||
WS->>PS: createThread(...)
|
||||
PS->>DB: INSERT thread + terminal defaults + state_event
|
||||
DB-->>PS: committed row + seq
|
||||
PS-->>WS: thread
|
||||
WS-->>UI: response(thread)
|
||||
WS-->>UI: push state.event(thread.upsert, seq)
|
||||
```
|
||||
|
||||
### 3) Send turn + stream + persist
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI
|
||||
participant WS
|
||||
participant PM as ProviderManager
|
||||
participant CASM as CodexAppServerManager
|
||||
participant Codex as codex app-server
|
||||
participant PS as PersistenceService
|
||||
participant DB as SQLite
|
||||
|
||||
UI->>WS: providers.startSession(threadId, resumeThreadId?)
|
||||
WS->>PM: startSession(...)
|
||||
PM->>CASM: thread/start or thread/resume
|
||||
CASM->>Codex: JSON-RPC
|
||||
Codex-->>CASM: notifications/events
|
||||
CASM-->>PM: ProviderEvent
|
||||
PM-->>PS: ingestProviderEvent(event)
|
||||
PS->>DB: INSERT provider_events + projection updates + state_event
|
||||
DB-->>PS: seq
|
||||
PM-->>WS: provider event
|
||||
WS-->>UI: push providers.event
|
||||
WS-->>UI: push state.event
|
||||
|
||||
UI->>WS: providers.sendTurn(sessionId, input, attachments)
|
||||
WS->>PM: sendTurn(...)
|
||||
PM->>CASM: turn/start
|
||||
CASM->>Codex: JSON-RPC
|
||||
```
|
||||
|
||||
### 4) Checkpoint capture + diff summary
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant PM as ProviderManager
|
||||
participant FCS as FilesystemCheckpointStore
|
||||
participant G as Git refs/t3/checkpoints
|
||||
participant PS as PersistenceService
|
||||
participant DB as SQLite
|
||||
participant WS as wsServer
|
||||
participant UI as Web Client
|
||||
|
||||
PM->>FCS: captureCheckpoint(threadId, turnCount)
|
||||
FCS->>G: update-ref refs/t3/checkpoints/...
|
||||
PM->>FCS: diffCheckpoints(turnCount-1, turnCount)
|
||||
FCS-->>PM: unified patch
|
||||
PM->>PS: persistTurnDiffSummary(turnId, patch)
|
||||
PS->>PS: parse patch with @pierre/diffs
|
||||
PS->>DB: upsert thread_turn_summaries + thread_turn_diff_files + state_event
|
||||
DB-->>PS: seq
|
||||
PS-->>WS: state.event(turn summary upsert)
|
||||
WS-->>UI: push state.event
|
||||
```
|
||||
|
||||
## Provider Role in the New Model
|
||||
Provider components are unchanged in purpose, but persistence boundaries become explicit:
|
||||
|
||||
1. `CodexAppServerManager`
|
||||
- runtime bridge to `codex app-server`
|
||||
- emits provider events
|
||||
- no direct durability ownership
|
||||
|
||||
2. `ProviderManager`
|
||||
- session lifecycle + checkpoint orchestration
|
||||
- forwards provider events to:
|
||||
- websocket push (`providers.event`)
|
||||
- persistence projection (`PersistenceService`)
|
||||
|
||||
3. `PersistenceService` (new)
|
||||
- canonicalizes thread/message state
|
||||
- stores provider event log
|
||||
- stores turn summary metadata
|
||||
- emits `state.event` patches
|
||||
|
||||
This cleanly separates runtime execution concerns from durable conversation state.
|
||||
|
||||
## Client Data Flow (Server -> Client)
|
||||
### Current issue
|
||||
- Web client computes and persists canonical messages/thread state locally (`reducer`, `applyEventToMessages`, `deriveTurnDiffSummaries`), so reconnect and multi-window consistency rely on localStorage.
|
||||
|
||||
### New flow
|
||||
1. Client bootstraps from server (`state.bootstrap`) instead of localStorage hydration.
|
||||
2. Client uses `state.event` as authoritative mutation stream.
|
||||
3. Client may still use optimistic UI for latency, but server-issued canonical IDs/rows win.
|
||||
4. `providers.event` remains for live UX details (in-progress deltas, approvals, lifecycle).
|
||||
|
||||
## Migration Plan
|
||||
### A) Server-side source migrations
|
||||
1. Introduce DB migration runner.
|
||||
2. On startup, import `projects.json` into SQLite if present and not yet imported.
|
||||
3. Preserve `projects.json` as backup:
|
||||
- rename to `projects.json.bak.<timestamp>`
|
||||
4. Keep keybindings migration path untouched (`~/.t3/keybindings.json` remains canonical).
|
||||
|
||||
### B) Client-side legacy state migration
|
||||
1. Detect legacy localStorage keys:
|
||||
- `t3code:renderer-state:v7` and legacy list in `apps/web/src/store.ts`
|
||||
2. Add one-time method `state.importLegacyRendererState(payload)`.
|
||||
3. Server validates and sanitizes payload with shared schema (port from `apps/web/src/persistenceSchema.ts` to contracts/server module).
|
||||
4. Server upserts projects/threads/messages/terminal metadata into SQLite.
|
||||
5. Server writes `metadata` marker to prevent duplicate imports.
|
||||
6. Client clears legacy localStorage keys after successful import.
|
||||
|
||||
### C) Browser UX preference boundary
|
||||
Default behavior: keep these browser-scoped and do not move them into SQLite or `~/.t3/*.json`:
|
||||
- `t3code:theme`
|
||||
- `t3code:last-editor`
|
||||
- `t3code:last-invoked-script-by-project`
|
||||
|
||||
Optional future mode (not required for this revamp):
|
||||
- Add server-backed preferences storage for users who want zero browser persistence.
|
||||
|
||||
## Implementation Phases
|
||||
### Phase 0: Foundation
|
||||
1. Add SQLite dependency and persistence modules:
|
||||
- `apps/server/src/stateDb.ts`
|
||||
- `apps/server/src/stateMigrations.ts`
|
||||
- `apps/server/src/persistenceService.ts`
|
||||
2. Add migration boot in `apps/server/src/index.ts`.
|
||||
3. Update default state path to `~/.t3/state.sqlite` (with env override).
|
||||
|
||||
### Phase 1: Document store cut-in (projects + threads first)
|
||||
1. Replace `ProjectRegistry` JSON backend with DB-backed document repository.
|
||||
2. Add `threads.*` methods to server routes.
|
||||
3. Keep web reducer but stop writing to localStorage for these entities.
|
||||
|
||||
### Phase 2: Message + turn document persistence
|
||||
1. Ingest provider events into DB (`provider_events`).
|
||||
2. Project events into `documents` rows for `message` and `turn_summary` kinds.
|
||||
3. Add `state.event` push and `state.catchUp`.
|
||||
|
||||
### Phase 3: Web client cutover
|
||||
1. Replace `readPersistedState()` boot path with `state.bootstrap`.
|
||||
2. Remove `persistState()` localStorage writes for core state.
|
||||
3. Keep only in-memory reducer/cache for volatile UI fields.
|
||||
|
||||
### Phase 4: Preference boundary hardening
|
||||
1. Keep `~/.t3/keybindings.json` as the only required JSON config in this revamp.
|
||||
2. Keep `theme` / `last-editor` / `last-invoked-script-by-project` browser-scoped (explicitly non-canonical).
|
||||
3. Ensure no core entity (`projects`, `threads`, `messages`, turn summaries) is read from or written to browser storage.
|
||||
|
||||
### Phase 5: Cleanup + compatibility
|
||||
1. Remove deprecated localStorage/persistence schema paths once migration is stable.
|
||||
2. Keep temporary migration fallback for one release window.
|
||||
3. (Optional) add a follow-up normalization milestone when schemas settle.
|
||||
|
||||
## Streaming/Projection Design Notes
|
||||
1. Durable append:
|
||||
- always append raw provider events first.
|
||||
2. Projection:
|
||||
- update message/thread projections in the same transaction when practical.
|
||||
- if expensive, queue projection jobs but keep deterministic ordering by provider event `seq`.
|
||||
3. Backpressure:
|
||||
- avoid heavyweight diff parsing on hot delta path.
|
||||
- compute checkpoint diff summaries only on checkpoint/turn completion.
|
||||
|
||||
## Reliability and Performance Settings
|
||||
1. SQLite pragmas:
|
||||
- `journal_mode=WAL`
|
||||
- `synchronous=FULL` (or `NORMAL` only if validated under load)
|
||||
- `busy_timeout=5000`
|
||||
- `foreign_keys=ON`
|
||||
2. Prepared statements for hot paths.
|
||||
3. Batch/paginate message retrieval for large threads.
|
||||
4. Add caps/retention for `provider_events` if DB growth becomes material.
|
||||
|
||||
## Testing Plan
|
||||
Backend changes require new tests and runtime validation.
|
||||
|
||||
### Unit tests
|
||||
1. DB schema + migrations
|
||||
2. Document repository CRUD (`project`/`thread`/`message`/`turn_summary`)
|
||||
3. Provider event projection logic
|
||||
4. Checkpoint summary parser (`@pierre/diffs` integration and malformed diff fallback)
|
||||
5. Keybindings JSON behavior remains unchanged (read/write + malformed-file handling)
|
||||
|
||||
### Integration tests (`wsServer`)
|
||||
1. `state.bootstrap` returns canonical snapshot
|
||||
2. `state.event` emits ordered `seq`
|
||||
3. reconnect + `state.catchUp` replays missing events
|
||||
4. `providers.event` + `state.event` coherence on a streamed turn
|
||||
5. localStorage import endpoint idempotence
|
||||
|
||||
### Migration tests
|
||||
1. `projects.json` import -> DB rows
|
||||
2. localStorage v7 import -> DB rows
|
||||
3. legacy payload rejection safety
|
||||
|
||||
### Frontend tests
|
||||
1. store boot without localStorage core snapshot
|
||||
2. reducer handling of `state.event` patches
|
||||
3. fallback behavior when server unavailable
|
||||
|
||||
## Risks and Mitigations
|
||||
1. Risk: Split writes between provider stream and DB create race conditions.
|
||||
- Mitigation: single persistence ingestion queue per session/thread, transactional writes, monotonic `seq`.
|
||||
2. Risk: Message duplication with optimistic UI.
|
||||
- Mitigation: client-supplied message IDs echoed by server; idempotent upserts.
|
||||
3. Risk: DB write amplification on text deltas.
|
||||
- Mitigation: append-only provider event log + projection throttling/finalization.
|
||||
4. Risk: migration corruption from malformed local data.
|
||||
- Mitigation: strict schema validation + partial-row rejection + migration markers + backups.
|
||||
5. Risk: checkpoint summary parsing overhead.
|
||||
- Mitigation: parse only finalized checkpoint ranges and fallback to lightweight stat extraction.
|
||||
6. Risk: JSON shape drift across fast iterations.
|
||||
- Mitigation: per-kind Zod schemas + `schema_version` in documents + migration tests for older payloads.
|
||||
|
||||
## Done Criteria
|
||||
1. No core durable app data depends on renderer localStorage.
|
||||
2. Projects/threads/messages/turn summaries persist in `~/.t3/state.sqlite` via JSON-first documents.
|
||||
3. Checkpoint patch content remains Git-backed; optional summaries are in DB.
|
||||
4. Keybindings remain JSON-backed at `~/.t3/keybindings.json`.
|
||||
5. Theme/editor/last-invoked-script remain browser-scoped (or explicitly migrated in a separate opt-in feature).
|
||||
6. App reload/reconnect reconstructs state from server snapshot + event catch-up.
|
||||
7. Lint/typecheck/tests pass across server/web/contracts.
|
||||
|
||||
## Concrete File Impact (Expected)
|
||||
### Server
|
||||
- `apps/server/src/index.ts` (state db path + bootstrap)
|
||||
- `apps/server/src/wsServer.ts` (new state/thread routes + push channel)
|
||||
- `apps/server/src/providerManager.ts` (persist event hooks + checkpoint summary writes)
|
||||
- `apps/server/src/projectRegistry.ts` (replace or wrap with document-backed repo)
|
||||
- new persistence modules (`stateDb`, migrations, document repository, persistence service)
|
||||
|
||||
### Web
|
||||
- `apps/web/src/store.ts` (remove localStorage core persistence)
|
||||
- `apps/web/src/persistenceSchema.ts` (migration-only use then eventual removal)
|
||||
- `apps/web/src/routes/__root.tsx` (state bootstrap and catch-up wiring)
|
||||
- `apps/web/src/wsNativeApi.ts` / contracts (new methods/channels)
|
||||
- preference callsites remain browser-scoped by default (`useTheme`, editor/script preference keys)
|
||||
|
||||
### Contracts
|
||||
- `packages/contracts/src/ws.ts` (new methods/channels)
|
||||
- `packages/contracts/src/ipc.ts` (new NativeApi sections for state/threads)
|
||||
- new schemas for thread/message/state-event payloads
|
||||
|
||||
## Open Questions
|
||||
1. Should runtime mode (`full-access` vs `approval-required`) remain browser-scoped UX state, or be elevated to machine policy?
|
||||
2. Should terminal panel layout/state be in SQLite (shared) or stay browser-scoped UX state?
|
||||
3. Do we need provider event retention limits from day one?
|
||||
4. Do we keep `.logs/threads/*.events.ndjson` as debug mirror after DB event log is live?
|
||||
5. For non-desktop/browser mode, should state still centralize to `~/.t3/state.sqlite` or support workspace-local override by default?
|
||||
@@ -1,129 +0,0 @@
|
||||
# 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.
|
||||
@@ -10,5 +10,3 @@
|
||||
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`
|
||||
@@ -56,9 +56,6 @@ T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
|
||||
bun run build
|
||||
bun run start
|
||||
|
||||
# Build a shareable macOS .dmg (arm64 by default)
|
||||
bun run dist:desktop:dmg
|
||||
|
||||
# Or from any project directory after publishing:
|
||||
npx t3
|
||||
```
|
||||
@@ -72,17 +69,6 @@ npx t3
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
|
||||
### Running multiple dev instances
|
||||
|
||||
@@ -101,45 +87,6 @@ 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:
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
# 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.
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
## Small things
|
||||
|
||||
- [ ] Plan mode
|
||||
- [ ] Submitting new messages should scroll to bottom
|
||||
- [ ] 1 click copy in codeblocks
|
||||
- [x] Pasting/adding images to submit with prompts
|
||||
- [ ] Only show last 10 threads for a given project
|
||||
@@ -14,7 +12,7 @@
|
||||
- [x] "Response" bar should ONLY appear on work completed
|
||||
- [x] "Response" bar should ONLY appear above the FINAL message in a series
|
||||
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
|
||||
- [x] Insta focus input on new thread creation
|
||||
- [ ] Insta focus input on new thread creation
|
||||
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||
- [x] Making new thread should auto-focus input box
|
||||
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
|
||||
|
||||
@@ -1,2 +1 @@
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
@@ -2,20 +2,19 @@
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"productName": "T3 Code (Alpha)",
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "bun run scripts/start-electron.mjs",
|
||||
"start": "electron dist-electron/main.js",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"electron": "40.6.0"
|
||||
"electron": "33.4.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.2",
|
||||
|
||||
|
Before Width: | Height: | Size: 279 KiB |
|
Before Width: | Height: | Size: 313 KiB |
@@ -1,10 +1,7 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import electronmon from "electronmon";
|
||||
import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
|
||||
@@ -17,57 +14,18 @@ await waitOn({
|
||||
],
|
||||
});
|
||||
|
||||
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const monitor = await electronmon({
|
||||
cwd: desktopDir,
|
||||
args: ["dist-electron/main.js"],
|
||||
const child = spawn(command, ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
electronPath: resolveElectronPath(),
|
||||
});
|
||||
|
||||
let shuttingDown = false;
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
async function shutdown(exitCode) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
try {
|
||||
await Promise.race([
|
||||
monitor.destroy(),
|
||||
new Promise((resolve) => setTimeout(resolve, 1_500)),
|
||||
]);
|
||||
} catch {
|
||||
// Best effort only; fallback process kill below handles stubborn children.
|
||||
}
|
||||
|
||||
killChildTree("TERM");
|
||||
setTimeout(() => {
|
||||
killChildTree("KILL");
|
||||
}, 1_200).unref();
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void shutdown(130);
|
||||
});
|
||||
process.once("SIGTERM", () => {
|
||||
void shutdown(143);
|
||||
});
|
||||
process.once("SIGHUP", () => {
|
||||
void shutdown(129);
|
||||
child.on("exit", (code) => {
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
@@ -1,173 +0,0 @@
|
||||
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
copyFileSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 1;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = spawnSync(
|
||||
"plutil",
|
||||
["-replace", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (replaceResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertResult = spawnSync(
|
||||
"plutil",
|
||||
["-insert", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (insertResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const details = [replaceResult.stderr, insertResult.stderr]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
throw new Error(
|
||||
`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
|
||||
|
||||
const resourcesDir = join(appBundlePath, "Contents", "Resources");
|
||||
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
|
||||
if (!existsSync(frameworksDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
|
||||
continue;
|
||||
}
|
||||
if (!entry.name.startsWith("Electron Helper")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const helperPlistPath = join(
|
||||
frameworksDir,
|
||||
entry.name,
|
||||
"Contents",
|
||||
"Info.plist",
|
||||
);
|
||||
if (!existsSync(helperPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suffix = entry.name
|
||||
.replace("Electron Helper", "")
|
||||
.replace(".app", "")
|
||||
.trim();
|
||||
const helperName = suffix
|
||||
? `${APP_DISPLAY_NAME} Helper ${suffix}`
|
||||
: `${APP_DISPLAY_NAME} Helper`;
|
||||
const helperIdSuffix = suffix
|
||||
.replace(/[()]/g, "")
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, "-");
|
||||
const helperBundleId = helperIdSuffix
|
||||
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
|
||||
: `${APP_BUNDLE_ID}.helper`;
|
||||
|
||||
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = resolve(electronBinaryPath, "../../..");
|
||||
const runtimeDir = join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = join(
|
||||
targetAppBundlePath,
|
||||
"Contents",
|
||||
"MacOS",
|
||||
"Electron",
|
||||
);
|
||||
const iconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
const expectedMetadata = {
|
||||
launcherVersion: LAUNCHER_VERSION,
|
||||
sourceAppBundlePath,
|
||||
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
|
||||
iconMtimeMs: statSync(iconPath).mtimeMs,
|
||||
};
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
existsSync(targetBinaryPath) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
process.kill(process.pid, signal);
|
||||
return;
|
||||
}
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
@@ -5,16 +5,7 @@ import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
dialog,
|
||||
ipcMain,
|
||||
Menu,
|
||||
type MenuItemConstructorOptions,
|
||||
protocol,
|
||||
shell,
|
||||
} from "electron";
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { fixPath } from "./fixPath";
|
||||
@@ -25,13 +16,11 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
|
||||
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
|
||||
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess | null = null;
|
||||
@@ -41,235 +30,6 @@ let backendWsUrl = "";
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
let desktopProtocolRegistered = false;
|
||||
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
function resolveAppRoot(): string {
|
||||
if (!app.isPackaged) {
|
||||
return ROOT_DIR;
|
||||
}
|
||||
return app.getAppPath();
|
||||
}
|
||||
|
||||
function resolveBackendEntry(): string {
|
||||
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
}
|
||||
|
||||
function resolveBackendCwd(): string {
|
||||
if (!app.isPackaged) {
|
||||
return resolveAppRoot();
|
||||
}
|
||||
return os.homedir();
|
||||
}
|
||||
|
||||
function resolveDesktopStaticDir(): string | null {
|
||||
const appRoot = resolveAppRoot();
|
||||
const candidates = [
|
||||
path.join(appRoot, "apps/server/dist/client"),
|
||||
path.join(appRoot, "apps/web/dist"),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(path.join(candidate, "index.html"))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
|
||||
const url = new URL(requestUrl);
|
||||
const rawPath = decodeURIComponent(url.pathname);
|
||||
const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
|
||||
if (normalizedPath.includes("..")) {
|
||||
return path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
|
||||
const resolvedPath = path.join(staticRoot, requestedPath);
|
||||
|
||||
if (path.extname(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
const nestedIndex = path.join(resolvedPath, "index.html");
|
||||
if (fs.existsSync(nestedIndex)) {
|
||||
return nestedIndex;
|
||||
}
|
||||
|
||||
return path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function registerDesktopProtocol(): void {
|
||||
if (isDevelopment || desktopProtocolRegistered) return;
|
||||
|
||||
const staticRoot = resolveDesktopStaticDir();
|
||||
if (!staticRoot) {
|
||||
throw new Error("Desktop static bundle missing. Build apps/server (with bundled client) first.");
|
||||
}
|
||||
|
||||
const staticRootResolved = path.resolve(staticRoot);
|
||||
const staticRootPrefix = `${staticRootResolved}${path.sep}`;
|
||||
const fallbackIndex = path.join(staticRootResolved, "index.html");
|
||||
|
||||
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
|
||||
try {
|
||||
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
|
||||
const resolvedCandidate = path.resolve(candidate);
|
||||
const isInRoot =
|
||||
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
|
||||
const isAssetRequest = isStaticAssetRequest(request.url);
|
||||
|
||||
if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
|
||||
if (isAssetRequest) {
|
||||
callback({ error: -6 });
|
||||
return;
|
||||
}
|
||||
callback({ path: fallbackIndex });
|
||||
return;
|
||||
}
|
||||
|
||||
callback({ path: resolvedCandidate });
|
||||
} catch {
|
||||
callback({ path: fallbackIndex });
|
||||
}
|
||||
});
|
||||
|
||||
desktopProtocolRegistered = true;
|
||||
}
|
||||
|
||||
function dispatchMenuAction(action: string): void {
|
||||
const existingWindow = BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
|
||||
const targetWindow = existingWindow ?? createWindow();
|
||||
if (!existingWindow) {
|
||||
mainWindow = targetWindow;
|
||||
}
|
||||
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
|
||||
if (!targetWindow.isVisible()) {
|
||||
targetWindow.show();
|
||||
}
|
||||
targetWindow.focus();
|
||||
};
|
||||
|
||||
if (targetWindow.webContents.isLoadingMainFrame()) {
|
||||
targetWindow.webContents.once("did-finish-load", send);
|
||||
return;
|
||||
}
|
||||
|
||||
send();
|
||||
}
|
||||
|
||||
function configureApplicationMenu(): void {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
template.push({
|
||||
label: app.name,
|
||||
submenu: [
|
||||
{ role: "about" },
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => dispatchMenuAction("open-settings"),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ role: "services" },
|
||||
{ type: "separator" },
|
||||
{ role: "hide" },
|
||||
{ role: "hideOthers" },
|
||||
{ role: "unhide" },
|
||||
{ type: "separator" },
|
||||
{ role: "quit" },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
template.push(
|
||||
{
|
||||
label: "File",
|
||||
submenu: [
|
||||
...(process.platform === "darwin"
|
||||
? []
|
||||
: [
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => dispatchMenuAction("open-settings"),
|
||||
},
|
||||
{ type: "separator" as const },
|
||||
]),
|
||||
{ role: process.platform === "darwin" ? "close" : "quit" },
|
||||
],
|
||||
},
|
||||
{ role: "editMenu" },
|
||||
{ role: "viewMenu" },
|
||||
{ role: "windowMenu" },
|
||||
);
|
||||
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||
}
|
||||
|
||||
function resolveResourcePath(fileName: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, "../resources", fileName),
|
||||
path.join(process.resourcesPath, "resources", fileName),
|
||||
path.join(process.resourcesPath, fileName),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
|
||||
return resolveResourcePath(`icon.${ext}`);
|
||||
}
|
||||
|
||||
function configureAppIdentity(): void {
|
||||
app.setName(APP_DISPLAY_NAME);
|
||||
app.setAboutPanelOptions({
|
||||
applicationName: APP_DISPLAY_NAME,
|
||||
});
|
||||
|
||||
if (process.platform === "win32") {
|
||||
app.setAppUserModelId(APP_USER_MODEL_ID);
|
||||
}
|
||||
|
||||
if (process.platform === "darwin" && app.dock) {
|
||||
const iconPath = resolveIconPath("png");
|
||||
if (iconPath) {
|
||||
app.dock.setIcon(iconPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -300,42 +60,6 @@ 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;
|
||||
|
||||
@@ -352,16 +76,19 @@ function scheduleBackendRestart(reason: string): void {
|
||||
function startBackend(): void {
|
||||
if (isQuitting || backendProcess) return;
|
||||
|
||||
const backendEntry = resolveBackendEntry();
|
||||
if (!fs.existsSync(backendEntry)) {
|
||||
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
|
||||
if (!fs.existsSync(BACKEND_ENTRY)) {
|
||||
scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const launch = resolveBackendLaunch(backendEntry);
|
||||
const child = spawn(launch.command, launch.args, {
|
||||
cwd: resolveBackendCwd(),
|
||||
env: launch.env,
|
||||
const child = spawn(process.execPath, [BACKEND_ENTRY], {
|
||||
cwd: ROOT_DIR,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
stdio: "inherit",
|
||||
});
|
||||
backendProcess = child;
|
||||
@@ -397,10 +124,10 @@ function stopBackend(): void {
|
||||
backendProcess = null;
|
||||
if (!child) return;
|
||||
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
if (!child.killed) {
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
if (!child.killed) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, 2_000).unref();
|
||||
@@ -477,13 +204,6 @@ function registerIpcHandlers(): void {
|
||||
});
|
||||
}
|
||||
|
||||
function getIconOption(): { icon: string } | Record<string, never> {
|
||||
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = process.platform === "win32" ? "ico" : "png";
|
||||
const iconPath = resolveIconPath(ext);
|
||||
return iconPath ? { icon: iconPath } : {};
|
||||
}
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
width: 1100,
|
||||
@@ -492,8 +212,6 @@ function createWindow(): BrowserWindow {
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
webPreferences: {
|
||||
@@ -505,13 +223,6 @@ function createWindow(): BrowserWindow {
|
||||
});
|
||||
|
||||
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
|
||||
window.on("page-title-updated", (event) => {
|
||||
event.preventDefault();
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
});
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
});
|
||||
window.once("ready-to-show", () => {
|
||||
window.show();
|
||||
});
|
||||
@@ -520,7 +231,10 @@ function createWindow(): BrowserWindow {
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
|
||||
if (!fs.existsSync(WEB_ENTRY)) {
|
||||
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
|
||||
}
|
||||
void window.loadFile(WEB_ENTRY);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -532,8 +246,6 @@ function createWindow(): BrowserWindow {
|
||||
return window;
|
||||
}
|
||||
|
||||
configureAppIdentity();
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
backendPort = await reserveLoopbackPort();
|
||||
backendAuthToken = randomBytes(24).toString("hex");
|
||||
@@ -551,9 +263,6 @@ app.on("before-quit", () => {
|
||||
});
|
||||
|
||||
app.whenReady().then(() => {
|
||||
configureAppIdentity();
|
||||
configureApplicationMenu();
|
||||
registerDesktopProtocol();
|
||||
void bootstrap();
|
||||
|
||||
app.on("activate", () => {
|
||||
@@ -568,19 +277,3 @@ app.on("window-all-closed", () => {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
if (process.platform !== "win32") {
|
||||
process.on("SIGINT", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
stopBackend();
|
||||
app.quit();
|
||||
});
|
||||
|
||||
process.on("SIGTERM", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
stopBackend();
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
@@ -4,7 +4,6 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
@@ -14,15 +13,4 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
showContextMenu: (items: { id: string; label: string }[]) =>
|
||||
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
|
||||
onMenuAction: (listener: (action: string) => void) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
if (typeof action !== "string") return;
|
||||
listener(action);
|
||||
};
|
||||
|
||||
ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -17,9 +17,6 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@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"
|
||||
|
||||
@@ -163,14 +163,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const codexBinaryPath = input.codexBinaryPath?.trim() || "codex";
|
||||
const codexHomePath = input.codexHomePath?.trim();
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
const child = spawn("codex", ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
env: process.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
@@ -617,32 +617,6 @@ describe("git integration", () => {
|
||||
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
|
||||
expect(existsSync(wtPath)).toBe(false);
|
||||
});
|
||||
|
||||
it("removeGitWorktree force removes a dirty worktree", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
const wtPath = path.join(tmp.path, "wt-dirty-dir");
|
||||
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(b) => b.current,
|
||||
)!.name;
|
||||
|
||||
await createGitWorktree({
|
||||
cwd: tmp.path,
|
||||
branch: currentBranch,
|
||||
newBranch: "wt-dirty",
|
||||
path: wtPath,
|
||||
});
|
||||
expect(existsSync(wtPath)).toBe(true);
|
||||
|
||||
await writeFile(path.join(wtPath, "README.md"), "dirty change\n");
|
||||
|
||||
await expect(removeGitWorktree({ cwd: tmp.path, path: wtPath })).rejects.toThrow();
|
||||
expect(existsSync(wtPath)).toBe(true);
|
||||
|
||||
await removeGitWorktree({ cwd: tmp.path, path: wtPath, force: true });
|
||||
expect(existsSync(wtPath)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Full flow: local branch checkout ──
|
||||
|
||||
@@ -546,11 +546,7 @@ export class GitCoreService {
|
||||
}
|
||||
|
||||
async removeWorktree(input: GitRemoveWorktreeInput): Promise<void> {
|
||||
const args = ["worktree", "remove"];
|
||||
if (input.force) {
|
||||
args.push("--force");
|
||||
}
|
||||
args.push(input.path);
|
||||
const args = ["worktree", "remove", input.path] as const;
|
||||
try {
|
||||
await executeGit(input.cwd, args, {
|
||||
timeoutMs: 15_000,
|
||||
|
||||
@@ -6,13 +6,7 @@ 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 { ProjectRegistry } from "./projectRegistry";
|
||||
import { createServer } from "./wsServer";
|
||||
|
||||
fixPath();
|
||||
@@ -55,13 +49,6 @@ 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();
|
||||
@@ -114,71 +101,8 @@ async function main() {
|
||||
const requestedPort = parsePort(process.env.T3CODE_PORT);
|
||||
const port =
|
||||
requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
|
||||
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 stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
|
||||
const projectRegistry = new ProjectRegistry(stateDir);
|
||||
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;
|
||||
@@ -196,9 +120,7 @@ async function main() {
|
||||
cwd,
|
||||
staticDir,
|
||||
devUrl,
|
||||
persistenceService,
|
||||
stateSyncEngine,
|
||||
syncEngineMode,
|
||||
projectRegistry,
|
||||
authToken,
|
||||
});
|
||||
await server.start();
|
||||
@@ -208,17 +130,7 @@ async function main() {
|
||||
url,
|
||||
cwd,
|
||||
mode,
|
||||
stateDbPath,
|
||||
legacyStateDir,
|
||||
syncEngineMode,
|
||||
enforceLiveStoreOnly,
|
||||
liveStoreBootstrapParityCheck: enableLiveStoreBootstrapParityCheck,
|
||||
liveStoreCatchUpParityCheck: enableLiveStoreCatchUpParityCheck,
|
||||
liveStoreListMessagesParityCheck: enableLiveStoreListMessagesParityCheck,
|
||||
liveStoreShadowBootstrapParityCheck: enableLiveStoreShadowBootstrapParityCheck,
|
||||
liveStoreShadowCatchUpParityCheck: enableLiveStoreShadowCatchUpParityCheck,
|
||||
liveStoreShadowListMessagesParityCheck: enableLiveStoreShadowListMessagesParityCheck,
|
||||
liveStoreDisableReadFallback: disableLiveStoreDelegateReadFallback,
|
||||
stateDir,
|
||||
authEnabled: Boolean(authToken),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,197 +0,0 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,323 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
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,
|
||||
});
|
||||
@@ -1,208 +0,0 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,60 +0,0 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
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",
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,180 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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;
|
||||
@@ -1,541 +0,0 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
@@ -57,8 +57,6 @@ describe("ProjectRegistry scripts", () => {
|
||||
expect(listed[0]?.scripts).toHaveLength(2);
|
||||
expect(listed[0]?.scripts[0]?.id).toBe("run");
|
||||
expect(listed[0]?.scripts[1]?.id).toBe("setup");
|
||||
registry.close();
|
||||
reloaded.close();
|
||||
});
|
||||
|
||||
it("deduplicates script ids and allows only one setup script", () => {
|
||||
@@ -99,7 +97,6 @@ describe("ProjectRegistry scripts", () => {
|
||||
expect(updated.project.scripts[0]?.runOnWorktreeCreate).toBe(true);
|
||||
expect(updated.project.scripts[1]?.id).toBe("another");
|
||||
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(false);
|
||||
registry.close();
|
||||
});
|
||||
|
||||
it("throws when updating scripts for an unknown project id", () => {
|
||||
@@ -112,6 +109,5 @@ describe("ProjectRegistry scripts", () => {
|
||||
scripts: [],
|
||||
}),
|
||||
).toThrowError("Project not found");
|
||||
registry.close();
|
||||
});
|
||||
});
|
||||
@@ -1,47 +1,235 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import type {
|
||||
ProjectAddInput,
|
||||
ProjectAddResult,
|
||||
ProjectListResult,
|
||||
ProjectRemoveInput,
|
||||
ProjectUpdateScriptsInput,
|
||||
ProjectUpdateScriptsResult,
|
||||
import {
|
||||
type ProjectAddInput,
|
||||
type ProjectAddResult,
|
||||
type ProjectListResult,
|
||||
type ProjectRecord,
|
||||
type ProjectRemoveInput,
|
||||
type ProjectScript,
|
||||
type ProjectUpdateScriptsInput,
|
||||
type ProjectUpdateScriptsResult,
|
||||
normalizeProjectScripts,
|
||||
projectAddInputSchema,
|
||||
projectRecordSchema,
|
||||
projectRemoveInputSchema,
|
||||
projectScriptsSchema,
|
||||
projectUpdateScriptsInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { PersistenceService } from "./persistenceService";
|
||||
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";
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compatible wrapper retained for tests and legacy callsites.
|
||||
* Core storage now lives in SQLite through PersistenceService.
|
||||
*/
|
||||
export class ProjectRegistry {
|
||||
private readonly persistenceService: PersistenceService;
|
||||
private readonly stateDir: string;
|
||||
private readonly filePath: string;
|
||||
private projects: ProjectRecord[];
|
||||
|
||||
constructor(stateDir: string) {
|
||||
this.persistenceService = new PersistenceService({
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
|
||||
});
|
||||
this.stateDir = stateDir;
|
||||
this.filePath = path.join(this.stateDir, "projects.json");
|
||||
fs.mkdirSync(this.stateDir, { recursive: true });
|
||||
this.projects = this.loadFromDisk();
|
||||
}
|
||||
|
||||
list(): ProjectListResult {
|
||||
return this.persistenceService.listProjects();
|
||||
return this.projects.map((project) => ({
|
||||
...project,
|
||||
scripts: cloneScripts(project.scripts),
|
||||
}));
|
||||
}
|
||||
|
||||
add(raw: ProjectAddInput): ProjectAddResult {
|
||||
return this.persistenceService.addProject(raw);
|
||||
const input = projectAddInputSchema.parse(raw);
|
||||
const normalizedCwd = normalizeCwd(input.cwd);
|
||||
if (!isDirectory(normalizedCwd)) {
|
||||
throw new Error(`Project path does not exist: ${normalizedCwd}`);
|
||||
}
|
||||
|
||||
const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd);
|
||||
if (existing) {
|
||||
return {
|
||||
project: {
|
||||
...existing,
|
||||
scripts: cloneScripts(existing.scripts),
|
||||
},
|
||||
created: false,
|
||||
};
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const project: ProjectRecord = {
|
||||
id: randomUUID(),
|
||||
cwd: normalizedCwd,
|
||||
name: inferProjectName(normalizedCwd),
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.projects = [project, ...this.projects];
|
||||
this.persist();
|
||||
return {
|
||||
project: {
|
||||
...project,
|
||||
scripts: cloneScripts(project.scripts),
|
||||
},
|
||||
created: true,
|
||||
};
|
||||
}
|
||||
|
||||
remove(raw: ProjectRemoveInput): void {
|
||||
this.persistenceService.removeProject(raw);
|
||||
const input = projectRemoveInputSchema.parse(raw);
|
||||
const next = this.projects.filter((project) => project.id !== input.id);
|
||||
if (next.length === this.projects.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.projects = next;
|
||||
this.persist();
|
||||
}
|
||||
|
||||
updateScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
|
||||
return this.persistenceService.updateProjectScripts(raw);
|
||||
const input = projectUpdateScriptsInputSchema.parse(raw);
|
||||
const index = this.projects.findIndex((project) => project.id === input.id);
|
||||
if (index < 0) {
|
||||
throw new Error(`Project not found: ${input.id}`);
|
||||
}
|
||||
|
||||
const nextScripts = normalizeProjectScripts(projectScriptsSchema.parse(input.scripts));
|
||||
const nextUpdatedAt = new Date().toISOString();
|
||||
const nextProject: ProjectRecord = {
|
||||
...this.projects[index]!,
|
||||
scripts: nextScripts,
|
||||
updatedAt: nextUpdatedAt,
|
||||
};
|
||||
|
||||
const nextProjects = [...this.projects];
|
||||
nextProjects[index] = nextProject;
|
||||
this.projects = nextProjects;
|
||||
this.persist();
|
||||
|
||||
return {
|
||||
project: { ...nextProject, scripts: cloneScripts(nextProject.scripts) },
|
||||
};
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.persistenceService.close();
|
||||
private loadFromDisk(): ProjectRecord[] {
|
||||
const loaded = this.readPersistedProjects();
|
||||
const deduped = new Map<string, ProjectRecord>();
|
||||
const normalizedProjects: ProjectRecord[] = [];
|
||||
|
||||
for (const project of loaded) {
|
||||
const normalizedCwd = normalizeCwd(project.cwd);
|
||||
if (!isDirectory(normalizedCwd)) {
|
||||
continue;
|
||||
}
|
||||
if (deduped.has(normalizedCwd)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedProject: ProjectRecord = {
|
||||
...project,
|
||||
cwd: normalizedCwd,
|
||||
name:
|
||||
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
|
||||
scripts: normalizeProjectScripts(project.scripts),
|
||||
};
|
||||
deduped.set(normalizedCwd, normalizedProject);
|
||||
normalizedProjects.push(normalizedProject);
|
||||
}
|
||||
|
||||
const changed =
|
||||
normalizedProjects.length !== loaded.length ||
|
||||
normalizedProjects.some((project, index) => {
|
||||
const source = loaded[index];
|
||||
if (!source) return true;
|
||||
return (
|
||||
source.id !== project.id ||
|
||||
source.cwd !== project.cwd ||
|
||||
source.name !== project.name ||
|
||||
JSON.stringify(source.scripts) !== JSON.stringify(project.scripts) ||
|
||||
source.createdAt !== project.createdAt ||
|
||||
source.updatedAt !== project.updatedAt
|
||||
);
|
||||
});
|
||||
|
||||
if (changed) {
|
||||
this.projects = normalizedProjects;
|
||||
this.persist();
|
||||
}
|
||||
|
||||
return normalizedProjects;
|
||||
}
|
||||
|
||||
private readPersistedProjects(): ProjectRecord[] {
|
||||
try {
|
||||
const raw = fs.readFileSync(this.filePath, "utf8");
|
||||
const parsed = JSON.parse(raw) as { projects?: unknown };
|
||||
if (!parsed || !Array.isArray(parsed.projects)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const projects: ProjectRecord[] = [];
|
||||
for (const candidate of parsed.projects) {
|
||||
const row = projectRecordSchema.safeParse(candidate);
|
||||
if (!row.success) {
|
||||
continue;
|
||||
}
|
||||
projects.push(row.data);
|
||||
}
|
||||
return projects;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private persist(): void {
|
||||
const payload = JSON.stringify(
|
||||
{
|
||||
version: 1,
|
||||
projects: this.projects,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const tempFile = `${this.filePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
fs.writeFileSync(tempFile, payload);
|
||||
fs.renameSync(tempFile, this.filePath);
|
||||
}
|
||||
}
|
||||
@@ -296,82 +296,6 @@ describe("ProviderManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("emits checkpoint/captured after turn completion checkpoint capture", async () => {
|
||||
const manager = new ProviderManager();
|
||||
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 } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const internals = manager as unknown as {
|
||||
onCodexEvent: (event: {
|
||||
id: string;
|
||||
kind: "notification";
|
||||
provider: "codex";
|
||||
sessionId: string;
|
||||
createdAt: string;
|
||||
method: string;
|
||||
threadId: string;
|
||||
}) => void;
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
captureCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<void>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
});
|
||||
const captureCheckpoint = vi.fn(async () => undefined);
|
||||
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
internals.onCodexEvent({
|
||||
id: "evt-turn-complete",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess_1",
|
||||
createdAt: "2026-02-19T00:00:00.000Z",
|
||||
method: "turn/completed",
|
||||
threadId: "thr_1",
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(captureCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(events.some((event) => event.method === "checkpoint/captured")).toBe(true);
|
||||
});
|
||||
|
||||
const checkpointCapturedEvent = events.find((event) => event.method === "checkpoint/captured");
|
||||
expect(checkpointCapturedEvent?.threadId).toBe("thr_1");
|
||||
expect(checkpointCapturedEvent?.payload).toEqual({
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("lazily initializes filesystem checkpoints before diffing when cache is missing", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
|
||||
@@ -31,11 +31,6 @@ 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];
|
||||
@@ -168,7 +163,6 @@ 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,21 +176,12 @@ 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(options: ProviderManagerOptions = {}) {
|
||||
constructor() {
|
||||
super();
|
||||
this.persistenceService = options.persistenceService;
|
||||
|
||||
const logsDir = path.resolve(process.cwd(), ".logs");
|
||||
this.threadLogsDir = path.join(logsDir, "threads");
|
||||
@@ -212,17 +197,6 @@ 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);
|
||||
@@ -241,11 +215,6 @@ 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);
|
||||
}
|
||||
|
||||
@@ -270,7 +239,6 @@ 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);
|
||||
@@ -509,20 +477,11 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
|
||||
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
|
||||
if (!checkpointCwd) {
|
||||
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId)
|
||||
.then(async (initializedCwd) => {
|
||||
if (!initializedCwd || !this.codex.hasSession(event.sessionId)) {
|
||||
return;
|
||||
}
|
||||
const snapshot = await this.codex.readThread(event.sessionId);
|
||||
await this.persistCheckpointSummaryForTurn(event, initializedCwd, snapshot.threadId, snapshot.turns);
|
||||
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
|
||||
})
|
||||
.catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId).catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -537,30 +496,12 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
await this.persistCheckpointSummaryForTurn(event, checkpointCwd, snapshot.threadId, snapshot.turns);
|
||||
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
|
||||
}).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
}
|
||||
|
||||
private emitCheckpointCaptured(sessionId: string, threadId: string, turnCount: number): void {
|
||||
this.emit("event", {
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "checkpoint/captured",
|
||||
threadId,
|
||||
payload: {
|
||||
threadId,
|
||||
turnCount,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private emitFilesystemCheckpointError(
|
||||
sessionId: string,
|
||||
message: string,
|
||||
@@ -673,47 +614,4 @@ 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
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",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,119 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -1,645 +0,0 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,439 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,296 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
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.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
import { GitManager } from "./gitManager";
|
||||
import {
|
||||
@@ -32,12 +33,6 @@ import {
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
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",
|
||||
@@ -61,13 +56,10 @@ export interface ServerOptions {
|
||||
staticDir?: string | undefined;
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
persistenceService?: PersistenceService | undefined;
|
||||
stateSyncEngine?: StateSyncEngine | undefined;
|
||||
stateDbPath?: string | undefined;
|
||||
projectRegistry?: ProjectRegistry | undefined;
|
||||
gitManager?: GitManager | undefined;
|
||||
terminalManager?: TerminalManager | undefined;
|
||||
authToken?: string | undefined;
|
||||
syncEngineMode?: SyncEngineMode | undefined;
|
||||
}
|
||||
|
||||
function parseBooleanEnv(value: string | undefined): boolean | undefined {
|
||||
@@ -86,26 +78,15 @@ export function createServer(options: ServerOptions) {
|
||||
staticDir,
|
||||
devUrl,
|
||||
logWebSocketEvents: explicitLogWsEvents,
|
||||
persistenceService: providedPersistenceService,
|
||||
stateSyncEngine: providedStateSyncEngine,
|
||||
stateDbPath,
|
||||
projectRegistry: providedRegistry,
|
||||
gitManager: providedGitManager,
|
||||
terminalManager: providedTerminalManager,
|
||||
authToken,
|
||||
syncEngineMode: providedSyncEngineMode,
|
||||
} = options;
|
||||
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 providerManager = new ProviderManager();
|
||||
const terminalManager = providedTerminalManager ?? new TerminalManager();
|
||||
const projectRegistry =
|
||||
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
|
||||
const gitManager = providedGitManager ?? new GitManager();
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
@@ -140,24 +121,6 @@ export function createServer(options: ServerOptions) {
|
||||
logOutgoingPush(push, recipients);
|
||||
});
|
||||
|
||||
const onStateEvent = (event: unknown) => {
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.stateEvent,
|
||||
data: event,
|
||||
};
|
||||
const message = JSON.stringify(push);
|
||||
let recipients = 0;
|
||||
for (const client of clients) {
|
||||
if (client.readyState === client.OPEN) {
|
||||
client.send(message);
|
||||
recipients += 1;
|
||||
}
|
||||
}
|
||||
logOutgoingPush(push, recipients);
|
||||
};
|
||||
const unsubscribeStateEvents = stateSyncEngine.onStateEvent(onStateEvent);
|
||||
|
||||
const onTerminalEvent = (event: TerminalEvent) => {
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
@@ -354,85 +317,22 @@ export function createServer(options: ServerOptions) {
|
||||
return providerManager.getCheckpointDiff(request.params as never);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
return providerManager.revertToCheckpoint(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsList:
|
||||
return stateSyncEngine.listProjects();
|
||||
return projectRegistry.list();
|
||||
|
||||
case WS_METHODS.projectsAdd:
|
||||
return stateSyncEngine.addProject(request.params as never);
|
||||
return projectRegistry.add(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsRemove:
|
||||
stateSyncEngine.removeProject(request.params as never);
|
||||
projectRegistry.remove(request.params as never);
|
||||
return undefined;
|
||||
|
||||
case WS_METHODS.projectsSearchEntries:
|
||||
return searchWorkspaceEntries(request.params as never);
|
||||
case WS_METHODS.projectsUpdateScripts:
|
||||
return stateSyncEngine.updateProjectScripts(request.params as never);
|
||||
return projectRegistry.updateScripts(request.params as never);
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const params = request.params as {
|
||||
@@ -529,7 +429,6 @@ export function createServer(options: ServerOptions) {
|
||||
case WS_METHODS.serverGetConfig:
|
||||
return {
|
||||
cwd,
|
||||
syncEngineMode,
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
@@ -565,16 +464,9 @@ export function createServer(options: ServerOptions) {
|
||||
|
||||
async function stop(): Promise<void> {
|
||||
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();
|
||||
@@ -615,16 +507,3 @@ 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";
|
||||
}
|
||||
@@ -3,15 +3,13 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300..800;1,9..40,300..800&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<title>T3 Code (Alpha)</title>
|
||||
<title>T3 Code</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"@tanstack/react-virtual": "^3.13.18",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
|
||||
|
Before Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 279 KiB |
@@ -1,4 +0,0 @@
|
||||
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M0 10C0 4.47715 4.47715 0 10 0H118C123.523 0 128 4.47715 128 10V118C128 123.523 123.523 128 118 128H10C4.47715 128 0 123.523 0 118V10Z" fill="black"/>
|
||||
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="white"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
@@ -1,159 +0,0 @@
|
||||
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 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,319 +0,0 @@
|
||||
import {
|
||||
type AppSettings as BackendAppSettings,
|
||||
appSettingsSchema as backendAppSettingsSchema,
|
||||
appSettingsUpdateInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
import { readNativeApi } from "./session-logic";
|
||||
|
||||
const LOCAL_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:local:v1";
|
||||
const LEGACY_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
|
||||
const localAppSettingsSchema = z.object({
|
||||
confirmThreadDelete: z.boolean().default(true),
|
||||
});
|
||||
|
||||
const legacyAppSettingsSchema = backendAppSettingsSchema.extend({
|
||||
confirmThreadDelete: z.boolean().default(true),
|
||||
});
|
||||
|
||||
const appSettingsSchema = backendAppSettingsSchema.extend({
|
||||
confirmThreadDelete: z.boolean().default(true),
|
||||
});
|
||||
|
||||
export type AppSettings = z.infer<typeof appSettingsSchema>;
|
||||
|
||||
const DEFAULT_BACKEND_APP_SETTINGS: BackendAppSettings = backendAppSettingsSchema.parse({});
|
||||
const DEFAULT_LOCAL_APP_SETTINGS = localAppSettingsSchema.parse({});
|
||||
const DEFAULT_APP_SETTINGS: AppSettings = {
|
||||
...DEFAULT_BACKEND_APP_SETTINGS,
|
||||
...DEFAULT_LOCAL_APP_SETTINGS,
|
||||
};
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let cachedBackendSettings: BackendAppSettings = DEFAULT_BACKEND_APP_SETTINGS;
|
||||
let cachedBackendCacheKey = JSON.stringify(DEFAULT_BACKEND_APP_SETTINGS);
|
||||
let cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
|
||||
let cachedLocalCacheKey: string | undefined;
|
||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||
let cachedSnapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
|
||||
let backendHydrationPromise: Promise<void> | null = null;
|
||||
let backendHydrated = false;
|
||||
let backendUpdateSequence = 0;
|
||||
let optimisticWriteSequence = 0;
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
function setCachedBackendSettings(next: BackendAppSettings): void {
|
||||
cachedBackendSettings = next;
|
||||
cachedBackendCacheKey = JSON.stringify(next);
|
||||
}
|
||||
|
||||
function parseLegacySettings(value: string | null): z.infer<typeof legacyAppSettingsSchema> | null {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(value) as unknown;
|
||||
return legacyAppSettingsSchema.parse(parsed);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readLegacySettingsSnapshot(): z.infer<typeof legacyAppSettingsSchema> | null {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
return parseLegacySettings(window.localStorage.getItem(LEGACY_APP_SETTINGS_STORAGE_KEY));
|
||||
}
|
||||
|
||||
function readLocalSettingsSnapshot() {
|
||||
if (typeof window === "undefined") {
|
||||
return DEFAULT_LOCAL_APP_SETTINGS;
|
||||
}
|
||||
|
||||
const rawLocal = window.localStorage.getItem(LOCAL_APP_SETTINGS_STORAGE_KEY);
|
||||
const rawLegacy = rawLocal === null ? window.localStorage.getItem(LEGACY_APP_SETTINGS_STORAGE_KEY) : null;
|
||||
const cacheKey = rawLocal !== null ? `local:${rawLocal}` : `legacy:${rawLegacy ?? ""}`;
|
||||
if (cacheKey === cachedLocalCacheKey) {
|
||||
return cachedLocalSettings;
|
||||
}
|
||||
|
||||
if (rawLocal !== null) {
|
||||
try {
|
||||
const parsed = JSON.parse(rawLocal) as unknown;
|
||||
cachedLocalSettings = localAppSettingsSchema.parse(parsed);
|
||||
} catch {
|
||||
cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
|
||||
}
|
||||
} else {
|
||||
const legacySettings = parseLegacySettings(rawLegacy);
|
||||
cachedLocalSettings = localAppSettingsSchema.parse({
|
||||
confirmThreadDelete: legacySettings?.confirmThreadDelete ?? DEFAULT_LOCAL_APP_SETTINGS.confirmThreadDelete,
|
||||
});
|
||||
}
|
||||
|
||||
cachedLocalCacheKey = cacheKey;
|
||||
return cachedLocalSettings;
|
||||
}
|
||||
|
||||
function persistLocalSettings(next: z.infer<typeof localAppSettingsSchema>): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const normalized = localAppSettingsSchema.parse(next);
|
||||
const raw = JSON.stringify(normalized);
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(LOCAL_APP_SETTINGS_STORAGE_KEY, raw);
|
||||
} catch {
|
||||
// Best-effort persistence only.
|
||||
}
|
||||
|
||||
cachedLocalSettings = normalized;
|
||||
cachedLocalCacheKey = `local:${raw}`;
|
||||
}
|
||||
|
||||
function normalizeBackendSettings(value: unknown): BackendAppSettings {
|
||||
const parsed = backendAppSettingsSchema.safeParse(value);
|
||||
if (parsed.success) {
|
||||
return parsed.data;
|
||||
}
|
||||
return DEFAULT_BACKEND_APP_SETTINGS;
|
||||
}
|
||||
|
||||
async function hydrateBackendSettings(): Promise<void> {
|
||||
if (typeof window === "undefined" || backendHydrated) {
|
||||
return;
|
||||
}
|
||||
if (backendHydrationPromise) {
|
||||
await backendHydrationPromise;
|
||||
return;
|
||||
}
|
||||
|
||||
const hydrationSequence = optimisticWriteSequence;
|
||||
const hasOptimisticWriteSinceHydration = () => hydrationSequence !== optimisticWriteSequence;
|
||||
|
||||
backendHydrationPromise = (async () => {
|
||||
const api = readNativeApi();
|
||||
if (!api?.appSettings || typeof api.appSettings.get !== "function") {
|
||||
backendHydrated = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const legacySettings = readLegacySettingsSnapshot();
|
||||
let next = normalizeBackendSettings(await api.appSettings.get());
|
||||
if (!hasOptimisticWriteSinceHydration()) {
|
||||
const migrationPatch = appSettingsUpdateInputSchema.parse({
|
||||
...(next.codexBinaryPath.length === 0 && legacySettings?.codexBinaryPath
|
||||
? { codexBinaryPath: legacySettings.codexBinaryPath }
|
||||
: {}),
|
||||
...(next.codexHomePath.length === 0 && legacySettings?.codexHomePath
|
||||
? { codexHomePath: legacySettings.codexHomePath }
|
||||
: {}),
|
||||
});
|
||||
const hasMigrationPatch =
|
||||
migrationPatch.codexBinaryPath !== undefined || migrationPatch.codexHomePath !== undefined;
|
||||
if (hasMigrationPatch) {
|
||||
next = normalizeBackendSettings(await api.appSettings.update(migrationPatch));
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasOptimisticWriteSinceHydration()) {
|
||||
setCachedBackendSettings(next);
|
||||
|
||||
if (legacySettings) {
|
||||
persistLocalSettings({
|
||||
confirmThreadDelete: legacySettings.confirmThreadDelete,
|
||||
});
|
||||
}
|
||||
|
||||
emitChange();
|
||||
}
|
||||
|
||||
backendHydrated = true;
|
||||
if (legacySettings) {
|
||||
try {
|
||||
window.localStorage.removeItem(LEGACY_APP_SETTINGS_STORAGE_KEY);
|
||||
} catch {
|
||||
// Best-effort legacy cleanup only.
|
||||
}
|
||||
}
|
||||
})()
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
backendHydrationPromise = null;
|
||||
});
|
||||
|
||||
await backendHydrationPromise;
|
||||
}
|
||||
|
||||
export function getAppSettingsSnapshot(): AppSettings {
|
||||
const localSettings = readLocalSettingsSnapshot();
|
||||
const snapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
|
||||
if (snapshotKey === cachedSnapshotKey) {
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
cachedSnapshot = appSettingsSchema.parse({
|
||||
...cachedBackendSettings,
|
||||
...localSettings,
|
||||
});
|
||||
cachedSnapshotKey = snapshotKey;
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
export function ensureAppSettingsHydrated(): Promise<void> {
|
||||
return hydrateBackendSettings();
|
||||
}
|
||||
|
||||
export function updateAppSettings(patch: Partial<AppSettings>): void {
|
||||
const parsedPatch = appSettingsSchema.partial().parse(patch);
|
||||
let didChange = false;
|
||||
let didOptimisticWrite = false;
|
||||
const markOptimisticWrite = () => {
|
||||
if (didOptimisticWrite) return;
|
||||
didOptimisticWrite = true;
|
||||
optimisticWriteSequence += 1;
|
||||
};
|
||||
|
||||
if (parsedPatch.confirmThreadDelete !== undefined) {
|
||||
markOptimisticWrite();
|
||||
persistLocalSettings({
|
||||
...readLocalSettingsSnapshot(),
|
||||
confirmThreadDelete: parsedPatch.confirmThreadDelete,
|
||||
});
|
||||
didChange = true;
|
||||
}
|
||||
|
||||
const backendPatch = appSettingsUpdateInputSchema.parse({
|
||||
...(parsedPatch.codexBinaryPath !== undefined
|
||||
? { codexBinaryPath: parsedPatch.codexBinaryPath }
|
||||
: {}),
|
||||
...(parsedPatch.codexHomePath !== undefined ? { codexHomePath: parsedPatch.codexHomePath } : {}),
|
||||
});
|
||||
const hasBackendPatch =
|
||||
backendPatch.codexBinaryPath !== undefined || backendPatch.codexHomePath !== undefined;
|
||||
if (hasBackendPatch) {
|
||||
markOptimisticWrite();
|
||||
const previous = cachedBackendSettings;
|
||||
const optimisticNext = backendAppSettingsSchema.parse({
|
||||
...cachedBackendSettings,
|
||||
...backendPatch,
|
||||
});
|
||||
setCachedBackendSettings(optimisticNext);
|
||||
backendHydrated = true;
|
||||
didChange = true;
|
||||
|
||||
const updateSequence = ++backendUpdateSequence;
|
||||
const api = readNativeApi();
|
||||
if (api?.appSettings && typeof api.appSettings.update === "function") {
|
||||
void api.appSettings
|
||||
.update(backendPatch)
|
||||
.then((response) => {
|
||||
if (updateSequence !== backendUpdateSequence) return;
|
||||
setCachedBackendSettings(normalizeBackendSettings(response));
|
||||
emitChange();
|
||||
})
|
||||
.catch(() => {
|
||||
if (updateSequence !== backendUpdateSequence) return;
|
||||
setCachedBackendSettings(previous);
|
||||
emitChange();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (didChange) {
|
||||
emitChange();
|
||||
}
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.push(listener);
|
||||
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (
|
||||
event.key === null ||
|
||||
event.key === LOCAL_APP_SETTINGS_STORAGE_KEY ||
|
||||
event.key === LEGACY_APP_SETTINGS_STORAGE_KEY
|
||||
) {
|
||||
emitChange();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => {
|
||||
listeners = listeners.filter((entry) => entry !== listener);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
};
|
||||
}
|
||||
|
||||
export function useAppSettings() {
|
||||
const settings = useSyncExternalStore(subscribe, getAppSettingsSnapshot, () => DEFAULT_APP_SETTINGS);
|
||||
|
||||
useEffect(() => {
|
||||
void ensureAppSettingsHydrated();
|
||||
}, []);
|
||||
|
||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||
updateAppSettings(patch);
|
||||
}, []);
|
||||
|
||||
const resetSettings = useCallback(() => {
|
||||
updateSettings(DEFAULT_APP_SETTINGS);
|
||||
}, [updateSettings]);
|
||||
|
||||
return {
|
||||
settings,
|
||||
updateSettings,
|
||||
resetSettings,
|
||||
defaults: DEFAULT_APP_SETTINGS,
|
||||
} as const;
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export const APP_BASE_NAME = "T3 Code";
|
||||
export const APP_STAGE_LABEL = import.meta.env.DEV ? "Dev" : "Alpha";
|
||||
export const APP_DISPLAY_NAME = `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
|
||||
@@ -1,17 +1,21 @@
|
||||
import { parsePatchFiles } from "@pierre/diffs";
|
||||
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import {
|
||||
FileDiff,
|
||||
type FileDiffMetadata,
|
||||
Virtualizer,
|
||||
WorkerPoolContextProvider,
|
||||
} from "@pierre/diffs/react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions, providerQueryKeys } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { isElectron } from "../env";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { formatTimestamp } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
|
||||
@@ -67,46 +71,51 @@ function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
|
||||
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
|
||||
}
|
||||
|
||||
function formatTurnChipTimestamp(isoDate: string): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
}).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
interface DiffPanelProps {
|
||||
mode?: "inline" | "sheet";
|
||||
}
|
||||
|
||||
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
const workerPoolSize = useMemo(() => {
|
||||
const cores = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
||||
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<WorkerPoolContextProvider
|
||||
poolOptions={{
|
||||
workerFactory: () =>
|
||||
new Worker(new URL("../workers/diffs.worker.ts", import.meta.url), { type: "module" }),
|
||||
poolSize: workerPoolSize,
|
||||
totalASTLRUCacheSize: 240,
|
||||
}}
|
||||
highlighterOptions={{
|
||||
tokenizeMaxLineLength: 1_000,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</WorkerPoolContextProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const api = useNativeApi();
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { state } = useStore();
|
||||
const { state, dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
|
||||
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
|
||||
const params = useParams({ strict: false });
|
||||
const rawSearch = useSearch({ strict: false });
|
||||
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
|
||||
const diffSearch = useMemo(
|
||||
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
|
||||
[rawSearch],
|
||||
);
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||
const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId);
|
||||
const activeThreadRuntimeId =
|
||||
activeThread?.codexThreadId ?? activeThread?.session?.threadId ?? null;
|
||||
const activeSessionId = activeThread?.session?.sessionId ?? null;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
|
||||
const selectedTurnId = diffSearch.diffTurnId ?? null;
|
||||
const selectedFilePath = selectedTurnId !== null ? (diffSearch.diffFilePath ?? null) : null;
|
||||
const canApplyStoredTarget = Boolean(activeThread && state.diffThreadId === activeThread.id);
|
||||
const selectedTurnId = canApplyStoredTarget ? state.diffTurnId : null;
|
||||
const selectedFilePath =
|
||||
canApplyStoredTarget && selectedTurnId !== null ? state.diffFilePath : null;
|
||||
const selectedTurn =
|
||||
selectedTurnId === null
|
||||
? undefined
|
||||
@@ -180,7 +189,99 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
? "Failed to load checkpoint diff."
|
||||
: null;
|
||||
|
||||
const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id || !selectedTurn || !selectedTurnCheckpointDiff) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS",
|
||||
threadId: activeThread.id,
|
||||
checkpointDiffByTurnId: {
|
||||
[selectedTurn.turnId]: selectedTurnCheckpointDiff,
|
||||
},
|
||||
});
|
||||
}, [activeThread?.id, dispatch, selectedTurn, selectedTurnCheckpointDiff]);
|
||||
|
||||
const selectedPatch = useMemo(() => {
|
||||
const patchForSummary = (summary: (typeof turnDiffSummaries)[number]): string | undefined => {
|
||||
const checkpointTurnCount =
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
if (activeSessionId && typeof checkpointTurnCount === "number") {
|
||||
const checkpointPatch = queryClient.getQueryData<{ diff: string }>(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
sessionId: activeSessionId,
|
||||
threadRuntimeId: activeThreadRuntimeId,
|
||||
fromTurnCount: Math.max(0, checkpointTurnCount - 1),
|
||||
toTurnCount: checkpointTurnCount,
|
||||
cacheScope: `turn:${summary.turnId}`,
|
||||
}),
|
||||
)?.diff;
|
||||
if (checkpointPatch) {
|
||||
return checkpointPatch;
|
||||
}
|
||||
}
|
||||
if (summary.unifiedDiff) {
|
||||
return summary.unifiedDiff;
|
||||
}
|
||||
const filePatches = summary.files
|
||||
.map((file) => file.diff?.trim())
|
||||
.filter((patch): patch is string => Boolean(patch));
|
||||
if (filePatches.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return filePatches.join("\n\n");
|
||||
};
|
||||
|
||||
if (selectedTurn) {
|
||||
return selectedTurnCheckpointDiff ?? patchForSummary(selectedTurn);
|
||||
}
|
||||
|
||||
if (conversationCheckpointDiff) {
|
||||
return conversationCheckpointDiff;
|
||||
}
|
||||
|
||||
// Fallback when a conversation checkpoint diff isn't available yet:
|
||||
// keep one patch per file path (latest change wins) so files aren't duplicated.
|
||||
const latestPatchByPath = new Map<string, string>();
|
||||
for (const summary of turnDiffSummaries) {
|
||||
for (const file of summary.files) {
|
||||
if (latestPatchByPath.has(file.path)) {
|
||||
continue;
|
||||
}
|
||||
const patch = file.diff?.trim();
|
||||
if (!patch) {
|
||||
continue;
|
||||
}
|
||||
latestPatchByPath.set(file.path, patch);
|
||||
}
|
||||
}
|
||||
if (latestPatchByPath.size > 0) {
|
||||
return Array.from(latestPatchByPath.entries())
|
||||
.toSorted(([leftPath], [rightPath]) =>
|
||||
leftPath.localeCompare(rightPath, undefined, { numeric: true, sensitivity: "base" }),
|
||||
)
|
||||
.map(([, patch]) => patch)
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
const patches = turnDiffSummaries
|
||||
.toReversed()
|
||||
.map((summary) => patchForSummary(summary)?.trim())
|
||||
.filter((patch): patch is string => Boolean(patch));
|
||||
if (patches.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return patches.join("\n\n");
|
||||
}, [
|
||||
activeSessionId,
|
||||
activeThreadRuntimeId,
|
||||
conversationCheckpointDiff,
|
||||
inferredCheckpointTurnCountByTurnId,
|
||||
queryClient,
|
||||
selectedTurn,
|
||||
selectedTurnCheckpointDiff,
|
||||
turnDiffSummaries,
|
||||
]);
|
||||
const renderablePatch = useMemo(() => getRenderablePatch(selectedPatch), [selectedPatch]);
|
||||
const renderableFiles = useMemo(() => {
|
||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
||||
@@ -206,84 +307,19 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
|
||||
const selectTurn = (turnId: string) => {
|
||||
if (!activeThread) return;
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: activeThread.id },
|
||||
search: (previous) => {
|
||||
const rest = stripDiffSearchParams(previous);
|
||||
return { ...rest, diff: "1", diffTurnId: turnId };
|
||||
},
|
||||
dispatch({
|
||||
type: "SET_DIFF_TARGET",
|
||||
threadId: activeThread.id,
|
||||
turnId,
|
||||
});
|
||||
};
|
||||
const selectWholeConversation = () => {
|
||||
if (!activeThread) return;
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: activeThread.id },
|
||||
search: (previous) => {
|
||||
const rest = stripDiffSearchParams(previous);
|
||||
return { ...rest, diff: "1" };
|
||||
},
|
||||
dispatch({
|
||||
type: "SET_DIFF_TARGET",
|
||||
threadId: activeThread.id,
|
||||
});
|
||||
};
|
||||
const updateTurnStripScrollState = useCallback(() => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) {
|
||||
setCanScrollTurnStripLeft(false);
|
||||
setCanScrollTurnStripRight(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
|
||||
setCanScrollTurnStripLeft(element.scrollLeft > 4);
|
||||
setCanScrollTurnStripRight(element.scrollLeft < maxScrollLeft - 4);
|
||||
}, []);
|
||||
const scrollTurnStripBy = useCallback((offset: number) => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
element.scrollBy({ left: offset, behavior: "smooth" });
|
||||
}, []);
|
||||
const onTurnStripWheel = useCallback((event: WheelEvent) => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
if (element.scrollWidth <= element.clientWidth + 1) return;
|
||||
if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
|
||||
|
||||
event.preventDefault();
|
||||
element.scrollBy({ left: event.deltaY, behavior: "auto" });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
|
||||
updateTurnStripScrollState();
|
||||
const onScroll = () => updateTurnStripScrollState();
|
||||
|
||||
element.addEventListener("scroll", onScroll, { passive: true });
|
||||
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
|
||||
resizeObserver.observe(element);
|
||||
|
||||
return () => {
|
||||
element.removeEventListener("scroll", onScroll);
|
||||
element.removeEventListener("wheel", onTurnStripWheel);
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [updateTurnStripScrollState, onTurnStripWheel]);
|
||||
|
||||
useEffect(() => {
|
||||
updateTurnStripScrollState();
|
||||
}, [turnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
|
||||
|
||||
useEffect(() => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
|
||||
const selectedChip = element.querySelector<HTMLElement>("[data-turn-chip-selected='true']");
|
||||
selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
|
||||
}, [selectedTurn?.turnId, selectedTurnId]);
|
||||
|
||||
const shouldUseDragRegion = isElectron && mode === "inline";
|
||||
|
||||
@@ -298,98 +334,49 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-2 border-b border-border px-4",
|
||||
"flex items-center justify-between border-b border-border px-4",
|
||||
shouldUseDragRegion ? "drag-region h-[52px]" : "py-3",
|
||||
)}
|
||||
>
|
||||
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
|
||||
{canScrollTurnStripLeft && (
|
||||
<div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-gradient-to-r from-card to-transparent" />
|
||||
)}
|
||||
{canScrollTurnStripRight && (
|
||||
<div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-gradient-to-l from-card to-transparent" />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"absolute left-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
|
||||
canScrollTurnStripLeft
|
||||
? "border-border/70 hover:border-border hover:text-foreground"
|
||||
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
|
||||
)}
|
||||
onClick={() => scrollTurnStripBy(-180)}
|
||||
disabled={!canScrollTurnStripLeft}
|
||||
aria-label="Scroll turn list left"
|
||||
>
|
||||
<ChevronLeftIcon className="size-3.5" />
|
||||
<div className="flex gap-1.5 overflow-x-auto pb-0.5">
|
||||
<button type="button" className="shrink-0 rounded-md" onClick={selectWholeConversation}>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
selectedTurnId === null
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
||||
)}
|
||||
>
|
||||
<div className="text-[10px] font-medium">All turns</div>
|
||||
<div className="text-[8px] opacity-70">Conversation</div>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"absolute right-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
|
||||
canScrollTurnStripRight
|
||||
? "border-border/70 hover:border-border hover:text-foreground"
|
||||
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
|
||||
)}
|
||||
onClick={() => scrollTurnStripBy(180)}
|
||||
disabled={!canScrollTurnStripRight}
|
||||
aria-label="Scroll turn list right"
|
||||
>
|
||||
<ChevronRightIcon className="size-3.5" />
|
||||
</button>
|
||||
<div
|
||||
ref={turnStripRef}
|
||||
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
|
||||
>
|
||||
{turnDiffSummaries.map((summary, index) => (
|
||||
<button
|
||||
key={summary.turnId}
|
||||
type="button"
|
||||
className="shrink-0 rounded-md"
|
||||
onClick={selectWholeConversation}
|
||||
data-turn-chip-selected={selectedTurnId === null}
|
||||
onClick={() => selectTurn(summary.turnId)}
|
||||
title={summary.turnId}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
selectedTurnId === null
|
||||
summary.turnId === selectedTurn?.turnId
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
||||
)}
|
||||
>
|
||||
<div className="text-[10px] leading-tight font-medium">All turns</div>
|
||||
<div className="text-[10px] font-medium">
|
||||
Turn {turnDiffSummaries.length - index}
|
||||
</div>
|
||||
<div className="text-[8px] opacity-70">{formatTimestamp(summary.completedAt)}</div>
|
||||
</div>
|
||||
</button>
|
||||
{turnDiffSummaries.map((summary, index) => (
|
||||
<button
|
||||
key={summary.turnId}
|
||||
type="button"
|
||||
className="shrink-0 rounded-md"
|
||||
onClick={() => selectTurn(summary.turnId)}
|
||||
title={summary.turnId}
|
||||
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
summary.turnId === selectedTurn?.turnId
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-[10px] leading-tight font-medium">
|
||||
Turn {turnDiffSummaries.length - index}
|
||||
</span>
|
||||
<span className="text-[9px] leading-tight opacity-70">
|
||||
{formatTurnChipTimestamp(summary.completedAt)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<ToggleGroup
|
||||
className="shrink-0 [-webkit-app-region:no-drag]"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
value={[diffRenderMode]}
|
||||
@@ -420,6 +407,13 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
) : (
|
||||
<>
|
||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
||||
{!canApplyStoredTarget && state.diffThreadId && (
|
||||
<div className="px-3 pt-2">
|
||||
<p className="mb-2 text-[11px] text-muted-foreground/65">
|
||||
Showing diffs for the active thread.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{checkpointDiffError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
|
||||
import { useMemo, type ReactNode } from "react";
|
||||
|
||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
const workerPoolSize = useMemo(() => {
|
||||
const cores = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
||||
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<WorkerPoolContextProvider
|
||||
poolOptions={{
|
||||
workerFactory: () =>
|
||||
new Worker(new URL("../workers/diffs.worker.ts", import.meta.url), { type: "module" }),
|
||||
poolSize: workerPoolSize,
|
||||
totalASTLRUCacheSize: 240,
|
||||
}}
|
||||
highlighterOptions={{
|
||||
tokenizeMaxLineLength: 1_000,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</WorkerPoolContextProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
import { TerminalIcon } from "lucide-react";
|
||||
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
import { APP_STAGE_LABEL } from "../branding";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
@@ -16,8 +15,9 @@ 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";
|
||||
import { createThread } from "../threadFactory";
|
||||
|
||||
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
|
||||
function formatRelativeTime(iso: string): string {
|
||||
@@ -116,7 +116,6 @@ export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useNativeApi();
|
||||
const navigate = useNavigate();
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
const params = useParams({ strict: false });
|
||||
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
|
||||
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
|
||||
@@ -127,6 +126,7 @@ export default function Sidebar() {
|
||||
const removeWorktreeMutation = useMutation(
|
||||
gitRemoveWorktreeMutationOptions({ api, queryClient }),
|
||||
);
|
||||
const { theme, setTheme } = useTheme();
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
@@ -147,71 +147,21 @@ export default function Sidebar() {
|
||||
worktreePath?: string | null;
|
||||
},
|
||||
) => {
|
||||
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.
|
||||
}
|
||||
})();
|
||||
const thread = createThread(projectId, {
|
||||
model: state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL,
|
||||
branch: options?.branch ?? null,
|
||||
worktreePath: options?.worktreePath ?? null,
|
||||
});
|
||||
dispatch({
|
||||
type: "ADD_THREAD",
|
||||
thread,
|
||||
});
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: thread.id },
|
||||
});
|
||||
},
|
||||
[api, dispatch, navigate, state.projects],
|
||||
[dispatch, navigate, state.projects],
|
||||
);
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
@@ -240,7 +190,29 @@ export default function Sidebar() {
|
||||
|
||||
setIsAddingProject(true);
|
||||
try {
|
||||
if (!api) {
|
||||
if (isElectron && api) {
|
||||
const result = await api.projects.add({ cwd });
|
||||
const project: Project = {
|
||||
id: result.project.id,
|
||||
name: result.project.name,
|
||||
cwd: result.project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
scripts: result.project.scripts,
|
||||
};
|
||||
const existingById = state.projects.find((p) => p.id === project.id);
|
||||
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
|
||||
if (!existingById && !existingByCwd) {
|
||||
dispatch({ type: "ADD_PROJECT", project });
|
||||
}
|
||||
const resolvedProjectId = existingByCwd?.id ?? project.id;
|
||||
|
||||
if (result.created) {
|
||||
handleNewThread(resolvedProjectId);
|
||||
} else {
|
||||
focusMostRecentThreadForProject(resolvedProjectId);
|
||||
}
|
||||
} else {
|
||||
const existing = state.projects.find((project) => project.cwd === cwd);
|
||||
if (existing) {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
@@ -258,29 +230,6 @@ export default function Sidebar() {
|
||||
};
|
||||
dispatch({ type: "ADD_PROJECT", project });
|
||||
handleNewThread(project.id);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await api.projects.add({ cwd });
|
||||
const project: Project = {
|
||||
id: result.project.id,
|
||||
name: result.project.name,
|
||||
cwd: result.project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
scripts: result.project.scripts,
|
||||
};
|
||||
const existingById = state.projects.find((p) => p.id === project.id);
|
||||
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
|
||||
if (!existingById && !existingByCwd) {
|
||||
dispatch({ type: "ADD_PROJECT", project });
|
||||
}
|
||||
const resolvedProjectId = existingByCwd?.id ?? project.id;
|
||||
|
||||
if (result.created) {
|
||||
handleNewThread(resolvedProjectId);
|
||||
} else {
|
||||
focusMostRecentThreadForProject(resolvedProjectId);
|
||||
}
|
||||
} finally {
|
||||
setIsAddingProject(false);
|
||||
@@ -322,17 +271,6 @@ export default function Sidebar() {
|
||||
|
||||
const thread = state.threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
if (appSettings.confirmThreadDelete) {
|
||||
const confirmed = await api.dialogs.confirm(
|
||||
[
|
||||
`Delete thread \"${thread.title}\"?`,
|
||||
"This permanently clears conversation history for this thread.",
|
||||
].join("\n"),
|
||||
);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const threadProject = state.projects.find((project) => project.id === thread.projectId);
|
||||
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
|
||||
const displayWorktreePath = orphanedWorktreePath
|
||||
@@ -372,7 +310,6 @@ export default function Sidebar() {
|
||||
|
||||
const shouldNavigateToFallback = routeThreadId === threadId;
|
||||
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
||||
void api.threads.delete({ threadId }).catch(() => undefined);
|
||||
dispatch({ type: "DELETE_THREAD", threadId });
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
@@ -394,7 +331,6 @@ export default function Sidebar() {
|
||||
await removeWorktreeMutation.mutateAsync({
|
||||
cwd: threadProject.cwd,
|
||||
path: orphanedWorktreePath,
|
||||
force: true,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
|
||||
@@ -411,16 +347,7 @@ export default function Sidebar() {
|
||||
});
|
||||
}
|
||||
},
|
||||
[
|
||||
api,
|
||||
appSettings.confirmThreadDelete,
|
||||
dispatch,
|
||||
navigate,
|
||||
removeWorktreeMutation,
|
||||
routeThreadId,
|
||||
state.projects,
|
||||
state.threads,
|
||||
],
|
||||
[api, dispatch, navigate, removeWorktreeMutation, routeThreadId, state.projects, state.threads],
|
||||
);
|
||||
|
||||
const handleProjectContextMenu = useCallback(
|
||||
@@ -503,14 +430,24 @@ export default function Sidebar() {
|
||||
<div
|
||||
className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<span className="truncate text-sm font-semibold tracking-tight text-foreground">
|
||||
T3 <span className="font-normal text-muted-foreground">Code</span>
|
||||
</span>
|
||||
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">
|
||||
{APP_STAGE_LABEL}
|
||||
</span>
|
||||
</div>
|
||||
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
|
||||
T3 <span className="font-normal text-muted-foreground">Code</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1.5 text-muted-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-muted-foreground"
|
||||
onClick={() => setTheme(THEME_CYCLE[theme])}
|
||||
aria-label={`Theme: ${theme}`}
|
||||
title={`Theme: ${theme}`}
|
||||
>
|
||||
{theme === "system" ? (
|
||||
<MonitorIcon className="size-3.5" />
|
||||
) : theme === "light" ? (
|
||||
<SunIcon className="size-3.5" />
|
||||
) : (
|
||||
<MoonIcon className="size-3.5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* New thread (global) */}
|
||||
|
||||
@@ -252,7 +252,6 @@ function TerminalViewport({
|
||||
),
|
||||
);
|
||||
});
|
||||
let didReceiveRenderableEventSinceOpen = false;
|
||||
|
||||
const themeObserver = new MutationObserver(() => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
@@ -280,14 +279,9 @@ function TerminalViewport({
|
||||
...(runtimeEnv ? { env: runtimeEnv } : {}),
|
||||
});
|
||||
if (disposed) return;
|
||||
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);
|
||||
}
|
||||
activeTerminal.write("\u001bc");
|
||||
if (snapshot.history.length > 0) {
|
||||
activeTerminal.write(snapshot.history);
|
||||
}
|
||||
if (autoFocus) {
|
||||
window.requestAnimationFrame(() => {
|
||||
@@ -308,10 +302,6 @@ function TerminalViewport({
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) return;
|
||||
|
||||
if (event.type !== "activity") {
|
||||
didReceiveRenderableEventSinceOpen = true;
|
||||
}
|
||||
|
||||
if (event.type === "output") {
|
||||
activeTerminal.write(event.data);
|
||||
return;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { Toast } from "@base-ui/react/toast";
|
||||
import { useEffect } from "react";
|
||||
import { useParams } from "@tanstack/react-router";
|
||||
import { useRouterState } from "@tanstack/react-router";
|
||||
import {
|
||||
CircleAlertIcon,
|
||||
CircleCheckIcon,
|
||||
@@ -56,9 +56,17 @@ function shouldRenderForActiveThread(
|
||||
}
|
||||
|
||||
function useActiveThreadIdFromRoute(): string | null {
|
||||
return useParams({
|
||||
strict: false,
|
||||
select: (params) => params.threadId ?? null,
|
||||
return useRouterState({
|
||||
select: (routerState) => {
|
||||
for (let index = routerState.matches.length - 1; index >= 0; index -= 1) {
|
||||
const params = routerState.matches[index]?.params as Record<string, unknown> | undefined;
|
||||
const threadId = params?.threadId;
|
||||
if (typeof threadId === "string" && threadId.length > 0) {
|
||||
return threadId;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseDiffRouteSearch } from "./diffRouteSearch";
|
||||
|
||||
describe("parseDiffRouteSearch", () => {
|
||||
it("parses valid diff search values", () => {
|
||||
const parsed = parseDiffRouteSearch({
|
||||
diff: "1",
|
||||
diffTurnId: "turn-1",
|
||||
diffFilePath: "src/app.ts",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
diff: "1",
|
||||
diffTurnId: "turn-1",
|
||||
diffFilePath: "src/app.ts",
|
||||
});
|
||||
});
|
||||
|
||||
it("treats numeric and boolean diff toggles as open", () => {
|
||||
expect(
|
||||
parseDiffRouteSearch({
|
||||
diff: 1,
|
||||
diffTurnId: "turn-1",
|
||||
}),
|
||||
).toEqual({
|
||||
diff: "1",
|
||||
diffTurnId: "turn-1",
|
||||
});
|
||||
|
||||
expect(
|
||||
parseDiffRouteSearch({
|
||||
diff: true,
|
||||
diffTurnId: "turn-1",
|
||||
}),
|
||||
).toEqual({
|
||||
diff: "1",
|
||||
diffTurnId: "turn-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("drops turn and file values when diff is closed", () => {
|
||||
const parsed = parseDiffRouteSearch({
|
||||
diff: "0",
|
||||
diffTurnId: "turn-1",
|
||||
diffFilePath: "src/app.ts",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({});
|
||||
});
|
||||
|
||||
it("drops file value when turn is not selected", () => {
|
||||
const parsed = parseDiffRouteSearch({
|
||||
diff: "1",
|
||||
diffFilePath: "src/app.ts",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
diff: "1",
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes whitespace-only values", () => {
|
||||
const parsed = parseDiffRouteSearch({
|
||||
diff: "1",
|
||||
diffTurnId: " ",
|
||||
diffFilePath: " ",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
diff: "1",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
export interface DiffRouteSearch {
|
||||
diff?: "1";
|
||||
diffTurnId?: string;
|
||||
diffFilePath?: string;
|
||||
}
|
||||
|
||||
function isDiffOpenValue(value: unknown): boolean {
|
||||
return value === "1" || value === 1 || value === true;
|
||||
}
|
||||
|
||||
function normalizeSearchString(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = value.trim();
|
||||
return normalized.length > 0 ? normalized : undefined;
|
||||
}
|
||||
|
||||
export function stripDiffSearchParams<T extends Record<string, unknown>>(
|
||||
params: T,
|
||||
): Omit<T, "diff" | "diffTurnId" | "diffFilePath"> {
|
||||
const { diff: _diff, diffTurnId: _diffTurnId, diffFilePath: _diffFilePath, ...rest } = params;
|
||||
return rest as Omit<T, "diff" | "diffTurnId" | "diffFilePath">;
|
||||
}
|
||||
|
||||
export function parseDiffRouteSearch(search: Record<string, unknown>): DiffRouteSearch {
|
||||
const diff = isDiffOpenValue(search.diff) ? "1" : undefined;
|
||||
const diffTurnId = diff ? normalizeSearchString(search.diffTurnId) : undefined;
|
||||
const diffFilePath = diff && diffTurnId ? normalizeSearchString(search.diffFilePath) : undefined;
|
||||
|
||||
return {
|
||||
...(diff ? { diff } : {}),
|
||||
...(diffTurnId ? { diffTurnId } : {}),
|
||||
...(diffFilePath ? { diffFilePath } : {}),
|
||||
};
|
||||
}
|
||||
@@ -190,16 +190,6 @@ input {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
.turn-chip-strip {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
overscroll-behavior-x: contain;
|
||||
}
|
||||
|
||||
.turn-chip-strip::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Terminal drawer scrollbar parity with chat */
|
||||
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical {
|
||||
width: 6px !important;
|
||||
|
||||
@@ -173,11 +173,11 @@ export function gitRemoveWorktreeMutationOptions(input: {
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationFn: async ({ cwd, path, force }: { cwd: string; path: string; force?: boolean }) => {
|
||||
mutationFn: async ({ cwd, path }: { cwd: string; path: string }) => {
|
||||
if (!input.api) {
|
||||
throw new Error("Git worktree removal is unavailable.");
|
||||
}
|
||||
return input.api.git.removeWorktree({ cwd, path, force });
|
||||
return input.api.git.removeWorktree({ cwd, path });
|
||||
},
|
||||
onSettled: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
|
||||
@@ -52,60 +52,4 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
toTurnCount: 4,
|
||||
});
|
||||
});
|
||||
|
||||
it("retries checkpoint-not-ready errors longer than generic failures", () => {
|
||||
const options = checkpointDiffQueryOptions(undefined, {
|
||||
sessionId: "session-id",
|
||||
threadRuntimeId: "thread-id",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
const retry = options.retry;
|
||||
expect(typeof retry).toBe("function");
|
||||
if (typeof retry !== "function") {
|
||||
throw new Error("Expected retry to be a function.");
|
||||
}
|
||||
|
||||
expect(retry(1, new Error("Checkpoint turn count 2 exceeds current turn count 1."))).toBe(true);
|
||||
expect(
|
||||
retry(
|
||||
11,
|
||||
new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1."),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
retry(
|
||||
12,
|
||||
new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1."),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(retry(2, new Error("Something else failed."))).toBe(true);
|
||||
expect(retry(3, new Error("Something else failed."))).toBe(false);
|
||||
});
|
||||
|
||||
it("backs off longer for checkpoint-not-ready errors", () => {
|
||||
const options = checkpointDiffQueryOptions(undefined, {
|
||||
sessionId: "session-id",
|
||||
threadRuntimeId: "thread-id",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
const retryDelay = options.retryDelay;
|
||||
expect(typeof retryDelay).toBe("function");
|
||||
if (typeof retryDelay !== "function") {
|
||||
throw new Error("Expected retryDelay to be a function.");
|
||||
}
|
||||
|
||||
const checkpointDelay = retryDelay(
|
||||
4,
|
||||
new Error("Checkpoint turn count 2 exceeds current turn count 1."),
|
||||
);
|
||||
const genericDelay = retryDelay(4, new Error("Network failure"));
|
||||
|
||||
expect(typeof checkpointDelay).toBe("number");
|
||||
expect(typeof genericDelay).toBe("number");
|
||||
expect((checkpointDelay ?? 0) > (genericDelay ?? 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -23,25 +23,6 @@ export const providerQueryKeys = {
|
||||
] as const,
|
||||
};
|
||||
|
||||
function asCheckpointErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
if (typeof error === "string") {
|
||||
return error;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
|
||||
const message = asCheckpointErrorMessage(error).toLowerCase();
|
||||
return (
|
||||
message.includes("exceeds current turn count") ||
|
||||
message.includes("checkpoint is unavailable for turn") ||
|
||||
message.includes("filesystem checkpoint is unavailable")
|
||||
);
|
||||
}
|
||||
|
||||
export function checkpointDiffQueryOptions(
|
||||
api: NativeApi | undefined,
|
||||
input: CheckpointDiffQueryInput,
|
||||
@@ -73,15 +54,7 @@ export function checkpointDiffQueryOptions(
|
||||
},
|
||||
enabled: !!api && !!input.sessionId && hasValidRange,
|
||||
staleTime: Infinity,
|
||||
retry: (failureCount, error) => {
|
||||
if (isCheckpointTemporarilyUnavailable(error)) {
|
||||
return failureCount < 12;
|
||||
}
|
||||
return failureCount < 3;
|
||||
},
|
||||
retryDelay: (attempt, error) =>
|
||||
isCheckpointTemporarilyUnavailable(error)
|
||||
? Math.min(5_000, 250 * 2 ** (attempt - 1))
|
||||
: Math.min(1_000, 100 * 2 ** (attempt - 1)),
|
||||
retry: 8,
|
||||
retryDelay: (attempt) => Math.min(2_000, 150 * 2 ** (attempt - 1)),
|
||||
});
|
||||
}
|
||||
@@ -9,14 +9,12 @@ import "@xterm/xterm/css/xterm.css";
|
||||
import "highlight.js/styles/github-dark.css";
|
||||
import "./index.css";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
import { isElectron } from "./env";
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
|
||||
const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
document.title = APP_DISPLAY_NAME;
|
||||
|
||||
const router = createRouter({
|
||||
routeTree,
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DEFAULT_MODEL } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
describe("hydratePersistedState", () => {
|
||||
it("returns null for invalid payloads", () => {
|
||||
expect(hydratePersistedState('{"projects":"bad"}', false)).toBeNull();
|
||||
expect(hydratePersistedState("not-json", false)).toBeNull();
|
||||
});
|
||||
|
||||
it("migrates the legacy default model to the current default", () => {
|
||||
const payload = JSON.stringify({
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.2-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.2-codex",
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "assistant",
|
||||
text: "Hello",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: true,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, true);
|
||||
expect(hydrated).not.toBeNull();
|
||||
expect(hydrated?.projects[0]?.model).toBe(DEFAULT_MODEL);
|
||||
expect(hydrated?.threads[0]?.model).toBe(DEFAULT_MODEL);
|
||||
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
|
||||
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
|
||||
expect(hydrated?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("filters unknown project references and repairs active thread", () => {
|
||||
const payload = JSON.stringify({
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
projectId: "p-1",
|
||||
title: "Valid thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: "t-2",
|
||||
projectId: "p-missing",
|
||||
title: "Dangling thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-2",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated).not.toBeNull();
|
||||
expect(hydrated?.threads.map((thread) => thread.id)).toEqual(["t-1"]);
|
||||
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
|
||||
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
expect(hydrated?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("hydrates runtime mode from v3 payload", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 3,
|
||||
runtimeMode: "approval-required",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
activeThreadId: null,
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("hydrates terminal fields from legacy v6 payload", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 6,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 360,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalLayout: "tabs",
|
||||
splitTerminalIds: [],
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
lastVisitedAt: "2026-02-08T10:01:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.terminalOpen).toBe(true);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(360);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe("term-2");
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
|
||||
expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z");
|
||||
});
|
||||
|
||||
it("hydrates legacy split layout into a grouped split", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 6,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 360,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalLayout: "split",
|
||||
splitTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("defaults terminalHeight when hydrating v5 payloads", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 5,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("hydrates persisted turn diff summaries and clears persisted loaded flags", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 7,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
checkpointTurnCount: 1,
|
||||
checkpointDiffLoaded: true,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops malformed persisted turn diff summaries instead of rejecting the whole snapshot", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 7,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
files: [{ path: 123 }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated).not.toBeNull();
|
||||
expect(hydrated?.threads[0]?.id).toBe("t-1");
|
||||
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toPersistedState", () => {
|
||||
it("writes v7 payload and strips non-persisted thread fields", () => {
|
||||
const thread: Thread = {
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-2",
|
||||
session: null,
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4_096,
|
||||
previewUrl: "blob:preview-1",
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
events: [],
|
||||
error: "boom",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
lastVisitedAt: "2026-02-08T10:02:00.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
status: "completed",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
diff: "diff --git a/src/app.ts b/src/app.ts",
|
||||
},
|
||||
],
|
||||
unifiedDiff: "diff --git a/src/app.ts b/src/app.ts",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const persisted = toPersistedState({
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
expect(persisted.version).toBe(7);
|
||||
expect(persisted.runtimeMode).toBe("full-access");
|
||||
expect(persisted.threads[0]).toEqual({
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-2",
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4_096,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
createdAt: thread.createdAt,
|
||||
lastVisitedAt: thread.lastVisitedAt,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
status: "completed",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const persistedThread = persisted.threads[0];
|
||||
expect(persistedThread).toBeDefined();
|
||||
if (!persistedThread) return;
|
||||
|
||||
expect("error" in persistedThread).toBe(false);
|
||||
expect("session" in persistedThread).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,400 @@
|
||||
import { z } from "zod";
|
||||
import { projectScriptSchema } from "@t3tools/contracts";
|
||||
|
||||
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
|
||||
|
||||
const persistedProjectSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
cwd: z.string().min(1),
|
||||
model: z.string().min(1),
|
||||
expanded: z.boolean(),
|
||||
scripts: z.array(projectScriptSchema).default([]),
|
||||
});
|
||||
|
||||
const persistedMessageSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
role: z.enum(["user", "assistant"]),
|
||||
text: z.string(),
|
||||
attachments: z
|
||||
.array(
|
||||
z.object({
|
||||
type: z.literal("image"),
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
mimeType: z.string().min(1),
|
||||
sizeBytes: z.number().int().min(1),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
createdAt: z.string().min(1),
|
||||
streaming: z.boolean(),
|
||||
});
|
||||
|
||||
const persistedTerminalGroupSchema = z.object({
|
||||
id: z.string().trim().min(1),
|
||||
terminalIds: z.array(z.string().trim().min(1)),
|
||||
});
|
||||
|
||||
const persistedTurnDiffFileChangeSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
kind: z.string().min(1).optional(),
|
||||
additions: z.number().int().min(0).optional(),
|
||||
deletions: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
const persistedTurnDiffSummarySchema = z.object({
|
||||
turnId: z.string().min(1),
|
||||
completedAt: z.string().min(1),
|
||||
status: z.string().min(1).optional(),
|
||||
files: z.array(persistedTurnDiffFileChangeSchema),
|
||||
assistantMessageId: z.string().min(1).optional(),
|
||||
checkpointTurnCount: z.number().int().min(0).optional(),
|
||||
checkpointDiffLoaded: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const persistedThreadSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
codexThreadId: z.string().min(1).nullable().default(null),
|
||||
projectId: z.string().min(1),
|
||||
title: z.string().min(1),
|
||||
model: z.string().min(1),
|
||||
terminalOpen: z.boolean().default(false),
|
||||
terminalHeight: z.number().int().min(120).max(4_096).default(DEFAULT_THREAD_TERMINAL_HEIGHT),
|
||||
terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]),
|
||||
activeTerminalId: z.string().trim().min(1).default(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalGroups: z.array(persistedTerminalGroupSchema).default([]),
|
||||
activeTerminalGroupId: z.string().trim().min(1).optional(),
|
||||
// Legacy v6 and older fields retained for migration.
|
||||
terminalLayout: z.enum(["single", "split", "tabs"]).optional(),
|
||||
splitTerminalIds: z.array(z.string().trim().min(1)).optional(),
|
||||
messages: z.array(persistedMessageSchema),
|
||||
createdAt: z.string().min(1),
|
||||
lastVisitedAt: z.string().min(1).optional(),
|
||||
branch: z.string().min(1).nullable().optional(),
|
||||
worktreePath: z.string().min(1).nullable().optional(),
|
||||
turnDiffSummaries: z.array(persistedTurnDiffSummarySchema).catch([]).default([]),
|
||||
});
|
||||
|
||||
const persistedStateBodySchema = z.object({
|
||||
projects: z.array(persistedProjectSchema),
|
||||
threads: z.array(persistedThreadSchema),
|
||||
activeThreadId: z.string().min(1).nullable().optional(),
|
||||
});
|
||||
|
||||
const runtimeModeSchema = z.enum(["approval-required", "full-access"]);
|
||||
|
||||
export const persistedStateV1Schema = persistedStateBodySchema.extend({
|
||||
version: z.literal(1).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV2Schema = persistedStateBodySchema.extend({
|
||||
version: z.literal(2).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV3Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(3).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV4Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(4).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV6Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(6).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV7Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(7).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV5Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(5).optional(),
|
||||
});
|
||||
|
||||
const persistedStateSchema = z.union([
|
||||
persistedStateV7Schema,
|
||||
persistedStateV6Schema,
|
||||
persistedStateV5Schema,
|
||||
persistedStateV4Schema,
|
||||
persistedStateV3Schema,
|
||||
persistedStateV2Schema,
|
||||
persistedStateV1Schema,
|
||||
]);
|
||||
|
||||
export interface PersistedStoreSnapshot {
|
||||
projects: Project[];
|
||||
threads: Thread[];
|
||||
runtimeMode: RuntimeMode;
|
||||
}
|
||||
|
||||
function maybeMigrateLegacyModel(model: string, isLegacyPayload: boolean): string {
|
||||
if (!isLegacyPayload) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return model === LEGACY_DEFAULT_MODEL ? DEFAULT_MODEL : model;
|
||||
}
|
||||
|
||||
function hydrateProject(
|
||||
project: z.infer<typeof persistedProjectSchema>,
|
||||
isLegacyPayload: boolean,
|
||||
): Project {
|
||||
return {
|
||||
...project,
|
||||
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
|
||||
scripts: project.scripts,
|
||||
};
|
||||
}
|
||||
|
||||
function hydrateThread(
|
||||
thread: z.infer<typeof persistedThreadSchema>,
|
||||
isLegacyPayload: boolean,
|
||||
): Thread {
|
||||
const terminalIds = [
|
||||
...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
|
||||
];
|
||||
const safeTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
|
||||
? thread.activeTerminalId
|
||||
: (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const safeTerminalIdSet = new Set(safeTerminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const usedGroupIds = new Set<string>();
|
||||
const normalizedGroups: ThreadTerminalGroup[] = [];
|
||||
const assignUniqueGroupId = (groupId: string): string => {
|
||||
if (!usedGroupIds.has(groupId)) {
|
||||
usedGroupIds.add(groupId);
|
||||
return groupId;
|
||||
}
|
||||
let suffix = 2;
|
||||
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
const uniqueGroupId = `${groupId}-${suffix}`;
|
||||
usedGroupIds.add(uniqueGroupId);
|
||||
return uniqueGroupId;
|
||||
};
|
||||
|
||||
for (const terminalGroup of thread.terminalGroups) {
|
||||
const nextTerminalIds = [
|
||||
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
|
||||
].filter((terminalId) => {
|
||||
if (!safeTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (nextTerminalIds.length === 0) continue;
|
||||
for (const terminalId of nextTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
terminalGroup.id.trim().length > 0
|
||||
? terminalGroup.id.trim()
|
||||
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId),
|
||||
terminalIds: nextTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
|
||||
const splitTerminalIds = [
|
||||
...new Set(
|
||||
(thread.splitTerminalIds ?? []).map((id) => id.trim()).filter((id) => id.length > 0),
|
||||
),
|
||||
].filter((terminalId) => safeTerminalIdSet.has(terminalId));
|
||||
if (splitTerminalIds.length >= 2) {
|
||||
const splitGroupTerminalIds = splitTerminalIds.slice(0, 2);
|
||||
for (const terminalId of splitGroupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(`group-${splitGroupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`),
|
||||
terminalIds: splitGroupTerminalIds,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const terminalId of safeTerminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(`group-${terminalId}`),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
const activeGroupIndexFromId = normalizedGroups.findIndex(
|
||||
(terminalGroup) => terminalGroup.id === thread.activeTerminalGroupId,
|
||||
);
|
||||
const activeGroupIndexFromTerminal = normalizedGroups.findIndex((terminalGroup) =>
|
||||
terminalGroup.terminalIds.includes(activeTerminalId),
|
||||
);
|
||||
const activeGroupIndex =
|
||||
activeGroupIndexFromId >= 0
|
||||
? activeGroupIndexFromId
|
||||
: activeGroupIndexFromTerminal >= 0
|
||||
? activeGroupIndexFromTerminal
|
||||
: 0;
|
||||
const activeTerminalGroupId =
|
||||
normalizedGroups[activeGroupIndex]?.id ??
|
||||
normalizedGroups[0]?.id ??
|
||||
`group-${DEFAULT_THREAD_TERMINAL_ID}`;
|
||||
|
||||
return {
|
||||
id: thread.id,
|
||||
codexThreadId: thread.codexThreadId,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
|
||||
terminalOpen: thread.terminalOpen ?? false,
|
||||
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: safeTerminalIds,
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId,
|
||||
terminalGroups: normalizedGroups,
|
||||
activeTerminalGroupId,
|
||||
session: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
|
||||
return {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
...(hydratedAttachments && hydratedAttachments.length > 0
|
||||
? { attachments: hydratedAttachments }
|
||||
: {}),
|
||||
createdAt: message.createdAt,
|
||||
streaming: false,
|
||||
};
|
||||
}),
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: thread.createdAt,
|
||||
lastVisitedAt: thread.lastVisitedAt,
|
||||
branch: thread.branch ?? null,
|
||||
worktreePath: thread.worktreePath ?? null,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files: summary.files.map((file) => ({
|
||||
path: file.path,
|
||||
...(file.kind ? { kind: file.kind } : {}),
|
||||
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
|
||||
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
|
||||
})),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: summary.checkpointTurnCount }
|
||||
: {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function hydratePersistedState(
|
||||
raw: string,
|
||||
isLegacyPayload: boolean,
|
||||
): PersistedStoreSnapshot | null {
|
||||
let parsedJson: unknown;
|
||||
try {
|
||||
parsedJson = JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsedState = persistedStateSchema.safeParse(parsedJson);
|
||||
if (!parsedState.success) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const projects = parsedState.data.projects.map((project) =>
|
||||
hydrateProject(project, isLegacyPayload),
|
||||
);
|
||||
const projectIds = new Set(projects.map((project) => project.id));
|
||||
const threads = parsedState.data.threads
|
||||
.map((thread) => hydrateThread(thread, isLegacyPayload))
|
||||
.filter((thread) => projectIds.has(thread.projectId));
|
||||
return {
|
||||
projects,
|
||||
threads,
|
||||
runtimeMode:
|
||||
"runtimeMode" in parsedState.data ? parsedState.data.runtimeMode : DEFAULT_RUNTIME_MODE,
|
||||
};
|
||||
}
|
||||
|
||||
export function toPersistedState(
|
||||
state: PersistedStoreSnapshot,
|
||||
): z.infer<typeof persistedStateV7Schema> {
|
||||
return {
|
||||
version: 7,
|
||||
projects: state.projects,
|
||||
threads: state.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
codexThreadId: thread.codexThreadId,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: thread.model,
|
||||
terminalOpen: thread.terminalOpen,
|
||||
terminalHeight: thread.terminalHeight,
|
||||
terminalIds: thread.terminalIds,
|
||||
activeTerminalId: thread.activeTerminalId,
|
||||
terminalGroups: thread.terminalGroups,
|
||||
activeTerminalGroupId: thread.activeTerminalGroupId,
|
||||
messages: thread.messages.map((message) => ({
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
...(message.attachments && message.attachments.length > 0
|
||||
? {
|
||||
attachments: message.attachments.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
})),
|
||||
createdAt: thread.createdAt,
|
||||
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files: summary.files.map((file) => ({
|
||||
path: file.path,
|
||||
...(file.kind ? { kind: file.kind } : {}),
|
||||
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
|
||||
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
|
||||
})),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: summary.checkpointTurnCount }
|
||||
: {}),
|
||||
})),
|
||||
})),
|
||||
runtimeMode: state.runtimeMode,
|
||||
};
|
||||
}
|
||||
@@ -11,7 +11,6 @@
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as ChatRouteImport } from './routes/_chat'
|
||||
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
|
||||
import { Route as ChatSettingsRouteImport } from './routes/_chat.settings'
|
||||
import { Route as ChatThreadIdRouteImport } from './routes/_chat.$threadId'
|
||||
|
||||
const ChatRoute = ChatRouteImport.update({
|
||||
@@ -23,11 +22,6 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
|
||||
path: '/',
|
||||
getParentRoute: () => ChatRoute,
|
||||
} as any)
|
||||
const ChatSettingsRoute = ChatSettingsRouteImport.update({
|
||||
id: '/settings',
|
||||
path: '/settings',
|
||||
getParentRoute: () => ChatRoute,
|
||||
} as any)
|
||||
const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
|
||||
id: '/$threadId',
|
||||
path: '/$threadId',
|
||||
@@ -37,26 +31,23 @@ const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof ChatIndexRoute
|
||||
'/$threadId': typeof ChatThreadIdRoute
|
||||
'/settings': typeof ChatSettingsRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/$threadId': typeof ChatThreadIdRoute
|
||||
'/settings': typeof ChatSettingsRoute
|
||||
'/': typeof ChatIndexRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/_chat': typeof ChatRouteWithChildren
|
||||
'/_chat/$threadId': typeof ChatThreadIdRoute
|
||||
'/_chat/settings': typeof ChatSettingsRoute
|
||||
'/_chat/': typeof ChatIndexRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths: '/' | '/$threadId' | '/settings'
|
||||
fullPaths: '/' | '/$threadId'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/$threadId' | '/settings' | '/'
|
||||
id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/settings' | '/_chat/'
|
||||
to: '/$threadId' | '/'
|
||||
id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
@@ -79,13 +70,6 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof ChatIndexRouteImport
|
||||
parentRoute: typeof ChatRoute
|
||||
}
|
||||
'/_chat/settings': {
|
||||
id: '/_chat/settings'
|
||||
path: '/settings'
|
||||
fullPath: '/settings'
|
||||
preLoaderRoute: typeof ChatSettingsRouteImport
|
||||
parentRoute: typeof ChatRoute
|
||||
}
|
||||
'/_chat/$threadId': {
|
||||
id: '/_chat/$threadId'
|
||||
path: '/$threadId'
|
||||
@@ -98,13 +82,11 @@ declare module '@tanstack/react-router' {
|
||||
|
||||
interface ChatRouteChildren {
|
||||
ChatThreadIdRoute: typeof ChatThreadIdRoute
|
||||
ChatSettingsRoute: typeof ChatSettingsRoute
|
||||
ChatIndexRoute: typeof ChatIndexRoute
|
||||
}
|
||||
|
||||
const ChatRouteChildren: ChatRouteChildren = {
|
||||
ChatThreadIdRoute: ChatThreadIdRoute,
|
||||
ChatSettingsRoute: ChatSettingsRoute,
|
||||
ChatIndexRoute: ChatIndexRoute,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,12 @@
|
||||
import {
|
||||
Outlet,
|
||||
createRootRouteWithContext,
|
||||
type ErrorComponentProps,
|
||||
useParams,
|
||||
} from "@tanstack/react-router";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { Outlet, createRootRouteWithContext, useParams } from "@tanstack/react-router";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "../branding";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
|
||||
import { isElectron } from "../env";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { invalidateGitQueries } from "../lib/gitReactQuery";
|
||||
import { createStateSource } from "../stateSource";
|
||||
import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { useStore } from "../store";
|
||||
import { onServerWelcome } from "../wsNativeApi";
|
||||
|
||||
@@ -21,7 +14,6 @@ export const Route = createRootRouteWithContext<{
|
||||
queryClient: QueryClient;
|
||||
}>()({
|
||||
component: RootRouteView,
|
||||
errorComponent: RootRouteErrorView,
|
||||
});
|
||||
|
||||
function RootRouteView() {
|
||||
@@ -31,9 +23,7 @@ function RootRouteView() {
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background text-foreground">
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Connecting to {APP_DISPLAY_NAME} server...
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">Connecting to T3 Code server...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -42,86 +32,16 @@ function RootRouteView() {
|
||||
return (
|
||||
<ToastProvider>
|
||||
<AnchoredToastProvider>
|
||||
<StateSyncRouter />
|
||||
<BrowserDefaultProjectBootstrap />
|
||||
<EventRouter />
|
||||
<AutoProjectBootstrap />
|
||||
<DesktopProjectBootstrap />
|
||||
<Outlet />
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
|
||||
const message = errorMessage(error);
|
||||
const details = errorDetails(error);
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
|
||||
<div className="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-red-500)_16%,transparent),transparent)]" />
|
||||
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
|
||||
</div>
|
||||
|
||||
<section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
|
||||
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
|
||||
{APP_DISPLAY_NAME}
|
||||
</p>
|
||||
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
|
||||
Something went wrong.
|
||||
</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
|
||||
|
||||
<div className="mt-5 flex flex-wrap gap-2">
|
||||
<Button size="sm" onClick={() => reset()}>
|
||||
Try again
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => window.location.reload()}>
|
||||
Reload app
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
|
||||
<summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
|
||||
<span className="group-open:hidden">Show error details</span>
|
||||
<span className="hidden group-open:inline">Hide error details</span>
|
||||
</summary>
|
||||
<pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
|
||||
{details}
|
||||
</pre>
|
||||
</details>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
if (typeof error === "string" && error.trim().length > 0) {
|
||||
return error;
|
||||
}
|
||||
|
||||
return "An unexpected router error occurred.";
|
||||
}
|
||||
|
||||
function errorDetails(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.stack ?? error.message;
|
||||
}
|
||||
|
||||
if (typeof error === "string") {
|
||||
return error;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.stringify(error, null, 2);
|
||||
} catch {
|
||||
return "No additional error details are available.";
|
||||
}
|
||||
}
|
||||
|
||||
function StateSyncRouter() {
|
||||
function EventRouter() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
@@ -130,77 +50,6 @@ function StateSyncRouter() {
|
||||
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;
|
||||
@@ -208,17 +57,6 @@ function StateSyncRouter() {
|
||||
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",
|
||||
@@ -229,22 +67,6 @@ function StateSyncRouter() {
|
||||
});
|
||||
}, [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);
|
||||
}, [activeThreadId, api, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.terminal.onEvent((event) => {
|
||||
@@ -258,33 +80,96 @@ function StateSyncRouter() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function BrowserDefaultProjectBootstrap() {
|
||||
const api = useNativeApi();
|
||||
const { state } = useStore();
|
||||
const createdRef = useRef(false);
|
||||
function AutoProjectBootstrap() {
|
||||
const { state, dispatch } = useStore();
|
||||
const bootstrappedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isElectron || !api || !state.threadsHydrated) {
|
||||
return;
|
||||
}
|
||||
// Browser mode bootstraps from server welcome.
|
||||
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
|
||||
if (isElectron) return;
|
||||
|
||||
return onServerWelcome((payload) => {
|
||||
if (createdRef.current) {
|
||||
return;
|
||||
}
|
||||
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) {
|
||||
createdRef.current = true;
|
||||
bootstrappedRef.current = true;
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
return;
|
||||
}
|
||||
|
||||
createdRef.current = true;
|
||||
void api.projects.add({ cwd: payload.cwd }).catch(() => {
|
||||
createdRef.current = false;
|
||||
bootstrappedRef.current = true;
|
||||
|
||||
// Create project + thread from server cwd
|
||||
const projectId = crypto.randomUUID();
|
||||
dispatch({
|
||||
type: "ADD_PROJECT",
|
||||
project: {
|
||||
id: projectId,
|
||||
name: payload.projectName,
|
||||
cwd: payload.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
});
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
});
|
||||
}, [api, state.projects, state.threadsHydrated]);
|
||||
}, [state.projects, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function DesktopProjectBootstrap() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
const bootstrappedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isElectron || !api || bootstrappedRef.current) return;
|
||||
|
||||
let disposed = false;
|
||||
let retryDelayMs = 500;
|
||||
let retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const attemptBootstrap = async () => {
|
||||
try {
|
||||
const projects = await api.projects.list();
|
||||
if (disposed) return;
|
||||
dispatch({
|
||||
type: "SYNC_PROJECTS",
|
||||
projects: projects.map((project) => ({
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
cwd: project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
scripts: project.scripts,
|
||||
})),
|
||||
});
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
bootstrappedRef.current = true;
|
||||
} catch {
|
||||
if (disposed) return;
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
void attemptBootstrap();
|
||||
}, retryDelayMs);
|
||||
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
|
||||
}
|
||||
};
|
||||
|
||||
void attemptBootstrap();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
if (retryTimer) {
|
||||
clearTimeout(retryTimer);
|
||||
}
|
||||
};
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,67 +1,14 @@
|
||||
import { createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import ChatView from "../components/ChatView";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { useStore } from "../store";
|
||||
import { Sheet, SheetPopup } from "../components/ui/sheet";
|
||||
|
||||
const DiffPanel = lazy(() => import("../components/DiffPanel"));
|
||||
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
|
||||
|
||||
const DiffPanelWrapper = (props: {
|
||||
children: ReactNode;
|
||||
sheet: boolean;
|
||||
diffOpen: boolean;
|
||||
onCloseDiff: () => void;
|
||||
}) => {
|
||||
if (props.sheet) {
|
||||
return (
|
||||
<Sheet
|
||||
open={props.diffOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
props.onCloseDiff();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SheetPopup
|
||||
side="right"
|
||||
showCloseButton={false}
|
||||
keepMounted
|
||||
className="w-[min(88vw,820px)] max-w-[820px] p-0"
|
||||
>
|
||||
{props.children}
|
||||
</SheetPopup>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className={props.diffOpen ? undefined : "hidden"} aria-hidden={!props.diffOpen}>
|
||||
{props.children}
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
|
||||
function ChatThreadRouteView() {
|
||||
const { state } = useStore();
|
||||
const navigate = useNavigate();
|
||||
const { threadId } = Route.useParams();
|
||||
const search = Route.useSearch();
|
||||
const threadExists = threadId ? state.threads.some((thread) => thread.id === threadId) : false;
|
||||
const diffOpen = search.diff === "1";
|
||||
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
|
||||
const closeDiff = useCallback(() => {
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
search: (previous) => {
|
||||
return stripDiffSearchParams(previous);
|
||||
},
|
||||
});
|
||||
}, [navigate, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!threadId) {
|
||||
@@ -83,30 +30,9 @@ function ChatThreadRouteView() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const diffLoadingFallback =
|
||||
!diffOpen || shouldUseDiffSheet ? (
|
||||
<div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
|
||||
Loading diff viewer...
|
||||
</div>
|
||||
) : (
|
||||
<aside className="flex h-full w-[560px] shrink-0 items-center justify-center border-l border-border bg-card px-4 text-center text-xs text-muted-foreground/70">
|
||||
Loading diff viewer...
|
||||
</aside>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ChatView threadId={threadId} />
|
||||
<DiffPanelWrapper sheet={shouldUseDiffSheet} diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||
<Suspense fallback={diffLoadingFallback}>
|
||||
<DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
|
||||
</Suspense>
|
||||
</DiffPanelWrapper>
|
||||
</>
|
||||
);
|
||||
return <ChatView threadId={threadId} />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/_chat/$threadId")({
|
||||
validateSearch: (search) => parseDiffRouteSearch(search),
|
||||
component: ChatThreadRouteView,
|
||||
});
|
||||
@@ -1,259 +0,0 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useStore } from "../store";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { Switch } from "../components/ui/switch";
|
||||
|
||||
const THEME_OPTIONS = [
|
||||
{
|
||||
value: "system",
|
||||
label: "System",
|
||||
description: "Match your OS appearance setting.",
|
||||
},
|
||||
{
|
||||
value: "light",
|
||||
label: "Light",
|
||||
description: "Always use the light theme.",
|
||||
},
|
||||
{
|
||||
value: "dark",
|
||||
label: "Dark",
|
||||
description: "Always use the dark theme.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
const RUNTIME_MODE_OPTIONS = [
|
||||
{
|
||||
value: "full-access",
|
||||
label: "Full access",
|
||||
description: "Allow commands to run without confirmation prompts.",
|
||||
},
|
||||
{
|
||||
value: "approval-required",
|
||||
label: "Supervised",
|
||||
description: "Require approval prompts before command execution.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
function SettingsRouteView() {
|
||||
const { theme, setTheme, resolvedTheme } = useTheme();
|
||||
const { state, dispatch } = useStore();
|
||||
const { settings, defaults, updateSettings } = useAppSettings();
|
||||
|
||||
const codexBinaryPath = settings.codexBinaryPath;
|
||||
const codexHomePath = settings.codexHomePath;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||
{isElectron && (
|
||||
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
|
||||
<span className="text-xs font-medium tracking-wide text-muted-foreground/70">Settings</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-6">
|
||||
<header className="space-y-1">
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-foreground">Settings</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Configure app-level preferences for this device.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Appearance</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Choose how T3 Code handles light and dark mode.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2" role="radiogroup" aria-label="Theme preference">
|
||||
{THEME_OPTIONS.map((option) => {
|
||||
const selected = theme === option.value;
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={selected}
|
||||
className={`flex w-full items-start justify-between rounded-lg border px-3 py-2 text-left transition-colors ${
|
||||
selected
|
||||
? "border-primary/60 bg-primary/8 text-foreground"
|
||||
: "border-border bg-background text-muted-foreground hover:bg-accent"
|
||||
}`}
|
||||
onClick={() => setTheme(option.value)}
|
||||
>
|
||||
<span className="flex flex-col">
|
||||
<span className="text-sm font-medium">{option.label}</span>
|
||||
<span className="text-xs">{option.description}</span>
|
||||
</span>
|
||||
{selected ? (
|
||||
<span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
|
||||
Selected
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<p className="mt-4 text-xs text-muted-foreground">
|
||||
Active theme: <span className="font-medium text-foreground">{resolvedTheme}</span>
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Codex App Server</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
These overrides apply to new sessions and let you use a non-default Codex install.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<label className="block space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">Codex binary path</span>
|
||||
<Input
|
||||
value={codexBinaryPath}
|
||||
onChange={(event) => updateSettings({ codexBinaryPath: event.target.value })}
|
||||
placeholder="codex"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Leave blank to use <code>codex</code> from your PATH.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label className="block space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">CODEX_HOME path</span>
|
||||
<Input
|
||||
value={codexHomePath}
|
||||
onChange={(event) => updateSettings({ codexHomePath: event.target.value })}
|
||||
placeholder="/Users/you/.codex"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Optional custom Codex home/config directory.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<p>
|
||||
Binary source: <span className="font-medium text-foreground">{codexBinaryPath || "PATH"}</span>
|
||||
</p>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
codexBinaryPath: defaults.codexBinaryPath,
|
||||
codexHomePath: defaults.codexHomePath,
|
||||
})
|
||||
}
|
||||
>
|
||||
Reset codex overrides
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Select the default execution policy for this client.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2" role="radiogroup" aria-label="Runtime mode preference">
|
||||
{RUNTIME_MODE_OPTIONS.map((option) => {
|
||||
const selected = state.runtimeMode === option.value;
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={selected}
|
||||
className={`flex w-full items-start justify-between rounded-lg border px-3 py-2 text-left transition-colors ${
|
||||
selected
|
||||
? "border-primary/60 bg-primary/8 text-foreground"
|
||||
: "border-border bg-background text-muted-foreground hover:bg-accent"
|
||||
}`}
|
||||
onClick={() => {
|
||||
dispatch({
|
||||
type: "SET_RUNTIME_MODE",
|
||||
mode: option.value,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<span className="flex flex-col">
|
||||
<span className="text-sm font-medium">{option.label}</span>
|
||||
<span className="text-xs">{option.description}</span>
|
||||
</span>
|
||||
{selected ? (
|
||||
<span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
|
||||
Selected
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Safety</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Additional guardrails for destructive local actions.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">Confirm thread deletion</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Ask for confirmation before deleting a thread and its chat history.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={settings.confirmThreadDelete}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
confirmThreadDelete: Boolean(checked),
|
||||
})
|
||||
}
|
||||
aria-label="Confirm thread deletion"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{settings.confirmThreadDelete !== defaults.confirmThreadDelete ? (
|
||||
<div className="mt-3 flex justify-end">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
confirmThreadDelete: defaults.confirmThreadDelete,
|
||||
})
|
||||
}
|
||||
>
|
||||
Restore default
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/_chat/settings")({
|
||||
component: SettingsRouteView,
|
||||
});
|
||||
@@ -1,34 +1,21 @@
|
||||
import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||
import { useEffect } from "react";
|
||||
import { Outlet, createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
|
||||
import DiffPanel, { DiffWorkerPoolProvider } from "../components/DiffPanel";
|
||||
import Sidebar from "../components/Sidebar";
|
||||
import { useStore } from "../store";
|
||||
|
||||
function ChatRouteLayout() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const onMenuAction = window.desktopBridge?.onMenuAction;
|
||||
if (typeof onMenuAction !== "function") {
|
||||
return;
|
||||
}
|
||||
|
||||
const unsubscribe = onMenuAction((action) => {
|
||||
if (action !== "open-settings") return;
|
||||
void navigate({ to: "/settings" });
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribe?.();
|
||||
};
|
||||
}, [navigate]);
|
||||
const { state } = useStore();
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-background text-foreground isolate">
|
||||
<Sidebar />
|
||||
<DiffWorkerPoolProvider>
|
||||
<Outlet />
|
||||
</DiffWorkerPoolProvider>
|
||||
<Outlet />
|
||||
{state.diffOpen && (
|
||||
<DiffWorkerPoolProvider>
|
||||
<DiffPanel />
|
||||
</DiffWorkerPoolProvider>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -36,4 +23,3 @@ function ChatRouteLayout() {
|
||||
export const Route = createFileRoute("/_chat")({
|
||||
component: ChatRouteLayout,
|
||||
});
|
||||
|
||||
@@ -493,11 +493,11 @@ describe("deriveTurnDiffSummaries", () => {
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
||||
expect(summaries[0]?.assistantMessageId).toBe("msg-1");
|
||||
expect(summaries[0]?.unifiedDiff).toContain("diff --git a/src/a.ts b/src/a.ts");
|
||||
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", () => {
|
||||
@@ -537,10 +537,9 @@ describe("deriveTurnDiffSummaries", () => {
|
||||
payload: {
|
||||
diff: [
|
||||
"diff --git a/src/example.ts b/src/example.ts",
|
||||
"@@ -1 +1,2 @@",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+older",
|
||||
"+extra",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
@@ -573,9 +572,8 @@ describe("deriveTurnDiffSummaries", () => {
|
||||
]);
|
||||
|
||||
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);
|
||||
expect(summaries[0]?.unifiedDiff).toContain("+newest");
|
||||
expect(summaries[0]?.unifiedDiff).not.toContain("+older");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -595,6 +593,8 @@ describe("deriveTurnDiffFilesFromUnifiedDiff", () => {
|
||||
);
|
||||
|
||||
expect(files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
||||
expect(files[0]?.diff).toContain("diff --git a/src/a.ts b/src/a.ts");
|
||||
expect(files[1]?.diff).toContain("diff --git a/src/b.ts b/src/b.ts");
|
||||
expect(files[0]?.additions).toBe(1);
|
||||
expect(files[0]?.deletions).toBe(1);
|
||||
});
|
||||
|
||||
@@ -453,7 +453,7 @@ interface MutableTurnDiffSummary {
|
||||
completedAt: string | undefined;
|
||||
status: string | undefined;
|
||||
assistantMessageId: string | undefined;
|
||||
hasTurnDiffUpdate: boolean;
|
||||
unifiedDiff: string | undefined;
|
||||
filesByPath: Map<string, TurnDiffFileChange>;
|
||||
}
|
||||
|
||||
@@ -485,6 +485,7 @@ function parseFileChangeEntriesFromEvent(event: ProviderEvent): TurnDiffFileChan
|
||||
parsed.push({
|
||||
path,
|
||||
...(kind ? { kind } : {}),
|
||||
...(diff ? { diff } : {}),
|
||||
...(additions !== undefined ? { additions } : stat ? { additions: stat.additions } : {}),
|
||||
...(deletions !== undefined ? { deletions } : stat ? { deletions: stat.deletions } : {}),
|
||||
});
|
||||
@@ -506,6 +507,9 @@ function mergeTurnDiffFileChange(
|
||||
if (existing.kind === undefined && incoming.kind !== undefined) {
|
||||
existing.kind = incoming.kind;
|
||||
}
|
||||
if (existing.diff === undefined && incoming.diff !== undefined) {
|
||||
existing.diff = incoming.diff;
|
||||
}
|
||||
if (existing.additions === undefined && incoming.additions !== undefined) {
|
||||
existing.additions = incoming.additions;
|
||||
}
|
||||
@@ -561,6 +565,7 @@ export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileCh
|
||||
const stat = countDiffStat(fileDiff);
|
||||
return {
|
||||
path,
|
||||
diff: fileDiff,
|
||||
additions: stat.additions,
|
||||
deletions: stat.deletions,
|
||||
};
|
||||
@@ -640,7 +645,7 @@ export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummar
|
||||
completedAt: undefined,
|
||||
status: undefined,
|
||||
assistantMessageId: undefined,
|
||||
hasTurnDiffUpdate: false,
|
||||
unifiedDiff: undefined,
|
||||
filesByPath: new Map<string, TurnDiffFileChange>(),
|
||||
};
|
||||
byTurnId.set(turnId, next);
|
||||
@@ -672,10 +677,10 @@ export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummar
|
||||
}
|
||||
}
|
||||
|
||||
if (event.method === "turn/diff/updated" && !summary.hasTurnDiffUpdate) {
|
||||
summary.hasTurnDiffUpdate = true;
|
||||
if (event.method === "turn/diff/updated" && summary.unifiedDiff === undefined) {
|
||||
const diff = normalizeDetail(asString(asObject(event.payload)?.diff));
|
||||
if (diff) {
|
||||
summary.unifiedDiff = diff;
|
||||
for (const file of deriveTurnDiffFilesFromUnifiedDiff(diff)) {
|
||||
mergeTurnDiffFileChange(summary.filesByPath, file);
|
||||
}
|
||||
@@ -698,6 +703,7 @@ export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummar
|
||||
files: Array.from(summary.filesByPath.values()).toSorted((a, b) =>
|
||||
a.path.localeCompare(b.path),
|
||||
),
|
||||
...(summary.unifiedDiff ? { unifiedDiff: summary.unifiedDiff } : {}),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,198 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
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),
|
||||
};
|
||||
}
|
||||
@@ -81,6 +81,10 @@ function makeState(thread: Thread): AppState {
|
||||
threads: [thread],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -145,6 +149,21 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.terminalOpen).toBe(true);
|
||||
});
|
||||
|
||||
it("opens diff panel with an explicit turn/file target", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "OPEN_DIFF",
|
||||
threadId: "thread-local-1",
|
||||
turnId: "turn-1",
|
||||
filePath: "src/app.ts",
|
||||
});
|
||||
|
||||
expect(next.diffOpen).toBe(true);
|
||||
expect(next.diffThreadId).toBe("thread-local-1");
|
||||
expect(next.diffTurnId).toBe("turn-1");
|
||||
expect(next.diffFilePath).toBe("src/app.ts");
|
||||
});
|
||||
|
||||
it("sets terminal open state per thread", () => {
|
||||
const state = makeState(makeThread({ terminalOpen: true }));
|
||||
const next = reducer(state, {
|
||||
@@ -550,168 +569,6 @@ describe("store reducer thread continuity", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not clear persisted turn summaries on thread.upsert snapshots", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:01.000Z",
|
||||
files: [{ path: "src/existing.ts", kind: "modified" }],
|
||||
assistantMessageId: "msg-1",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STATE_EVENT",
|
||||
event: {
|
||||
seq: 1,
|
||||
eventType: "thread.upsert",
|
||||
entityId: "thread-local-1",
|
||||
createdAt: "2026-02-09T00:00:05.000Z",
|
||||
payload: {
|
||||
thread: {
|
||||
id: "thread-local-1",
|
||||
codexThreadId: "thr-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
updatedAt: "2026-02-09T00:00:05.000Z",
|
||||
lastVisitedAt: "2026-02-09T00:00:05.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe("msg-1");
|
||||
});
|
||||
|
||||
it("preserves existing terminal arrays when thread.upsert omits them", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalOpen: true,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalIds: ["term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
{
|
||||
id: "group-term-2",
|
||||
terminalIds: ["term-2"],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: "group-term-2",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STATE_EVENT",
|
||||
event: {
|
||||
seq: 1,
|
||||
eventType: "thread.upsert",
|
||||
entityId: "thread-local-1",
|
||||
createdAt: "2026-02-09T00:00:06.000Z",
|
||||
payload: {
|
||||
thread: {
|
||||
id: "thread-local-1",
|
||||
codexThreadId: "thr-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
activeTerminalId: "term-2",
|
||||
activeTerminalGroupId: "group-term-2",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
updatedAt: "2026-02-09T00:00:06.000Z",
|
||||
lastVisitedAt: "2026-02-09T00:00:06.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual(["term-2"]);
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
{
|
||||
id: "group-term-2",
|
||||
terminalIds: ["term-2"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses safe terminal defaults when a new thread.upsert omits terminal arrays", () => {
|
||||
const state = makeState(makeThread());
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STATE_EVENT",
|
||||
event: {
|
||||
seq: 1,
|
||||
eventType: "thread.upsert",
|
||||
entityId: "thread-local-2",
|
||||
createdAt: "2026-02-09T00:00:06.000Z",
|
||||
payload: {
|
||||
thread: {
|
||||
id: "thread-local-2",
|
||||
codexThreadId: null,
|
||||
projectId: "project-1",
|
||||
title: "Second thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
updatedAt: "2026-02-09T00:00:06.000Z",
|
||||
lastVisitedAt: "2026-02-09T00:00:06.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createdThread = next.threads.find((thread) => thread.id === "thread-local-2");
|
||||
expect(createdThread).toBeDefined();
|
||||
expect(createdThread?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(createdThread?.runningTerminalIds).toEqual([]);
|
||||
expect(createdThread?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(createdThread?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("infers checkpoint turn counts when deriving turn summaries from an empty baseline", () => {
|
||||
const state = makeState(makeThread({ turnDiffSummaries: [] }));
|
||||
const next = reducer(state, {
|
||||
@@ -761,6 +618,10 @@ describe("store reducer thread continuity", () => {
|
||||
],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: true,
|
||||
diffThreadId: "thread-b",
|
||||
diffTurnId: "turn-b",
|
||||
diffFilePath: "src/removed.ts",
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
@@ -784,6 +645,10 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads).toHaveLength(1);
|
||||
expect(next.threads[0]?.id).toBe("thread-a");
|
||||
expect(next.threads[0]?.projectId).toBe("project-new-a");
|
||||
expect(next.diffOpen).toBe(false);
|
||||
expect(next.diffThreadId).toBeNull();
|
||||
expect(next.diffTurnId).toBeNull();
|
||||
expect(next.diffFilePath).toBeNull();
|
||||
});
|
||||
|
||||
it("treats empty scripts from sync as authoritative", () => {
|
||||
@@ -809,6 +674,10 @@ describe("store reducer thread continuity", () => {
|
||||
threads: [makeThread({ id: "thread-a", projectId: "project-old-a" })],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
@@ -897,6 +766,10 @@ describe("store reducer thread continuity", () => {
|
||||
],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: true,
|
||||
diffThreadId: "thread-a",
|
||||
diffTurnId: "turn-a",
|
||||
diffFilePath: "src/a.ts",
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
@@ -908,6 +781,10 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.projects[0]?.id).toBe("project-2");
|
||||
expect(next.threads).toHaveLength(1);
|
||||
expect(next.threads[0]?.id).toBe("thread-b");
|
||||
expect(next.diffOpen).toBe(false);
|
||||
expect(next.diffThreadId).toBeNull();
|
||||
expect(next.diffTurnId).toBeNull();
|
||||
expect(next.diffFilePath).toBeNull();
|
||||
});
|
||||
|
||||
it("marks completion as seen immediately for the active thread", () => {
|
||||
@@ -938,24 +815,6 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.lastVisitedAt).toBe(completedAt);
|
||||
});
|
||||
|
||||
it("marks a thread as visited when selected", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
latestTurnCompletedAt: "2026-02-08T10:00:10.000Z",
|
||||
lastVisitedAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const nextVisitedAt = "2026-02-08T10:00:20.000Z";
|
||||
const next = reducer(state, {
|
||||
type: "MARK_THREAD_VISITED",
|
||||
threadId: "thread-local-1",
|
||||
visitedAt: nextVisitedAt,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.lastVisitedAt).toBe(nextVisitedAt);
|
||||
});
|
||||
|
||||
it("reverts thread state to a checkpoint snapshot", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
@@ -1034,7 +893,7 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn_1"]);
|
||||
});
|
||||
|
||||
it("keeps existing turn file metadata when later events for the same turn arrive", () => {
|
||||
it("keeps checkpoint-derived turn files when later events for the same turn arrive", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
turnDiffSummaries: [
|
||||
@@ -1044,10 +903,11 @@ describe("store reducer thread continuity", () => {
|
||||
files: [
|
||||
{
|
||||
path: "src/from-checkpoint.ts",
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
diff: "diff --git a/src/from-checkpoint.ts b/src/from-checkpoint.ts",
|
||||
},
|
||||
],
|
||||
unifiedDiff: "diff --git a/src/from-checkpoint.ts b/src/from-checkpoint.ts",
|
||||
checkpointDiffLoaded: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
@@ -1067,11 +927,11 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files.map((file) => file.path)).toEqual([
|
||||
"src/from-checkpoint.ts",
|
||||
]);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files[0]?.additions).toBe(1);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files[0]?.deletions).toBe(1);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointDiffLoaded).toBe(true);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.unifiedDiff).toContain("from-checkpoint.ts");
|
||||
});
|
||||
|
||||
it("updates checkpoint turn counts from authoritative checkpoint mappings", () => {
|
||||
it("updates turn summaries from checkpoint diffs and marks them as loaded", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
turnDiffSummaries: [
|
||||
@@ -1081,65 +941,31 @@ describe("store reducer thread continuity", () => {
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
},
|
||||
{
|
||||
turnId: "turn-2",
|
||||
completedAt: "2026-02-09T00:00:04.000Z",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS",
|
||||
threadId: "thread-local-1",
|
||||
checkpointTurnCountByTurnId: {
|
||||
"turn-1": 2,
|
||||
"turn-2": 3,
|
||||
checkpointDiffByTurnId: {
|
||||
"turn-1": [
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-a",
|
||||
"+new-a",
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-b",
|
||||
"+new-b",
|
||||
].join("\n"),
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointTurnCount).toBe(2);
|
||||
expect(next.threads[0]?.turnDiffSummaries[1]?.checkpointTurnCount).toBe(3);
|
||||
});
|
||||
|
||||
it("does not rederive completed turn summaries from late turn diff events", () => {
|
||||
const completed = reducer(makeState(makeThread()), {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-09T00:00:03.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(completed.threads[0]?.turnDiffSummaries[0]?.files).toEqual([]);
|
||||
|
||||
const withLateDiff = reducer(completed, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-09T00:00:04.000Z",
|
||||
payload: {
|
||||
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",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(withLateDiff.threads[0]?.turnDiffSummaries[0]?.files).toEqual([]);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files.map((file) => file.path)).toEqual([
|
||||
"src/a.ts",
|
||||
"src/b.ts",
|
||||
]);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointDiffLoaded).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -8,20 +8,14 @@ import {
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import {
|
||||
type ProviderEvent,
|
||||
type ProviderSession,
|
||||
type StateBootstrapResult,
|
||||
type StateBootstrapThread,
|
||||
type StateEvent,
|
||||
type TerminalEvent,
|
||||
normalizeProjectScripts,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
||||
import { type ProviderEvent, type ProviderSession, type TerminalEvent, normalizeProjectScripts } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import {
|
||||
applyEventToMessages,
|
||||
asObject,
|
||||
asString,
|
||||
deriveTurnDiffFilesFromUnifiedDiff,
|
||||
deriveTurnDiffSummaries,
|
||||
inferCheckpointTurnCountByTurnId,
|
||||
evolveSession,
|
||||
@@ -41,8 +35,6 @@ import {
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
type Action =
|
||||
| { type: "HYDRATE_FROM_SERVER"; snapshot: StateBootstrapResult }
|
||||
| { type: "APPLY_STATE_EVENT"; event: StateEvent }
|
||||
| { type: "ADD_PROJECT"; project: Project }
|
||||
| { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
|
||||
| { type: "SYNC_PROJECTS"; projects: Project[] }
|
||||
@@ -57,6 +49,20 @@ type Action =
|
||||
| { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "TOGGLE_DIFF" }
|
||||
| {
|
||||
type: "OPEN_DIFF";
|
||||
threadId: string;
|
||||
turnId?: string;
|
||||
filePath?: string;
|
||||
}
|
||||
| {
|
||||
type: "SET_DIFF_TARGET";
|
||||
threadId: string;
|
||||
turnId?: string;
|
||||
filePath?: string;
|
||||
}
|
||||
| { type: "CLOSE_DIFF" }
|
||||
| {
|
||||
type: "APPLY_EVENT";
|
||||
event: ProviderEvent;
|
||||
@@ -88,13 +94,17 @@ type Action =
|
||||
threadId: string;
|
||||
checkpointTurnCountByTurnId: Record<string, number>;
|
||||
}
|
||||
| {
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS";
|
||||
threadId: string;
|
||||
checkpointDiffByTurnId: Record<string, string>;
|
||||
}
|
||||
| {
|
||||
type: "SET_THREAD_BRANCH";
|
||||
threadId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}
|
||||
| { type: "MARK_THREAD_VISITED"; threadId: string; visitedAt?: string }
|
||||
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode }
|
||||
| { type: "DELETE_THREAD"; threadId: string };
|
||||
|
||||
@@ -105,15 +115,33 @@ export interface AppState {
|
||||
threads: Thread[];
|
||||
threadsHydrated: boolean;
|
||||
runtimeMode: RuntimeMode;
|
||||
diffOpen: boolean;
|
||||
diffThreadId: string | null;
|
||||
diffTurnId: string | null;
|
||||
diffFilePath: string | null;
|
||||
}
|
||||
|
||||
const RUNTIME_MODE_STORAGE_KEY = "t3code:runtime-mode";
|
||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
|
||||
const LEGACY_PERSISTED_STATE_KEYS = [
|
||||
"t3code:renderer-state:v6",
|
||||
"t3code:renderer-state:v5",
|
||||
"t3code:renderer-state:v4",
|
||||
"t3code:renderer-state:v3",
|
||||
"codething:renderer-state:v4",
|
||||
"codething:renderer-state:v3",
|
||||
"codething:renderer-state:v2",
|
||||
"codething:renderer-state:v1",
|
||||
] as const;
|
||||
|
||||
const initialState: AppState = {
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
@@ -122,14 +150,25 @@ function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
|
||||
try {
|
||||
const rawRuntimeMode = window.localStorage.getItem(RUNTIME_MODE_STORAGE_KEY);
|
||||
const runtimeMode =
|
||||
rawRuntimeMode === "approval-required" || rawRuntimeMode === "full-access"
|
||||
? rawRuntimeMode
|
||||
: DEFAULT_RUNTIME_MODE;
|
||||
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
|
||||
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
|
||||
const raw = rawCurrent ?? rawLegacy;
|
||||
if (!raw) return initialState;
|
||||
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
|
||||
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
const threads = hydrated.threads.map((thread) => normalizeThreadTerminals(thread));
|
||||
|
||||
return {
|
||||
...initialState,
|
||||
runtimeMode,
|
||||
...hydrated,
|
||||
threads,
|
||||
threadsHydrated: threads.length > 0,
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
} catch {
|
||||
return initialState;
|
||||
@@ -140,9 +179,12 @@ function persistState(state: AppState): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(RUNTIME_MODE_STORAGE_KEY, state.runtimeMode);
|
||||
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
|
||||
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
|
||||
window.localStorage.removeItem(legacyKey);
|
||||
}
|
||||
} catch {
|
||||
// Ignore storage failures to avoid breaking chat UX.
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,6 +196,32 @@ function updateThread(
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
}
|
||||
|
||||
function resetDiffTargetIfMissing(state: AppState, threads: Thread[]) {
|
||||
if (!state.diffThreadId) {
|
||||
return {
|
||||
diffOpen: state.diffOpen,
|
||||
diffThreadId: state.diffThreadId,
|
||||
diffTurnId: state.diffTurnId,
|
||||
diffFilePath: state.diffFilePath,
|
||||
};
|
||||
}
|
||||
const hasThread = threads.some((thread) => thread.id === state.diffThreadId);
|
||||
if (hasThread) {
|
||||
return {
|
||||
diffOpen: state.diffOpen,
|
||||
diffThreadId: state.diffThreadId,
|
||||
diffTurnId: state.diffTurnId,
|
||||
diffFilePath: state.diffFilePath,
|
||||
};
|
||||
}
|
||||
return {
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
}
|
||||
|
||||
function mergeTurnDiffSummaries(
|
||||
existing: Thread["turnDiffSummaries"],
|
||||
next: Thread["turnDiffSummaries"],
|
||||
@@ -167,12 +235,21 @@ function mergeTurnDiffSummaries(
|
||||
return summary;
|
||||
}
|
||||
|
||||
const prefersCheckpointDiff = previous.checkpointDiffLoaded || summary.checkpointDiffLoaded;
|
||||
const files =
|
||||
summary.files.length === 0 && previous.files.length > 0 ? previous.files : summary.files;
|
||||
prefersCheckpointDiff ||
|
||||
(summary.files.length === 0 && previous.files.length > 0 && summary.unifiedDiff === undefined)
|
||||
? previous.files
|
||||
: summary.files;
|
||||
const unifiedDiff =
|
||||
prefersCheckpointDiff || summary.unifiedDiff === undefined
|
||||
? (previous.unifiedDiff ?? summary.unifiedDiff)
|
||||
: summary.unifiedDiff;
|
||||
|
||||
return {
|
||||
...summary,
|
||||
files,
|
||||
...(unifiedDiff !== undefined ? { unifiedDiff } : {}),
|
||||
...(summary.assistantMessageId
|
||||
? {}
|
||||
: previous.assistantMessageId
|
||||
@@ -183,6 +260,9 @@ function mergeTurnDiffSummaries(
|
||||
: typeof previous.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: previous.checkpointTurnCount }
|
||||
: {}),
|
||||
...(summary.checkpointDiffLoaded || previous.checkpointDiffLoaded
|
||||
? { checkpointDiffLoaded: true }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -212,58 +292,6 @@ function mergeTurnDiffSummaries(
|
||||
);
|
||||
}
|
||||
|
||||
function hydrateThreadFromBootstrap(
|
||||
thread: StateBootstrapThread,
|
||||
existing: Thread | undefined,
|
||||
): Thread {
|
||||
return normalizeThreadTerminals({
|
||||
id: thread.id,
|
||||
codexThreadId: thread.codexThreadId ?? null,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlug(thread.model),
|
||||
terminalOpen: thread.terminalOpen,
|
||||
terminalHeight: thread.terminalHeight,
|
||||
terminalIds: thread.terminalIds,
|
||||
runningTerminalIds: thread.runningTerminalIds,
|
||||
activeTerminalId: thread.activeTerminalId,
|
||||
terminalGroups: thread.terminalGroups,
|
||||
activeTerminalGroupId: thread.activeTerminalGroupId,
|
||||
session: existing?.session ?? null,
|
||||
messages: thread.messages.map((message) => ({
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
...(message.attachments
|
||||
? { attachments: message.attachments.map((attachment) => ({ ...attachment })) }
|
||||
: {}),
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
})),
|
||||
events: existing?.events ?? [],
|
||||
error: existing?.error ?? null,
|
||||
createdAt: thread.createdAt,
|
||||
latestTurnId: thread.latestTurnId,
|
||||
latestTurnStartedAt: thread.latestTurnStartedAt,
|
||||
latestTurnCompletedAt: thread.latestTurnCompletedAt,
|
||||
latestTurnDurationMs: thread.latestTurnDurationMs,
|
||||
lastVisitedAt: thread.lastVisitedAt ?? thread.createdAt,
|
||||
branch: thread.branch ?? null,
|
||||
worktreePath: thread.worktreePath ?? null,
|
||||
turnDiffSummaries: thread.turnDiffSummaries ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
function upsertThreadMessage(messages: Thread["messages"], message: Thread["messages"][number]) {
|
||||
const index = messages.findIndex((entry) => entry.id === message.id);
|
||||
if (index < 0) {
|
||||
return [...messages, message];
|
||||
}
|
||||
const next = [...messages];
|
||||
next[index] = message;
|
||||
return next;
|
||||
}
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
@@ -533,253 +561,10 @@ function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread>
|
||||
return {};
|
||||
}
|
||||
|
||||
function resetDiffTargetIfMissing(
|
||||
_state: AppState,
|
||||
_threads: Thread[],
|
||||
): Partial<AppState> {
|
||||
return {};
|
||||
}
|
||||
|
||||
// ── Reducer ──────────────────────────────────────────────────────────
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "HYDRATE_FROM_SERVER": {
|
||||
const previousProjectById = new Map(
|
||||
state.projects.map((project) => [project.id, project] as const),
|
||||
);
|
||||
const nextProjects = action.snapshot.projects.map((project) => {
|
||||
const previous = previousProjectById.get(project.id);
|
||||
return {
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
cwd: project.cwd,
|
||||
model: resolveModelSlug(previous?.model ?? DEFAULT_MODEL),
|
||||
expanded: previous?.expanded ?? true,
|
||||
scripts: normalizeProjectScripts(project.scripts),
|
||||
};
|
||||
});
|
||||
const nextProjectIdSet = new Set(nextProjects.map((project) => project.id));
|
||||
const previousThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const));
|
||||
const nextThreads = action.snapshot.threads
|
||||
.filter((thread) => nextProjectIdSet.has(thread.projectId))
|
||||
.map((thread) => hydrateThreadFromBootstrap(thread, previousThreadById.get(thread.id)));
|
||||
const diffState = resetDiffTargetIfMissing(state, nextThreads);
|
||||
return {
|
||||
...state,
|
||||
projects: nextProjects,
|
||||
threads: nextThreads,
|
||||
threadsHydrated: true,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
case "APPLY_STATE_EVENT": {
|
||||
const payload = asObject(action.event.payload);
|
||||
const eventType = action.event.eventType;
|
||||
|
||||
if (eventType === "project.upsert") {
|
||||
const project = asObject(payload?.project);
|
||||
const id = asString(project?.id);
|
||||
const name = asString(project?.name);
|
||||
const cwd = asString(project?.cwd);
|
||||
const scripts = Array.isArray(project?.scripts) ? (project.scripts as ProjectScript[]) : [];
|
||||
if (!id || !name || !cwd) {
|
||||
return state;
|
||||
}
|
||||
const previous = state.projects.find((entry) => entry.id === id);
|
||||
const nextProject: Project = {
|
||||
id,
|
||||
name,
|
||||
cwd,
|
||||
model: resolveModelSlug(previous?.model ?? DEFAULT_MODEL),
|
||||
expanded: previous?.expanded ?? true,
|
||||
scripts: normalizeProjectScripts(scripts),
|
||||
};
|
||||
const nextProjects = previous
|
||||
? state.projects.map((entry) => (entry.id === id ? nextProject : entry))
|
||||
: [...state.projects, nextProject];
|
||||
return {
|
||||
...state,
|
||||
projects: nextProjects,
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "project.delete") {
|
||||
const projectId = asString(payload?.projectId) ?? action.event.entityId;
|
||||
const projects = state.projects.filter((project) => project.id !== projectId);
|
||||
const threads = state.threads.filter((thread) => thread.projectId !== projectId);
|
||||
const diffState = resetDiffTargetIfMissing(state, threads);
|
||||
return {
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "thread.upsert") {
|
||||
const threadPayload = asObject(payload?.thread);
|
||||
const threadId = asString(threadPayload?.id);
|
||||
const projectId = asString(threadPayload?.projectId);
|
||||
if (!threadId || !projectId) {
|
||||
return state;
|
||||
}
|
||||
if (!state.projects.some((project) => project.id === projectId)) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const existing = state.threads.find((thread) => thread.id === threadId);
|
||||
const existingStateMessages =
|
||||
existing?.messages.map((message) => ({
|
||||
id: message.id,
|
||||
threadId,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
...(message.attachments
|
||||
? {
|
||||
attachments: message.attachments.map((attachment) => ({ ...attachment })),
|
||||
}
|
||||
: {}),
|
||||
createdAt: message.createdAt,
|
||||
updatedAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
})) ?? [];
|
||||
const payloadTurnDiffSummaries = Array.isArray(threadPayload?.turnDiffSummaries)
|
||||
? (threadPayload.turnDiffSummaries as Thread["turnDiffSummaries"])
|
||||
: undefined;
|
||||
const payloadTerminalIds = Array.isArray(threadPayload?.terminalIds)
|
||||
? (threadPayload.terminalIds as string[])
|
||||
: (existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID]);
|
||||
const payloadRunningTerminalIds = Array.isArray(threadPayload?.runningTerminalIds)
|
||||
? (threadPayload.runningTerminalIds as string[])
|
||||
: (existing?.runningTerminalIds ?? []);
|
||||
const payloadTerminalGroups = Array.isArray(threadPayload?.terminalGroups)
|
||||
? (threadPayload.terminalGroups as ThreadTerminalGroup[])
|
||||
: (existing?.terminalGroups ?? []);
|
||||
const bootstrapThread: StateBootstrapThread = {
|
||||
...(threadPayload as unknown as Omit<StateBootstrapThread, "messages">),
|
||||
terminalIds: payloadTerminalIds,
|
||||
runningTerminalIds: payloadRunningTerminalIds,
|
||||
terminalGroups: payloadTerminalGroups,
|
||||
messages: existingStateMessages,
|
||||
turnDiffSummaries: payloadTurnDiffSummaries
|
||||
? mergeTurnDiffSummaries(existing?.turnDiffSummaries ?? [], payloadTurnDiffSummaries)
|
||||
: existing?.turnDiffSummaries ?? [],
|
||||
};
|
||||
const nextThread = hydrateThreadFromBootstrap(bootstrapThread, existing);
|
||||
const nextThreads = existing
|
||||
? state.threads.map((thread) => (thread.id === nextThread.id ? nextThread : thread))
|
||||
: [...state.threads, nextThread];
|
||||
return {
|
||||
...state,
|
||||
threads: nextThreads,
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "thread.delete") {
|
||||
const threadId = asString(payload?.threadId) ?? action.event.entityId;
|
||||
const nextThreads = state.threads.filter((thread) => thread.id !== threadId);
|
||||
const diffState = resetDiffTargetIfMissing(state, nextThreads);
|
||||
return {
|
||||
...state,
|
||||
threads: nextThreads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "message.upsert") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const messagePayload = asObject(payload?.message);
|
||||
const messageId = asString(messagePayload?.id);
|
||||
const role = messagePayload?.role === "assistant" ? "assistant" : "user";
|
||||
const text = typeof messagePayload?.text === "string" ? messagePayload.text : "";
|
||||
const createdAt = asString(messagePayload?.createdAt);
|
||||
if (!threadId || !messageId || !createdAt) {
|
||||
return state;
|
||||
}
|
||||
const attachments = Array.isArray(messagePayload?.attachments)
|
||||
? (messagePayload.attachments as Thread["messages"][number]["attachments"])
|
||||
: undefined;
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
messages: upsertThreadMessage(thread.messages, {
|
||||
id: messageId,
|
||||
role,
|
||||
text,
|
||||
...(attachments ? { attachments } : {}),
|
||||
createdAt,
|
||||
streaming: messagePayload?.streaming === true,
|
||||
}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "message.delete") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const messageId = asString(payload?.messageId);
|
||||
if (!threadId || !messageId) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
messages: thread.messages.filter((message) => message.id !== messageId),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "turn_summary.upsert") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const summaryPayload = asObject(payload?.turnSummary);
|
||||
const turnId = asString(summaryPayload?.turnId);
|
||||
const completedAt = asString(summaryPayload?.completedAt);
|
||||
if (!threadId || !turnId || !completedAt) {
|
||||
return state;
|
||||
}
|
||||
const summary: Thread["turnDiffSummaries"][number] = {
|
||||
turnId,
|
||||
completedAt,
|
||||
status: asString(summaryPayload?.status),
|
||||
files: Array.isArray(summaryPayload?.files)
|
||||
? (summaryPayload.files as Thread["turnDiffSummaries"][number]["files"])
|
||||
: [],
|
||||
assistantMessageId: asString(summaryPayload?.assistantMessageId),
|
||||
checkpointTurnCount:
|
||||
typeof summaryPayload?.checkpointTurnCount === "number"
|
||||
? summaryPayload.checkpointTurnCount
|
||||
: undefined,
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
turnDiffSummaries: mergeTurnDiffSummaries(thread.turnDiffSummaries, [summary]),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "turn_summary.delete") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const turnId = asString(payload?.turnId);
|
||||
if (!threadId || !turnId) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.filter((summary) => summary.turnId !== turnId),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
case "ADD_PROJECT":
|
||||
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
|
||||
return state;
|
||||
@@ -847,11 +632,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
});
|
||||
})
|
||||
.filter((thread): thread is Thread => thread !== null);
|
||||
const diffState = resetDiffTargetIfMissing(state, nextThreads);
|
||||
|
||||
return {
|
||||
...state,
|
||||
projects: nextProjects,
|
||||
threads: nextThreads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -870,11 +657,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
}
|
||||
|
||||
const threads = state.threads.filter((thread) => thread.projectId !== action.projectId);
|
||||
const diffState = resetDiffTargetIfMissing(state, threads);
|
||||
|
||||
return {
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -885,15 +674,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
|
||||
turnDiffSummaries: action.thread.turnDiffSummaries ?? [],
|
||||
});
|
||||
const existingIndex = state.threads.findIndex((thread) => thread.id === nextThread.id);
|
||||
if (existingIndex >= 0) {
|
||||
const nextThreads = [...state.threads];
|
||||
nextThreads[existingIndex] = nextThread;
|
||||
return {
|
||||
...state,
|
||||
threads: nextThreads,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: [...state.threads, nextThread],
|
||||
@@ -1067,6 +847,29 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
),
|
||||
};
|
||||
|
||||
case "TOGGLE_DIFF":
|
||||
return { ...state, diffOpen: !state.diffOpen };
|
||||
|
||||
case "OPEN_DIFF":
|
||||
return {
|
||||
...state,
|
||||
diffOpen: true,
|
||||
diffThreadId: action.threadId,
|
||||
diffTurnId: action.turnId ?? null,
|
||||
diffFilePath: action.filePath ?? null,
|
||||
};
|
||||
|
||||
case "SET_DIFF_TARGET":
|
||||
return {
|
||||
...state,
|
||||
diffThreadId: action.threadId,
|
||||
diffTurnId: action.turnId ?? null,
|
||||
diffFilePath: action.filePath ?? null,
|
||||
};
|
||||
|
||||
case "CLOSE_DIFF":
|
||||
return { ...state, diffOpen: false };
|
||||
|
||||
case "APPLY_TERMINAL_EVENT":
|
||||
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
|
||||
return state;
|
||||
@@ -1105,18 +908,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
...state,
|
||||
threads: updateThread(state.threads, target.id, (t) => {
|
||||
const nextEvents = [event, ...t.events];
|
||||
const eventTurnId = getEventTurnId(event);
|
||||
const hasCompletedSummaryForTurn = Boolean(
|
||||
eventTurnId && t.turnDiffSummaries.some((summary) => summary.turnId === eventTurnId),
|
||||
);
|
||||
const itemType = asString(asObject(asObject(event.payload)?.item)?.type);
|
||||
const normalizedItemType = itemType?.replace(/[_-]/g, "").toLowerCase();
|
||||
const isMetadataItemCompleted =
|
||||
event.method === "item/completed" &&
|
||||
(normalizedItemType === "agentmessage" || normalizedItemType === "filechange");
|
||||
const shouldRederiveDiffs =
|
||||
event.method === "turn/completed" ||
|
||||
(hasCompletedSummaryForTurn && isMetadataItemCompleted);
|
||||
event.method === "turn/diff/updated" ||
|
||||
(event.method === "item/completed" &&
|
||||
(normalizedItemType === "agentmessage" || normalizedItemType === "filechange"));
|
||||
const turnDiffSummaries = shouldRederiveDiffs
|
||||
? mergeTurnDiffSummaries(t.turnDiffSummaries, deriveTurnDiffSummaries(nextEvents))
|
||||
: t.turnDiffSummaries;
|
||||
@@ -1272,6 +1070,59 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TURN_CHECKPOINT_DIFFS":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
||||
let hasUpdates = false;
|
||||
const updatedSummaries = t.turnDiffSummaries.map((summary) => {
|
||||
const checkpointDiff = action.checkpointDiffByTurnId[summary.turnId];
|
||||
if (checkpointDiff === undefined) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(checkpointDiff);
|
||||
const filesUnchanged =
|
||||
files.length === summary.files.length &&
|
||||
files.every((file, index) => {
|
||||
const existing = summary.files[index];
|
||||
return (
|
||||
existing !== undefined &&
|
||||
existing.path === file.path &&
|
||||
existing.diff === file.diff &&
|
||||
existing.kind === file.kind &&
|
||||
existing.additions === file.additions &&
|
||||
existing.deletions === file.deletions
|
||||
);
|
||||
});
|
||||
if (
|
||||
summary.unifiedDiff === checkpointDiff &&
|
||||
filesUnchanged &&
|
||||
summary.checkpointDiffLoaded
|
||||
) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
hasUpdates = true;
|
||||
return {
|
||||
...summary,
|
||||
unifiedDiff: checkpointDiff,
|
||||
files,
|
||||
checkpointDiffLoaded: true,
|
||||
};
|
||||
});
|
||||
|
||||
if (!hasUpdates) {
|
||||
return t;
|
||||
}
|
||||
|
||||
return {
|
||||
...t,
|
||||
turnDiffSummaries: updatedSummaries,
|
||||
};
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_BRANCH": {
|
||||
return {
|
||||
...state,
|
||||
@@ -1290,28 +1141,21 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
};
|
||||
}
|
||||
|
||||
case "MARK_THREAD_VISITED": {
|
||||
const visitedAt = action.visitedAt ?? new Date().toISOString();
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
lastVisitedAt: visitedAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
case "SET_RUNTIME_MODE":
|
||||
return {
|
||||
...state,
|
||||
runtimeMode: action.mode,
|
||||
};
|
||||
|
||||
case "DELETE_THREAD":
|
||||
case "DELETE_THREAD": {
|
||||
const threads = state.threads.filter((t) => t.id !== action.threadId);
|
||||
const diffState = resetDiffTargetIfMissing(state, threads);
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.filter((t) => t.id !== action.threadId),
|
||||
threads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
return state;
|
||||
@@ -1330,7 +1174,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
persistState(state);
|
||||
}, [state.runtimeMode]);
|
||||
}, [state]);
|
||||
|
||||
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@ export function createThread(projectId: string, options: CreateThreadOptions = {
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
turnDiffSummaries: [],
|
||||
error: null,
|
||||
createdAt,
|
||||
branch: options.branch ?? null,
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface ChatMessage {
|
||||
export interface TurnDiffFileChange {
|
||||
path: string;
|
||||
kind?: string | undefined;
|
||||
diff?: string | undefined;
|
||||
additions?: number | undefined;
|
||||
deletions?: number | undefined;
|
||||
}
|
||||
@@ -49,8 +50,10 @@ export interface TurnDiffSummary {
|
||||
completedAt: string;
|
||||
status?: string | undefined;
|
||||
files: TurnDiffFileChange[];
|
||||
unifiedDiff?: string | undefined;
|
||||
assistantMessageId?: string | undefined;
|
||||
checkpointTurnCount?: number | undefined;
|
||||
checkpointDiffLoaded?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
|
||||
@@ -8,7 +8,6 @@ interface DesktopBridge {
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
showContextMenu: (items: readonly { id: string; label: string }[]) => Promise<string | null>;
|
||||
openExternal: (url: string) => Promise<boolean>;
|
||||
onMenuAction: (listener: (action: string) => void) => () => void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -98,27 +98,6 @@ export function createWsNativeApi(): NativeApi {
|
||||
onEvent: (callback) =>
|
||||
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
|
||||
},
|
||||
state: {
|
||||
bootstrap: () => transport.request(WS_METHODS.stateBootstrap),
|
||||
listMessages: (input) => transport.request(WS_METHODS.stateListMessages, input),
|
||||
catchUp: (input) => transport.request(WS_METHODS.stateCatchUp, input),
|
||||
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),
|
||||
add: (input) => transport.request(WS_METHODS.projectsAdd, input),
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { tanstackRouter } from "@tanstack/router-plugin/vite";
|
||||
import { defineConfig } from "vite";
|
||||
const port = Number(process.env.PORT ?? 5173);
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
tanstackRouter(),
|
||||
react({
|
||||
babel: {
|
||||
plugins: [["babel-plugin-react-compiler", { target: "19" }]],
|
||||
},
|
||||
}),
|
||||
tailwindcss(),
|
||||
],
|
||||
define: {
|
||||
// In dev mode, tell the web app where the WebSocket server lives
|
||||
"import.meta.env.VITE_WS_URL": JSON.stringify(process.env.VITE_WS_URL ?? ""),
|
||||
},
|
||||
experimental: {
|
||||
enableNativePlugin: true,
|
||||
},
|
||||
resolve: {
|
||||
tsconfigPaths: true,
|
||||
},
|
||||
server: {
|
||||
port,
|
||||
strictPort: true,
|
||||
hmr: {
|
||||
// Explicit config so Vite's HMR WebSocket connects reliably
|
||||
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
|
||||
// connection logs — enable "Verbose" in DevTools to see them.
|
||||
protocol: "ws",
|
||||
host: "localhost",
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: "dist",
|
||||
emptyOutDir: true,
|
||||
},
|
||||
});
|
||||
@@ -15,9 +15,6 @@ export default defineConfig({
|
||||
}),
|
||||
tailwindcss(),
|
||||
],
|
||||
optimizeDeps: {
|
||||
include: ["@pierre/diffs", "@pierre/diffs/react", "@pierre/diffs/worker/worker.js"],
|
||||
},
|
||||
define: {
|
||||
// In dev mode, tell the web app where the WebSocket server lives
|
||||
"import.meta.env.VITE_WS_URL": JSON.stringify(process.env.VITE_WS_URL ?? ""),
|
||||
|
||||
|
Before Width: | Height: | Size: 1.3 MiB |
|
Before Width: | Height: | Size: 4.5 MiB |
@@ -1,4 +0,0 @@
|
||||
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M0 10C0 4.47715 4.47715 0 10 0H118C123.523 0 128 4.47715 128 10V118C128 123.523 123.523 128 118 128H10C4.47715 128 0 123.523 0 118V10Z" fill="black"/>
|
||||
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="white"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 105 KiB |