Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
605c74bb8c | ||
|
|
2880ef8276 | ||
|
|
05aa27a0d9 | ||
|
|
e81c2acb78 | ||
|
|
fda3073e0c | ||
|
|
7214778b64 | ||
|
|
27bd9192ad | ||
|
|
0da96d5c93 | ||
|
|
25dbfa7bc7 | ||
|
|
78b7070042 | ||
|
|
1332c488ad | ||
|
|
384878a3f1 | ||
|
|
bf9f653331 | ||
|
|
e7e289f4ba |
No files matched your search
@@ -0,0 +1,482 @@
|
||||
# Plan: Centralize Core Persistence in SQLite (`~/.t3/state.sqlite`)
|
||||
|
||||
## Summary
|
||||
Move durable core app state out of renderer `localStorage` and into a centralized SQLite database at `~/.t3/state.sqlite`, while keeping machine-level editable config in JSON (keybindings) and browser UX preferences in browser-scoped state by default.
|
||||
|
||||
This plan preserves existing checkpoint patch storage in Git (`refs/t3/checkpoints/...`) and adds optional checkpoint diff summaries in SQLite (parsed via `@pierre/diffs`) for fast UI metadata rendering.
|
||||
|
||||
Core migration goals:
|
||||
1. Data persistence scalability.
|
||||
2. Move as much logic and state control as possible to the server, keeping the frontend simple.
|
||||
|
||||
## Why This Revamp
|
||||
Current persistence is split across multiple stores:
|
||||
|
||||
- Renderer core state in `apps/web/src/store.ts` (`localStorage`, key `t3code:renderer-state:v7`)
|
||||
- Server project registry in `~/.t3/userdata/projects.json` (`apps/server/src/projectRegistry.ts`)
|
||||
- Provider thread event logs in `.logs/threads/*.events.ndjson` (`apps/server/src/providerManager.ts`)
|
||||
- Terminal history in `.logs/terminals/*.log` (`apps/server/src/terminalManager.ts`)
|
||||
- Keybindings in `~/.t3/keybindings.json` (`apps/server/src/keybindings.ts`)
|
||||
|
||||
This produces a split-brain model (client-local canonical thread/message state, server-local provider runtime state), weak multi-window consistency, and fragile reconnect/restart behavior.
|
||||
|
||||
## Goals
|
||||
1. Make SQLite the canonical durable store for core app entities:
|
||||
- projects
|
||||
- threads
|
||||
- messages
|
||||
- turn/checkpoint diff metadata (summary only)
|
||||
2. Keep checkpoint patch contents in Git only.
|
||||
3. Keep machine-level editable config in JSON files (keybindings), and keep browser UX preferences browser-scoped by default.
|
||||
4. Make server authoritative for durable state; client becomes a cache/subscriber.
|
||||
5. Support reliable reconnect/catch-up without `localStorage`.
|
||||
|
||||
## Non-Goals
|
||||
1. Replacing Git checkpoint storage with DB blob storage.
|
||||
2. Persisting raw terminal output into SQLite (keep file-based terminal history for now).
|
||||
3. Supporting provider implementations beyond current Codex flow in this revamp.
|
||||
4. Full event-sourcing rewrite of all UI state in v1.
|
||||
|
||||
## Data Classification and Storage Policy
|
||||
| Data class | Examples | Store | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| Core durable app data | projects, threads, messages, thread metadata, turn summaries | SQLite (`~/.t3/state.sqlite`) | Canonical source of truth |
|
||||
| Checkpoint patch content | unified diff between checkpoints | Git refs (`refs/t3/checkpoints/...`) | Existing `FilesystemCheckpointStore` remains |
|
||||
| Checkpoint metadata | changed files, +/- per file, checkpoint turn mapping | SQLite | Derived from Git diff + `@pierre/diffs` |
|
||||
| Machine-level editable config | keybindings | `~/.t3/keybindings.json` | Existing behavior, stays human-editable |
|
||||
| Browser-scoped UX preferences | theme, preferred editor, last-invoked script by project | Browser storage (currently `localStorage`) | Not canonical app data; per-browser behavior |
|
||||
| Volatile runtime state | active websocket connections, in-flight turn status, pending approvals | Memory | Rebuilt from runtime/provider events |
|
||||
|
||||
## Preference Scope Clarification
|
||||
1. `project.scripts` belongs to core app data and is persisted in SQLite with the project record.
|
||||
2. `script preference` means UX memory only, specifically the current `t3code:last-invoked-script-by-project` map used to preselect/run convenience actions.
|
||||
3. Theme/editor/script-preference keys are per-browser UX and are intentionally separate from shared project/thread/message data.
|
||||
4. Runtime mode default (`full-access` vs `approval-required`) should be treated as UX preference by default unless we explicitly decide it is a machine policy.
|
||||
|
||||
## Current vs Target Architecture
|
||||
### Current (simplified)
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI[apps/web] -->|ws rpc + push| WS[apps/server/wsServer]
|
||||
UI -->|localStorage| LS[(Browser localStorage)]
|
||||
WS --> PR[ProjectRegistry]
|
||||
PR --> PJ[projects.json]
|
||||
WS --> PM[ProviderManager]
|
||||
PM --> CASM[CodexAppServerManager]
|
||||
CASM --> C[codex app-server]
|
||||
PM --> TL[thread .ndjson logs]
|
||||
PM --> FCS[FilesystemCheckpointStore]
|
||||
FCS --> GIT[(Git refs/t3/checkpoints)]
|
||||
```
|
||||
|
||||
### Target
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI[apps/web] -->|ws rpc + push| WS[apps/server/wsServer]
|
||||
WS --> PS[PersistenceService]
|
||||
PS --> DB[(~/.t3/state.sqlite)]
|
||||
WS --> CFG[Keybinding Config]
|
||||
CFG --> JSON[(~/.t3/keybindings.json)]
|
||||
UI --> BSTATE[(Browser UX prefs)]
|
||||
WS --> PM[ProviderManager]
|
||||
PM --> CASM[CodexAppServerManager]
|
||||
CASM --> C[codex app-server]
|
||||
PM --> FCS[FilesystemCheckpointStore]
|
||||
FCS --> GIT[(Git refs/t3/checkpoints)]
|
||||
PM --> PS
|
||||
PS -->|state push| WS
|
||||
```
|
||||
|
||||
Provider remains the runtime execution engine. PersistenceService becomes the durable state authority and broadcaster.
|
||||
|
||||
## Core Domain Model (SQLite)
|
||||
Use strict schema + migrations (e.g. `PRAGMA user_version` or migration table), WAL mode, and transactional writes.
|
||||
|
||||
### JSON-first (iteration-friendly) schema
|
||||
Use a document-style core table with a minimal indexed envelope. Put evolving entity fields in `data_json`.
|
||||
|
||||
1. `documents`
|
||||
- `id TEXT PRIMARY KEY`
|
||||
- examples: `project:<uuid>`, `thread:<uuid>`, `message:<uuid>`, `turn_summary:<threadId>:<turnId>`
|
||||
- `kind TEXT NOT NULL`
|
||||
- `project` | `thread` | `message` | `turn_summary`
|
||||
- `project_id TEXT NULL`
|
||||
- `thread_id TEXT NULL`
|
||||
- `sort_key INTEGER NULL`
|
||||
- message order, thread ordering hints, summary ordering, etc.
|
||||
- `schema_version INTEGER NOT NULL DEFAULT 1`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- `data_json TEXT NOT NULL`
|
||||
|
||||
2. `provider_events`
|
||||
- `seq INTEGER PRIMARY KEY AUTOINCREMENT`
|
||||
- `id TEXT NOT NULL UNIQUE`
|
||||
- `session_id TEXT NOT NULL`
|
||||
- `provider TEXT NOT NULL`
|
||||
- `kind TEXT NOT NULL`
|
||||
- `method TEXT NOT NULL`
|
||||
- `thread_id TEXT NULL`
|
||||
- `turn_id TEXT NULL`
|
||||
- `item_id TEXT NULL`
|
||||
- `request_id TEXT NULL`
|
||||
- `request_kind TEXT NULL`
|
||||
- `text_delta TEXT NULL`
|
||||
- `message TEXT NULL`
|
||||
- `payload_json TEXT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
|
||||
3. `state_events`
|
||||
- `seq INTEGER PRIMARY KEY AUTOINCREMENT`
|
||||
- `event_type TEXT NOT NULL` (e.g. `project.upsert`, `thread.delete`, `message.upsert`)
|
||||
- `entity_id TEXT NOT NULL`
|
||||
- `payload_json TEXT NOT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
|
||||
4. `metadata`
|
||||
- `key TEXT PRIMARY KEY`
|
||||
- `value_json TEXT NOT NULL`
|
||||
- for one-time migrations/import markers
|
||||
|
||||
### Envelope indexes
|
||||
- `documents(kind)`
|
||||
- `documents(project_id, kind)`
|
||||
- `documents(thread_id, kind, sort_key)`
|
||||
- `documents(kind, updated_at DESC)`
|
||||
- `provider_events(session_id, seq)`
|
||||
- `provider_events(thread_id, seq)`
|
||||
- `state_events(seq)`
|
||||
|
||||
### Document conventions
|
||||
1. Validate each `kind` with Zod before writes and after reads.
|
||||
2. Keep envelope fields stable (`kind`, `project_id`, `thread_id`, `sort_key`) for fast list/filter queries.
|
||||
3. Put fast-changing/evolving structure in `data_json`:
|
||||
- project: name/cwd/model/expanded/scripts
|
||||
- thread: title/model/codex thread id/terminal layout/branch/worktree
|
||||
- message: role/text/attachments/streaming/provider ids
|
||||
- turn_summary: completed/status/checkpoint turn count/file +/- summary
|
||||
4. Use `schema_version` per document to support incremental document migrations without global table churn.
|
||||
|
||||
### Normalization runway (later, optional)
|
||||
When model shapes stabilize, we can materialize normalized tables from `documents` without changing the external protocol:
|
||||
1. Add typed read models (`projects_v2`, `messages_v2`, etc.).
|
||||
2. Backfill from `documents`.
|
||||
3. Switch read paths gradually.
|
||||
|
||||
## Streaming Protocol and Synchronization
|
||||
Keep current WS request/response envelope and push model. Extend with state snapshot + patch stream.
|
||||
|
||||
### New/extended WS methods
|
||||
1. `state.bootstrap`
|
||||
- returns complete durable snapshot for initial render:
|
||||
- projects (+scripts)
|
||||
- threads (+terminal metadata + turn summaries)
|
||||
- messages (+attachments), optionally capped per thread then paged
|
||||
- `lastStateSeq`
|
||||
|
||||
2. `state.listMessages` (paged)
|
||||
- for large threads and virtualized history
|
||||
|
||||
3. `threads.create`
|
||||
4. `threads.update`
|
||||
5. `threads.delete`
|
||||
6. `threads.markVisited`
|
||||
7. `threads.updateTerminalState`
|
||||
8. `threads.updateModel`
|
||||
9. `threads.updateTitle`
|
||||
|
||||
10. `state.catchUp`
|
||||
- input: `afterSeq`
|
||||
- returns ordered `state_events` for reconnect recovery
|
||||
|
||||
Existing `projects.*`, `providers.*`, `terminal.*`, `git.*`, `server.*` remain; they route through persistence-aware services.
|
||||
|
||||
### Push channels
|
||||
1. Keep `providers.event` for raw runtime/provider telemetry.
|
||||
2. Add `state.event` for canonical persisted mutations (`seq` ordered).
|
||||
3. Keep `terminal.event` and `server.welcome`.
|
||||
|
||||
### Ordering guarantees
|
||||
- Every durable mutation writes `state_events` in the same DB transaction as row changes.
|
||||
- Server broadcasts `state.event` after commit.
|
||||
- Clients apply events strictly by `seq`.
|
||||
- Reconnect uses `state.catchUp(afterSeq)` to fill gaps.
|
||||
|
||||
## Core App Flows
|
||||
### 1) Startup + hydration
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Web Client
|
||||
participant WS as wsServer
|
||||
participant PS as PersistenceService
|
||||
participant DB as SQLite
|
||||
|
||||
UI->>WS: connect websocket
|
||||
WS-->>UI: push server.welcome
|
||||
UI->>WS: state.bootstrap()
|
||||
WS->>PS: loadSnapshot()
|
||||
PS->>DB: SELECT projects/threads/messages/metadata
|
||||
DB-->>PS: snapshot + lastStateSeq
|
||||
PS-->>WS: bootstrap payload
|
||||
WS-->>UI: response(snapshot)
|
||||
UI->>WS: subscribe state.event/providers.event
|
||||
```
|
||||
|
||||
### 2) Create thread
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI
|
||||
participant WS
|
||||
participant PS
|
||||
participant DB
|
||||
|
||||
UI->>WS: threads.create(projectId, model, title, branch,...)
|
||||
WS->>PS: createThread(...)
|
||||
PS->>DB: INSERT thread + terminal defaults + state_event
|
||||
DB-->>PS: committed row + seq
|
||||
PS-->>WS: thread
|
||||
WS-->>UI: response(thread)
|
||||
WS-->>UI: push state.event(thread.upsert, seq)
|
||||
```
|
||||
|
||||
### 3) Send turn + stream + persist
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI
|
||||
participant WS
|
||||
participant PM as ProviderManager
|
||||
participant CASM as CodexAppServerManager
|
||||
participant Codex as codex app-server
|
||||
participant PS as PersistenceService
|
||||
participant DB as SQLite
|
||||
|
||||
UI->>WS: providers.startSession(threadId, resumeThreadId?)
|
||||
WS->>PM: startSession(...)
|
||||
PM->>CASM: thread/start or thread/resume
|
||||
CASM->>Codex: JSON-RPC
|
||||
Codex-->>CASM: notifications/events
|
||||
CASM-->>PM: ProviderEvent
|
||||
PM-->>PS: ingestProviderEvent(event)
|
||||
PS->>DB: INSERT provider_events + projection updates + state_event
|
||||
DB-->>PS: seq
|
||||
PM-->>WS: provider event
|
||||
WS-->>UI: push providers.event
|
||||
WS-->>UI: push state.event
|
||||
|
||||
UI->>WS: providers.sendTurn(sessionId, input, attachments)
|
||||
WS->>PM: sendTurn(...)
|
||||
PM->>CASM: turn/start
|
||||
CASM->>Codex: JSON-RPC
|
||||
```
|
||||
|
||||
### 4) Checkpoint capture + diff summary
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant PM as ProviderManager
|
||||
participant FCS as FilesystemCheckpointStore
|
||||
participant G as Git refs/t3/checkpoints
|
||||
participant PS as PersistenceService
|
||||
participant DB as SQLite
|
||||
participant WS as wsServer
|
||||
participant UI as Web Client
|
||||
|
||||
PM->>FCS: captureCheckpoint(threadId, turnCount)
|
||||
FCS->>G: update-ref refs/t3/checkpoints/...
|
||||
PM->>FCS: diffCheckpoints(turnCount-1, turnCount)
|
||||
FCS-->>PM: unified patch
|
||||
PM->>PS: persistTurnDiffSummary(turnId, patch)
|
||||
PS->>PS: parse patch with @pierre/diffs
|
||||
PS->>DB: upsert thread_turn_summaries + thread_turn_diff_files + state_event
|
||||
DB-->>PS: seq
|
||||
PS-->>WS: state.event(turn summary upsert)
|
||||
WS-->>UI: push state.event
|
||||
```
|
||||
|
||||
## Provider Role in the New Model
|
||||
Provider components are unchanged in purpose, but persistence boundaries become explicit:
|
||||
|
||||
1. `CodexAppServerManager`
|
||||
- runtime bridge to `codex app-server`
|
||||
- emits provider events
|
||||
- no direct durability ownership
|
||||
|
||||
2. `ProviderManager`
|
||||
- session lifecycle + checkpoint orchestration
|
||||
- forwards provider events to:
|
||||
- websocket push (`providers.event`)
|
||||
- persistence projection (`PersistenceService`)
|
||||
|
||||
3. `PersistenceService` (new)
|
||||
- canonicalizes thread/message state
|
||||
- stores provider event log
|
||||
- stores turn summary metadata
|
||||
- emits `state.event` patches
|
||||
|
||||
This cleanly separates runtime execution concerns from durable conversation state.
|
||||
|
||||
## Client Data Flow (Server -> Client)
|
||||
### Current issue
|
||||
- Web client computes and persists canonical messages/thread state locally (`reducer`, `applyEventToMessages`, `deriveTurnDiffSummaries`), so reconnect and multi-window consistency rely on localStorage.
|
||||
|
||||
### New flow
|
||||
1. Client bootstraps from server (`state.bootstrap`) instead of localStorage hydration.
|
||||
2. Client uses `state.event` as authoritative mutation stream.
|
||||
3. Client may still use optimistic UI for latency, but server-issued canonical IDs/rows win.
|
||||
4. `providers.event` remains for live UX details (in-progress deltas, approvals, lifecycle).
|
||||
|
||||
## Migration Plan
|
||||
### A) Server-side source migrations
|
||||
1. Introduce DB migration runner.
|
||||
2. On startup, import `projects.json` into SQLite if present and not yet imported.
|
||||
3. Preserve `projects.json` as backup:
|
||||
- rename to `projects.json.bak.<timestamp>`
|
||||
4. Keep keybindings migration path untouched (`~/.t3/keybindings.json` remains canonical).
|
||||
|
||||
### B) Client-side legacy state migration
|
||||
1. Detect legacy localStorage keys:
|
||||
- `t3code:renderer-state:v7` and legacy list in `apps/web/src/store.ts`
|
||||
2. Add one-time method `state.importLegacyRendererState(payload)`.
|
||||
3. Server validates and sanitizes payload with shared schema (port from `apps/web/src/persistenceSchema.ts` to contracts/server module).
|
||||
4. Server upserts projects/threads/messages/terminal metadata into SQLite.
|
||||
5. Server writes `metadata` marker to prevent duplicate imports.
|
||||
6. Client clears legacy localStorage keys after successful import.
|
||||
|
||||
### C) Browser UX preference boundary
|
||||
Default behavior: keep these browser-scoped and do not move them into SQLite or `~/.t3/*.json`:
|
||||
- `t3code:theme`
|
||||
- `t3code:last-editor`
|
||||
- `t3code:last-invoked-script-by-project`
|
||||
|
||||
Optional future mode (not required for this revamp):
|
||||
- Add server-backed preferences storage for users who want zero browser persistence.
|
||||
|
||||
## Implementation Phases
|
||||
### Phase 0: Foundation
|
||||
1. Add SQLite dependency and persistence modules:
|
||||
- `apps/server/src/stateDb.ts`
|
||||
- `apps/server/src/stateMigrations.ts`
|
||||
- `apps/server/src/persistenceService.ts`
|
||||
2. Add migration boot in `apps/server/src/index.ts`.
|
||||
3. Update default state path to `~/.t3/state.sqlite` (with env override).
|
||||
|
||||
### Phase 1: Document store cut-in (projects + threads first)
|
||||
1. Replace `ProjectRegistry` JSON backend with DB-backed document repository.
|
||||
2. Add `threads.*` methods to server routes.
|
||||
3. Keep web reducer but stop writing to localStorage for these entities.
|
||||
|
||||
### Phase 2: Message + turn document persistence
|
||||
1. Ingest provider events into DB (`provider_events`).
|
||||
2. Project events into `documents` rows for `message` and `turn_summary` kinds.
|
||||
3. Add `state.event` push and `state.catchUp`.
|
||||
|
||||
### Phase 3: Web client cutover
|
||||
1. Replace `readPersistedState()` boot path with `state.bootstrap`.
|
||||
2. Remove `persistState()` localStorage writes for core state.
|
||||
3. Keep only in-memory reducer/cache for volatile UI fields.
|
||||
|
||||
### Phase 4: Preference boundary hardening
|
||||
1. Keep `~/.t3/keybindings.json` as the only required JSON config in this revamp.
|
||||
2. Keep `theme` / `last-editor` / `last-invoked-script-by-project` browser-scoped (explicitly non-canonical).
|
||||
3. Ensure no core entity (`projects`, `threads`, `messages`, turn summaries) is read from or written to browser storage.
|
||||
|
||||
### Phase 5: Cleanup + compatibility
|
||||
1. Remove deprecated localStorage/persistence schema paths once migration is stable.
|
||||
2. Keep temporary migration fallback for one release window.
|
||||
3. (Optional) add a follow-up normalization milestone when schemas settle.
|
||||
|
||||
## Streaming/Projection Design Notes
|
||||
1. Durable append:
|
||||
- always append raw provider events first.
|
||||
2. Projection:
|
||||
- update message/thread projections in the same transaction when practical.
|
||||
- if expensive, queue projection jobs but keep deterministic ordering by provider event `seq`.
|
||||
3. Backpressure:
|
||||
- avoid heavyweight diff parsing on hot delta path.
|
||||
- compute checkpoint diff summaries only on checkpoint/turn completion.
|
||||
|
||||
## Reliability and Performance Settings
|
||||
1. SQLite pragmas:
|
||||
- `journal_mode=WAL`
|
||||
- `synchronous=FULL` (or `NORMAL` only if validated under load)
|
||||
- `busy_timeout=5000`
|
||||
- `foreign_keys=ON`
|
||||
2. Prepared statements for hot paths.
|
||||
3. Batch/paginate message retrieval for large threads.
|
||||
4. Add caps/retention for `provider_events` if DB growth becomes material.
|
||||
|
||||
## Testing Plan
|
||||
Backend changes require new tests and runtime validation.
|
||||
|
||||
### Unit tests
|
||||
1. DB schema + migrations
|
||||
2. Document repository CRUD (`project`/`thread`/`message`/`turn_summary`)
|
||||
3. Provider event projection logic
|
||||
4. Checkpoint summary parser (`@pierre/diffs` integration and malformed diff fallback)
|
||||
5. Keybindings JSON behavior remains unchanged (read/write + malformed-file handling)
|
||||
|
||||
### Integration tests (`wsServer`)
|
||||
1. `state.bootstrap` returns canonical snapshot
|
||||
2. `state.event` emits ordered `seq`
|
||||
3. reconnect + `state.catchUp` replays missing events
|
||||
4. `providers.event` + `state.event` coherence on a streamed turn
|
||||
5. localStorage import endpoint idempotence
|
||||
|
||||
### Migration tests
|
||||
1. `projects.json` import -> DB rows
|
||||
2. localStorage v7 import -> DB rows
|
||||
3. legacy payload rejection safety
|
||||
|
||||
### Frontend tests
|
||||
1. store boot without localStorage core snapshot
|
||||
2. reducer handling of `state.event` patches
|
||||
3. fallback behavior when server unavailable
|
||||
|
||||
## Risks and Mitigations
|
||||
1. Risk: Split writes between provider stream and DB create race conditions.
|
||||
- Mitigation: single persistence ingestion queue per session/thread, transactional writes, monotonic `seq`.
|
||||
2. Risk: Message duplication with optimistic UI.
|
||||
- Mitigation: client-supplied message IDs echoed by server; idempotent upserts.
|
||||
3. Risk: DB write amplification on text deltas.
|
||||
- Mitigation: append-only provider event log + projection throttling/finalization.
|
||||
4. Risk: migration corruption from malformed local data.
|
||||
- Mitigation: strict schema validation + partial-row rejection + migration markers + backups.
|
||||
5. Risk: checkpoint summary parsing overhead.
|
||||
- Mitigation: parse only finalized checkpoint ranges and fallback to lightweight stat extraction.
|
||||
6. Risk: JSON shape drift across fast iterations.
|
||||
- Mitigation: per-kind Zod schemas + `schema_version` in documents + migration tests for older payloads.
|
||||
|
||||
## Done Criteria
|
||||
1. No core durable app data depends on renderer localStorage.
|
||||
2. Projects/threads/messages/turn summaries persist in `~/.t3/state.sqlite` via JSON-first documents.
|
||||
3. Checkpoint patch content remains Git-backed; optional summaries are in DB.
|
||||
4. Keybindings remain JSON-backed at `~/.t3/keybindings.json`.
|
||||
5. Theme/editor/last-invoked-script remain browser-scoped (or explicitly migrated in a separate opt-in feature).
|
||||
6. App reload/reconnect reconstructs state from server snapshot + event catch-up.
|
||||
7. Lint/typecheck/tests pass across server/web/contracts.
|
||||
|
||||
## Concrete File Impact (Expected)
|
||||
### Server
|
||||
- `apps/server/src/index.ts` (state db path + bootstrap)
|
||||
- `apps/server/src/wsServer.ts` (new state/thread routes + push channel)
|
||||
- `apps/server/src/providerManager.ts` (persist event hooks + checkpoint summary writes)
|
||||
- `apps/server/src/projectRegistry.ts` (replace or wrap with document-backed repo)
|
||||
- new persistence modules (`stateDb`, migrations, document repository, persistence service)
|
||||
|
||||
### Web
|
||||
- `apps/web/src/store.ts` (remove localStorage core persistence)
|
||||
- `apps/web/src/persistenceSchema.ts` (migration-only use then eventual removal)
|
||||
- `apps/web/src/routes/__root.tsx` (state bootstrap and catch-up wiring)
|
||||
- `apps/web/src/wsNativeApi.ts` / contracts (new methods/channels)
|
||||
- preference callsites remain browser-scoped by default (`useTheme`, editor/script preference keys)
|
||||
|
||||
### Contracts
|
||||
- `packages/contracts/src/ws.ts` (new methods/channels)
|
||||
- `packages/contracts/src/ipc.ts` (new NativeApi sections for state/threads)
|
||||
- new schemas for thread/message/state-event payloads
|
||||
|
||||
## Open Questions
|
||||
1. Should runtime mode (`full-access` vs `approval-required`) remain browser-scoped UX state, or be elevated to machine policy?
|
||||
2. Should terminal panel layout/state be in SQLite (shared) or stay browser-scoped UX state?
|
||||
3. Do we need provider event retention limits from day one?
|
||||
4. Do we keep `.logs/threads/*.events.ndjson` as debug mirror after DB event log is live?
|
||||
5. For non-desktop/browser mode, should state still centralize to `~/.t3/state.sqlite` or support workspace-local override by default?
|
||||
@@ -0,0 +1,179 @@
|
||||
# Plan: Remove Legacy localStorage Migration Paths and Resolve CR Feedback Cohesively
|
||||
|
||||
## Summary
|
||||
Delete all runtime migration pathways that ingest legacy browser localStorage state into the new SQLite-backed model, then resolve the remaining code review (CR) findings in grouped workstreams.
|
||||
|
||||
This plan intentionally removes migration code instead of improving it. The target is a single canonical state flow: server-backed bootstrap + state events only, with no legacy data import bridge.
|
||||
|
||||
## Goals
|
||||
1. Remove legacy localStorage migration for renderer state completely.
|
||||
2. Remove dead contracts, RPC methods, server handlers, client callers, and tests tied to that migration.
|
||||
3. Resolve valid CR findings on the retained architecture.
|
||||
4. Close review threads with explicit outcomes: fixed, superseded by deletion, or declined with rationale.
|
||||
|
||||
## Non-Goals
|
||||
1. Preserving one-time automatic import of old renderer localStorage data.
|
||||
2. Refactoring unrelated UX persistence (theme/editor preferences) unless directly required by CR items.
|
||||
3. Large behavior changes outside correctness/reliability fixes raised in CR.
|
||||
|
||||
## Architecture Decision
|
||||
- Canonical state source remains SQLite + `state.bootstrap` + `state.catchUp` + streamed `stateEvent` updates.
|
||||
- Legacy renderer-state migration is removed entirely.
|
||||
- Existing server-side `projects.json` import path is kept unless explicitly removed in a follow-up (it is not localStorage-based).
|
||||
|
||||
## Workstream 1: Delete Legacy localStorage Migration End-to-End [COMPLETE]
|
||||
|
||||
### 1.1 Contracts and WS protocol cleanup
|
||||
- Remove `stateImportLegacyRendererState` from `packages/contracts/src/ws.ts`.
|
||||
- Remove state import input/result schemas and exported types from `packages/contracts/src/state.ts`.
|
||||
- Remove IPC surface for `state.importLegacyRendererState` in `packages/contracts/src/ipc.ts`.
|
||||
- Update and prune contracts tests in `packages/contracts/src/state.test.ts` and any IPC/WS tests that reference removed symbols.
|
||||
|
||||
### 1.2 Server cleanup
|
||||
- Remove `PersistenceService.importLegacyRendererState(...)` and associated metadata key/constants used only for this import path.
|
||||
- Remove WS routing case for `WS_METHODS.stateImportLegacyRendererState` in `apps/server/src/wsServer.ts`.
|
||||
- Remove server tests that exercise legacy renderer import via RPC and service unit tests.
|
||||
- Ensure no dead helpers remain (payload mapping, metadata flags, schema imports, etc.).
|
||||
|
||||
### 1.3 Web client cleanup
|
||||
- Remove legacy key constants and helper functions from `apps/web/src/routes/__root.tsx`:
|
||||
- `CURRENT_RENDERER_STATE_KEY`
|
||||
- `LEGACY_RENDERER_STATE_KEYS`
|
||||
- `readLegacyRendererImportPayload`
|
||||
- `clearLegacyRendererState`
|
||||
- import-and-refresh bootstrap branch invoking `api.state.importLegacyRendererState(...)`
|
||||
- Remove `hydratePersistedState` dependency from root route.
|
||||
- Delete or narrow `apps/web/src/persistenceSchema.ts` to only what is still used. If unused after migration removal, delete file and tests.
|
||||
- Remove `state.importLegacyRendererState` call path from `apps/web/src/wsNativeApi.ts`.
|
||||
|
||||
### 1.4 Dead-code verification pass
|
||||
- `rg` for: `importLegacyRendererState`, `stateImportLegacyRendererState`, `renderer-state:v`, `hydratePersistedState`, legacy metadata keys.
|
||||
- Ensure zero references remain in app code, contracts, and tests.
|
||||
|
||||
## Workstream 2: Resolve CR Findings in Surviving Code (Grouped by Relevance) [COMPLETE]
|
||||
|
||||
### Group A: Data integrity and transactional correctness (highest priority)
|
||||
- `apps/server/src/persistenceService.ts`
|
||||
- Fix `listMessages` pagination progress: use fetched row count for `nextOffset`.
|
||||
- Guard `withTransaction` post-commit event emission so listener exceptions do not surface as transaction failures.
|
||||
- Preserve `checkpointTurnCount = 0` in turn-summary merge logic.
|
||||
- Prevent `item/started` from clobbering previously accumulated assistant text when events arrive out of order.
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- Wrap/contain `applyCheckpointRevert` persistence update so provider revert success is not falsely returned as failure.
|
||||
- `apps/server/src/stateDb.ts`
|
||||
- Close DB when migration initialization fails in constructor.
|
||||
- Preserve original transaction error if rollback also throws.
|
||||
|
||||
### Group B: API/contract clarity and ownership boundaries
|
||||
- `apps/server/src/wsServer.ts` + `packages/contracts/src/ipc.ts` + `apps/web/src/wsNativeApi.ts`
|
||||
- Remove ambiguous generic `threads.update` or make it explicit/unsupported (single canonical terminal-state update route).
|
||||
- Align method names/types with actual handlers.
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- Track ownership of injected `persistenceService`; only close internally owned instance in `stop()`.
|
||||
- `apps/server/src/sqliteAdapter.ts`
|
||||
- Add explicit guard/error message when `node:sqlite` is unavailable.
|
||||
|
||||
### Group C: Client consistency and race prevention
|
||||
- `apps/web/src/appSettings.ts`
|
||||
- Add hydration/update sequence guard so hydration cannot overwrite optimistic writes.
|
||||
- `apps/web/src/store.ts`
|
||||
- Harden `thread.upsert` normalization to avoid crashes on missing terminal arrays (safe defaults before terminal normalization).
|
||||
- `apps/web/src/components/Sidebar.tsx`
|
||||
- Fix no-API thread creation path (do not call API-gated `handleNewThread` in browser-only fallback).
|
||||
- `apps/web/src/components/BranchToolbar.tsx` + `apps/web/src/components/ChatView.tsx`
|
||||
- Remove duplicate `updateBranch` network write path.
|
||||
|
||||
### Group D: Test reliability and cleanup
|
||||
- `apps/server/src/persistenceService.test.ts`
|
||||
- Make timestamp helper deterministic.
|
||||
- Ensure service instances are always closed via `try/finally`.
|
||||
- Replace always-true catch-up sequence assertion with monotonic/defined sequence checks.
|
||||
- Update/add tests for Group A/B/C behavior changes.
|
||||
|
||||
## Workstream 3: Review Thread Triage/Closure Strategy [COMPLETE]
|
||||
|
||||
### Threads closed by deletion (Workstream 1)
|
||||
- Legacy renderer import flow/race concerns in root route.
|
||||
- Legacy import schemas, WS method concerns, and related service import concerns.
|
||||
- Any CR comments rooted in the removed migration path.
|
||||
|
||||
### Threads closed by fixes (Workstream 2)
|
||||
- Transaction semantics, pagination correctness, branch update duplication, no-API thread creation, etc.
|
||||
|
||||
### Threads closed with rationale (no change)
|
||||
- Keep concise “not adopted” notes only where behavior is intentional and safe.
|
||||
|
||||
### Disposition Matrix (Ready for PR Thread Closure)
|
||||
- `superseded-by-deletion`
|
||||
- Legacy renderer-state import path comments (root-route import race, legacy import RPC/schema/service concerns).
|
||||
- Rationale: Workstream 1 deleted the entire runtime migration pathway and removed related contracts/callers/handlers.
|
||||
- `fixed`
|
||||
- `listMessages` pagination progress now advances by fetched row count.
|
||||
- `withTransaction` post-commit event emission no longer surfaces listener exceptions as write failures.
|
||||
- `checkpointTurnCount = 0` is preserved in summary merge logic.
|
||||
- Out-of-order `item/started` no longer clobbers accumulated assistant text.
|
||||
- Provider checkpoint revert no longer returns failure when persistence follow-up write fails.
|
||||
- Generic `threads.update` is explicitly unsupported; canonical path is `threads.updateTerminalState`.
|
||||
- `wsServer.stop()` now closes persistence only when internally owned.
|
||||
- `StateDb` closes DB on migration failure and preserves original transaction error if rollback also fails.
|
||||
- `sqliteAdapter` now emits explicit guidance when `node:sqlite` is unavailable.
|
||||
- `appSettings` hydration now guards against overwriting optimistic writes.
|
||||
- `thread.upsert` reducer path now safely defaults missing terminal arrays.
|
||||
- Sidebar no-API fallback now creates a local thread.
|
||||
- Duplicate `updateBranch` write path removed from `BranchToolbar`; canonical write remains in `ChatView` effect.
|
||||
- `declined-with-rationale`
|
||||
- None in this workstream. No remaining high/medium CR findings required intentional non-adoption.
|
||||
|
||||
### Evidence Anchors for Thread Replies
|
||||
- Server behavior fixes:
|
||||
- `apps/server/src/persistenceService.ts`
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- `apps/server/src/stateDb.ts`
|
||||
- `apps/server/src/sqliteAdapter.ts`
|
||||
- Web/contracts fixes:
|
||||
- `packages/contracts/src/ws.ts`
|
||||
- `packages/contracts/src/ipc.ts`
|
||||
- `apps/web/src/wsNativeApi.ts`
|
||||
- `apps/web/src/appSettings.ts`
|
||||
- `apps/web/src/store.ts`
|
||||
- `apps/web/src/components/Sidebar.tsx`
|
||||
- `apps/web/src/components/BranchToolbar.tsx`
|
||||
- Regression coverage:
|
||||
- `apps/server/src/persistenceService.test.ts`
|
||||
- `apps/server/src/wsServer.test.ts`
|
||||
- `apps/server/src/stateDb.test.ts`
|
||||
- `apps/server/src/sqliteAdapter.test.ts`
|
||||
- `apps/web/src/appSettings.test.ts`
|
||||
- `apps/web/src/store.test.ts`
|
||||
- `apps/web/src/components/Sidebar.logic.test.ts`
|
||||
- `packages/contracts/src/ws.test.ts`
|
||||
|
||||
### Suggested Reply Templates
|
||||
- `superseded-by-deletion`: "Superseded by Workstream 1 removal of legacy renderer-state migration path; related RPC/schema/client callsites were deleted."
|
||||
- `fixed`: "Fixed in Workstream 2 with tests added; see referenced file(s) and regression coverage."
|
||||
- `declined-with-rationale`: "Intentional behavior retained; safe by design and documented here with rationale and test coverage."
|
||||
|
||||
## Execution Order
|
||||
1. Contracts + protocol deletions (Workstream 1.1).
|
||||
2. Server deletion and compilation fixes (Workstream 1.2).
|
||||
3. Web deletion and compilation fixes (Workstream 1.3).
|
||||
4. Dead-code sweep and test pruning (Workstream 1.4).
|
||||
5. Group A fixes + tests.
|
||||
6. Group B fixes + tests.
|
||||
7. Group C fixes + tests.
|
||||
8. Group D test hardening.
|
||||
9. Final lint/test pass; prepare review-thread response mapping.
|
||||
|
||||
## Validation Matrix
|
||||
- Lint: `bun run lint`.
|
||||
- Contracts tests: `bun --cwd packages/contracts test` (or workspace equivalent).
|
||||
- Server tests (required for backend changes): `bun --cwd apps/server test`.
|
||||
- Web tests: `bun --cwd apps/web test`.
|
||||
- Grep-based dead-code validation for removed migration symbols.
|
||||
|
||||
## Done Criteria
|
||||
1. No runtime path exists to import legacy renderer localStorage into server state.
|
||||
2. No dead symbols remain for removed migration APIs.
|
||||
3. CR high/medium validity issues in retained code are fixed or explicitly dispositioned.
|
||||
4. Backend tests and project lint pass.
|
||||
5. PR discussion can be answered thread-by-thread with: fixed / superseded / intentionally declined.
|
||||
@@ -10,3 +10,5 @@
|
||||
8. `08-precommit-format-and-lint.md`
|
||||
9. `09-event-state-test-expansion.md`
|
||||
10. `10-unify-process-session-abstraction.md`
|
||||
11. `11-centralized-sqlite-persistence-revamp.md`
|
||||
12. `12-remove-legacy-localstorage-migrations-and-cr-hardening.md`
|
||||
@@ -63,6 +63,19 @@ bun run dist:desktop:dmg
|
||||
npx t3
|
||||
```
|
||||
|
||||
## Remote usage (phone/tablet/laptop)
|
||||
|
||||
To run the server on one device and control it from another (for example over Tailscale), use:
|
||||
|
||||
- `docs/remote-access.md`
|
||||
|
||||
This includes:
|
||||
|
||||
- architecture and security model
|
||||
- production setup for remote control
|
||||
- remote dev setup with hot reload
|
||||
- troubleshooting for cross-device connectivity
|
||||
|
||||
## Scripts
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
|
||||
|
||||
@@ -300,6 +300,42 @@ function backendEnv(): NodeJS.ProcessEnv {
|
||||
};
|
||||
}
|
||||
|
||||
function resolveBackendLaunch(backendEntry: string): {
|
||||
command: string;
|
||||
args: string[];
|
||||
env: NodeJS.ProcessEnv;
|
||||
} {
|
||||
const runtimeOverride = process.env.T3CODE_BACKEND_RUNTIME?.trim();
|
||||
if (runtimeOverride && runtimeOverride.length > 0) {
|
||||
if (runtimeOverride === "electron-node") {
|
||||
return {
|
||||
command: process.execPath,
|
||||
args: [backendEntry],
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
command: runtimeOverride,
|
||||
args: [backendEntry],
|
||||
env: backendEnv(),
|
||||
};
|
||||
}
|
||||
|
||||
// Default to Node-mode execution under Electron in both dev and production.
|
||||
// This matches main and avoids runtime-specific PTY behavior differences.
|
||||
return {
|
||||
command: process.execPath,
|
||||
args: [backendEntry],
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleBackendRestart(reason: string): void {
|
||||
if (isQuitting || restartTimer) return;
|
||||
|
||||
@@ -322,14 +358,10 @@ function startBackend(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const child = spawn(process.execPath, [backendEntry], {
|
||||
const launch = resolveBackendLaunch(backendEntry);
|
||||
const child = spawn(launch.command, launch.args, {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
env: launch.env,
|
||||
stdio: "inherit",
|
||||
});
|
||||
backendProcess = child;
|
||||
|
||||
@@ -17,9 +17,7 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/core": "workspace:*",
|
||||
"@t3tools/infra-sqlite": "workspace:*",
|
||||
"effect": "^3.18.4",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
EffectFanout,
|
||||
OrchestrationEngine,
|
||||
QueueProjector,
|
||||
type AppViewState,
|
||||
} from "@t3tools/core";
|
||||
import { createSqliteStores } from "@t3tools/infra-sqlite";
|
||||
|
||||
import type { ProviderManager } from "./providerManager";
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
export class CoreRuntime {
|
||||
private readonly fanout = new EffectFanout();
|
||||
private readonly stores;
|
||||
private readonly projector: QueueProjector;
|
||||
private readonly engine: OrchestrationEngine;
|
||||
|
||||
constructor(dbDir: string) {
|
||||
const dbPath = path.join(dbDir, "event-store.sqlite");
|
||||
this.stores = createSqliteStores(dbPath);
|
||||
this.projector = new QueueProjector(this.stores.projectionStore, this.fanout);
|
||||
this.engine = new OrchestrationEngine(
|
||||
this.stores.eventStore,
|
||||
this.stores.projectionStore,
|
||||
this.projector,
|
||||
);
|
||||
}
|
||||
|
||||
async start(cwd: string, projectName: string): Promise<void> {
|
||||
await this.engine.start();
|
||||
await this.engine.execute({
|
||||
id: crypto.randomUUID(),
|
||||
type: "app.bootstrap",
|
||||
issuedAt: nowIso(),
|
||||
payload: { cwd, projectName },
|
||||
});
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await this.engine.stop();
|
||||
this.stores.db.close();
|
||||
}
|
||||
|
||||
async state(): Promise<AppViewState> {
|
||||
return this.engine.currentState();
|
||||
}
|
||||
|
||||
async dispatch(command: Parameters<OrchestrationEngine["execute"]>[0]): Promise<AppViewState> {
|
||||
return this.engine.execute(command);
|
||||
}
|
||||
|
||||
subscribe() {
|
||||
return this.fanout.subscribe();
|
||||
}
|
||||
|
||||
bindProviderEvents(providerManager: ProviderManager): void {
|
||||
providerManager.on("event", (event: ProviderEvent) => {
|
||||
void this.ingestProviderEvent(event);
|
||||
});
|
||||
}
|
||||
|
||||
async bindProviderSession(threadId: string, session: ProviderSession): Promise<void> {
|
||||
await this.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.updateProviderSession",
|
||||
issuedAt: nowIso(),
|
||||
payload: { threadId, session },
|
||||
});
|
||||
}
|
||||
|
||||
async clearProviderSession(threadId: string): Promise<void> {
|
||||
await this.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.updateProviderSession",
|
||||
issuedAt: nowIso(),
|
||||
payload: { threadId, session: null },
|
||||
});
|
||||
}
|
||||
|
||||
async ingestProviderEvent(event: ProviderEvent): Promise<void> {
|
||||
const state = await this.state();
|
||||
const target = state.threads.find((thread) => thread.session?.sessionId === event.sessionId);
|
||||
if (!target) return;
|
||||
await this.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.recordProviderEvent",
|
||||
issuedAt: event.createdAt,
|
||||
payload: {
|
||||
threadId: target.id,
|
||||
event,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
import { fixPath } from "./fixPath";
|
||||
import { createLogger } from "./logger";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { PersistenceService } from "./persistenceService";
|
||||
import { createServer } from "./wsServer";
|
||||
|
||||
fixPath();
|
||||
@@ -49,6 +49,13 @@ function resolveStateDir(raw: string | undefined): string {
|
||||
return path.resolve(expandHomePath(raw.trim()));
|
||||
}
|
||||
|
||||
function resolveStateDbPath(raw: string | undefined): string {
|
||||
if (!raw || raw.trim().length === 0) {
|
||||
return path.join(os.homedir(), ".t3", "state.sqlite");
|
||||
}
|
||||
return path.resolve(expandHomePath(raw.trim()));
|
||||
}
|
||||
|
||||
async function findAvailablePort(preferred: number): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
@@ -101,8 +108,12 @@ async function main() {
|
||||
const requestedPort = parsePort(process.env.T3CODE_PORT);
|
||||
const port =
|
||||
requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
|
||||
const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
|
||||
const projectRegistry = new ProjectRegistry(stateDir);
|
||||
const legacyStateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
|
||||
const stateDbPath = resolveStateDbPath(process.env.T3CODE_STATE_DB_PATH);
|
||||
const persistenceService = new PersistenceService({
|
||||
dbPath: stateDbPath,
|
||||
legacyProjectsJsonPath: path.join(legacyStateDir, "projects.json"),
|
||||
});
|
||||
const devUrl = process.env.VITE_DEV_SERVER_URL;
|
||||
const noBrowser = parseBooleanEnv(process.env.T3CODE_NO_BROWSER) ?? mode === "desktop";
|
||||
const authToken = process.env.T3CODE_AUTH_TOKEN;
|
||||
@@ -120,8 +131,7 @@ async function main() {
|
||||
cwd,
|
||||
staticDir,
|
||||
devUrl,
|
||||
projectRegistry,
|
||||
stateDir,
|
||||
persistenceService,
|
||||
authToken,
|
||||
});
|
||||
await server.start();
|
||||
@@ -131,7 +141,8 @@ async function main() {
|
||||
url,
|
||||
cwd,
|
||||
mode,
|
||||
stateDir,
|
||||
stateDbPath,
|
||||
legacyStateDir,
|
||||
authEnabled: Boolean(authToken),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { ProviderEvent } from "@t3tools/contracts";
|
||||
import { PersistenceService } from "./persistenceService";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
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();
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -57,6 +57,8 @@ describe("ProjectRegistry scripts", () => {
|
||||
expect(listed[0]?.scripts).toHaveLength(2);
|
||||
expect(listed[0]?.scripts[0]?.id).toBe("run");
|
||||
expect(listed[0]?.scripts[1]?.id).toBe("setup");
|
||||
registry.close();
|
||||
reloaded.close();
|
||||
});
|
||||
|
||||
it("deduplicates script ids and allows only one setup script", () => {
|
||||
@@ -97,6 +99,7 @@ describe("ProjectRegistry scripts", () => {
|
||||
expect(updated.project.scripts[0]?.runOnWorktreeCreate).toBe(true);
|
||||
expect(updated.project.scripts[1]?.id).toBe("another");
|
||||
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(false);
|
||||
registry.close();
|
||||
});
|
||||
|
||||
it("throws when updating scripts for an unknown project id", () => {
|
||||
@@ -109,5 +112,6 @@ describe("ProjectRegistry scripts", () => {
|
||||
scripts: [],
|
||||
}),
|
||||
).toThrowError("Project not found");
|
||||
registry.close();
|
||||
});
|
||||
});
|
||||
@@ -1,235 +1,47 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
type ProjectAddInput,
|
||||
type ProjectAddResult,
|
||||
type ProjectListResult,
|
||||
type ProjectRecord,
|
||||
type ProjectRemoveInput,
|
||||
type ProjectScript,
|
||||
type ProjectUpdateScriptsInput,
|
||||
type ProjectUpdateScriptsResult,
|
||||
normalizeProjectScripts,
|
||||
projectAddInputSchema,
|
||||
projectRecordSchema,
|
||||
projectRemoveInputSchema,
|
||||
projectScriptsSchema,
|
||||
projectUpdateScriptsInputSchema,
|
||||
import type {
|
||||
ProjectAddInput,
|
||||
ProjectAddResult,
|
||||
ProjectListResult,
|
||||
ProjectRemoveInput,
|
||||
ProjectUpdateScriptsInput,
|
||||
ProjectUpdateScriptsResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
function cloneScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
|
||||
const cloned: ProjectScript[] = [];
|
||||
for (const script of scripts) {
|
||||
cloned.push({
|
||||
id: script.id,
|
||||
name: script.name,
|
||||
command: script.command,
|
||||
icon: script.icon,
|
||||
runOnWorktreeCreate: script.runOnWorktreeCreate,
|
||||
});
|
||||
}
|
||||
return cloned;
|
||||
}
|
||||
|
||||
function normalizeCwd(rawCwd: string): string {
|
||||
const resolved = path.resolve(rawCwd.trim());
|
||||
const normalized = path.normalize(resolved);
|
||||
if (process.platform === "win32") {
|
||||
return normalized.toLowerCase();
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function isDirectory(cwd: string): boolean {
|
||||
try {
|
||||
return fs.statSync(cwd).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function inferProjectName(cwd: string): string {
|
||||
const name = path.basename(cwd);
|
||||
return name.length > 0 ? name : "project";
|
||||
}
|
||||
import { PersistenceService } from "./persistenceService";
|
||||
|
||||
/**
|
||||
* Backward-compatible wrapper retained for tests and legacy callsites.
|
||||
* Core storage now lives in SQLite through PersistenceService.
|
||||
*/
|
||||
export class ProjectRegistry {
|
||||
private readonly stateDir: string;
|
||||
private readonly filePath: string;
|
||||
private projects: ProjectRecord[];
|
||||
private readonly persistenceService: PersistenceService;
|
||||
|
||||
constructor(stateDir: string) {
|
||||
this.stateDir = stateDir;
|
||||
this.filePath = path.join(this.stateDir, "projects.json");
|
||||
fs.mkdirSync(this.stateDir, { recursive: true });
|
||||
this.projects = this.loadFromDisk();
|
||||
this.persistenceService = new PersistenceService({
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
|
||||
});
|
||||
}
|
||||
|
||||
list(): ProjectListResult {
|
||||
return this.projects.map((project) => ({
|
||||
...project,
|
||||
scripts: cloneScripts(project.scripts),
|
||||
}));
|
||||
return this.persistenceService.listProjects();
|
||||
}
|
||||
|
||||
add(raw: ProjectAddInput): ProjectAddResult {
|
||||
const input = projectAddInputSchema.parse(raw);
|
||||
const normalizedCwd = normalizeCwd(input.cwd);
|
||||
if (!isDirectory(normalizedCwd)) {
|
||||
throw new Error(`Project path does not exist: ${normalizedCwd}`);
|
||||
}
|
||||
|
||||
const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd);
|
||||
if (existing) {
|
||||
return {
|
||||
project: {
|
||||
...existing,
|
||||
scripts: cloneScripts(existing.scripts),
|
||||
},
|
||||
created: false,
|
||||
};
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const project: ProjectRecord = {
|
||||
id: randomUUID(),
|
||||
cwd: normalizedCwd,
|
||||
name: inferProjectName(normalizedCwd),
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.projects = [project, ...this.projects];
|
||||
this.persist();
|
||||
return {
|
||||
project: {
|
||||
...project,
|
||||
scripts: cloneScripts(project.scripts),
|
||||
},
|
||||
created: true,
|
||||
};
|
||||
return this.persistenceService.addProject(raw);
|
||||
}
|
||||
|
||||
remove(raw: ProjectRemoveInput): void {
|
||||
const input = projectRemoveInputSchema.parse(raw);
|
||||
const next = this.projects.filter((project) => project.id !== input.id);
|
||||
if (next.length === this.projects.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.projects = next;
|
||||
this.persist();
|
||||
this.persistenceService.removeProject(raw);
|
||||
}
|
||||
|
||||
updateScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
|
||||
const input = projectUpdateScriptsInputSchema.parse(raw);
|
||||
const index = this.projects.findIndex((project) => project.id === input.id);
|
||||
if (index < 0) {
|
||||
throw new Error(`Project not found: ${input.id}`);
|
||||
}
|
||||
|
||||
const nextScripts = normalizeProjectScripts(projectScriptsSchema.parse(input.scripts));
|
||||
const nextUpdatedAt = new Date().toISOString();
|
||||
const nextProject: ProjectRecord = {
|
||||
...this.projects[index]!,
|
||||
scripts: nextScripts,
|
||||
updatedAt: nextUpdatedAt,
|
||||
};
|
||||
|
||||
const nextProjects = [...this.projects];
|
||||
nextProjects[index] = nextProject;
|
||||
this.projects = nextProjects;
|
||||
this.persist();
|
||||
|
||||
return {
|
||||
project: { ...nextProject, scripts: cloneScripts(nextProject.scripts) },
|
||||
};
|
||||
return this.persistenceService.updateProjectScripts(raw);
|
||||
}
|
||||
|
||||
private loadFromDisk(): ProjectRecord[] {
|
||||
const loaded = this.readPersistedProjects();
|
||||
const deduped = new Map<string, ProjectRecord>();
|
||||
const normalizedProjects: ProjectRecord[] = [];
|
||||
|
||||
for (const project of loaded) {
|
||||
const normalizedCwd = normalizeCwd(project.cwd);
|
||||
if (!isDirectory(normalizedCwd)) {
|
||||
continue;
|
||||
}
|
||||
if (deduped.has(normalizedCwd)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedProject: ProjectRecord = {
|
||||
...project,
|
||||
cwd: normalizedCwd,
|
||||
name:
|
||||
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
|
||||
scripts: normalizeProjectScripts(project.scripts),
|
||||
};
|
||||
deduped.set(normalizedCwd, normalizedProject);
|
||||
normalizedProjects.push(normalizedProject);
|
||||
}
|
||||
|
||||
const changed =
|
||||
normalizedProjects.length !== loaded.length ||
|
||||
normalizedProjects.some((project, index) => {
|
||||
const source = loaded[index];
|
||||
if (!source) return true;
|
||||
return (
|
||||
source.id !== project.id ||
|
||||
source.cwd !== project.cwd ||
|
||||
source.name !== project.name ||
|
||||
JSON.stringify(source.scripts) !== JSON.stringify(project.scripts) ||
|
||||
source.createdAt !== project.createdAt ||
|
||||
source.updatedAt !== project.updatedAt
|
||||
);
|
||||
});
|
||||
|
||||
if (changed) {
|
||||
this.projects = normalizedProjects;
|
||||
this.persist();
|
||||
}
|
||||
|
||||
return normalizedProjects;
|
||||
}
|
||||
|
||||
private readPersistedProjects(): ProjectRecord[] {
|
||||
try {
|
||||
const raw = fs.readFileSync(this.filePath, "utf8");
|
||||
const parsed = JSON.parse(raw) as { projects?: unknown };
|
||||
if (!parsed || !Array.isArray(parsed.projects)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const projects: ProjectRecord[] = [];
|
||||
for (const candidate of parsed.projects) {
|
||||
const row = projectRecordSchema.safeParse(candidate);
|
||||
if (!row.success) {
|
||||
continue;
|
||||
}
|
||||
projects.push(row.data);
|
||||
}
|
||||
return projects;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private persist(): void {
|
||||
const payload = JSON.stringify(
|
||||
{
|
||||
version: 1,
|
||||
projects: this.projects,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const tempFile = `${this.filePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
fs.writeFileSync(tempFile, payload);
|
||||
fs.renameSync(tempFile, this.filePath);
|
||||
close(): void {
|
||||
this.persistenceService.close();
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,11 @@ import {
|
||||
import type { CodexThreadTurnSnapshot } from "./codexAppServerManager";
|
||||
import { CodexAppServerManager } from "./codexAppServerManager";
|
||||
import { FilesystemCheckpointStore } from "./filesystemCheckpointStore";
|
||||
import type { PersistenceService } from "./persistenceService";
|
||||
|
||||
export interface ProviderManagerOptions {
|
||||
persistenceService?: PersistenceService | undefined;
|
||||
}
|
||||
|
||||
export interface ProviderManagerEvents {
|
||||
event: [event: ProviderEvent];
|
||||
@@ -163,6 +168,7 @@ function buildCheckpoints(turns: CodexThreadTurnSnapshot[]): ProviderCheckpoint[
|
||||
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
private readonly codex = new CodexAppServerManager();
|
||||
private readonly filesystemCheckpointStore = new FilesystemCheckpointStore();
|
||||
private readonly persistenceService: PersistenceService | undefined;
|
||||
private readonly threadLogsDir: string;
|
||||
private readonly threadLogStreams = new Map<string, fs.WriteStream>();
|
||||
private readonly sessionThreadIds = new Map<string, string>();
|
||||
@@ -176,12 +182,21 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
}
|
||||
|
||||
this.routeEventToThreadLog(event);
|
||||
try {
|
||||
this.persistenceService?.ingestProviderEvent(event);
|
||||
} catch {
|
||||
// Persistence failures should not break provider streaming.
|
||||
}
|
||||
if (event.method === "session/closed" || event.method === "session/exited") {
|
||||
this.persistenceService?.unbindSession(event.sessionId);
|
||||
}
|
||||
this.emit("event", event);
|
||||
this.maybeCaptureFilesystemCheckpoint(event);
|
||||
};
|
||||
|
||||
constructor() {
|
||||
constructor(options: ProviderManagerOptions = {}) {
|
||||
super();
|
||||
this.persistenceService = options.persistenceService;
|
||||
|
||||
const logsDir = path.resolve(process.cwd(), ".logs");
|
||||
this.threadLogsDir = path.join(logsDir, "threads");
|
||||
@@ -197,6 +212,17 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
}
|
||||
|
||||
const session = await this.codex.startSession(input);
|
||||
if (input.threadId) {
|
||||
try {
|
||||
this.persistenceService?.bindSessionToThread(
|
||||
session.sessionId,
|
||||
input.threadId,
|
||||
session.threadId ?? null,
|
||||
);
|
||||
} catch {
|
||||
// Runtime session establishment should proceed even if persistence fails.
|
||||
}
|
||||
}
|
||||
if (session.threadId) {
|
||||
this.sessionThreadIds.set(session.sessionId, session.threadId);
|
||||
this.flushPendingSessionEvents(session.sessionId, session.threadId);
|
||||
@@ -215,6 +241,11 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
try {
|
||||
this.persistenceService?.persistUserMessageForTurn(input);
|
||||
} catch {
|
||||
// User turn persistence is best-effort on runtime send.
|
||||
}
|
||||
return this.codex.sendTurn(input);
|
||||
}
|
||||
|
||||
@@ -239,6 +270,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
stopSession(raw: ProviderStopSessionInput): void {
|
||||
const input = providerStopSessionInputSchema.parse(raw);
|
||||
this.codex.stopSession(input.sessionId);
|
||||
this.persistenceService?.unbindSession(input.sessionId);
|
||||
this.sessionThreadIds.delete(input.sessionId);
|
||||
this.pendingEventsBySession.delete(input.sessionId);
|
||||
this.sessionCheckpointCwds.delete(input.sessionId);
|
||||
@@ -483,6 +515,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
return;
|
||||
}
|
||||
const snapshot = await this.codex.readThread(event.sessionId);
|
||||
await this.persistCheckpointSummaryForTurn(event, initializedCwd, snapshot.threadId, snapshot.turns);
|
||||
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -504,6 +537,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
await this.persistCheckpointSummaryForTurn(event, checkpointCwd, snapshot.threadId, snapshot.turns);
|
||||
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
|
||||
}).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
|
||||
@@ -639,4 +673,47 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.threadLogStreams.set(threadId, stream);
|
||||
return stream;
|
||||
}
|
||||
|
||||
private async persistCheckpointSummaryForTurn(
|
||||
event: ProviderEvent,
|
||||
cwd: string,
|
||||
runtimeThreadId: string,
|
||||
turns: CodexThreadTurnSnapshot[],
|
||||
): Promise<void> {
|
||||
if (!this.persistenceService) {
|
||||
return;
|
||||
}
|
||||
if (turns.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const toTurnCount = turns.length;
|
||||
const fromTurnCount = Math.max(0, toTurnCount - 1);
|
||||
let diff = "";
|
||||
try {
|
||||
diff = await this.filesystemCheckpointStore.diffCheckpoints({
|
||||
cwd,
|
||||
threadId: runtimeThreadId,
|
||||
fromTurnCount,
|
||||
toTurnCount,
|
||||
});
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
const latestTurn = turns[toTurnCount - 1];
|
||||
const turnId = asString(turn?.id) ?? latestTurn?.id ?? null;
|
||||
const status = asString(turn?.status);
|
||||
this.persistenceService.persistTurnDiffSummaryFromCheckpoint({
|
||||
sessionId: event.sessionId,
|
||||
runtimeThreadId,
|
||||
turnId,
|
||||
checkpointTurnCount: toTurnCount,
|
||||
completedAt: event.createdAt,
|
||||
...(status ? { status } : {}),
|
||||
diff,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { openSqliteDatabase } from "./sqliteAdapter";
|
||||
|
||||
describe("sqliteAdapter", () => {
|
||||
it("opens a database and runs basic statements", () => {
|
||||
const db = openSqliteDatabase(":memory:");
|
||||
db.exec("CREATE TABLE sample (id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT NOT NULL);");
|
||||
|
||||
const insertResult = db.prepare("INSERT INTO sample (value) VALUES (?);").run("hello") as {
|
||||
changes?: number;
|
||||
lastInsertRowid?: number;
|
||||
};
|
||||
expect(insertResult.changes).toBe(1);
|
||||
|
||||
const row = db.prepare("SELECT value FROM sample WHERE id = ?;").get(1) as
|
||||
| { value?: string }
|
||||
| undefined;
|
||||
expect(row?.value).toBe("hello");
|
||||
|
||||
const rows = db.prepare("SELECT value FROM sample ORDER BY id ASC;").all() as Array<{
|
||||
value?: string;
|
||||
}>;
|
||||
expect(rows.map((entry) => entry.value)).toEqual(["hello"]);
|
||||
|
||||
db.close();
|
||||
});
|
||||
|
||||
it("throws a helpful error when node:sqlite is unavailable", () => {
|
||||
const missingModuleError = new Error("No such built-in module: node:sqlite");
|
||||
(missingModuleError as NodeJS.ErrnoException).code = "ERR_UNKNOWN_BUILTIN_MODULE";
|
||||
const requireFn = vi.fn((specifier: string) => {
|
||||
if (specifier === "node:sqlite") {
|
||||
throw missingModuleError;
|
||||
}
|
||||
throw new Error(`Unexpected module request: ${specifier}`);
|
||||
});
|
||||
|
||||
expect(() => openSqliteDatabase(":memory:", requireFn as never, false)).toThrow(
|
||||
"node:sqlite is unavailable",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
|
||||
export interface SqliteStatement {
|
||||
run: (...params: unknown[]) => unknown;
|
||||
get: (...params: unknown[]) => unknown;
|
||||
all: (...params: unknown[]) => unknown[];
|
||||
}
|
||||
|
||||
export interface SqliteDatabase {
|
||||
exec: (sql: string) => void;
|
||||
prepare: (sql: string) => SqliteStatement;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
interface NodeSqliteModule {
|
||||
DatabaseSync: new (filename: string) => {
|
||||
exec: (sql: string) => void;
|
||||
prepare: (sql: string) => SqliteStatement;
|
||||
close: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
interface BunSqliteStatement {
|
||||
run: (...params: unknown[]) => unknown;
|
||||
get: (...params: unknown[]) => unknown;
|
||||
all: (...params: unknown[]) => unknown[];
|
||||
}
|
||||
|
||||
interface BunSqliteModule {
|
||||
Database: new (filename: string) => {
|
||||
exec: (sql: string) => unknown;
|
||||
query: (sql: string) => BunSqliteStatement;
|
||||
close: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
function isNodeSqliteUnavailableError(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) {
|
||||
return false;
|
||||
}
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === "ERR_UNKNOWN_BUILTIN_MODULE" || code === "MODULE_NOT_FOUND") {
|
||||
return true;
|
||||
}
|
||||
return error.message.includes("node:sqlite");
|
||||
}
|
||||
|
||||
function openNodeSqliteDatabase(
|
||||
requireFn: ReturnType<typeof createRequire>,
|
||||
dbPath: string,
|
||||
): SqliteDatabase {
|
||||
let nodeSqlite: NodeSqliteModule;
|
||||
try {
|
||||
nodeSqlite = requireFn("node:sqlite") as NodeSqliteModule;
|
||||
} catch (error) {
|
||||
if (isNodeSqliteUnavailableError(error)) {
|
||||
throw new Error(
|
||||
"node:sqlite is unavailable in this runtime. Use Node.js 22+ (or run the server with Bun).",
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (typeof nodeSqlite.DatabaseSync !== "function") {
|
||||
throw new Error(
|
||||
"node:sqlite was loaded but DatabaseSync is missing. Upgrade Node.js or run the server with Bun.",
|
||||
);
|
||||
}
|
||||
const db = new nodeSqlite.DatabaseSync(dbPath);
|
||||
return {
|
||||
exec: (sql) => {
|
||||
db.exec(sql);
|
||||
},
|
||||
prepare: (sql) => db.prepare(sql),
|
||||
close: () => {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function openBunSqliteDatabase(
|
||||
requireFn: ReturnType<typeof createRequire>,
|
||||
dbPath: string,
|
||||
): SqliteDatabase {
|
||||
const bunSqlite = requireFn("bun:sqlite") as BunSqliteModule;
|
||||
const db = new bunSqlite.Database(dbPath);
|
||||
return {
|
||||
exec: (sql) => {
|
||||
db.exec(sql);
|
||||
},
|
||||
prepare: (sql) => {
|
||||
const statement = db.query(sql);
|
||||
return {
|
||||
run: (...params: unknown[]) => statement.run(...params),
|
||||
get: (...params: unknown[]) => statement.get(...params),
|
||||
all: (...params: unknown[]) => statement.all(...params),
|
||||
};
|
||||
},
|
||||
close: () => {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function openSqliteDatabase(
|
||||
dbPath: string,
|
||||
requireFn: ReturnType<typeof createRequire> = createRequire(
|
||||
path.join(process.cwd(), "t3code-sqlite-adapter.cjs"),
|
||||
),
|
||||
runtimeIsBun = Boolean(process.versions.bun),
|
||||
): SqliteDatabase {
|
||||
if (runtimeIsBun) {
|
||||
// Development mode runs in Bun, so use Bun's SQLite adapter
|
||||
return openBunSqliteDatabase(requireFn, dbPath);
|
||||
}
|
||||
|
||||
return openNodeSqliteDatabase(requireFn, dbPath);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { StateDb } from "./stateDb";
|
||||
import * as sqliteAdapter from "./sqliteAdapter";
|
||||
import { STATE_DB_SCHEMA_VERSION } from "./stateMigrations";
|
||||
import * as stateMigrations from "./stateMigrations";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("StateDb", () => {
|
||||
it("creates the SQLite schema and applies migrations", () => {
|
||||
const tempDir = makeTempDir("t3code-state-db-");
|
||||
const dbPath = path.join(tempDir, "state.sqlite");
|
||||
const stateDb = new StateDb({ dbPath });
|
||||
|
||||
const tables = stateDb.db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table';")
|
||||
.all() as Array<{ name: string }>;
|
||||
const tableNames = new Set(tables.map((table) => table.name));
|
||||
expect(tableNames.has("documents")).toBe(true);
|
||||
expect(tableNames.has("provider_events")).toBe(true);
|
||||
expect(tableNames.has("state_events")).toBe(true);
|
||||
expect(tableNames.has("metadata")).toBe(true);
|
||||
|
||||
const userVersion = stateDb.db
|
||||
.prepare("PRAGMA user_version;")
|
||||
.get() as { user_version: number } | undefined;
|
||||
expect(userVersion?.user_version).toBe(STATE_DB_SCHEMA_VERSION);
|
||||
|
||||
stateDb.close();
|
||||
});
|
||||
|
||||
it("closes the database when migrations fail during construction", () => {
|
||||
const tempDir = makeTempDir("t3code-state-db-migration-fail-");
|
||||
const dbPath = path.join(tempDir, "state.sqlite");
|
||||
const close = vi.fn();
|
||||
const fakeDb = {
|
||||
exec: vi.fn(),
|
||||
prepare: vi.fn(),
|
||||
close,
|
||||
};
|
||||
vi.spyOn(sqliteAdapter, "openSqliteDatabase").mockReturnValue(
|
||||
fakeDb as unknown as sqliteAdapter.SqliteDatabase,
|
||||
);
|
||||
vi.spyOn(stateMigrations, "runStateMigrations").mockImplementation(() => {
|
||||
throw new Error("migration failed");
|
||||
});
|
||||
|
||||
expect(() => new StateDb({ dbPath })).toThrow("migration failed");
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("preserves the original transaction error when rollback fails", () => {
|
||||
const tempDir = makeTempDir("t3code-state-db-rollback-fail-");
|
||||
const dbPath = path.join(tempDir, "state.sqlite");
|
||||
const rollbackError = new Error("rollback failed");
|
||||
const exec = vi.fn((sql: string) => {
|
||||
if (sql === "ROLLBACK;") {
|
||||
throw rollbackError;
|
||||
}
|
||||
});
|
||||
const fakeDb = {
|
||||
exec,
|
||||
prepare: vi.fn(),
|
||||
close: vi.fn(),
|
||||
};
|
||||
vi.spyOn(sqliteAdapter, "openSqliteDatabase").mockReturnValue(
|
||||
fakeDb as unknown as sqliteAdapter.SqliteDatabase,
|
||||
);
|
||||
vi.spyOn(stateMigrations, "runStateMigrations").mockImplementation(() => {});
|
||||
|
||||
const stateDb = new StateDb({ dbPath });
|
||||
const originalError = new Error("operation failed");
|
||||
|
||||
let thrown: unknown;
|
||||
try {
|
||||
stateDb.transaction(() => {
|
||||
throw originalError;
|
||||
});
|
||||
} catch (error) {
|
||||
thrown = error;
|
||||
}
|
||||
|
||||
expect(thrown).toBe(originalError);
|
||||
expect(exec).toHaveBeenCalledWith("ROLLBACK;");
|
||||
stateDb.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { openSqliteDatabase, type SqliteDatabase } from "./sqliteAdapter";
|
||||
import { runStateMigrations } from "./stateMigrations";
|
||||
|
||||
export interface StateDbOptions {
|
||||
dbPath: string;
|
||||
}
|
||||
|
||||
export class StateDb {
|
||||
readonly dbPath: string;
|
||||
readonly db: SqliteDatabase;
|
||||
|
||||
constructor(options: StateDbOptions) {
|
||||
this.dbPath = path.resolve(options.dbPath);
|
||||
fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
|
||||
this.db = openSqliteDatabase(this.dbPath);
|
||||
try {
|
||||
runStateMigrations(this.db);
|
||||
} catch (error) {
|
||||
try {
|
||||
this.db.close();
|
||||
} catch {
|
||||
// Best effort close on failed initialization.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
|
||||
transaction<T>(fn: () => T): T {
|
||||
this.db.exec("BEGIN IMMEDIATE;");
|
||||
try {
|
||||
const result = fn();
|
||||
this.db.exec("COMMIT;");
|
||||
return result;
|
||||
} catch (error) {
|
||||
try {
|
||||
this.db.exec("ROLLBACK;");
|
||||
} catch {
|
||||
// Preserve the original transactional failure.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { SqliteDatabase } from "./sqliteAdapter";
|
||||
|
||||
export const STATE_DB_SCHEMA_VERSION = 1;
|
||||
|
||||
export function applyStateDbPragmas(db: SqliteDatabase): void {
|
||||
db.exec("PRAGMA journal_mode=WAL;");
|
||||
db.exec("PRAGMA synchronous=FULL;");
|
||||
db.exec("PRAGMA busy_timeout=5000;");
|
||||
db.exec("PRAGMA foreign_keys=ON;");
|
||||
}
|
||||
|
||||
function readUserVersion(db: SqliteDatabase): number {
|
||||
const row = db.prepare("PRAGMA user_version;").get() as { user_version?: number } | undefined;
|
||||
const value = row?.user_version;
|
||||
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
|
||||
return 0;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function migrationV1(db: SqliteDatabase): void {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS documents (
|
||||
id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
project_id TEXT NULL,
|
||||
thread_id TEXT NULL,
|
||||
sort_key INTEGER NULL,
|
||||
schema_version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
data_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS provider_events (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
id TEXT NOT NULL UNIQUE,
|
||||
session_id TEXT NOT NULL,
|
||||
provider TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
method TEXT NOT NULL,
|
||||
thread_id TEXT NULL,
|
||||
turn_id TEXT NULL,
|
||||
item_id TEXT NULL,
|
||||
request_id TEXT NULL,
|
||||
request_kind TEXT NULL,
|
||||
text_delta TEXT NULL,
|
||||
message TEXT NULL,
|
||||
payload_json TEXT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS state_events (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
event_type TEXT NOT NULL,
|
||||
entity_id TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS metadata (
|
||||
key TEXT PRIMARY KEY,
|
||||
value_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_kind ON documents(kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_project_kind ON documents(project_id, kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_thread_kind_sort ON documents(thread_id, kind, sort_key);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_kind_updated ON documents(kind, updated_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_events_session_seq ON provider_events(session_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_events_thread_seq ON provider_events(thread_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS idx_state_events_seq ON state_events(seq);
|
||||
`);
|
||||
}
|
||||
|
||||
export function runStateMigrations(db: SqliteDatabase): void {
|
||||
applyStateDbPragmas(db);
|
||||
|
||||
const userVersion = readUserVersion(db);
|
||||
if (userVersion >= STATE_DB_SCHEMA_VERSION) {
|
||||
return;
|
||||
}
|
||||
|
||||
db.exec("BEGIN IMMEDIATE;");
|
||||
try {
|
||||
if (userVersion < 1) {
|
||||
migrationV1(db);
|
||||
}
|
||||
db.exec(`PRAGMA user_version=${STATE_DB_SCHEMA_VERSION};`);
|
||||
db.exec("COMMIT;");
|
||||
} catch (error) {
|
||||
db.exec("ROLLBACK;");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,10 @@ import {
|
||||
WS_METHODS,
|
||||
type KeybindingsConfig,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type StateEvent,
|
||||
type WsPush,
|
||||
type WsResponse,
|
||||
} from "@t3tools/contracts";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { compileResolvedKeybindingRule, DEFAULT_KEYBINDINGS } from "./keybindings";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
@@ -28,6 +28,8 @@ import type {
|
||||
TerminalWriteInput,
|
||||
} from "@t3tools/contracts";
|
||||
import type { TerminalManager } from "./terminalManager";
|
||||
import { PersistenceService } from "./persistenceService";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
|
||||
interface PendingMessages {
|
||||
queue: unknown[];
|
||||
@@ -207,6 +209,15 @@ function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsCon
|
||||
return resolved;
|
||||
}
|
||||
|
||||
async function waitForPush(ws: WebSocket, channel: string): Promise<WsPush> {
|
||||
while (true) {
|
||||
const message = (await waitForMessage(ws)) as WsPush;
|
||||
if (message.type === "push" && message.channel === channel) {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
|
||||
|
||||
function mergeWithDefaultsForTest(custom: KeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
@@ -225,6 +236,7 @@ describe("WebSocket Server", () => {
|
||||
let server: ReturnType<typeof createServer> | null = null;
|
||||
const connections: WebSocket[] = [];
|
||||
const tempDirs: string[] = [];
|
||||
const injectedPersistenceServices: PersistenceService[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
@@ -243,15 +255,23 @@ describe("WebSocket Server", () => {
|
||||
runStackedAction: (input: { cwd: string; action: string }) => Promise<unknown>;
|
||||
};
|
||||
terminalManager?: TerminalManager;
|
||||
persistenceService?: PersistenceService;
|
||||
} = {},
|
||||
): ReturnType<typeof createServer> {
|
||||
const stateDir = options.stateDir ?? makeTempDir("t3code-ws-state-");
|
||||
const persistenceService =
|
||||
options.persistenceService ??
|
||||
new PersistenceService({
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
|
||||
});
|
||||
injectedPersistenceServices.push(persistenceService);
|
||||
return createServer({
|
||||
port: 0,
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
...(options.devUrl ? { devUrl: options.devUrl } : {}),
|
||||
...(options.authToken ? { authToken: options.authToken } : {}),
|
||||
projectRegistry: new ProjectRegistry(stateDir),
|
||||
persistenceService,
|
||||
...(options.gitManager ? { gitManager: options.gitManager as never } : {}),
|
||||
...(options.terminalManager ? { terminalManager: options.terminalManager } : {}),
|
||||
});
|
||||
@@ -266,6 +286,9 @@ describe("WebSocket Server", () => {
|
||||
await server.stop();
|
||||
}
|
||||
server = null;
|
||||
for (const service of injectedPersistenceServices.splice(0, injectedPersistenceServices.length)) {
|
||||
service.close();
|
||||
}
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -646,6 +669,135 @@ describe("WebSocket Server", () => {
|
||||
expect(response.result).toEqual([]);
|
||||
});
|
||||
|
||||
it("persists app settings through appSettings RPC methods", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-app-settings-");
|
||||
server = createTestServer({ cwd: "/test", stateDir });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const initial = await sendRequest(ws, WS_METHODS.appSettingsGet);
|
||||
expect(initial.error).toBeUndefined();
|
||||
expect(initial.result).toEqual({
|
||||
codexBinaryPath: "",
|
||||
codexHomePath: "",
|
||||
});
|
||||
|
||||
const updated = await sendRequest(ws, WS_METHODS.appSettingsUpdate, {
|
||||
codexBinaryPath: " /opt/codex/bin/codex ",
|
||||
codexHomePath: " /Users/theo/.codex ",
|
||||
});
|
||||
expect(updated.error).toBeUndefined();
|
||||
expect(updated.result).toEqual({
|
||||
codexBinaryPath: "/opt/codex/bin/codex",
|
||||
codexHomePath: "/Users/theo/.codex",
|
||||
});
|
||||
|
||||
const roundTrip = await sendRequest(ws, WS_METHODS.appSettingsGet);
|
||||
expect(roundTrip.error).toBeUndefined();
|
||||
expect(roundTrip.result).toEqual({
|
||||
codexBinaryPath: "/opt/codex/bin/codex",
|
||||
codexHomePath: "/Users/theo/.codex",
|
||||
});
|
||||
});
|
||||
|
||||
it("supports state bootstrap and ordered catch-up events", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-state-bootstrap-");
|
||||
const projectCwd = makeTempDir("t3code-ws-state-project-");
|
||||
server = createTestServer({ cwd: "/test", stateDir });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const addedProject = await sendRequest(ws, WS_METHODS.projectsAdd, { cwd: projectCwd });
|
||||
expect(addedProject.error).toBeUndefined();
|
||||
const projectId = (addedProject.result as { project: { id: string } }).project.id;
|
||||
|
||||
const createdThread = await sendRequest(ws, WS_METHODS.threadsCreate, {
|
||||
projectId,
|
||||
title: "My Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
});
|
||||
expect(createdThread.error).toBeUndefined();
|
||||
const threadId = (createdThread.result as { thread: { id: string } }).thread.id;
|
||||
|
||||
const updatedThread = await sendRequest(ws, WS_METHODS.threadsUpdateTitle, {
|
||||
threadId,
|
||||
title: "Updated Thread Title",
|
||||
});
|
||||
expect(updatedThread.error).toBeUndefined();
|
||||
|
||||
const bootstrap = await sendRequest(ws, WS_METHODS.stateBootstrap);
|
||||
expect(bootstrap.error).toBeUndefined();
|
||||
const snapshot = bootstrap.result as {
|
||||
projects: Array<{ id: string }>;
|
||||
threads: Array<{ id: string; title: string }>;
|
||||
lastStateSeq: number;
|
||||
};
|
||||
expect(snapshot.projects).toHaveLength(1);
|
||||
expect(snapshot.threads).toHaveLength(1);
|
||||
expect(snapshot.threads[0]?.title).toBe("Updated Thread Title");
|
||||
expect(snapshot.lastStateSeq).toBeGreaterThan(0);
|
||||
|
||||
const catchUp = await sendRequest(ws, WS_METHODS.stateCatchUp, { afterSeq: 0 });
|
||||
expect(catchUp.error).toBeUndefined();
|
||||
const events = (catchUp.result as { events: StateEvent[] }).events;
|
||||
expect(events.length).toBeGreaterThanOrEqual(3);
|
||||
for (let index = 1; index < events.length; index += 1) {
|
||||
const previous = events[index - 1];
|
||||
const current = events[index];
|
||||
expect(previous).toBeDefined();
|
||||
expect(current).toBeDefined();
|
||||
if (!previous || !current) continue;
|
||||
expect(current.seq).toBeGreaterThan(previous.seq);
|
||||
}
|
||||
expect(events.some((event) => event.eventType === "project.upsert")).toBe(true);
|
||||
expect(events.some((event) => event.eventType === "thread.upsert")).toBe(true);
|
||||
});
|
||||
|
||||
it("broadcasts ordered state.event pushes", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-state-events-");
|
||||
const projectCwd = makeTempDir("t3code-ws-state-events-project-");
|
||||
server = createTestServer({ cwd: "/test", stateDir });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const writerWs = await connectWs(port);
|
||||
connections.push(writerWs);
|
||||
await waitForMessage(writerWs);
|
||||
|
||||
const observerWs = await connectWs(port);
|
||||
connections.push(observerWs);
|
||||
await waitForMessage(observerWs);
|
||||
|
||||
const addedProject = await sendRequest(writerWs, WS_METHODS.projectsAdd, { cwd: projectCwd });
|
||||
expect(addedProject.error).toBeUndefined();
|
||||
const firstStatePush = await waitForPush(observerWs, WS_CHANNELS.stateEvent);
|
||||
const firstEvent = firstStatePush.data as StateEvent;
|
||||
expect(firstEvent.eventType).toBe("project.upsert");
|
||||
|
||||
const projectId = (addedProject.result as { project: { id: string } }).project.id;
|
||||
const createdThread = await sendRequest(writerWs, WS_METHODS.threadsCreate, {
|
||||
projectId,
|
||||
title: "State Event Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
});
|
||||
expect(createdThread.error).toBeUndefined();
|
||||
const secondStatePush = await waitForPush(observerWs, WS_CHANNELS.stateEvent);
|
||||
const secondEvent = secondStatePush.data as StateEvent;
|
||||
expect(secondEvent.eventType).toBe("thread.upsert");
|
||||
expect(secondEvent.seq).toBeGreaterThan(firstEvent.seq);
|
||||
});
|
||||
|
||||
it("returns unknown-session errors for checkpoint RPCs without an active provider session", async () => {
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
await server.start();
|
||||
@@ -678,6 +830,91 @@ describe("WebSocket Server", () => {
|
||||
expect(diffResponse.error?.message).toContain("Unknown provider session");
|
||||
});
|
||||
|
||||
it("returns provider revert results even if checkpoint revert persistence fails", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-revert-failure-state-");
|
||||
const persistenceService = new PersistenceService({
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
|
||||
});
|
||||
|
||||
const revertResult = {
|
||||
threadId: "runtime-thread-1",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
rolledBackTurns: 1,
|
||||
checkpoints: [
|
||||
{
|
||||
id: "root",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
label: "Start of conversation",
|
||||
isCurrent: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
vi.spyOn(ProviderManager.prototype, "revertToCheckpoint").mockResolvedValue(revertResult);
|
||||
vi.spyOn(persistenceService, "applyCheckpointRevert").mockImplementation(() => {
|
||||
throw new Error("persistence write failed");
|
||||
});
|
||||
|
||||
server = createTestServer({ cwd: "/test", stateDir, persistenceService });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.providersRevertToCheckpoint, {
|
||||
sessionId: "sess-1",
|
||||
turnCount: 0,
|
||||
});
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual(revertResult);
|
||||
});
|
||||
|
||||
it("rejects threads.update and keeps threads.updateTerminalState as the canonical route", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-threads-update-state-");
|
||||
const projectCwd = makeTempDir("t3code-ws-threads-update-project-");
|
||||
server = createTestServer({ cwd: "/test", stateDir });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const addedProject = await sendRequest(ws, WS_METHODS.projectsAdd, { cwd: projectCwd });
|
||||
expect(addedProject.error).toBeUndefined();
|
||||
const projectId = (addedProject.result as { project: { id: string } }).project.id;
|
||||
|
||||
const createdThread = await sendRequest(ws, WS_METHODS.threadsCreate, {
|
||||
projectId,
|
||||
title: "Thread Terminal State",
|
||||
model: "gpt-5.3-codex",
|
||||
});
|
||||
expect(createdThread.error).toBeUndefined();
|
||||
const threadId = (createdThread.result as { thread: { id: string } }).thread.id;
|
||||
|
||||
const deprecatedResponse = await sendRequest(ws, "threads.update", {
|
||||
threadId,
|
||||
terminalOpen: true,
|
||||
});
|
||||
expect(deprecatedResponse.result).toBeUndefined();
|
||||
expect(deprecatedResponse.error?.message).toContain('"threads.update" is unsupported');
|
||||
|
||||
const canonicalResponse = await sendRequest(ws, WS_METHODS.threadsUpdateTerminalState, {
|
||||
threadId,
|
||||
terminalOpen: true,
|
||||
});
|
||||
expect(canonicalResponse.error).toBeUndefined();
|
||||
expect((canonicalResponse.result as { thread: { terminalOpen: boolean } }).thread.terminalOpen).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("routes terminal RPC methods and broadcasts terminal events", async () => {
|
||||
const cwd = makeTempDir("t3code-ws-terminal-cwd-");
|
||||
const terminalManager = new MockTerminalManager();
|
||||
@@ -766,6 +1003,43 @@ describe("WebSocket Server", () => {
|
||||
expect(terminalManager.listenerCount("event")).toBe(0);
|
||||
});
|
||||
|
||||
it("does not close an injected persistence service on stop", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-injected-persistence-state-");
|
||||
const persistenceService = new PersistenceService({
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
|
||||
});
|
||||
const closeSpy = vi.spyOn(persistenceService, "close");
|
||||
server = createServer({
|
||||
port: 0,
|
||||
cwd: "/test",
|
||||
persistenceService,
|
||||
});
|
||||
|
||||
await server.start();
|
||||
await server.stop();
|
||||
server = null;
|
||||
|
||||
expect(closeSpy).not.toHaveBeenCalled();
|
||||
persistenceService.close();
|
||||
});
|
||||
|
||||
it("closes internally owned persistence service on stop", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-internal-persistence-state-");
|
||||
const closeSpy = vi.spyOn(PersistenceService.prototype, "close");
|
||||
server = createServer({
|
||||
port: 0,
|
||||
cwd: "/test",
|
||||
stateDbPath: path.join(stateDir, "state.sqlite"),
|
||||
});
|
||||
|
||||
await server.start();
|
||||
await server.stop();
|
||||
server = null;
|
||||
|
||||
expect(closeSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("returns validation errors for invalid terminal open params", async () => {
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
await server.start();
|
||||
|
||||
+131
-197
@@ -3,11 +3,9 @@ import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import type { Duplex } from "node:stream";
|
||||
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
EDITORS,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
@@ -20,7 +18,6 @@ import {
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
import { GitManager } from "./gitManager";
|
||||
import {
|
||||
@@ -35,7 +32,7 @@ import {
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
import { CoreRuntime } from "./coreRuntime";
|
||||
import { PersistenceService } from "./persistenceService";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -59,8 +56,8 @@ export interface ServerOptions {
|
||||
staticDir?: string | undefined;
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
projectRegistry?: ProjectRegistry | undefined;
|
||||
stateDir?: string | undefined;
|
||||
persistenceService?: PersistenceService | undefined;
|
||||
stateDbPath?: string | undefined;
|
||||
gitManager?: GitManager | undefined;
|
||||
terminalManager?: TerminalManager | undefined;
|
||||
authToken?: string | undefined;
|
||||
@@ -82,23 +79,23 @@ export function createServer(options: ServerOptions) {
|
||||
staticDir,
|
||||
devUrl,
|
||||
logWebSocketEvents: explicitLogWsEvents,
|
||||
projectRegistry: providedRegistry,
|
||||
stateDir,
|
||||
persistenceService: providedPersistenceService,
|
||||
stateDbPath,
|
||||
gitManager: providedGitManager,
|
||||
terminalManager: providedTerminalManager,
|
||||
authToken,
|
||||
} = options;
|
||||
const providerManager = new ProviderManager();
|
||||
const persistenceService =
|
||||
providedPersistenceService ??
|
||||
new PersistenceService({
|
||||
dbPath: stateDbPath ?? path.join(os.homedir(), ".t3", "state.sqlite"),
|
||||
});
|
||||
const ownsPersistenceService = providedPersistenceService === undefined;
|
||||
const providerManager = new ProviderManager({ persistenceService });
|
||||
const terminalManager = providedTerminalManager ?? new TerminalManager();
|
||||
const projectRegistry =
|
||||
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
|
||||
const gitManager = providedGitManager ?? new GitManager();
|
||||
const runtimeStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
|
||||
const coreRuntime = new CoreRuntime(runtimeStateDir);
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
const segments = cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
const logWebSocketEvents =
|
||||
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
|
||||
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
|
||||
@@ -112,7 +109,13 @@ export function createServer(options: ServerOptions) {
|
||||
});
|
||||
}
|
||||
|
||||
function broadcastPush(push: WsPush): void {
|
||||
// Forward provider events to all connected WebSocket clients
|
||||
providerManager.on("event", (event) => {
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.providerEvent,
|
||||
data: event,
|
||||
};
|
||||
const message = JSON.stringify(push);
|
||||
let recipients = 0;
|
||||
for (const client of clients) {
|
||||
@@ -122,31 +125,43 @@ export function createServer(options: ServerOptions) {
|
||||
}
|
||||
}
|
||||
logOutgoingPush(push, recipients);
|
||||
}
|
||||
});
|
||||
|
||||
const onStateEvent = (event: unknown) => {
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.stateEvent,
|
||||
data: event,
|
||||
};
|
||||
const message = JSON.stringify(push);
|
||||
let recipients = 0;
|
||||
for (const client of clients) {
|
||||
if (client.readyState === client.OPEN) {
|
||||
client.send(message);
|
||||
recipients += 1;
|
||||
}
|
||||
}
|
||||
logOutgoingPush(push, recipients);
|
||||
};
|
||||
persistenceService.on("stateEvent", onStateEvent);
|
||||
|
||||
const onTerminalEvent = (event: TerminalEvent) => {
|
||||
broadcastPush({
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.terminalEvent,
|
||||
data: event,
|
||||
});
|
||||
if (event.type === "activity" || event.type === "exited" || event.type === "error") {
|
||||
void coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.setTerminalActivity",
|
||||
issuedAt: event.createdAt,
|
||||
payload: {
|
||||
threadId: event.threadId,
|
||||
terminalId: event.terminalId,
|
||||
running: event.type === "activity" ? event.hasRunningSubprocess : false,
|
||||
},
|
||||
});
|
||||
};
|
||||
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);
|
||||
};
|
||||
terminalManager.on("event", onTerminalEvent);
|
||||
coreRuntime.bindProviderEvents(providerManager);
|
||||
let stateStreamStopped = false;
|
||||
let stateStreamTask: Promise<void> | null = null;
|
||||
|
||||
// HTTP server — serves static files or redirects to Vite dev server
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
@@ -244,6 +259,10 @@ export function createServer(options: ServerOptions) {
|
||||
wss.on("connection", (ws) => {
|
||||
clients.add(ws);
|
||||
|
||||
// Send welcome message with project info
|
||||
const segments = cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
const welcome: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
@@ -294,48 +313,12 @@ export function createServer(options: ServerOptions) {
|
||||
}
|
||||
|
||||
async function routeRequest(request: WsRequest): Promise<unknown> {
|
||||
const requestNow = new Date().toISOString();
|
||||
const paramsObj = (request.params ?? {}) as Record<string, unknown>;
|
||||
const state = await coreRuntime.state();
|
||||
const findThreadBySessionId = (sessionId: string | undefined) =>
|
||||
sessionId
|
||||
? state.threads.find((thread) => thread.session?.sessionId === sessionId)
|
||||
: undefined;
|
||||
|
||||
switch (request.method) {
|
||||
case WS_METHODS.providersStartSession: {
|
||||
const session = await providerManager.startSession(request.params as never);
|
||||
const uiThreadId =
|
||||
typeof paramsObj.uiThreadId === "string" ? paramsObj.uiThreadId : undefined;
|
||||
if (uiThreadId) {
|
||||
await coreRuntime.bindProviderSession(uiThreadId, session);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
case WS_METHODS.providersStartSession:
|
||||
return providerManager.startSession(request.params as never);
|
||||
|
||||
case WS_METHODS.providersSendTurn: {
|
||||
const sessionId = typeof paramsObj.sessionId === "string" ? paramsObj.sessionId : undefined;
|
||||
const uiThreadId =
|
||||
typeof paramsObj.uiThreadId === "string" ? paramsObj.uiThreadId : undefined;
|
||||
const targetThread = uiThreadId
|
||||
? state.threads.find((thread) => thread.id === uiThreadId)
|
||||
: findThreadBySessionId(sessionId);
|
||||
const inputText = typeof paramsObj.input === "string" ? paramsObj.input : undefined;
|
||||
if (targetThread && inputText && inputText.trim().length > 0) {
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.addUserMessage",
|
||||
issuedAt: requestNow,
|
||||
payload: {
|
||||
threadId: targetThread.id,
|
||||
messageId: crypto.randomUUID(),
|
||||
text: inputText,
|
||||
createdAt: requestNow,
|
||||
},
|
||||
});
|
||||
}
|
||||
case WS_METHODS.providersSendTurn:
|
||||
return providerManager.sendTurn(request.params as never);
|
||||
}
|
||||
|
||||
case WS_METHODS.providersInterruptTurn:
|
||||
return providerManager.interruptTurn(request.params as never);
|
||||
@@ -344,12 +327,7 @@ export function createServer(options: ServerOptions) {
|
||||
return providerManager.respondToRequest(request.params as never);
|
||||
|
||||
case WS_METHODS.providersStopSession: {
|
||||
const sessionId = typeof paramsObj.sessionId === "string" ? paramsObj.sessionId : undefined;
|
||||
const boundThread = findThreadBySessionId(sessionId);
|
||||
providerManager.stopSession(request.params as never);
|
||||
if (boundThread) {
|
||||
await coreRuntime.clearProviderSession(boundThread.id);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -363,54 +341,85 @@ export function createServer(options: ServerOptions) {
|
||||
return providerManager.getCheckpointDiff(request.params as never);
|
||||
|
||||
case WS_METHODS.providersRevertToCheckpoint:
|
||||
return providerManager.revertToCheckpoint(request.params as never);
|
||||
{
|
||||
const params = request.params as {
|
||||
sessionId: string;
|
||||
turnCount: number;
|
||||
};
|
||||
const result = await providerManager.revertToCheckpoint(params as never);
|
||||
try {
|
||||
persistenceService.applyCheckpointRevert({
|
||||
sessionId: params.sessionId,
|
||||
runtimeThreadId: result.threadId,
|
||||
turnCount: result.turnCount,
|
||||
messageCount: result.messageCount,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn("failed to persist checkpoint revert", {
|
||||
sessionId: params.sessionId,
|
||||
turnCount: params.turnCount,
|
||||
error,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
case WS_METHODS.stateBootstrap:
|
||||
return persistenceService.loadSnapshot();
|
||||
|
||||
case WS_METHODS.stateListMessages:
|
||||
return persistenceService.listMessages(request.params as never);
|
||||
|
||||
case WS_METHODS.stateCatchUp:
|
||||
return persistenceService.catchUp(request.params as never);
|
||||
|
||||
case WS_METHODS.appSettingsGet:
|
||||
return persistenceService.getAppSettings();
|
||||
|
||||
case WS_METHODS.appSettingsUpdate:
|
||||
return persistenceService.updateAppSettings((request.params ?? {}) as never);
|
||||
|
||||
case WS_METHODS.threadsCreate:
|
||||
return persistenceService.createThread(request.params as never);
|
||||
|
||||
case "threads.update":
|
||||
throw new Error(
|
||||
`"threads.update" is unsupported; use ${WS_METHODS.threadsUpdateTerminalState}`,
|
||||
);
|
||||
|
||||
case WS_METHODS.threadsUpdateTerminalState:
|
||||
return persistenceService.updateThreadTerminalState(request.params as never);
|
||||
|
||||
case WS_METHODS.threadsDelete:
|
||||
persistenceService.deleteThread(request.params as never);
|
||||
return undefined;
|
||||
|
||||
case WS_METHODS.threadsMarkVisited:
|
||||
return persistenceService.markThreadVisited(request.params as never);
|
||||
|
||||
case WS_METHODS.threadsUpdateModel:
|
||||
return persistenceService.updateThreadModel(request.params as never);
|
||||
|
||||
case WS_METHODS.threadsUpdateTitle:
|
||||
return persistenceService.updateThreadTitle(request.params as never);
|
||||
|
||||
case WS_METHODS.threadsUpdateBranch:
|
||||
return persistenceService.updateThreadBranch(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsList:
|
||||
return projectRegistry.list();
|
||||
return persistenceService.listProjects();
|
||||
|
||||
case WS_METHODS.projectsAdd: {
|
||||
const result = projectRegistry.add(request.params as never);
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "project.add",
|
||||
issuedAt: requestNow,
|
||||
payload: {
|
||||
id: result.project.id,
|
||||
name: result.project.name,
|
||||
cwd: result.project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
scripts: result.project.scripts,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
}
|
||||
case WS_METHODS.projectsAdd:
|
||||
return persistenceService.addProject(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsRemove: {
|
||||
const projectId = typeof paramsObj.id === "string" ? paramsObj.id : undefined;
|
||||
if (projectId) {
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "project.remove",
|
||||
issuedAt: requestNow,
|
||||
payload: { id: projectId },
|
||||
});
|
||||
}
|
||||
projectRegistry.remove(request.params as never);
|
||||
case WS_METHODS.projectsRemove:
|
||||
persistenceService.removeProject(request.params as never);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
case WS_METHODS.projectsSearchEntries:
|
||||
return searchWorkspaceEntries(request.params as never);
|
||||
case WS_METHODS.projectsUpdateScripts: {
|
||||
const result = projectRegistry.updateScripts(request.params as never);
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "project.updateScripts",
|
||||
issuedAt: requestNow,
|
||||
payload: { id: result.project.id, scripts: result.project.scripts },
|
||||
});
|
||||
return result;
|
||||
}
|
||||
case WS_METHODS.projectsUpdateScripts:
|
||||
return persistenceService.updateProjectScripts(request.params as never);
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const params = request.params as {
|
||||
@@ -516,61 +525,6 @@ export function createServer(options: ServerOptions) {
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
case WS_METHODS.stateGetSnapshot:
|
||||
return coreRuntime.state();
|
||||
|
||||
case WS_METHODS.stateCreateThread: {
|
||||
const params = request.params as {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
};
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.create",
|
||||
issuedAt: requestNow,
|
||||
payload: params,
|
||||
});
|
||||
return coreRuntime.state();
|
||||
}
|
||||
|
||||
case WS_METHODS.stateDeleteThread: {
|
||||
const params = request.params as { id: string };
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.delete",
|
||||
issuedAt: requestNow,
|
||||
payload: params,
|
||||
});
|
||||
return coreRuntime.state();
|
||||
}
|
||||
|
||||
case WS_METHODS.stateMarkThreadVisited: {
|
||||
const params = request.params as { threadId: string; visitedAt?: string };
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.markVisited",
|
||||
issuedAt: requestNow,
|
||||
payload: { threadId: params.threadId, visitedAt: params.visitedAt ?? requestNow },
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
case WS_METHODS.stateSetRuntimeMode: {
|
||||
const params = request.params as { mode: "approval-required" | "full-access" };
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "runtime.setMode",
|
||||
issuedAt: requestNow,
|
||||
payload: { mode: params.mode },
|
||||
});
|
||||
return coreRuntime.state();
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown method: ${request.method}`);
|
||||
}
|
||||
@@ -585,26 +539,7 @@ export function createServer(options: ServerOptions) {
|
||||
httpServer.once("error", onError);
|
||||
const onListening = () => {
|
||||
httpServer.off("error", onError);
|
||||
void (async () => {
|
||||
try {
|
||||
await coreRuntime.start(cwd, projectName);
|
||||
stateStreamStopped = false;
|
||||
stateStreamTask = (async () => {
|
||||
const iterable = await coreRuntime.subscribe();
|
||||
for await (const update of iterable) {
|
||||
if (stateStreamStopped) break;
|
||||
broadcastPush({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.stateUpdated,
|
||||
data: update.state,
|
||||
});
|
||||
}
|
||||
})();
|
||||
resolve();
|
||||
} catch (error) {
|
||||
reject(error as Error);
|
||||
}
|
||||
})();
|
||||
resolve();
|
||||
};
|
||||
if (host) {
|
||||
httpServer.listen(port, host, onListening);
|
||||
@@ -615,11 +550,14 @@ export function createServer(options: ServerOptions) {
|
||||
}
|
||||
|
||||
async function stop(): Promise<void> {
|
||||
stateStreamStopped = true;
|
||||
terminalManager.off("event", onTerminalEvent);
|
||||
persistenceService.off("stateEvent", onStateEvent);
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
terminalManager.dispose();
|
||||
if (ownsPersistenceService) {
|
||||
persistenceService.close();
|
||||
}
|
||||
|
||||
for (const client of clients) {
|
||||
client.close();
|
||||
@@ -655,10 +593,6 @@ export function createServer(options: ServerOptions) {
|
||||
});
|
||||
});
|
||||
|
||||
if (stateStreamTask) {
|
||||
await Promise.race([stateStreamTask, Promise.resolve()]);
|
||||
}
|
||||
await coreRuntime.stop();
|
||||
await Promise.all([closeWebSocketServer, closeHttpServer]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const LOCAL_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:local:v1";
|
||||
const LEGACY_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
|
||||
type StorageMap = Map<string, string>;
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
reject: (error?: unknown) => void;
|
||||
}
|
||||
|
||||
function createDeferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error?: unknown) => void;
|
||||
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
|
||||
resolve = resolvePromise;
|
||||
reject = rejectPromise;
|
||||
});
|
||||
return {
|
||||
promise,
|
||||
resolve,
|
||||
reject,
|
||||
};
|
||||
}
|
||||
|
||||
async function flushMicrotasks(times = 3): Promise<void> {
|
||||
if (times <= 0) return;
|
||||
await Promise.resolve();
|
||||
await flushMicrotasks(times - 1);
|
||||
}
|
||||
|
||||
function installWindowMock(initialStorage?: StorageMap): StorageMap {
|
||||
const storage = initialStorage ?? new Map<string, string>();
|
||||
|
||||
const localStorageMock = {
|
||||
length: 0,
|
||||
clear: () => {
|
||||
storage.clear();
|
||||
localStorageMock.length = 0;
|
||||
},
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
key: (index: number) => Array.from(storage.keys())[index] ?? null,
|
||||
removeItem: (key: string) => {
|
||||
storage.delete(key);
|
||||
localStorageMock.length = storage.size;
|
||||
},
|
||||
setItem: (key: string, value: string) => {
|
||||
storage.set(key, value);
|
||||
localStorageMock.length = storage.size;
|
||||
},
|
||||
};
|
||||
|
||||
localStorageMock.length = storage.size;
|
||||
|
||||
const windowMock = {
|
||||
localStorage: localStorageMock as Storage,
|
||||
addEventListener: () => undefined,
|
||||
removeEventListener: () => undefined,
|
||||
};
|
||||
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: windowMock,
|
||||
});
|
||||
|
||||
return storage;
|
||||
}
|
||||
|
||||
describe("appSettings", () => {
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
Reflect.deleteProperty(globalThis, "window");
|
||||
});
|
||||
|
||||
it("returns a stable snapshot reference when settings have not changed", async () => {
|
||||
installWindowMock();
|
||||
const module = await import("./appSettings");
|
||||
|
||||
const first = module.getAppSettingsSnapshot();
|
||||
const second = module.getAppSettingsSnapshot();
|
||||
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
|
||||
it("returns a new snapshot reference when local settings change", async () => {
|
||||
const storage = installWindowMock();
|
||||
const module = await import("./appSettings");
|
||||
|
||||
const first = module.getAppSettingsSnapshot();
|
||||
storage.set(LOCAL_APP_SETTINGS_STORAGE_KEY, JSON.stringify({ confirmThreadDelete: false }));
|
||||
const second = module.getAppSettingsSnapshot();
|
||||
|
||||
expect(second).not.toBe(first);
|
||||
expect(second.confirmThreadDelete).toBe(false);
|
||||
});
|
||||
|
||||
it("prevents hydration from overwriting optimistic backend writes", async () => {
|
||||
installWindowMock();
|
||||
const getDeferred = createDeferred<{ codexBinaryPath: string; codexHomePath: string }>();
|
||||
const updateDeferred = createDeferred<{ codexBinaryPath: string; codexHomePath: string }>();
|
||||
const get = vi.fn(() => getDeferred.promise);
|
||||
const update = vi.fn(() => updateDeferred.promise);
|
||||
window.nativeApi = {
|
||||
appSettings: {
|
||||
get,
|
||||
update,
|
||||
},
|
||||
} as unknown as NonNullable<Window["nativeApi"]>;
|
||||
|
||||
const module = await import("./appSettings");
|
||||
const hydration = module.ensureAppSettingsHydrated();
|
||||
module.updateAppSettings({ codexBinaryPath: "/opt/codex/new" });
|
||||
|
||||
getDeferred.resolve({ codexBinaryPath: "/opt/codex/stale", codexHomePath: "" });
|
||||
await hydration;
|
||||
|
||||
expect(module.getAppSettingsSnapshot().codexBinaryPath).toBe("/opt/codex/new");
|
||||
expect(update).toHaveBeenCalledTimes(1);
|
||||
|
||||
updateDeferred.resolve({ codexBinaryPath: "/opt/codex/new", codexHomePath: "" });
|
||||
await flushMicrotasks();
|
||||
expect(module.getAppSettingsSnapshot().codexBinaryPath).toBe("/opt/codex/new");
|
||||
});
|
||||
|
||||
it("prevents hydration from overwriting optimistic local writes", async () => {
|
||||
const storage = installWindowMock(
|
||||
new Map([
|
||||
[
|
||||
LEGACY_APP_SETTINGS_STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
confirmThreadDelete: true,
|
||||
}),
|
||||
],
|
||||
]),
|
||||
);
|
||||
const getDeferred = createDeferred<{ codexBinaryPath: string; codexHomePath: string }>();
|
||||
const get = vi.fn(() => getDeferred.promise);
|
||||
window.nativeApi = {
|
||||
appSettings: {
|
||||
get,
|
||||
update: vi.fn(async () => ({ codexBinaryPath: "", codexHomePath: "" })),
|
||||
},
|
||||
} as unknown as NonNullable<Window["nativeApi"]>;
|
||||
|
||||
const module = await import("./appSettings");
|
||||
const hydration = module.ensureAppSettingsHydrated();
|
||||
module.updateAppSettings({ confirmThreadDelete: false });
|
||||
|
||||
getDeferred.resolve({ codexBinaryPath: "", codexHomePath: "" });
|
||||
await hydration;
|
||||
|
||||
expect(module.getAppSettingsSnapshot().confirmThreadDelete).toBe(false);
|
||||
expect(storage.get(LOCAL_APP_SETTINGS_STORAGE_KEY)).toBe(
|
||||
JSON.stringify({ confirmThreadDelete: false }),
|
||||
);
|
||||
});
|
||||
});
|
||||
+249
-39
@@ -1,21 +1,48 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import {
|
||||
type AppSettings as BackendAppSettings,
|
||||
appSettingsSchema as backendAppSettingsSchema,
|
||||
appSettingsUpdateInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
import { readNativeApi } from "./session-logic";
|
||||
|
||||
const appSettingsSchema = z.object({
|
||||
codexBinaryPath: z.string().trim().max(4096).default(""),
|
||||
codexHomePath: z.string().trim().max(4096).default(""),
|
||||
const LOCAL_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:local:v1";
|
||||
const LEGACY_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
|
||||
const localAppSettingsSchema = z.object({
|
||||
confirmThreadDelete: z.boolean().default(true),
|
||||
});
|
||||
|
||||
const legacyAppSettingsSchema = backendAppSettingsSchema.extend({
|
||||
confirmThreadDelete: z.boolean().default(true),
|
||||
});
|
||||
|
||||
const appSettingsSchema = backendAppSettingsSchema.extend({
|
||||
confirmThreadDelete: z.boolean().default(true),
|
||||
});
|
||||
|
||||
export type AppSettings = z.infer<typeof appSettingsSchema>;
|
||||
|
||||
const DEFAULT_APP_SETTINGS: AppSettings = appSettingsSchema.parse({});
|
||||
const DEFAULT_BACKEND_APP_SETTINGS: BackendAppSettings = backendAppSettingsSchema.parse({});
|
||||
const DEFAULT_LOCAL_APP_SETTINGS = localAppSettingsSchema.parse({});
|
||||
const DEFAULT_APP_SETTINGS: AppSettings = {
|
||||
...DEFAULT_BACKEND_APP_SETTINGS,
|
||||
...DEFAULT_LOCAL_APP_SETTINGS,
|
||||
};
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let cachedRawSettings: string | null | undefined;
|
||||
let cachedBackendSettings: BackendAppSettings = DEFAULT_BACKEND_APP_SETTINGS;
|
||||
let cachedBackendCacheKey = JSON.stringify(DEFAULT_BACKEND_APP_SETTINGS);
|
||||
let cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
|
||||
let cachedLocalCacheKey: string | undefined;
|
||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||
let cachedSnapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
|
||||
let backendHydrationPromise: Promise<void> | null = null;
|
||||
let backendHydrated = false;
|
||||
let backendUpdateSequence = 0;
|
||||
let optimisticWriteSequence = 0;
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) {
|
||||
@@ -23,55 +50,240 @@ function emitChange(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function parsePersistedSettings(value: string | null): AppSettings {
|
||||
function setCachedBackendSettings(next: BackendAppSettings): void {
|
||||
cachedBackendSettings = next;
|
||||
cachedBackendCacheKey = JSON.stringify(next);
|
||||
}
|
||||
|
||||
function parseLegacySettings(value: string | null): z.infer<typeof legacyAppSettingsSchema> | null {
|
||||
if (!value) {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(value) as unknown;
|
||||
return appSettingsSchema.parse(parsed);
|
||||
return legacyAppSettingsSchema.parse(parsed);
|
||||
} catch {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getAppSettingsSnapshot(): AppSettings {
|
||||
function readLegacySettingsSnapshot(): z.infer<typeof legacyAppSettingsSchema> | null {
|
||||
if (typeof window === "undefined") {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
return null;
|
||||
}
|
||||
|
||||
const raw = window.localStorage.getItem(APP_SETTINGS_STORAGE_KEY);
|
||||
if (raw === cachedRawSettings) {
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
cachedRawSettings = raw;
|
||||
cachedSnapshot = parsePersistedSettings(raw);
|
||||
return cachedSnapshot;
|
||||
return parseLegacySettings(window.localStorage.getItem(LEGACY_APP_SETTINGS_STORAGE_KEY));
|
||||
}
|
||||
|
||||
function persistSettings(next: AppSettings): void {
|
||||
function readLocalSettingsSnapshot() {
|
||||
if (typeof window === "undefined") {
|
||||
return DEFAULT_LOCAL_APP_SETTINGS;
|
||||
}
|
||||
|
||||
const rawLocal = window.localStorage.getItem(LOCAL_APP_SETTINGS_STORAGE_KEY);
|
||||
const rawLegacy = rawLocal === null ? window.localStorage.getItem(LEGACY_APP_SETTINGS_STORAGE_KEY) : null;
|
||||
const cacheKey = rawLocal !== null ? `local:${rawLocal}` : `legacy:${rawLegacy ?? ""}`;
|
||||
if (cacheKey === cachedLocalCacheKey) {
|
||||
return cachedLocalSettings;
|
||||
}
|
||||
|
||||
if (rawLocal !== null) {
|
||||
try {
|
||||
const parsed = JSON.parse(rawLocal) as unknown;
|
||||
cachedLocalSettings = localAppSettingsSchema.parse(parsed);
|
||||
} catch {
|
||||
cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
|
||||
}
|
||||
} else {
|
||||
const legacySettings = parseLegacySettings(rawLegacy);
|
||||
cachedLocalSettings = localAppSettingsSchema.parse({
|
||||
confirmThreadDelete: legacySettings?.confirmThreadDelete ?? DEFAULT_LOCAL_APP_SETTINGS.confirmThreadDelete,
|
||||
});
|
||||
}
|
||||
|
||||
cachedLocalCacheKey = cacheKey;
|
||||
return cachedLocalSettings;
|
||||
}
|
||||
|
||||
function persistLocalSettings(next: z.infer<typeof localAppSettingsSchema>): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const raw = JSON.stringify(next);
|
||||
const normalized = localAppSettingsSchema.parse(next);
|
||||
const raw = JSON.stringify(normalized);
|
||||
|
||||
try {
|
||||
if (raw !== cachedRawSettings) {
|
||||
window.localStorage.setItem(APP_SETTINGS_STORAGE_KEY, raw);
|
||||
}
|
||||
window.localStorage.setItem(LOCAL_APP_SETTINGS_STORAGE_KEY, raw);
|
||||
} catch {
|
||||
// Best-effort persistence only.
|
||||
}
|
||||
|
||||
cachedRawSettings = raw;
|
||||
cachedSnapshot = next;
|
||||
cachedLocalSettings = normalized;
|
||||
cachedLocalCacheKey = `local:${raw}`;
|
||||
}
|
||||
|
||||
function normalizeBackendSettings(value: unknown): BackendAppSettings {
|
||||
const parsed = backendAppSettingsSchema.safeParse(value);
|
||||
if (parsed.success) {
|
||||
return parsed.data;
|
||||
}
|
||||
return DEFAULT_BACKEND_APP_SETTINGS;
|
||||
}
|
||||
|
||||
async function hydrateBackendSettings(): Promise<void> {
|
||||
if (typeof window === "undefined" || backendHydrated) {
|
||||
return;
|
||||
}
|
||||
if (backendHydrationPromise) {
|
||||
await backendHydrationPromise;
|
||||
return;
|
||||
}
|
||||
|
||||
const hydrationSequence = optimisticWriteSequence;
|
||||
const hasOptimisticWriteSinceHydration = () => hydrationSequence !== optimisticWriteSequence;
|
||||
|
||||
backendHydrationPromise = (async () => {
|
||||
const api = readNativeApi();
|
||||
if (!api?.appSettings || typeof api.appSettings.get !== "function") {
|
||||
backendHydrated = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const legacySettings = readLegacySettingsSnapshot();
|
||||
let next = normalizeBackendSettings(await api.appSettings.get());
|
||||
if (!hasOptimisticWriteSinceHydration()) {
|
||||
const migrationPatch = appSettingsUpdateInputSchema.parse({
|
||||
...(next.codexBinaryPath.length === 0 && legacySettings?.codexBinaryPath
|
||||
? { codexBinaryPath: legacySettings.codexBinaryPath }
|
||||
: {}),
|
||||
...(next.codexHomePath.length === 0 && legacySettings?.codexHomePath
|
||||
? { codexHomePath: legacySettings.codexHomePath }
|
||||
: {}),
|
||||
});
|
||||
const hasMigrationPatch =
|
||||
migrationPatch.codexBinaryPath !== undefined || migrationPatch.codexHomePath !== undefined;
|
||||
if (hasMigrationPatch) {
|
||||
next = normalizeBackendSettings(await api.appSettings.update(migrationPatch));
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasOptimisticWriteSinceHydration()) {
|
||||
setCachedBackendSettings(next);
|
||||
|
||||
if (legacySettings) {
|
||||
persistLocalSettings({
|
||||
confirmThreadDelete: legacySettings.confirmThreadDelete,
|
||||
});
|
||||
}
|
||||
|
||||
emitChange();
|
||||
}
|
||||
|
||||
backendHydrated = true;
|
||||
if (legacySettings) {
|
||||
try {
|
||||
window.localStorage.removeItem(LEGACY_APP_SETTINGS_STORAGE_KEY);
|
||||
} catch {
|
||||
// Best-effort legacy cleanup only.
|
||||
}
|
||||
}
|
||||
})()
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
backendHydrationPromise = null;
|
||||
});
|
||||
|
||||
await backendHydrationPromise;
|
||||
}
|
||||
|
||||
export function getAppSettingsSnapshot(): AppSettings {
|
||||
const localSettings = readLocalSettingsSnapshot();
|
||||
const snapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
|
||||
if (snapshotKey === cachedSnapshotKey) {
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
cachedSnapshot = appSettingsSchema.parse({
|
||||
...cachedBackendSettings,
|
||||
...localSettings,
|
||||
});
|
||||
cachedSnapshotKey = snapshotKey;
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
export function ensureAppSettingsHydrated(): Promise<void> {
|
||||
return hydrateBackendSettings();
|
||||
}
|
||||
|
||||
export function updateAppSettings(patch: Partial<AppSettings>): void {
|
||||
const parsedPatch = appSettingsSchema.partial().parse(patch);
|
||||
let didChange = false;
|
||||
let didOptimisticWrite = false;
|
||||
const markOptimisticWrite = () => {
|
||||
if (didOptimisticWrite) return;
|
||||
didOptimisticWrite = true;
|
||||
optimisticWriteSequence += 1;
|
||||
};
|
||||
|
||||
if (parsedPatch.confirmThreadDelete !== undefined) {
|
||||
markOptimisticWrite();
|
||||
persistLocalSettings({
|
||||
...readLocalSettingsSnapshot(),
|
||||
confirmThreadDelete: parsedPatch.confirmThreadDelete,
|
||||
});
|
||||
didChange = true;
|
||||
}
|
||||
|
||||
const backendPatch = appSettingsUpdateInputSchema.parse({
|
||||
...(parsedPatch.codexBinaryPath !== undefined
|
||||
? { codexBinaryPath: parsedPatch.codexBinaryPath }
|
||||
: {}),
|
||||
...(parsedPatch.codexHomePath !== undefined ? { codexHomePath: parsedPatch.codexHomePath } : {}),
|
||||
});
|
||||
const hasBackendPatch =
|
||||
backendPatch.codexBinaryPath !== undefined || backendPatch.codexHomePath !== undefined;
|
||||
if (hasBackendPatch) {
|
||||
markOptimisticWrite();
|
||||
const previous = cachedBackendSettings;
|
||||
const optimisticNext = backendAppSettingsSchema.parse({
|
||||
...cachedBackendSettings,
|
||||
...backendPatch,
|
||||
});
|
||||
setCachedBackendSettings(optimisticNext);
|
||||
backendHydrated = true;
|
||||
didChange = true;
|
||||
|
||||
const updateSequence = ++backendUpdateSequence;
|
||||
const api = readNativeApi();
|
||||
if (api?.appSettings && typeof api.appSettings.update === "function") {
|
||||
void api.appSettings
|
||||
.update(backendPatch)
|
||||
.then((response) => {
|
||||
if (updateSequence !== backendUpdateSequence) return;
|
||||
setCachedBackendSettings(normalizeBackendSettings(response));
|
||||
emitChange();
|
||||
})
|
||||
.catch(() => {
|
||||
if (updateSequence !== backendUpdateSequence) return;
|
||||
setCachedBackendSettings(previous);
|
||||
emitChange();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (didChange) {
|
||||
emitChange();
|
||||
}
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.push(listener);
|
||||
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (event.key === APP_SETTINGS_STORAGE_KEY) {
|
||||
if (
|
||||
event.key === null ||
|
||||
event.key === LOCAL_APP_SETTINGS_STORAGE_KEY ||
|
||||
event.key === LEGACY_APP_SETTINGS_STORAGE_KEY
|
||||
) {
|
||||
emitChange();
|
||||
}
|
||||
};
|
||||
@@ -86,19 +298,17 @@ function subscribe(listener: () => void): () => void {
|
||||
export function useAppSettings() {
|
||||
const settings = useSyncExternalStore(subscribe, getAppSettingsSnapshot, () => DEFAULT_APP_SETTINGS);
|
||||
|
||||
useEffect(() => {
|
||||
void ensureAppSettingsHydrated();
|
||||
}, []);
|
||||
|
||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||
const next = appSettingsSchema.parse({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
});
|
||||
persistSettings(next);
|
||||
emitChange();
|
||||
updateAppSettings(patch);
|
||||
}, []);
|
||||
|
||||
const resetSettings = useCallback(() => {
|
||||
persistSettings(DEFAULT_APP_SETTINGS);
|
||||
emitChange();
|
||||
}, []);
|
||||
updateSettings(DEFAULT_APP_SETTINGS);
|
||||
}, [updateSettings]);
|
||||
|
||||
return {
|
||||
settings,
|
||||
|
||||
@@ -182,7 +182,7 @@ export default function BranchToolbar({
|
||||
if (!activeThread || !activeProject) return null;
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
|
||||
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-1 sm:px-5 sm:pb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{envLocked || activeWorktreePath ? (
|
||||
<span className="border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
|
||||
|
||||
@@ -119,6 +119,7 @@ import {
|
||||
setupProjectScript,
|
||||
} from "~/projectScripts";
|
||||
import { Toggle } from "./ui/toggle";
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
if (!duration) return formatTimestamp(createdAt);
|
||||
@@ -415,6 +416,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
const checkpointHydrationSessionRequestRef = useRef(new Set<string>());
|
||||
const checkpointTurnCountSyncFingerprintRef = useRef(new Map<string, string>());
|
||||
const terminalStateSyncFingerprintRef = useRef(new Map<string, string>());
|
||||
|
||||
const activeThread = state.threads.find((t) => t.id === threadId);
|
||||
const diffSearch = useMemo(
|
||||
@@ -432,6 +434,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isWorking = phase === "running" || isSending || isConnecting || isRevertingCheckpoint;
|
||||
const canSend =
|
||||
Boolean(api) &&
|
||||
Boolean(activeThread) &&
|
||||
!isSending &&
|
||||
!isConnecting &&
|
||||
(prompt.trim().length > 0 || composerImages.length > 0);
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(activeThread?.events ?? [], undefined),
|
||||
@@ -763,6 +771,90 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const hasReachedTerminalLimit =
|
||||
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
|
||||
const activeThreadTerminalSyncId = activeThread?.id;
|
||||
const activeThreadTerminalSyncOpen = activeThread?.terminalOpen;
|
||||
const activeThreadTerminalSyncHeight = activeThread?.terminalHeight;
|
||||
const activeThreadTerminalSyncIds = activeThread?.terminalIds;
|
||||
const activeThreadTerminalSyncActiveId = activeThread?.activeTerminalId;
|
||||
const activeThreadTerminalSyncGroups = activeThread?.terminalGroups;
|
||||
const activeThreadTerminalSyncActiveGroupId = activeThread?.activeTerminalGroupId;
|
||||
|
||||
useEffect(() => {
|
||||
if (!api || !activeThread) return;
|
||||
void api.threads
|
||||
.updateTitle({
|
||||
threadId: activeThread.id,
|
||||
title: activeThread.title,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [activeThread?.id, activeThread?.title, api]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api || !activeThread) return;
|
||||
void api.threads
|
||||
.updateModel({
|
||||
threadId: activeThread.id,
|
||||
model: activeThread.model,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [activeThread?.id, activeThread?.model, api]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api || !activeThread) return;
|
||||
void api.threads
|
||||
.updateBranch({
|
||||
threadId: activeThread.id,
|
||||
branch: activeThread.branch,
|
||||
worktreePath: activeThread.worktreePath,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [activeThread?.id, activeThread?.branch, activeThread?.worktreePath, api]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!api ||
|
||||
!activeThreadTerminalSyncId ||
|
||||
activeThreadTerminalSyncOpen === undefined ||
|
||||
activeThreadTerminalSyncHeight === undefined ||
|
||||
activeThreadTerminalSyncIds === undefined ||
|
||||
activeThreadTerminalSyncActiveId === undefined ||
|
||||
activeThreadTerminalSyncGroups === undefined
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
threadId: activeThreadTerminalSyncId,
|
||||
terminalOpen: activeThreadTerminalSyncOpen,
|
||||
terminalHeight: activeThreadTerminalSyncHeight,
|
||||
terminalIds: activeThreadTerminalSyncIds,
|
||||
activeTerminalId: activeThreadTerminalSyncActiveId,
|
||||
terminalGroups: activeThreadTerminalSyncGroups,
|
||||
...(activeThreadTerminalSyncActiveGroupId !== undefined
|
||||
? { activeTerminalGroupId: activeThreadTerminalSyncActiveGroupId }
|
||||
: {}),
|
||||
};
|
||||
const fingerprint = JSON.stringify(payload);
|
||||
const previousFingerprint = terminalStateSyncFingerprintRef.current.get(payload.threadId);
|
||||
if (previousFingerprint === fingerprint) return;
|
||||
terminalStateSyncFingerprintRef.current.set(payload.threadId, fingerprint);
|
||||
void api.threads
|
||||
.updateTerminalState(payload)
|
||||
.catch(() => {
|
||||
const currentFingerprint = terminalStateSyncFingerprintRef.current.get(payload.threadId);
|
||||
if (currentFingerprint === fingerprint) {
|
||||
terminalStateSyncFingerprintRef.current.delete(payload.threadId);
|
||||
}
|
||||
});
|
||||
}, [
|
||||
api,
|
||||
activeThreadTerminalSyncId,
|
||||
activeThreadTerminalSyncOpen,
|
||||
activeThreadTerminalSyncHeight,
|
||||
activeThreadTerminalSyncIds,
|
||||
activeThreadTerminalSyncActiveId,
|
||||
activeThreadTerminalSyncGroups,
|
||||
activeThreadTerminalSyncActiveGroupId,
|
||||
]);
|
||||
|
||||
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
|
||||
for (const image of images) {
|
||||
@@ -949,7 +1041,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
scripts: input.nextScripts,
|
||||
});
|
||||
|
||||
if (!isElectron || !api) return;
|
||||
if (!api) return;
|
||||
|
||||
let scriptsPersisted = false;
|
||||
try {
|
||||
@@ -1074,7 +1166,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
dispatch({ type: "SET_RUNTIME_MODE", mode });
|
||||
scheduleComposerFocus();
|
||||
if (!api) return;
|
||||
await api.state.setRuntimeMode({ mode });
|
||||
|
||||
const sessionIds = state.threads
|
||||
.map((t) => t.session)
|
||||
@@ -1499,7 +1590,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
|
||||
const ensureSession = useCallback(
|
||||
async (cwdOverride?: string): Promise<EnsuredSessionInfo | null> => {
|
||||
async (
|
||||
cwdOverride?: string,
|
||||
options?: {
|
||||
silent?: boolean;
|
||||
},
|
||||
): Promise<EnsuredSessionInfo | null> => {
|
||||
if (!api || !activeThread || !activeProject) return null;
|
||||
if (activeThread.session && activeThread.session.status !== "closed") {
|
||||
const sessionThreadId = activeThread.session.threadId ?? null;
|
||||
@@ -1522,11 +1618,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
|
||||
const priorCodexThreadId = activeThread.codexThreadId;
|
||||
setIsConnecting(true);
|
||||
const shouldShowConnectingState = !options?.silent;
|
||||
if (shouldShowConnectingState) {
|
||||
setIsConnecting(true);
|
||||
}
|
||||
try {
|
||||
const session = await api.providers.startSession({
|
||||
uiThreadId: activeThread.id,
|
||||
provider: "codex",
|
||||
threadId: activeThread.id,
|
||||
cwd: cwdOverride ?? activeThread.worktreePath ?? activeProject.cwd,
|
||||
model: selectedModel || undefined,
|
||||
resumeThreadId: priorCodexThreadId ?? undefined,
|
||||
@@ -1565,7 +1664,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
if (shouldShowConnectingState) {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[
|
||||
@@ -1595,7 +1696,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
checkpointHydrationSessionRequestRef.current.add(requestKey);
|
||||
setThreadError(activeThreadId, null);
|
||||
void ensureSession().then(
|
||||
void ensureSession(undefined, { silent: true }).then(
|
||||
() => {
|
||||
checkpointHydrationSessionRequestRef.current.delete(requestKey);
|
||||
},
|
||||
@@ -1759,10 +1860,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
sizeBytes: image.sizeBytes,
|
||||
previewUrl: image.previewUrl,
|
||||
}));
|
||||
const clientMessageId = crypto.randomUUID();
|
||||
dispatch({
|
||||
type: "PUSH_USER_MESSAGE",
|
||||
threadId: activeThread.id,
|
||||
id: crypto.randomUUID(),
|
||||
id: clientMessageId,
|
||||
text: trimmed,
|
||||
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
|
||||
});
|
||||
@@ -1801,8 +1903,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
).text
|
||||
: trimmed || undefined;
|
||||
await api.providers.sendTurn({
|
||||
uiThreadId: activeThread.id,
|
||||
sessionId: sessionInfo.sessionId,
|
||||
clientMessageId,
|
||||
clientMessageText: trimmed,
|
||||
...(input ? { input } : {}),
|
||||
...(turnAttachments.length > 0 ? { attachments: turnAttachments } : {}),
|
||||
model: selectedModel || undefined,
|
||||
@@ -1818,6 +1921,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const triggerSend = () => {
|
||||
if (!canSend) return;
|
||||
const form = textareaRef.current?.form;
|
||||
if (form) {
|
||||
if (typeof form.requestSubmit === "function") {
|
||||
form.requestSubmit();
|
||||
} else {
|
||||
const submitEvent = new Event("submit", { bubbles: true, cancelable: true });
|
||||
const dispatched = form.dispatchEvent(submitEvent);
|
||||
if (!dispatched) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
void onSend({ preventDefault: () => undefined } as FormEvent);
|
||||
};
|
||||
|
||||
const onInterrupt = async () => {
|
||||
if (!api || !activeThread?.session) return;
|
||||
await api.providers.interruptTurn({
|
||||
@@ -1961,7 +2082,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
void onSend(e as unknown as FormEvent);
|
||||
triggerSend();
|
||||
}
|
||||
};
|
||||
const onToggleWorkGroup = useCallback((groupId: string) => {
|
||||
@@ -2031,7 +2152,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
|
||||
{/* Top bar */}
|
||||
<header
|
||||
className={`flex items-center justify-between border-b border-border px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
className={`flex items-center justify-between border-b border-border px-3 sm:px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
>
|
||||
<ChatHeader
|
||||
activeThreadId={activeThread.id}
|
||||
@@ -2065,7 +2186,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{/* Messages */}
|
||||
<div
|
||||
ref={messagesScrollRef}
|
||||
className="min-h-0 flex-1 overflow-y-auto px-5 py-4"
|
||||
className="min-h-0 flex-1 overflow-y-auto px-3 py-3 sm:px-5 sm:py-4"
|
||||
onScroll={onMessagesScroll}
|
||||
>
|
||||
<MessagesTimeline
|
||||
@@ -2090,7 +2211,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</div>
|
||||
|
||||
{/* Input bar */}
|
||||
<div className={cn("px-5 pt-2", isGitRepo ? "pb-1" : "pb-4")}>
|
||||
<div
|
||||
className={cn(
|
||||
"px-3 pt-2 sm:px-5 max-sm:pb-[calc(0.5rem+env(safe-area-inset-bottom))]",
|
||||
isGitRepo ? "pb-1" : "pb-4",
|
||||
)}
|
||||
>
|
||||
<form onSubmit={onSend} className="mx-auto max-w-3xl">
|
||||
<div
|
||||
className={`group rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring ${
|
||||
@@ -2189,8 +2315,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</div>
|
||||
|
||||
{/* Bottom toolbar */}
|
||||
<div className="flex items-center justify-between px-3 pb-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="flex items-center justify-end px-3 pb-3 sm:justify-between">
|
||||
<div className="hidden items-center gap-1 sm:flex">
|
||||
{/* Model picker */}
|
||||
<ModelPicker model={selectedModel} onModelChange={onModelSelect} />
|
||||
|
||||
@@ -2231,7 +2357,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{phase === "running" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full bg-rose-500/90 text-white transition-all duration-150 hover:bg-rose-500 hover:scale-105"
|
||||
className="relative z-10 flex h-10 w-10 touch-manipulation items-center justify-center rounded-full bg-rose-500/90 text-white transition-all duration-150 hover:bg-rose-500 pointer-events-auto sm:h-8 sm:w-8 sm:hover:scale-105"
|
||||
onClick={() => void onInterrupt()}
|
||||
aria-label="Stop generation"
|
||||
>
|
||||
@@ -2247,11 +2373,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="submit"
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100"
|
||||
disabled={
|
||||
isSending || isConnecting || (!prompt.trim() && composerImages.length === 0)
|
||||
}
|
||||
type="button"
|
||||
className="relative z-10 flex h-10 w-10 touch-manipulation items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary pointer-events-auto disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8 sm:hover:scale-105"
|
||||
disabled={!canSend}
|
||||
onClick={triggerSend}
|
||||
aria-label={
|
||||
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
|
||||
}
|
||||
@@ -2301,13 +2426,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</div>
|
||||
|
||||
{isGitRepo && (
|
||||
<BranchToolbar
|
||||
threadId={activeThread.id}
|
||||
envMode={envMode}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
/>
|
||||
<div className="hidden sm:block">
|
||||
<BranchToolbar
|
||||
threadId={activeThread.id}
|
||||
envMode={envMode}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeThread.terminalOpen && api && activeProject && (
|
||||
@@ -2411,28 +2538,43 @@ const ChatHeader = memo(function ChatHeader({
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<h2 className="truncate text-sm font-medium text-foreground" title={activeThreadTitle}>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
|
||||
<SidebarTrigger className="size-8 md:hidden" />
|
||||
<Separator orientation="vertical" className="md:hidden data-[orientation=vertical]:h-4" />
|
||||
<h2
|
||||
className="truncate text-xs font-medium text-foreground sm:text-sm"
|
||||
title={activeThreadTitle}
|
||||
>
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
{activeProjectName && <Badge variant="outline">{activeProjectName}</Badge>}
|
||||
{activeProjectName && (
|
||||
<Badge variant="outline" className="hidden sm:inline-flex">
|
||||
{activeProjectName}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="shrink-0 flex items-center gap-3">
|
||||
<div className="shrink-0 flex items-center gap-1.5 sm:gap-3">
|
||||
{activeProjectScripts && (
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
keybindings={keybindings}
|
||||
preferredScriptId={preferredScriptId}
|
||||
onRunScript={onRunProjectScript}
|
||||
onAddScript={onAddProjectScript}
|
||||
onUpdateScript={onUpdateProjectScript}
|
||||
/>
|
||||
<div className="hidden md:block">
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
keybindings={keybindings}
|
||||
preferredScriptId={preferredScriptId}
|
||||
onRunScript={onRunProjectScript}
|
||||
onAddScript={onAddProjectScript}
|
||||
onUpdateScript={onUpdateProjectScript}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{activeProjectName && (
|
||||
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
|
||||
<div className="hidden md:block">
|
||||
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
|
||||
</div>
|
||||
)}
|
||||
{activeProjectName && (
|
||||
<GitActionsControl api={api} gitCwd={gitCwd} activeThreadId={activeThreadId} />
|
||||
<div className="hidden md:block">
|
||||
<GitActionsControl api={api} gitCwd={gitCwd} activeThreadId={activeThreadId} />
|
||||
</div>
|
||||
)}
|
||||
<Toggle
|
||||
pressed={diffOpen}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { createLocalThreadForProject } from "./Sidebar.logic";
|
||||
|
||||
describe("createLocalThreadForProject", () => {
|
||||
it("creates a local thread with the project's configured model", () => {
|
||||
const thread = createLocalThreadForProject({
|
||||
projectId: "project-1",
|
||||
projects: [
|
||||
{
|
||||
id: "project-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "custom-project-model",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
options: {
|
||||
branch: "feature/test",
|
||||
worktreePath: "/tmp/project/worktrees/feature-test",
|
||||
},
|
||||
});
|
||||
|
||||
expect(thread.projectId).toBe("project-1");
|
||||
expect(thread.model).toBe("custom-project-model");
|
||||
expect(thread.branch).toBe("feature/test");
|
||||
expect(thread.worktreePath).toBe("/tmp/project/worktrees/feature-test");
|
||||
});
|
||||
|
||||
it("falls back to the default model when the project is missing", () => {
|
||||
const thread = createLocalThreadForProject({
|
||||
projectId: "missing-project",
|
||||
projects: [],
|
||||
});
|
||||
|
||||
expect(thread.projectId).toBe("missing-project");
|
||||
expect(thread.model).toBe(DEFAULT_MODEL);
|
||||
expect(thread.branch).toBeNull();
|
||||
expect(thread.worktreePath).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { createThread } from "../threadFactory";
|
||||
import type { Project, Thread } from "../types";
|
||||
|
||||
interface CreateLocalThreadInput {
|
||||
projectId: string;
|
||||
projects: Project[];
|
||||
options?: {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export function createLocalThreadForProject({
|
||||
projectId,
|
||||
projects,
|
||||
options,
|
||||
}: CreateLocalThreadInput): Thread {
|
||||
const model = projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
|
||||
return createThread(projectId, {
|
||||
model,
|
||||
branch: options?.branch ?? null,
|
||||
worktreePath: options?.worktreePath ?? null,
|
||||
});
|
||||
}
|
||||
@@ -10,13 +10,13 @@ import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||
import { type Thread } from "../types";
|
||||
import { type Project, type Thread } from "../types";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { createThread } from "../threadFactory";
|
||||
import { createLocalThreadForProject } from "./Sidebar.logic";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
|
||||
@@ -112,7 +112,11 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
||||
};
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
interface SidebarProps {
|
||||
embedded?: boolean;
|
||||
}
|
||||
|
||||
export default function Sidebar({ embedded = false }: SidebarProps = {}) {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useNativeApi();
|
||||
const navigate = useNavigate();
|
||||
@@ -140,33 +144,78 @@ export default function Sidebar() {
|
||||
}, [state.threads]);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
async (
|
||||
(
|
||||
projectId: string,
|
||||
options?: {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
},
|
||||
) => {
|
||||
const thread = createThread(projectId, {
|
||||
model: state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL,
|
||||
branch: options?.branch ?? null,
|
||||
worktreePath: options?.worktreePath ?? null,
|
||||
});
|
||||
await api?.state.createThread({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: thread.model,
|
||||
createdAt: thread.createdAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
});
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: thread.id },
|
||||
});
|
||||
if (!api) {
|
||||
const localThread = createLocalThreadForProject({
|
||||
projectId,
|
||||
projects: state.projects,
|
||||
...(options ? { options } : {}),
|
||||
});
|
||||
dispatch({
|
||||
type: "ADD_THREAD",
|
||||
thread: localThread,
|
||||
});
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: localThread.id },
|
||||
});
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await api.threads.create({
|
||||
projectId,
|
||||
model:
|
||||
state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL,
|
||||
branch: options?.branch ?? null,
|
||||
worktreePath: options?.worktreePath ?? null,
|
||||
});
|
||||
dispatch({
|
||||
type: "ADD_THREAD",
|
||||
thread: {
|
||||
id: result.thread.id,
|
||||
codexThreadId: result.thread.codexThreadId,
|
||||
projectId: result.thread.projectId,
|
||||
title: result.thread.title,
|
||||
model: result.thread.model,
|
||||
terminalOpen: result.thread.terminalOpen,
|
||||
terminalHeight: result.thread.terminalHeight,
|
||||
terminalIds: result.thread.terminalIds,
|
||||
runningTerminalIds: result.thread.runningTerminalIds,
|
||||
activeTerminalId: result.thread.activeTerminalId,
|
||||
terminalGroups: result.thread.terminalGroups,
|
||||
activeTerminalGroupId: result.thread.activeTerminalGroupId,
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: result.thread.createdAt,
|
||||
latestTurnId: result.thread.latestTurnId,
|
||||
latestTurnStartedAt: result.thread.latestTurnStartedAt,
|
||||
latestTurnCompletedAt: result.thread.latestTurnCompletedAt,
|
||||
latestTurnDurationMs: result.thread.latestTurnDurationMs,
|
||||
lastVisitedAt: result.thread.lastVisitedAt,
|
||||
branch: result.thread.branch,
|
||||
worktreePath: result.thread.worktreePath,
|
||||
turnDiffSummaries: result.thread.turnDiffSummaries ?? [],
|
||||
},
|
||||
});
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: result.thread.id },
|
||||
});
|
||||
} catch {
|
||||
// Ignore thread creation errors here; caller surfaces project-level failures.
|
||||
}
|
||||
})();
|
||||
},
|
||||
[api, navigate, state.projects],
|
||||
[api, dispatch, navigate, state.projects],
|
||||
);
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
@@ -195,25 +244,47 @@ export default function Sidebar() {
|
||||
|
||||
setIsAddingProject(true);
|
||||
try {
|
||||
if (isElectron && api) {
|
||||
const result = await api.projects.add({ cwd });
|
||||
const existingByCwd = state.projects.find((p) => p.cwd === result.project.cwd);
|
||||
const resolvedProjectId = existingByCwd?.id ?? result.project.id;
|
||||
|
||||
if (result.created) {
|
||||
await handleNewThread(resolvedProjectId);
|
||||
} else {
|
||||
focusMostRecentThreadForProject(resolvedProjectId);
|
||||
}
|
||||
} else {
|
||||
if (!api) {
|
||||
const existing = state.projects.find((project) => project.cwd === cwd);
|
||||
if (existing) {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
return;
|
||||
}
|
||||
if (!api) return;
|
||||
const result = await api.projects.add({ cwd });
|
||||
await handleNewThread(result.project.id);
|
||||
|
||||
const name = inferProjectName(cwd);
|
||||
const project: Project = {
|
||||
id: crypto.randomUUID(),
|
||||
name,
|
||||
cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
};
|
||||
dispatch({ type: "ADD_PROJECT", project });
|
||||
handleNewThread(project.id);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await api.projects.add({ cwd });
|
||||
const 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);
|
||||
@@ -305,7 +376,8 @@ export default function Sidebar() {
|
||||
|
||||
const shouldNavigateToFallback = routeThreadId === threadId;
|
||||
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
||||
await api.state.deleteThread({ id: threadId });
|
||||
void api.threads.delete({ threadId }).catch(() => undefined);
|
||||
dispatch({ type: "DELETE_THREAD", threadId });
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
void navigate({
|
||||
@@ -379,18 +451,23 @@ export default function Sidebar() {
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
await api.projects.remove({ id: projectId });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error deleting project.";
|
||||
console.error("Failed to remove project", { projectId, error });
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to delete "${project.name}"`,
|
||||
description: message,
|
||||
});
|
||||
return;
|
||||
if (isElectron) {
|
||||
try {
|
||||
await api.projects.remove({ id: projectId });
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Unknown error deleting project.";
|
||||
console.error("Failed to remove project", { projectId, error });
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to delete "${project.name}"`,
|
||||
description: message,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
dispatch({ type: "DELETE_PROJECT", projectId });
|
||||
},
|
||||
[api, dispatch, state.projects, state.threads],
|
||||
);
|
||||
@@ -424,8 +501,12 @@ export default function Sidebar() {
|
||||
};
|
||||
}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
|
||||
|
||||
const rootClassName = embedded
|
||||
? "sidebar flex h-full min-h-0 flex-col bg-card"
|
||||
: "sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card max-sm:w-[36vw] max-sm:min-w-[140px] max-sm:max-w-[200px]";
|
||||
|
||||
return (
|
||||
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
|
||||
<aside className={rootClassName}>
|
||||
{/* Branding */}
|
||||
<div
|
||||
className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
|
||||
@@ -434,7 +515,7 @@ export default function Sidebar() {
|
||||
<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">
|
||||
<span className="hidden rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60 sm:inline-block">
|
||||
{APP_STAGE_LABEL}
|
||||
</span>
|
||||
</div>
|
||||
@@ -451,7 +532,7 @@ export default function Sidebar() {
|
||||
return;
|
||||
}
|
||||
const firstProject = state.projects[0];
|
||||
if (firstProject) void handleNewThread(firstProject.id);
|
||||
if (firstProject) handleNewThread(firstProject.id);
|
||||
}}
|
||||
>
|
||||
<span className="text-foreground">+</span>
|
||||
@@ -490,7 +571,9 @@ export default function Sidebar() {
|
||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||
{project.name}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
|
||||
<span className="hidden text-[10px] text-muted-foreground/60 sm:inline">
|
||||
{threads.length}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{/* Threads */}
|
||||
@@ -554,7 +637,7 @@ export default function Sidebar() {
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[10px] text-muted-foreground/40">
|
||||
<span className="hidden text-[10px] text-muted-foreground/40 sm:inline">
|
||||
{formatRelativeTime(thread.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -566,9 +649,7 @@ export default function Sidebar() {
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground/80"
|
||||
onClick={() => {
|
||||
void handleNewThread(project.id);
|
||||
}}
|
||||
onClick={() => handleNewThread(project.id)}
|
||||
>
|
||||
<span>+</span> New thread
|
||||
</button>
|
||||
|
||||
@@ -252,6 +252,7 @@ function TerminalViewport({
|
||||
),
|
||||
);
|
||||
});
|
||||
let didReceiveRenderableEventSinceOpen = false;
|
||||
|
||||
const themeObserver = new MutationObserver(() => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
@@ -279,9 +280,14 @@ function TerminalViewport({
|
||||
...(runtimeEnv ? { env: runtimeEnv } : {}),
|
||||
});
|
||||
if (disposed) return;
|
||||
activeTerminal.write("\u001bc");
|
||||
if (snapshot.history.length > 0) {
|
||||
activeTerminal.write(snapshot.history);
|
||||
const shouldHydrateFromSnapshot =
|
||||
snapshot.history.length > 0 || !didReceiveRenderableEventSinceOpen;
|
||||
if (shouldHydrateFromSnapshot) {
|
||||
// Avoid clearing output that arrived before open() resolved.
|
||||
activeTerminal.write("\u001bc");
|
||||
if (snapshot.history.length > 0) {
|
||||
activeTerminal.write(snapshot.history);
|
||||
}
|
||||
}
|
||||
if (autoFocus) {
|
||||
window.requestAnimationFrame(() => {
|
||||
@@ -302,6 +308,10 @@ function TerminalViewport({
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) return;
|
||||
|
||||
if (event.type !== "activity") {
|
||||
didReceiveRenderableEventSinceOpen = true;
|
||||
}
|
||||
|
||||
if (event.type === "output") {
|
||||
activeTerminal.write(event.data);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,698 @@
|
||||
"use client";
|
||||
|
||||
import { mergeProps } from "@base-ui/react/merge-props";
|
||||
import { useRender } from "@base-ui/react/use-render";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { PanelLeftIcon } from "lucide-react";
|
||||
import * as React from "react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { Separator } from "~/components/ui/separator";
|
||||
import {
|
||||
Sheet,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetPopup,
|
||||
SheetTitle,
|
||||
} from "~/components/ui/sheet";
|
||||
import { Skeleton } from "~/components/ui/skeleton";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
import { useMediaQuery } from "~/hooks/useMediaQuery";
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state";
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
||||
const SIDEBAR_WIDTH = "16rem";
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem";
|
||||
const SIDEBAR_WIDTH_ICON = "3rem";
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed";
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
openMobile: boolean;
|
||||
setOpenMobile: (open: boolean) => void;
|
||||
isMobile: boolean;
|
||||
toggleSidebar: () => void;
|
||||
};
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext);
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.");
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}) {
|
||||
const isMobile = useMediaQuery("(max-width: 767px)");
|
||||
const [openMobile, setOpenMobile] = React.useState(false);
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen);
|
||||
const open = openProp ?? _open;
|
||||
const setOpen = React.useCallback(
|
||||
async (value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value;
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState);
|
||||
} else {
|
||||
_setOpen(openState);
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
await cookieStore.set({
|
||||
expires: Date.now() + SIDEBAR_COOKIE_MAX_AGE * 1000,
|
||||
name: SIDEBAR_COOKIE_NAME,
|
||||
path: "/",
|
||||
value: String(openState),
|
||||
});
|
||||
},
|
||||
[setOpenProp, open],
|
||||
);
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
|
||||
}, [isMobile, setOpen]);
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault();
|
||||
toggleSidebar();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [toggleSidebar]);
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed";
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
isMobile,
|
||||
open,
|
||||
openMobile,
|
||||
setOpen,
|
||||
setOpenMobile,
|
||||
state,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, toggleSidebar],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<div
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
|
||||
className,
|
||||
)}
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</SidebarContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right";
|
||||
variant?: "sidebar" | "floating" | "inset";
|
||||
collapsible?: "offcanvas" | "icon" | "none";
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
|
||||
className,
|
||||
)}
|
||||
data-slot="sidebar"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet onOpenChange={setOpenMobile} open={openMobile} {...props}>
|
||||
<SheetPopup
|
||||
className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
|
||||
data-mobile="true"
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
side={side}
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Sidebar</SheetTitle>
|
||||
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetPopup>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="group peer hidden text-sidebar-foreground md:block"
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
data-state={state}
|
||||
data-variant={variant}
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
|
||||
)}
|
||||
data-slot="sidebar-gap"
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className,
|
||||
)}
|
||||
data-slot="sidebar-container"
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm/5"
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn("size-7", className)}
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
onClick={(event) => {
|
||||
onClick?.(event);
|
||||
toggleSidebar();
|
||||
}}
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
|
||||
return (
|
||||
<button
|
||||
aria-label="Toggle Sidebar"
|
||||
className={cn(
|
||||
"-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
onClick={toggleSidebar}
|
||||
tabIndex={-1}
|
||||
title="Toggle Sidebar"
|
||||
type="button"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
className={cn(
|
||||
"relative flex w-full flex-1 flex-col bg-background",
|
||||
"md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ms-2 md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ms-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm/5",
|
||||
className,
|
||||
)}
|
||||
data-slot="sidebar-inset"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
className={cn("h-8 w-full bg-background shadow-none", className)}
|
||||
data-sidebar="input"
|
||||
data-slot="sidebar-input"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
data-sidebar="header"
|
||||
data-slot="sidebar-header"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
data-sidebar="footer"
|
||||
data-slot="sidebar-footer"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
className={cn("mx-2 w-auto bg-sidebar-border", className)}
|
||||
data-sidebar="separator"
|
||||
data-slot="sidebar-separator"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<ScrollArea className="**:data-[slot=scroll-area-scrollbar]:hidden" scrollFade>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="content"
|
||||
data-slot="sidebar-content"
|
||||
{...props}
|
||||
/>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
data-sidebar="group"
|
||||
data-slot="sidebar-group"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"flex h-8 shrink-0 items-center rounded-lg px-2 font-medium text-sidebar-foreground text-xs outline-hidden ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className,
|
||||
),
|
||||
"data-sidebar": "group-label",
|
||||
"data-slot": "sidebar-group-label",
|
||||
};
|
||||
|
||||
return useRender({
|
||||
defaultTagName: "div",
|
||||
props: mergeProps(defaultProps, props),
|
||||
render,
|
||||
});
|
||||
}
|
||||
|
||||
function SidebarGroupAction({ className, render, ...props }: useRender.ComponentProps<"button">) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:-inset-2 after:absolute md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className,
|
||||
),
|
||||
"data-sidebar": "group-action",
|
||||
"data-slot": "sidebar-group-action",
|
||||
};
|
||||
|
||||
return useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps(defaultProps, props),
|
||||
render,
|
||||
});
|
||||
}
|
||||
|
||||
function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn("w-full text-sm", className)}
|
||||
data-sidebar="group-content"
|
||||
data-slot="sidebar-group-content"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
data-sidebar="menu"
|
||||
data-slot="sidebar-menu"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
className={cn("group/menu-item relative", className)}
|
||||
data-sidebar="menu-item"
|
||||
data-slot="sidebar-menu-item"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
variant: "default",
|
||||
},
|
||||
variants: {
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
sm: "h-7 text-xs",
|
||||
},
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function SidebarMenuButton({
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"button"> & {
|
||||
isActive?: boolean;
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipPopup>;
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const { isMobile, state } = useSidebar();
|
||||
|
||||
const defaultProps = {
|
||||
className: cn(sidebarMenuButtonVariants({ size, variant }), className),
|
||||
"data-active": isActive,
|
||||
"data-sidebar": "menu-button",
|
||||
"data-size": size,
|
||||
"data-slot": "sidebar-menu-button",
|
||||
};
|
||||
|
||||
const buttonProps = mergeProps<"button">(defaultProps, props);
|
||||
|
||||
const buttonElement = useRender({
|
||||
defaultTagName: "button",
|
||||
props: buttonProps,
|
||||
render,
|
||||
});
|
||||
|
||||
if (!tooltip) {
|
||||
return buttonElement;
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={buttonElement as React.ReactElement<Record<string, unknown>>} />
|
||||
<TooltipPopup
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
side="right"
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
showOnHover = false,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"button"> & {
|
||||
showOnHover?: boolean;
|
||||
}) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:-inset-2 after:absolute md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
|
||||
className,
|
||||
),
|
||||
"data-sidebar": "menu-action",
|
||||
"data-slot": "sidebar-menu-action",
|
||||
};
|
||||
|
||||
return useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps<"button">(defaultProps, props),
|
||||
render,
|
||||
});
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-lg px-1 font-medium text-sidebar-foreground text-xs tabular-nums",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="menu-badge"
|
||||
data-slot="sidebar-menu-badge"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean;
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("flex h-8 items-center gap-2 rounded-lg px-2", className)}
|
||||
data-sidebar="menu-skeleton"
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
{...props}
|
||||
>
|
||||
{showIcon && <Skeleton className="size-4 rounded-lg" data-sidebar="menu-skeleton-icon" />}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
className={cn(
|
||||
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-sidebar-border border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="menu-sub"
|
||||
data-slot="sidebar-menu-sub"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
data-sidebar="menu-sub-item"
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"a"> & {
|
||||
size?: "sm" | "md";
|
||||
isActive?: boolean;
|
||||
}) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"-translate-x-px flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-lg px-2 text-sidebar-foreground outline-hidden ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className,
|
||||
),
|
||||
"data-active": isActive,
|
||||
"data-sidebar": "menu-sub-button",
|
||||
"data-size": size,
|
||||
"data-slot": "sidebar-menu-sub-button",
|
||||
};
|
||||
|
||||
return useRender({
|
||||
defaultTagName: "a",
|
||||
props: mergeProps<"a">(defaultProps, props),
|
||||
render,
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
"use client";
|
||||
|
||||
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const TooltipCreateHandle = TooltipPrimitive.createHandle;
|
||||
|
||||
const TooltipProvider = TooltipPrimitive.Provider;
|
||||
|
||||
const Tooltip = TooltipPrimitive.Root;
|
||||
|
||||
function TooltipTrigger(props: TooltipPrimitive.Trigger.Props) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function TooltipPopup({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
side = "top",
|
||||
anchor,
|
||||
children,
|
||||
...props
|
||||
}: TooltipPrimitive.Popup.Props & {
|
||||
align?: TooltipPrimitive.Positioner.Props["align"];
|
||||
side?: TooltipPrimitive.Positioner.Props["side"];
|
||||
sideOffset?: TooltipPrimitive.Positioner.Props["sideOffset"];
|
||||
anchor?: TooltipPrimitive.Positioner.Props["anchor"];
|
||||
}) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Positioner
|
||||
align={align}
|
||||
anchor={anchor}
|
||||
className="z-50 h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none"
|
||||
data-slot="tooltip-positioner"
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
>
|
||||
<TooltipPrimitive.Popup
|
||||
className={cn(
|
||||
"relative flex h-(--popup-height,auto) w-(--popup-width,auto) origin-(--transform-origin) text-balance rounded-md border bg-popover not-dark:bg-clip-padding text-popover-foreground text-xs shadow-md/5 transition-[width,height,scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-md)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 data-instant:duration-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
className,
|
||||
)}
|
||||
data-slot="tooltip-popup"
|
||||
{...props}
|
||||
>
|
||||
<TooltipPrimitive.Viewport
|
||||
className="relative size-full overflow-clip px-(--viewport-inline-padding) py-1 [--viewport-inline-padding:--spacing(2)] data-instant:transition-none **:data-current:data-ending-style:opacity-0 **:data-current:data-starting-style:opacity-0 **:data-previous:data-ending-style:opacity-0 **:data-previous:data-starting-style:opacity-0 **:data-current:w-[calc(var(--popup-width)-2*var(--viewport-inline-padding)-2px)] **:data-previous:w-[calc(var(--popup-width)-2*var(--viewport-inline-padding)-2px)] **:data-previous:truncate **:data-current:opacity-100 **:data-previous:opacity-100 **:data-current:transition-opacity **:data-previous:transition-opacity"
|
||||
data-slot="tooltip-viewport"
|
||||
>
|
||||
{children}
|
||||
</TooltipPrimitive.Viewport>
|
||||
</TooltipPrimitive.Popup>
|
||||
</TooltipPrimitive.Positioner>
|
||||
</TooltipPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
TooltipCreateHandle,
|
||||
TooltipProvider,
|
||||
Tooltip,
|
||||
TooltipTrigger,
|
||||
TooltipPopup,
|
||||
TooltipPopup as TooltipContent,
|
||||
};
|
||||
@@ -13,6 +13,18 @@ import { APP_DISPLAY_NAME } from "./branding";
|
||||
import { isElectron } from "./env";
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
|
||||
if (!globalThis.crypto.randomUUID) {
|
||||
// https://stackoverflow.com/a/2117523/2800218
|
||||
// LICENSE: https://creativecommons.org/licenses/by-sa/4.0/legalcode
|
||||
// oxlint-disable-next-line unicorn/consistent-function-scoping
|
||||
crypto.randomUUID = function randomUUID() {
|
||||
// @ts-expect-error -- Some cryptic stuff that this polyfill uses
|
||||
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
|
||||
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0]! & (15 >> (c / 4)))).toString(16),
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
+146
-63
@@ -13,9 +13,8 @@ import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
|
||||
import { isElectron } from "../env";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { invalidateGitQueries } from "../lib/gitReactQuery";
|
||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||
import { type AppState, useStore } from "../store";
|
||||
import { onServerStateUpdate, onServerWelcome } from "../wsNativeApi";
|
||||
import { useStore } from "../store";
|
||||
import { onServerWelcome } from "../wsNativeApi";
|
||||
|
||||
export const Route = createRootRouteWithContext<{
|
||||
queryClient: QueryClient;
|
||||
@@ -29,7 +28,7 @@ function RootRouteView() {
|
||||
|
||||
if (!api) {
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background text-foreground">
|
||||
<div className="flex h-dvh 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...
|
||||
@@ -42,9 +41,8 @@ function RootRouteView() {
|
||||
return (
|
||||
<ToastProvider>
|
||||
<AnchoredToastProvider>
|
||||
<EventRouter />
|
||||
<AutoProjectBootstrap />
|
||||
<DesktopProjectBootstrap />
|
||||
<StateSyncRouter />
|
||||
<BrowserDefaultProjectBootstrap />
|
||||
<Outlet />
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
@@ -122,84 +120,169 @@ function errorDetails(error: unknown): string {
|
||||
}
|
||||
}
|
||||
|
||||
function EventRouter() {
|
||||
function StateSyncRouter() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
const activeAssistantItemRef = useRef<string | null>(null);
|
||||
const activeThreadId = useParams({
|
||||
strict: false,
|
||||
select: (params) => params.threadId,
|
||||
});
|
||||
const prevTurnCompletionsRef = useRef<Map<string, string | undefined>>(new Map());
|
||||
const lastStateSeqRef = useRef(0);
|
||||
const stateQueueRef = useRef(Promise.resolve());
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
let mounted = true;
|
||||
void api.state.getSnapshot().then((snapshot) => {
|
||||
if (!mounted) return;
|
||||
dispatch({ type: "SET_SERVER_STATE", state: snapshot as AppState });
|
||||
});
|
||||
let disposed = false;
|
||||
let retryDelayMs = 500;
|
||||
let retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const bootstrap = async () => {
|
||||
try {
|
||||
const snapshot = await api.state.bootstrap();
|
||||
if (disposed) return;
|
||||
dispatch({
|
||||
type: "HYDRATE_FROM_SERVER",
|
||||
snapshot,
|
||||
});
|
||||
lastStateSeqRef.current = snapshot.lastStateSeq;
|
||||
} catch {
|
||||
if (disposed) return;
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
void bootstrap();
|
||||
}, retryDelayMs);
|
||||
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
|
||||
}
|
||||
};
|
||||
|
||||
void bootstrap();
|
||||
|
||||
return () => {
|
||||
mounted = false;
|
||||
disposed = true;
|
||||
if (retryTimer) {
|
||||
clearTimeout(retryTimer);
|
||||
}
|
||||
};
|
||||
}, [api, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
return onServerStateUpdate((snapshot) => {
|
||||
const serverState = snapshot as AppState;
|
||||
dispatch({ type: "SET_SERVER_STATE", state: serverState });
|
||||
|
||||
let hasNewTurnCompletion = false;
|
||||
for (const thread of serverState.threads) {
|
||||
const prev = prevTurnCompletionsRef.current.get(thread.id);
|
||||
if (thread.latestTurnCompletedAt && thread.latestTurnCompletedAt !== prev) {
|
||||
hasNewTurnCompletion = true;
|
||||
}
|
||||
}
|
||||
const nextMap = new Map<string, string | undefined>();
|
||||
for (const thread of serverState.threads) {
|
||||
nextMap.set(thread.id, thread.latestTurnCompletedAt);
|
||||
}
|
||||
prevTurnCompletionsRef.current = nextMap;
|
||||
|
||||
if (hasNewTurnCompletion) {
|
||||
void invalidateGitQueries(queryClient);
|
||||
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
|
||||
}
|
||||
});
|
||||
}, [dispatch, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) return;
|
||||
const visitedAt = new Date().toISOString();
|
||||
if (!api) return;
|
||||
void api.state.markThreadVisited({ threadId: activeThreadId, visitedAt });
|
||||
}, [activeThreadId, api]);
|
||||
return api.state.onEvent((event) => {
|
||||
stateQueueRef.current = stateQueueRef.current
|
||||
.then(async () => {
|
||||
if (event.seq <= lastStateSeqRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
if (event.seq > lastStateSeqRef.current + 1) {
|
||||
const catchUp = await api.state.catchUp({ afterSeq: lastStateSeqRef.current });
|
||||
for (const missingEvent of catchUp.events) {
|
||||
if (missingEvent.seq <= lastStateSeqRef.current) continue;
|
||||
dispatch({
|
||||
type: "APPLY_STATE_EVENT",
|
||||
event: missingEvent,
|
||||
});
|
||||
lastStateSeqRef.current = missingEvent.seq;
|
||||
}
|
||||
}
|
||||
|
||||
function AutoProjectBootstrap() {
|
||||
const { dispatch } = useStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (isElectron) return;
|
||||
return onServerWelcome(() => {
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
if (event.seq > lastStateSeqRef.current) {
|
||||
dispatch({
|
||||
type: "APPLY_STATE_EVENT",
|
||||
event,
|
||||
});
|
||||
lastStateSeqRef.current = event.seq;
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
});
|
||||
}, [dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function DesktopProjectBootstrap() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
}, [api, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isElectron || !api) return;
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
if (!api) return;
|
||||
return api.providers.onEvent((event) => {
|
||||
if (event.method === "turn/completed") {
|
||||
void invalidateGitQueries(queryClient);
|
||||
}
|
||||
if (event.method === "checkpoint/captured") {
|
||||
const payload = event.payload as { turnCount?: number } | undefined;
|
||||
const turnCount = payload?.turnCount;
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["providers", "checkpointDiff"] as const,
|
||||
predicate: (query) => {
|
||||
if (typeof turnCount !== "number") return true;
|
||||
return query.queryKey[5] === turnCount;
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!activeThreadId) return;
|
||||
dispatch({
|
||||
type: "APPLY_EVENT",
|
||||
event,
|
||||
activeAssistantItemRef,
|
||||
activeThreadId,
|
||||
});
|
||||
});
|
||||
}, [activeThreadId, api, dispatch, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api || !activeThreadId) return;
|
||||
const visitedAt = new Date().toISOString();
|
||||
dispatch({
|
||||
type: "MARK_THREAD_VISITED",
|
||||
threadId: activeThreadId,
|
||||
visitedAt,
|
||||
});
|
||||
void api.threads
|
||||
.markVisited({
|
||||
threadId: activeThreadId,
|
||||
visitedAt,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [activeThreadId, api, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.terminal.onEvent((event) => {
|
||||
dispatch({
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event,
|
||||
});
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function BrowserDefaultProjectBootstrap() {
|
||||
const api = useNativeApi();
|
||||
const { state } = useStore();
|
||||
const createdRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isElectron || !api || !state.threadsHydrated) {
|
||||
return;
|
||||
}
|
||||
|
||||
return onServerWelcome((payload) => {
|
||||
if (createdRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = state.projects.find((project) => project.cwd === payload.cwd);
|
||||
if (existing) {
|
||||
createdRef.current = true;
|
||||
return;
|
||||
}
|
||||
|
||||
createdRef.current = true;
|
||||
void api.projects.add({ cwd: payload.cwd }).catch(() => {
|
||||
createdRef.current = false;
|
||||
});
|
||||
});
|
||||
}, [api, state.projects, state.threadsHydrated]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
import { createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
|
||||
import { Suspense, lazy, type CSSProperties, type ReactNode, useCallback, useEffect } from "react";
|
||||
|
||||
import ChatView from "../components/ChatView";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { useStore } from "../store";
|
||||
import { Sheet, SheetPopup } from "../components/ui/sheet";
|
||||
import { Sidebar, SidebarProvider } from "../components/ui/sidebar";
|
||||
|
||||
const DiffPanel = lazy(() => import("../components/DiffPanel"));
|
||||
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
|
||||
@@ -53,6 +54,20 @@ function ChatThreadRouteView() {
|
||||
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 setDiffOpen = useCallback(
|
||||
(open: boolean) => {
|
||||
if (open === diffOpen) return;
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
search: (previous) => {
|
||||
const rest = stripDiffSearchParams(previous);
|
||||
return open ? { ...rest, diff: "1" } : rest;
|
||||
},
|
||||
});
|
||||
},
|
||||
[diffOpen, navigate, threadId],
|
||||
);
|
||||
const closeDiff = useCallback(() => {
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
@@ -83,26 +98,45 @@ 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>
|
||||
const diffLoadingFallback = (
|
||||
<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>
|
||||
);
|
||||
|
||||
if (shouldUseDiffSheet) {
|
||||
return (
|
||||
<>
|
||||
<ChatView threadId={threadId} />
|
||||
<DiffPanelWrapper sheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||
<Suspense fallback={diffLoadingFallback}>
|
||||
<DiffPanel mode="sheet" />
|
||||
</Suspense>
|
||||
</DiffPanelWrapper>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex min-h-0 min-w-0 flex-1">
|
||||
<ChatView threadId={threadId} />
|
||||
<DiffPanelWrapper sheet={shouldUseDiffSheet} diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||
<Suspense fallback={diffLoadingFallback}>
|
||||
<DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
|
||||
</Suspense>
|
||||
</DiffPanelWrapper>
|
||||
</>
|
||||
<SidebarProvider
|
||||
open={diffOpen}
|
||||
onOpenChange={setDiffOpen}
|
||||
className="w-0 min-w-0 flex-none"
|
||||
style={{ "--sidebar-width": "34rem" } as CSSProperties}
|
||||
>
|
||||
<Sidebar
|
||||
side="right"
|
||||
collapsible="offcanvas"
|
||||
className="border-l border-border bg-card text-foreground"
|
||||
>
|
||||
<Suspense fallback={diffLoadingFallback}>
|
||||
<DiffPanel mode="sheet" />
|
||||
</Suspense>
|
||||
</Sidebar>
|
||||
</SidebarProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { Separator } from "../components/ui/separator";
|
||||
import { SidebarTrigger } from "../components/ui/sidebar";
|
||||
|
||||
function ChatIndexRouteView() {
|
||||
return (
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-muted-foreground/40">
|
||||
{!isElectron && (
|
||||
<header className="sticky top-0 z-20 flex h-11 shrink-0 items-center gap-2 border-b border-border/70 bg-background/95 px-2 backdrop-blur md:hidden">
|
||||
<SidebarTrigger className="size-8" />
|
||||
<Separator orientation="vertical" className="data-[orientation=vertical]:h-4" />
|
||||
<span className="truncate text-xs text-muted-foreground/75">Threads</span>
|
||||
</header>
|
||||
)}
|
||||
{isElectron && (
|
||||
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
|
||||
<span className="text-xs text-muted-foreground/50">No active thread</span>
|
||||
|
||||
@@ -2,7 +2,8 @@ import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
|
||||
import Sidebar from "../components/Sidebar";
|
||||
import ThreadSidebar from "../components/Sidebar";
|
||||
import { Sidebar, SidebarInset, SidebarProvider } from "../components/ui/sidebar";
|
||||
|
||||
function ChatRouteLayout() {
|
||||
const navigate = useNavigate();
|
||||
@@ -24,16 +25,23 @@ function ChatRouteLayout() {
|
||||
}, [navigate]);
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-background text-foreground isolate">
|
||||
<Sidebar />
|
||||
<DiffWorkerPoolProvider>
|
||||
<Outlet />
|
||||
</DiffWorkerPoolProvider>
|
||||
</div>
|
||||
<SidebarProvider defaultOpen>
|
||||
<Sidebar
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
className="border-r border-border bg-card text-foreground"
|
||||
>
|
||||
<ThreadSidebar embedded />
|
||||
</Sidebar>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden bg-background text-foreground isolate">
|
||||
<DiffWorkerPoolProvider>
|
||||
<Outlet />
|
||||
</DiffWorkerPoolProvider>
|
||||
</SidebarInset>
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/_chat")({
|
||||
component: ChatRouteLayout,
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+580
-23
@@ -4,11 +4,28 @@ import {
|
||||
createContext,
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import { type ProviderSession, normalizeProjectScripts } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import {
|
||||
type ProviderEvent,
|
||||
type ProviderSession,
|
||||
type StateBootstrapResult,
|
||||
type StateBootstrapThread,
|
||||
type StateEvent,
|
||||
type TerminalEvent,
|
||||
normalizeProjectScripts,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
||||
import {
|
||||
applyEventToMessages,
|
||||
asObject,
|
||||
asString,
|
||||
deriveTurnDiffSummaries,
|
||||
inferCheckpointTurnCountByTurnId,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
@@ -24,7 +41,8 @@ import {
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
type Action =
|
||||
| { type: "SET_SERVER_STATE"; state: AppState }
|
||||
| { 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[] }
|
||||
@@ -39,6 +57,13 @@ 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: "APPLY_EVENT";
|
||||
event: ProviderEvent;
|
||||
activeAssistantItemRef: { current: string | null };
|
||||
activeThreadId?: string | null;
|
||||
}
|
||||
| { type: "APPLY_TERMINAL_EVENT"; event: TerminalEvent }
|
||||
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
|
||||
| {
|
||||
type: "PUSH_USER_MESSAGE";
|
||||
@@ -82,6 +107,8 @@ export interface AppState {
|
||||
runtimeMode: RuntimeMode;
|
||||
}
|
||||
|
||||
const RUNTIME_MODE_STORAGE_KEY = "t3code:runtime-mode";
|
||||
|
||||
const initialState: AppState = {
|
||||
projects: [],
|
||||
threads: [],
|
||||
@@ -92,11 +119,31 @@ const initialState: AppState = {
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
function readPersistedState(): AppState {
|
||||
return initialState;
|
||||
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;
|
||||
return {
|
||||
...initialState,
|
||||
runtimeMode,
|
||||
};
|
||||
} catch {
|
||||
return initialState;
|
||||
}
|
||||
}
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
void state;
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(RUNTIME_MODE_STORAGE_KEY, state.runtimeMode);
|
||||
} catch {
|
||||
// Ignore storage failures to avoid breaking chat UX.
|
||||
}
|
||||
}
|
||||
|
||||
function updateThread(
|
||||
@@ -107,6 +154,116 @@ function updateThread(
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
}
|
||||
|
||||
function mergeTurnDiffSummaries(
|
||||
existing: Thread["turnDiffSummaries"],
|
||||
next: Thread["turnDiffSummaries"],
|
||||
): Thread["turnDiffSummaries"] {
|
||||
if (next.length === 0) return existing;
|
||||
|
||||
const existingByTurnId = new Map(existing.map((summary) => [summary.turnId, summary] as const));
|
||||
const merged = next.map((summary) => {
|
||||
const previous = existingByTurnId.get(summary.turnId);
|
||||
if (!previous) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
const files =
|
||||
summary.files.length === 0 && previous.files.length > 0 ? previous.files : summary.files;
|
||||
|
||||
return {
|
||||
...summary,
|
||||
files,
|
||||
...(summary.assistantMessageId
|
||||
? {}
|
||||
: previous.assistantMessageId
|
||||
? { assistantMessageId: previous.assistantMessageId }
|
||||
: {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? {}
|
||||
: typeof previous.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: previous.checkpointTurnCount }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const mergedTurnIds = new Set(merged.map((summary) => summary.turnId));
|
||||
for (const summary of existing) {
|
||||
if (!mergedTurnIds.has(summary.turnId)) {
|
||||
merged.push(summary);
|
||||
}
|
||||
}
|
||||
|
||||
const sorted = merged.toSorted((a, b) => {
|
||||
const aTime = Date.parse(a.completedAt);
|
||||
const bTime = Date.parse(b.completedAt);
|
||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
||||
return b.completedAt.localeCompare(a.completedAt);
|
||||
}
|
||||
return bTime - aTime;
|
||||
});
|
||||
|
||||
const inferredTurnCountByTurnId = inferCheckpointTurnCountByTurnId(sorted);
|
||||
return sorted.map((summary) =>
|
||||
typeof summary.checkpointTurnCount === "number"
|
||||
? summary
|
||||
: Object.assign({}, summary, {
|
||||
checkpointTurnCount: inferredTurnCountByTurnId[summary.turnId],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -127,6 +284,7 @@ function normalizeRunningTerminalIds(
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
@@ -292,31 +450,336 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
});
|
||||
}
|
||||
|
||||
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
|
||||
return threads.find((t) => t.session?.sessionId === sessionId);
|
||||
}
|
||||
|
||||
function getEventTurnId(event: ProviderEvent): string | undefined {
|
||||
if (event.turnId) return event.turnId;
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
return asString(turn?.id);
|
||||
}
|
||||
|
||||
function getEventThreadId(event: ProviderEvent): string | undefined {
|
||||
if (event.threadId) return event.threadId;
|
||||
const payload = asObject(event.payload);
|
||||
const payloadThread = asObject(payload?.thread);
|
||||
const payloadMessage = asObject(payload?.msg);
|
||||
return (
|
||||
asString(payload?.threadId) ??
|
||||
asString(payloadThread?.id) ??
|
||||
asString(payload?.conversationId) ??
|
||||
asString(payload?.thread_id) ??
|
||||
asString(payloadMessage?.thread_id)
|
||||
);
|
||||
}
|
||||
|
||||
function shouldIgnoreForeignThreadEvent(thread: Thread, event: ProviderEvent): boolean {
|
||||
const eventThreadId = getEventThreadId(event);
|
||||
if (!eventThreadId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const expectedThreadId = thread.session?.threadId ?? thread.codexThreadId;
|
||||
if (!expectedThreadId || eventThreadId === expectedThreadId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// During connect, accept a thread/started notification as an identity rebind.
|
||||
if (event.method === "thread/started" && thread.session?.status === "connecting") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function durationMs(startIso: string, endIso: string): number | undefined {
|
||||
const start = Date.parse(startIso);
|
||||
const end = Date.parse(endIso);
|
||||
if (Number.isNaN(start) || Number.isNaN(end) || end < start) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return end - start;
|
||||
}
|
||||
|
||||
function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread> {
|
||||
if (event.method === "turn/started") {
|
||||
return {
|
||||
latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
|
||||
latestTurnStartedAt: event.createdAt,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
const completedTurnId = getEventTurnId(event) ?? thread.latestTurnId;
|
||||
const startedAt =
|
||||
completedTurnId && completedTurnId === thread.latestTurnId
|
||||
? thread.latestTurnStartedAt
|
||||
: undefined;
|
||||
const elapsed =
|
||||
startedAt && startedAt.length > 0 ? durationMs(startedAt, event.createdAt) : undefined;
|
||||
|
||||
return {
|
||||
latestTurnId: completedTurnId ?? thread.latestTurnId,
|
||||
latestTurnCompletedAt: event.createdAt,
|
||||
latestTurnDurationMs: elapsed,
|
||||
};
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
function resetDiffTargetIfMissing(
|
||||
_state: AppState,
|
||||
_threads: Thread[],
|
||||
): Partial<AppState> {
|
||||
return {};
|
||||
}
|
||||
|
||||
// ── Reducer ──────────────────────────────────────────────────────────
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "SET_SERVER_STATE": {
|
||||
const previousThreadById = new Map(
|
||||
state.threads.map((thread) => [thread.id, thread] as const),
|
||||
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 {
|
||||
...action.state,
|
||||
threads: action.state.threads.map((thread) => {
|
||||
const prev = previousThreadById.get(thread.id);
|
||||
if (!prev) return normalizeThreadTerminals(thread);
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalOpen: prev.terminalOpen,
|
||||
terminalHeight: prev.terminalHeight,
|
||||
activeTerminalId: prev.activeTerminalId,
|
||||
terminalGroups: prev.terminalGroups,
|
||||
activeTerminalGroupId: prev.activeTerminalGroupId,
|
||||
});
|
||||
}),
|
||||
...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;
|
||||
@@ -422,6 +885,15 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
|
||||
turnDiffSummaries: action.thread.turnDiffSummaries ?? [],
|
||||
});
|
||||
const existingIndex = state.threads.findIndex((thread) => thread.id === nextThread.id);
|
||||
if (existingIndex >= 0) {
|
||||
const nextThreads = [...state.threads];
|
||||
nextThreads[existingIndex] = nextThread;
|
||||
return {
|
||||
...state,
|
||||
threads: nextThreads,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: [...state.threads, nextThread],
|
||||
@@ -461,7 +933,10 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
if (
|
||||
isNewTerminal &&
|
||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
||||
) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
@@ -531,7 +1006,10 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
if (
|
||||
isNewTerminal &&
|
||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
||||
) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
@@ -589,6 +1067,81 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
),
|
||||
};
|
||||
|
||||
case "APPLY_TERMINAL_EVENT":
|
||||
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.event.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
|
||||
if (action.event.type === "started" || action.event.type === "restarted") {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
} else if (action.event.type === "activity") {
|
||||
if (action.event.hasRunningSubprocess) {
|
||||
runningTerminalIdSet.add(action.event.terminalId);
|
||||
} else {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
}
|
||||
} else if (action.event.type === "exited" || action.event.type === "error") {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
}
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
runningTerminalIds: [...runningTerminalIdSet],
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "APPLY_EVENT": {
|
||||
const { event, activeAssistantItemRef, activeThreadId } = action;
|
||||
const target = findThreadBySessionId(state.threads, event.sessionId);
|
||||
if (!target) return state;
|
||||
if (shouldIgnoreForeignThreadEvent(target, event)) return state;
|
||||
|
||||
return {
|
||||
...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);
|
||||
const turnDiffSummaries = shouldRederiveDiffs
|
||||
? mergeTurnDiffSummaries(t.turnDiffSummaries, deriveTurnDiffSummaries(nextEvents))
|
||||
: t.turnDiffSummaries;
|
||||
const eventThreadId = getEventThreadId(event);
|
||||
const shouldRebindIdentity =
|
||||
event.method === "thread/started" && t.session?.status === "connecting";
|
||||
return {
|
||||
...t,
|
||||
codexThreadId: shouldRebindIdentity
|
||||
? (eventThreadId ?? t.codexThreadId)
|
||||
: (t.codexThreadId ?? eventThreadId ?? null),
|
||||
error: event.kind === "error" && event.message ? event.message : t.error,
|
||||
session: t.session ? evolveSession(t.session, event) : t.session,
|
||||
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
|
||||
events: nextEvents,
|
||||
turnDiffSummaries,
|
||||
...updateTurnFields(t, event),
|
||||
...(event.method === "turn/completed" && t.id === activeThreadId
|
||||
? { lastVisitedAt: event.createdAt }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "UPDATE_SESSION":
|
||||
return {
|
||||
...state,
|
||||
@@ -775,6 +1328,10 @@ const StoreContext = createContext<{
|
||||
export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
|
||||
|
||||
useEffect(() => {
|
||||
persistState(state);
|
||||
}, [state.runtimeMode]);
|
||||
|
||||
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
|
||||
}
|
||||
|
||||
|
||||
+23
-34
@@ -5,9 +5,7 @@ import { WsTransport } from "./wsTransport";
|
||||
|
||||
let instance: { api: NativeApi; transport: WsTransport } | null = null;
|
||||
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
|
||||
const stateListeners = new Set<(state: unknown) => void>();
|
||||
let lastWelcome: WsWelcomePayload | null = null;
|
||||
let lastStateSnapshot: unknown = null;
|
||||
|
||||
/**
|
||||
* Subscribe to the server welcome message. If a welcome was already received
|
||||
@@ -31,20 +29,6 @@ export function onServerWelcome(listener: (payload: WsWelcomePayload) => void):
|
||||
};
|
||||
}
|
||||
|
||||
export function onServerStateUpdate(listener: (state: unknown) => void): () => void {
|
||||
stateListeners.add(listener);
|
||||
if (lastStateSnapshot) {
|
||||
try {
|
||||
listener(lastStateSnapshot);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
stateListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function createWsNativeApi(): NativeApi {
|
||||
if (instance) return instance.api;
|
||||
|
||||
@@ -63,16 +47,6 @@ export function createWsNativeApi(): NativeApi {
|
||||
}
|
||||
}
|
||||
});
|
||||
transport.subscribe(WS_CHANNELS.stateUpdated, (data) => {
|
||||
lastStateSnapshot = data;
|
||||
for (const listener of stateListeners) {
|
||||
try {
|
||||
listener(data);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const api: NativeApi = {
|
||||
todos: {
|
||||
@@ -121,7 +95,29 @@ export function createWsNativeApi(): NativeApi {
|
||||
getCheckpointDiff: (input) => transport.request(WS_METHODS.providersGetCheckpointDiff, input),
|
||||
revertToCheckpoint: (input) =>
|
||||
transport.request(WS_METHODS.providersRevertToCheckpoint, input),
|
||||
onEvent: () => () => {},
|
||||
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),
|
||||
@@ -174,13 +170,6 @@ export function createWsNativeApi(): NativeApi {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
||||
},
|
||||
state: {
|
||||
getSnapshot: () => transport.request(WS_METHODS.stateGetSnapshot),
|
||||
createThread: (input) => transport.request(WS_METHODS.stateCreateThread, input),
|
||||
deleteThread: (input) => transport.request(WS_METHODS.stateDeleteThread, input),
|
||||
markThreadVisited: (input) => transport.request(WS_METHODS.stateMarkThreadVisited, input),
|
||||
setRuntimeMode: (input) => transport.request(WS_METHODS.stateSetRuntimeMode, input),
|
||||
},
|
||||
};
|
||||
|
||||
instance = { api, transport };
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { appendTokenFromPageUrl, resolveWsUrl } from "./wsTransport";
|
||||
|
||||
describe("resolveWsUrl", () => {
|
||||
it("prefers explicit url when provided", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
explicitUrl: "ws://explicit.example:3773/socket",
|
||||
bridgeUrl: "ws://bridge.example:3773",
|
||||
envUrl: "ws://env.example:3773",
|
||||
pageUrl: "http://device.local:3773/?token=abc",
|
||||
pageProtocol: "http:",
|
||||
pageHostname: "device.local",
|
||||
pagePort: "3773",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("ws://explicit.example:3773/socket");
|
||||
});
|
||||
|
||||
it("prefers desktop bridge url over env url", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
bridgeUrl: "ws://bridge.example:3773",
|
||||
envUrl: "ws://env.example:3773",
|
||||
pageUrl: "http://device.local:3773/",
|
||||
pageProtocol: "http:",
|
||||
pageHostname: "device.local",
|
||||
pagePort: "3773",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("ws://bridge.example:3773");
|
||||
});
|
||||
|
||||
it("falls back to env url when bridge url is missing", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
envUrl: "ws://env.example:3773/path",
|
||||
pageUrl: "http://device.local:3773/",
|
||||
pageProtocol: "http:",
|
||||
pageHostname: "device.local",
|
||||
pagePort: "3773",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("ws://env.example:3773/path");
|
||||
});
|
||||
|
||||
it("derives wss url from https page when no explicit, bridge, or env url exists", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
pageUrl: "https://tailnet-host.ts.net/",
|
||||
pageProtocol: "https:",
|
||||
pageHostname: "tailnet-host.ts.net",
|
||||
pagePort: "",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("wss://tailnet-host.ts.net");
|
||||
});
|
||||
|
||||
it("adds token from page url when missing on websocket url", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
envUrl: "ws://tailnet-host.ts.net:3773",
|
||||
pageUrl: "http://tailnet-host.ts.net:3773/?token=super-secret",
|
||||
pageProtocol: "http:",
|
||||
pageHostname: "tailnet-host.ts.net",
|
||||
pagePort: "3773",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("ws://tailnet-host.ts.net:3773/?token=super-secret");
|
||||
});
|
||||
|
||||
it("does not overwrite existing websocket token", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
envUrl: "ws://tailnet-host.ts.net:3773/?token=already-set",
|
||||
pageUrl: "http://tailnet-host.ts.net:3773/?token=super-secret",
|
||||
pageProtocol: "http:",
|
||||
pageHostname: "tailnet-host.ts.net",
|
||||
pagePort: "3773",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("ws://tailnet-host.ts.net:3773/?token=already-set");
|
||||
});
|
||||
});
|
||||
|
||||
describe("appendTokenFromPageUrl", () => {
|
||||
it("returns original url for invalid page urls", () => {
|
||||
expect(appendTokenFromPageUrl("ws://localhost:3773", "not-a-url")).toBe("ws://localhost:3773");
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,56 @@ interface PendingRequest {
|
||||
const REQUEST_TIMEOUT_MS = 60_000;
|
||||
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
|
||||
|
||||
interface WsUrlResolutionInput {
|
||||
explicitUrl?: string;
|
||||
bridgeUrl?: string | null;
|
||||
envUrl?: string;
|
||||
pageUrl: string;
|
||||
pageProtocol: string;
|
||||
pageHostname: string;
|
||||
pagePort: string;
|
||||
}
|
||||
|
||||
function normalizeUrl(value: string | null | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function defaultWsUrlForPage(protocol: string, hostname: string, port: string): string {
|
||||
const wsProtocol = protocol === "https:" ? "wss" : "ws";
|
||||
const authority = port.length > 0 ? `${hostname}:${port}` : hostname;
|
||||
return `${wsProtocol}://${authority}`;
|
||||
}
|
||||
|
||||
export function appendTokenFromPageUrl(wsUrl: string, pageUrl: string): string {
|
||||
try {
|
||||
const page = new URL(pageUrl);
|
||||
const token = page.searchParams.get("token")?.trim();
|
||||
if (!token) return wsUrl;
|
||||
|
||||
const resolvedWsUrl = new URL(wsUrl, page.origin);
|
||||
if (!resolvedWsUrl.searchParams.has("token")) {
|
||||
resolvedWsUrl.searchParams.set("token", token);
|
||||
}
|
||||
return resolvedWsUrl.toString();
|
||||
} catch {
|
||||
return wsUrl;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveWsUrl(input: WsUrlResolutionInput): string {
|
||||
const explicitUrl = normalizeUrl(input.explicitUrl);
|
||||
if (explicitUrl) return explicitUrl;
|
||||
|
||||
const baseUrl =
|
||||
normalizeUrl(input.bridgeUrl) ??
|
||||
normalizeUrl(input.envUrl) ??
|
||||
defaultWsUrlForPage(input.pageProtocol, input.pageHostname, input.pagePort);
|
||||
|
||||
return appendTokenFromPageUrl(baseUrl, input.pageUrl);
|
||||
}
|
||||
|
||||
export class WsTransport {
|
||||
private ws: WebSocket | null = null;
|
||||
private nextId = 1;
|
||||
@@ -26,13 +76,15 @@ export class WsTransport {
|
||||
// In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.
|
||||
// In production, the page is served by the WS server on the same host:port.
|
||||
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
this.url =
|
||||
url ??
|
||||
(bridgeUrl && bridgeUrl.length > 0
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `ws://${window.location.hostname}:${window.location.port}`);
|
||||
this.url = resolveWsUrl({
|
||||
explicitUrl: url,
|
||||
bridgeUrl,
|
||||
envUrl,
|
||||
pageUrl: window.location.href,
|
||||
pageProtocol: window.location.protocol,
|
||||
pageHostname: window.location.hostname,
|
||||
pagePort: window.location.port,
|
||||
});
|
||||
this.connect();
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import { tanstackRouter } from "@tanstack/router-plugin/vite";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
const port = Number(process.env.PORT ?? 5173);
|
||||
const devServerHost = process.env.VITE_DEV_SERVER_HOST ?? "localhost";
|
||||
const hmrHost = process.env.VITE_HMR_HOST ?? "localhost";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
@@ -29,6 +31,7 @@ export default defineConfig({
|
||||
tsconfigPaths: true,
|
||||
},
|
||||
server: {
|
||||
host: devServerHost,
|
||||
port,
|
||||
strictPort: true,
|
||||
hmr: {
|
||||
@@ -36,7 +39,7 @@ export default defineConfig({
|
||||
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
|
||||
// connection logs — enable "Verbose" in DevTools to see them.
|
||||
protocol: "ws",
|
||||
host: "localhost",
|
||||
host: hmrHost,
|
||||
},
|
||||
},
|
||||
build: {
|
||||
|
||||
@@ -34,9 +34,7 @@
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/core": "workspace:*",
|
||||
"@t3tools/infra-sqlite": "workspace:*",
|
||||
"effect": "^3.18.4",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0",
|
||||
@@ -97,33 +95,6 @@
|
||||
"typescript": "^5.7.3",
|
||||
},
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@t3tools/core",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"effect": "^3.18.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
},
|
||||
"packages/infra-sqlite": {
|
||||
"name": "@t3tools/infra-sqlite",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@effect/sql": "^0.49.0",
|
||||
"@effect/sql-sqlite-node": "^0.50.1",
|
||||
"@t3tools/core": "workspace:*",
|
||||
"effect": "^3.18.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
|
||||
@@ -174,14 +145,6 @@
|
||||
|
||||
"@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.28.6", "@floating-ui/utils": "^0.2.10", "reselect": "^5.1.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-oYC7w0gp76RI5MxprlGLV0wze0SErZaRl3AAkeP3OnNB/UBMb6RqNf6ZSIlxOc9Qp68Ab3C2VOcJQyRs7Xc7Vw=="],
|
||||
|
||||
"@effect/experimental": ["@effect/[email protected]", "", { "dependencies": { "uuid": "^11.0.3" }, "peerDependencies": { "@effect/platform": "^0.94.0", "effect": "^3.19.13", "ioredis": "^5", "lmdb": "^3" }, "optionalPeers": ["ioredis", "lmdb"] }, "sha512-IEP9sapjF6rFy5TkoqDPc86st/fnqUfjT7Xa3pWJrFGr1hzaMXHo+mWsYOZS9LAOVKnpHuVziDK97EP5qsCHVA=="],
|
||||
|
||||
"@effect/platform": ["@effect/[email protected]", "", { "dependencies": { "find-my-way-ts": "^0.1.6", "msgpackr": "^1.11.4", "multipasta": "^0.2.7" }, "peerDependencies": { "effect": "^3.19.17" } }, "sha512-z05APUiDDPbodhTkH/RJqOLoCU11bU2IZLfcwLFrld03+ob1VeqRnELQlmueLIYm6NZifHAtjl32V+GRt34y4A=="],
|
||||
|
||||
"@effect/sql": ["@effect/[email protected]", "", { "dependencies": { "uuid": "^11.0.3" }, "peerDependencies": { "@effect/experimental": "^0.58.0", "@effect/platform": "^0.94.0", "effect": "^3.19.13" } }, "sha512-9UEKR+z+MrI/qMAmSvb/RiD9KlgIazjZUCDSpwNgm0lEK9/Q6ExEyfziiYFVCPiptp52cBw8uBHRic8hHnwqXA=="],
|
||||
|
||||
"@effect/sql-sqlite-node": ["@effect/[email protected]", "", { "dependencies": { "better-sqlite3": "^12.6.2" }, "peerDependencies": { "@effect/experimental": "^0.58.0", "@effect/platform": "^0.94.4", "@effect/sql": "^0.49.0", "effect": "^3.19.16" } }, "sha512-L7DlHcOVl9/9V5stttFyv9wjvA9PBbaXwsp9pU+KN8KqokWgAVBNBEDf/dVfboUrynbDpDWwMU9SJmRJ1LXASQ=="],
|
||||
|
||||
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
|
||||
|
||||
"@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" } }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
|
||||
@@ -282,18 +245,6 @@
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ=="],
|
||||
|
||||
"@mswjs/interceptors": ["@mswjs/[email protected]", "", { "dependencies": { "@open-draft/deferred-promise": "^2.2.0", "@open-draft/logger": "^0.3.0", "@open-draft/until": "^2.0.0", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "strict-event-emitter": "^0.5.1" } }, "sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA=="],
|
||||
|
||||
"@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1", "@tybys/wasm-util": "^0.10.1" } }, "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A=="],
|
||||
@@ -468,12 +419,8 @@
|
||||
|
||||
"@t3tools/contracts": ["@t3tools/contracts@workspace:packages/contracts"],
|
||||
|
||||
"@t3tools/core": ["@t3tools/core@workspace:packages/core"],
|
||||
|
||||
"@t3tools/desktop": ["@t3tools/desktop@workspace:apps/desktop"],
|
||||
|
||||
"@t3tools/infra-sqlite": ["@t3tools/infra-sqlite@workspace:packages/infra-sqlite"],
|
||||
|
||||
"@t3tools/web": ["@t3tools/web@workspace:apps/web"],
|
||||
|
||||
"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "enhanced-resolve": "^5.18.3", "jiti": "^2.6.1", "lightningcss": "1.30.2", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.1.18" } }, "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ=="],
|
||||
@@ -572,7 +519,7 @@
|
||||
|
||||
"@types/ms": ["@types/[email protected]", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
|
||||
|
||||
"@types/node": ["@types/node@25.3.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A=="],
|
||||
"@types/node": ["@types/node@22.19.11", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="],
|
||||
|
||||
@@ -636,28 +583,18 @@
|
||||
|
||||
"bail": ["[email protected]", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
|
||||
|
||||
"base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
|
||||
|
||||
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg=="],
|
||||
|
||||
"better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-8VYKM3MjCa9WcaSAI3hzwhmyHVlH8tiGFwf0RlTsZPWJ1I5MkzjiudCo4KC4DxOaL/53A5B1sI/IbldNFDbsKA=="],
|
||||
|
||||
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
|
||||
|
||||
"bindings": ["[email protected]", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="],
|
||||
|
||||
"birpc": ["[email protected]", "", {}, "sha512-LShSxJP0KTmd101b6DRyGBj57LZxSDYWKitQNW/mi8GRMvZb078Uf9+pveax1DrVL89vm7mWe+TovdI/UDOuPw=="],
|
||||
|
||||
"bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
|
||||
|
||||
"boolean": ["[email protected]", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
|
||||
|
||||
"braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
|
||||
|
||||
"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA=="],
|
||||
|
||||
"buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
|
||||
|
||||
"buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
@@ -688,8 +625,6 @@
|
||||
|
||||
"chokidar": ["[email protected]", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="],
|
||||
|
||||
"chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
|
||||
|
||||
"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
|
||||
|
||||
"cli-width": ["[email protected]", "", {}, "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ=="],
|
||||
@@ -722,8 +657,6 @@
|
||||
|
||||
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
|
||||
|
||||
"deep-extend": ["[email protected]", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="],
|
||||
|
||||
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
|
||||
|
||||
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
|
||||
@@ -754,8 +687,6 @@
|
||||
|
||||
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
"effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "fast-check": "^3.23.1" } }, "sha512-Yc8U/SVXo2dHnaP7zNBlAo83h/nzSJpi7vph6Hzyl4ulgMBIgPmz3UzOjb9sBgpFE00gC0iETR244sfXDNLHRg=="],
|
||||
|
||||
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
|
||||
|
||||
"electron-to-chromium": ["[email protected]", "", {}, "sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A=="],
|
||||
@@ -796,32 +727,22 @@
|
||||
|
||||
"estree-walker": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],
|
||||
|
||||
"expand-template": ["[email protected]", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
|
||||
|
||||
"expect-type": ["[email protected]", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],
|
||||
|
||||
"extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
|
||||
|
||||
"extract-zip": ["[email protected]", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="],
|
||||
|
||||
"fast-check": ["[email protected]", "", { "dependencies": { "pure-rand": "^6.1.0" } }, "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A=="],
|
||||
|
||||
"fd-slicer": ["[email protected]", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="],
|
||||
|
||||
"fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
||||
|
||||
"file-uri-to-path": ["[email protected]", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="],
|
||||
|
||||
"fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
|
||||
|
||||
"find-my-way-ts": ["[email protected]", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="],
|
||||
|
||||
"follow-redirects": ["[email protected]", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="],
|
||||
|
||||
"form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
|
||||
|
||||
"fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
|
||||
|
||||
"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
|
||||
|
||||
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
@@ -840,8 +761,6 @@
|
||||
|
||||
"get-tsconfig": ["[email protected]", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="],
|
||||
|
||||
"github-from-package": ["[email protected]", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
|
||||
|
||||
"glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
"global-agent": ["[email protected]", "", { "dependencies": { "boolean": "^3.0.1", "es6-error": "^4.1.1", "matcher": "^3.0.0", "roarr": "^2.15.3", "semver": "^7.3.2", "serialize-error": "^7.0.1" } }, "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q=="],
|
||||
@@ -890,16 +809,10 @@
|
||||
|
||||
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
|
||||
|
||||
"ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
|
||||
|
||||
"import-from": ["[email protected]", "", { "dependencies": { "resolve-from": "^5.0.0" } }, "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ=="],
|
||||
|
||||
"import-without-cache": ["[email protected]", "", {}, "sha512-B6Lc2s6yApwnD2/pMzFh/d5AVjdsDXjgkeJ766FmFuJELIGHNycKRj+l3A39yZPM4CchqNCB4RITEAYB1KUM6A=="],
|
||||
|
||||
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
|
||||
|
||||
"ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
|
||||
|
||||
"inline-style-parser": ["[email protected]", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
|
||||
|
||||
"is-alphabetical": ["[email protected]", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
|
||||
@@ -1094,30 +1007,16 @@
|
||||
|
||||
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
|
||||
|
||||
"mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
|
||||
|
||||
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"msgpackr": ["[email protected]", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
|
||||
|
||||
"msgpackr-extract": ["[email protected]", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA=="],
|
||||
|
||||
"msw": ["[email protected]", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-G3VUymSE0/iegFnuipujpwyTM2GuZAKXNeerUSrG2+Eg391wW63xFs5ixWsK9MWzr1AGoSkYGmyAzNgbR3+urw=="],
|
||||
|
||||
"multipasta": ["[email protected]", "", {}, "sha512-KPA58d68KgGil15oDqXjkUBEBYc00XvbPj5/X+dyzeo/lWm9Nc25pQRlf1D+gv4OpK7NM0J1odrbu9JNNGvynA=="],
|
||||
|
||||
"mute-stream": ["[email protected]", "", {}, "sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA=="],
|
||||
|
||||
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
|
||||
|
||||
"napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
|
||||
|
||||
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-+CGM1L1CgmtheLcBuleyYOn7NWPVu0s0EJH2C4puxgEZb9h8QpR9G2dBfZJOAUhi7VQxuBPMd0hiISWcTyiYyQ=="],
|
||||
|
||||
"node-addon-api": ["[email protected]", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
|
||||
|
||||
"node-gyp-build-optional-packages": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="],
|
||||
|
||||
"node-pty": ["[email protected]", "", { "dependencies": { "node-addon-api": "^7.1.0" } }, "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg=="],
|
||||
|
||||
"node-releases": ["[email protected]", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="],
|
||||
@@ -1162,8 +1061,6 @@
|
||||
|
||||
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
|
||||
|
||||
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
|
||||
|
||||
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
|
||||
|
||||
"progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
|
||||
@@ -1174,14 +1071,10 @@
|
||||
|
||||
"pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA=="],
|
||||
|
||||
"pure-rand": ["[email protected]", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
|
||||
|
||||
"quansync": ["[email protected]", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="],
|
||||
|
||||
"quick-lru": ["[email protected]", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="],
|
||||
|
||||
"rc": ["[email protected]", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
|
||||
|
||||
"react": ["[email protected]", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
|
||||
|
||||
"react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
|
||||
@@ -1190,8 +1083,6 @@
|
||||
|
||||
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
|
||||
|
||||
"readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
|
||||
|
||||
"readdirp": ["[email protected]", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
|
||||
|
||||
"recast": ["[email protected]", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA=="],
|
||||
@@ -1242,8 +1133,6 @@
|
||||
|
||||
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
|
||||
|
||||
"safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
|
||||
|
||||
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
|
||||
|
||||
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
|
||||
@@ -1262,10 +1151,6 @@
|
||||
|
||||
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
"simple-concat": ["[email protected]", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
|
||||
|
||||
"simple-get": ["[email protected]", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
|
||||
|
||||
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
|
||||
|
||||
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
@@ -1284,14 +1169,10 @@
|
||||
|
||||
"string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
|
||||
|
||||
"string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
|
||||
|
||||
"stringify-entities": ["[email protected]", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
|
||||
|
||||
"strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
|
||||
|
||||
"strip-json-comments": ["[email protected]", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
|
||||
|
||||
"style-to-js": ["[email protected]", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
|
||||
|
||||
"style-to-object": ["[email protected]", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="],
|
||||
@@ -1312,10 +1193,6 @@
|
||||
|
||||
"tapable": ["[email protected]", "", {}, "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg=="],
|
||||
|
||||
"tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ=="],
|
||||
|
||||
"tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
|
||||
|
||||
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
|
||||
|
||||
"tiny-warning": ["[email protected]", "", {}, "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="],
|
||||
@@ -1350,8 +1227,6 @@
|
||||
|
||||
"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
|
||||
|
||||
"tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
|
||||
|
||||
"turbo": ["[email protected]", "", { "optionalDependencies": { "turbo-darwin-64": "2.8.7", "turbo-darwin-arm64": "2.8.7", "turbo-linux-64": "2.8.7", "turbo-linux-arm64": "2.8.7", "turbo-windows-64": "2.8.7", "turbo-windows-arm64": "2.8.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-RBLh5caMAu1kFdTK1jgH2gH/z+jFsvX5rGbhgJ9nlIAWXSvxlzwId05uDlBA1+pBd3wO/UaKYzaQZQBXDd7kcA=="],
|
||||
|
||||
"turbo-darwin-64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Xr4TO/oDDwoozbDtBvunb66g//WK8uHRygl72vUthuwzmiw48pil4IuoG/QbMHd9RE8aBnVmzC0WZEWk/WWt3A=="],
|
||||
@@ -1372,7 +1247,7 @@
|
||||
|
||||
"unconfig-core": ["[email protected]", "", { "dependencies": { "@quansync/fs": "^1.0.0", "quansync": "^1.0.0" } }, "sha512-VgPCvLWugINbXvMQDf8Jh0mlbvNjNC6eSUziHsBCMpxR05OPrNrvDnyatdMjRgcHaaNsCqz+wjNXxNw1kRLHUg=="],
|
||||
|
||||
"undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
|
||||
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
|
||||
|
||||
@@ -1402,10 +1277,6 @@
|
||||
|
||||
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
|
||||
|
||||
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
||||
|
||||
"uuid": ["[email protected]", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A=="],
|
||||
|
||||
"vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
|
||||
|
||||
"vfile-message": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
|
||||
@@ -1472,8 +1343,6 @@
|
||||
|
||||
"@electron/get/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@t3tools/desktop/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.30.2", "lightningcss-darwin-arm64": "1.30.2", "lightningcss-darwin-x64": "1.30.2", "lightningcss-freebsd-x64": "1.30.2", "lightningcss-linux-arm-gnueabihf": "1.30.2", "lightningcss-linux-arm64-gnu": "1.30.2", "lightningcss-linux-arm64-musl": "1.30.2", "lightningcss-linux-x64-gnu": "1.30.2", "lightningcss-linux-x64-musl": "1.30.2", "lightningcss-win32-arm64-msvc": "1.30.2", "lightningcss-win32-x64-msvc": "1.30.2" } }, "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ=="],
|
||||
|
||||
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" }, "bundled": true }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
|
||||
@@ -1498,16 +1367,6 @@
|
||||
|
||||
"@types/babel__template/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
|
||||
|
||||
"@types/cacheable-request/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/keyv/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/responselike/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/ws/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/yauzl/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@vitejs/plugin-react/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
|
||||
|
||||
"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
@@ -1534,8 +1393,6 @@
|
||||
|
||||
"serialize-error/type-fest": ["[email protected]", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
|
||||
|
||||
"t3/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"unixify/normalize-path": ["[email protected]", "", { "dependencies": { "remove-trailing-separator": "^1.0.1" } }, "sha512-3pKJwH184Xo/lnH6oyP1q2pMd7HcypqqmRs91/6/i2CGtWwIKGCkOOMTm/zXbgTEWHw1uNpNi/igc3ePOYHb6w=="],
|
||||
|
||||
"vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
|
||||
@@ -1544,8 +1401,6 @@
|
||||
|
||||
"@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
|
||||
"@t3tools/desktop/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA=="],
|
||||
@@ -1568,20 +1423,8 @@
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
|
||||
|
||||
"@types/cacheable-request/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/keyv/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/responselike/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/ws/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/yauzl/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"electron/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
|
||||
"t3/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
# Remote Access Guide (Server on Computer, Client on Phone)
|
||||
|
||||
This guide explains how to run T3 Code on one machine and control it from another device (for example, your phone) over a private network like Tailscale.
|
||||
|
||||
## Goal
|
||||
|
||||
- Run the `apps/server` process on your computer.
|
||||
- Open the web client from another device.
|
||||
- Keep Codex running on the computer while controlling it remotely.
|
||||
|
||||
## Architecture
|
||||
|
||||
T3 Code is already split into backend and frontend roles:
|
||||
|
||||
- Backend (`apps/server`):
|
||||
- Runs on your computer.
|
||||
- Hosts HTTP pages + static assets.
|
||||
- Hosts the WebSocket API.
|
||||
- Spawns and manages Codex app-server sessions.
|
||||
- Reads/writes local state and your local workspace files.
|
||||
- Frontend (`apps/web`):
|
||||
- Runs in the browser on any device.
|
||||
- Connects to backend over WebSocket.
|
||||
- Renders thread state and sends commands.
|
||||
|
||||
Data path:
|
||||
|
||||
1. Phone browser opens `http://<computer-tailnet-host>:<port>`.
|
||||
2. Browser loads the T3 web app from that server.
|
||||
3. Web app opens a WebSocket to the same server.
|
||||
4. Server executes provider/terminal/git/file actions on the computer.
|
||||
5. Server streams updates back to the phone.
|
||||
|
||||
Important: your phone never runs Codex itself. The agent process stays on the computer.
|
||||
|
||||
## Security Model
|
||||
|
||||
- Recommended network boundary: Tailscale tailnet ACLs.
|
||||
- Optional app-layer auth: set `T3CODE_AUTH_TOKEN` on server start.
|
||||
- When `T3CODE_AUTH_TOKEN` is enabled, open the UI with `?token=<token>` in the URL so the browser can authenticate WebSocket requests.
|
||||
|
||||
Example:
|
||||
|
||||
`http://my-macbook.tailnet-name.ts.net:3773/?token=<your-token>`
|
||||
|
||||
## Recommended Setup (Production Build)
|
||||
|
||||
Use this for reliable "control from phone while away from home".
|
||||
|
||||
### 1. Prepare computer
|
||||
|
||||
- Ensure Codex CLI is installed and authenticated on the computer.
|
||||
- Ensure Tailscale is connected on the computer.
|
||||
- Build the app:
|
||||
|
||||
```bash
|
||||
bun run build
|
||||
```
|
||||
|
||||
### 2. Start server
|
||||
|
||||
- Choose a port (default is `3773`).
|
||||
- Create an auth token (recommended).
|
||||
|
||||
```bash
|
||||
export T3CODE_PORT=3773
|
||||
export T3CODE_NO_BROWSER=1
|
||||
export T3CODE_AUTH_TOKEN="$(openssl rand -hex 24)"
|
||||
bun run start
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `T3CODE_NO_BROWSER=1` avoids auto-opening a local browser tab.
|
||||
- Without `T3CODE_AUTH_TOKEN`, anyone with network reachability to your server can open a session.
|
||||
|
||||
### 3. Find Tailscale address of computer
|
||||
|
||||
```bash
|
||||
tailscale ip -4
|
||||
```
|
||||
|
||||
Or use MagicDNS hostname (for example `my-macbook.tailnet-name.ts.net`).
|
||||
|
||||
### 4. Open from phone
|
||||
|
||||
- Ensure your phone is connected to the same Tailscale tailnet.
|
||||
- In phone browser, open:
|
||||
|
||||
```text
|
||||
http://<tailscale-host-or-ip>:3773/?token=<T3CODE_AUTH_TOKEN>
|
||||
```
|
||||
|
||||
You should now control the agent running on your computer.
|
||||
|
||||
## Remote Dev Setup (Hot Reload)
|
||||
|
||||
This repo now supports remote dev host wiring directly.
|
||||
|
||||
### 1. Pick the public host
|
||||
|
||||
Use the computer's Tailscale hostname or IP as `T3CODE_PUBLIC_HOST`.
|
||||
|
||||
### 2. Run dev mode
|
||||
|
||||
```bash
|
||||
T3CODE_PUBLIC_HOST=my-macbook.tailnet-name.ts.net bun run dev
|
||||
```
|
||||
|
||||
What this config does:
|
||||
|
||||
- Vite dev server is reachable off-machine (`0.0.0.0` bind).
|
||||
- Server redirects to the public dev URL instead of localhost.
|
||||
- WebSocket target uses the same public host instead of localhost.
|
||||
- HMR uses the public host for browser reconnects.
|
||||
|
||||
If you also use auth token in dev:
|
||||
|
||||
1. set `T3CODE_AUTH_TOKEN=...` before running `bun run dev`
|
||||
2. open `http://<host>:<web-port>/?token=<token>`
|
||||
|
||||
## Operational Tips
|
||||
|
||||
- Keep the server process running in `tmux`, `screen`, or a service manager.
|
||||
- Use a long, random auth token.
|
||||
- Restrict tailnet access using Tailscale ACLs to only your user/devices.
|
||||
- Prefer production build for lower moving parts when remote.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- Page loads but no data:
|
||||
- Most likely missing/incorrect `?token=` when `T3CODE_AUTH_TOKEN` is set.
|
||||
- Phone cannot reach host:
|
||||
- Verify both devices are connected to Tailscale and can ping each other.
|
||||
- Dev mode opens localhost URL:
|
||||
- Ensure `T3CODE_PUBLIC_HOST` is set before `bun run dev`.
|
||||
- Live reload not working in remote dev:
|
||||
- Ensure `T3CODE_PUBLIC_HOST` resolves on the phone and no conflicting port overrides are set.
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { appSettingsSchema, appSettingsUpdateInputSchema } from "./appSettings";
|
||||
|
||||
describe("appSettings schemas", () => {
|
||||
it("applies defaults for codex paths", () => {
|
||||
expect(appSettingsSchema.parse({})).toEqual({
|
||||
codexBinaryPath: "",
|
||||
codexHomePath: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("trims codex path overrides in updates", () => {
|
||||
expect(
|
||||
appSettingsUpdateInputSchema.parse({
|
||||
codexBinaryPath: " /opt/codex/bin/codex ",
|
||||
codexHomePath: " /Users/alice/.codex ",
|
||||
}),
|
||||
).toEqual({
|
||||
codexBinaryPath: "/opt/codex/bin/codex",
|
||||
codexHomePath: "/Users/alice/.codex",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const appSettingsSchema = z.object({
|
||||
codexBinaryPath: z.string().trim().max(4096).default(""),
|
||||
codexHomePath: z.string().trim().max(4096).default(""),
|
||||
});
|
||||
|
||||
export const appSettingsUpdateInputSchema = z.object({
|
||||
codexBinaryPath: z.string().trim().max(4096).optional(),
|
||||
codexHomePath: z.string().trim().max(4096).optional(),
|
||||
});
|
||||
|
||||
export type AppSettings = z.infer<typeof appSettingsSchema>;
|
||||
export type AppSettingsUpdateInput = z.input<typeof appSettingsUpdateInputSchema>;
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from "./todo";
|
||||
export * from "./appSettings";
|
||||
export * from "./ipc";
|
||||
export * from "./agent";
|
||||
export * from "./terminal";
|
||||
@@ -9,3 +10,4 @@ export * from "./keybindings";
|
||||
export * from "./server";
|
||||
export * from "./project";
|
||||
export * from "./git";
|
||||
export * from "./state";
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AgentConfig, AgentExit, OutputChunk } from "./agent";
|
||||
import type { AppSettings, AppSettingsUpdateInput } from "./appSettings";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCreateBranchInput,
|
||||
@@ -42,7 +43,22 @@ import type {
|
||||
ProjectUpdateScriptsResult,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
type RuntimeMode = "approval-required" | "full-access";
|
||||
import type {
|
||||
StateBootstrapResult,
|
||||
StateCatchUpInput,
|
||||
StateCatchUpResult,
|
||||
StateEvent,
|
||||
StateListMessagesInput,
|
||||
StateListMessagesResult,
|
||||
ThreadsCreateInput,
|
||||
ThreadsDeleteInput,
|
||||
ThreadsMarkVisitedInput,
|
||||
ThreadsUpdateBranchInput,
|
||||
ThreadsUpdateModelInput,
|
||||
ThreadsUpdateResult,
|
||||
ThreadsUpdateTerminalStateInput,
|
||||
ThreadsUpdateTitleInput,
|
||||
} from "./state";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -107,6 +123,25 @@ export interface NativeApi {
|
||||
) => Promise<ProviderRevertToCheckpointResult>;
|
||||
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
|
||||
};
|
||||
state: {
|
||||
bootstrap: () => Promise<StateBootstrapResult>;
|
||||
listMessages: (input: StateListMessagesInput) => Promise<StateListMessagesResult>;
|
||||
catchUp: (input: StateCatchUpInput) => Promise<StateCatchUpResult>;
|
||||
onEvent: (callback: (event: StateEvent) => void) => () => void;
|
||||
};
|
||||
appSettings: {
|
||||
get: () => Promise<AppSettings>;
|
||||
update: (input: AppSettingsUpdateInput) => Promise<AppSettings>;
|
||||
};
|
||||
threads: {
|
||||
create: (input: ThreadsCreateInput) => Promise<ThreadsUpdateResult>;
|
||||
delete: (input: ThreadsDeleteInput) => Promise<void>;
|
||||
markVisited: (input: ThreadsMarkVisitedInput) => Promise<ThreadsUpdateResult>;
|
||||
updateTerminalState: (input: ThreadsUpdateTerminalStateInput) => Promise<ThreadsUpdateResult>;
|
||||
updateModel: (input: ThreadsUpdateModelInput) => Promise<ThreadsUpdateResult>;
|
||||
updateTitle: (input: ThreadsUpdateTitleInput) => Promise<ThreadsUpdateResult>;
|
||||
updateBranch: (input: ThreadsUpdateBranchInput) => Promise<ThreadsUpdateResult>;
|
||||
};
|
||||
projects: {
|
||||
list: () => Promise<ProjectListResult>;
|
||||
add: (input: ProjectAddInput) => Promise<ProjectAddResult>;
|
||||
@@ -141,19 +176,4 @@ export interface NativeApi {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
||||
};
|
||||
state: {
|
||||
getSnapshot: () => Promise<unknown>;
|
||||
createThread: (input: {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}) => Promise<unknown>;
|
||||
deleteThread: (input: { id: string }) => Promise<unknown>;
|
||||
markThreadVisited: (input: { threadId: string; visitedAt?: string }) => Promise<unknown>;
|
||||
setRuntimeMode: (input: { mode: RuntimeMode }) => Promise<unknown>;
|
||||
};
|
||||
}
|
||||
@@ -25,8 +25,10 @@ describe("providerSessionStartInputSchema", () => {
|
||||
|
||||
it("accepts optional resumeThreadId", () => {
|
||||
const parsed = providerSessionStartInputSchema.parse({
|
||||
threadId: "thread-local-1",
|
||||
resumeThreadId: "thread_123",
|
||||
});
|
||||
expect(parsed.threadId).toBe("thread-local-1");
|
||||
expect(parsed.resumeThreadId).toBe("thread_123");
|
||||
});
|
||||
|
||||
@@ -78,6 +80,8 @@ describe("providerSendTurnInputSchema", () => {
|
||||
it("accepts image-only turns", () => {
|
||||
const parsed = providerSendTurnInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
clientMessageId: "msg_1",
|
||||
clientMessageText: "",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
@@ -89,6 +93,8 @@ describe("providerSendTurnInputSchema", () => {
|
||||
],
|
||||
});
|
||||
expect(parsed.input).toBeUndefined();
|
||||
expect(parsed.clientMessageId).toBe("msg_1");
|
||||
expect(parsed.clientMessageText).toBe("");
|
||||
expect(parsed.attachments).toHaveLength(1);
|
||||
});
|
||||
|
||||
|
||||
@@ -46,8 +46,8 @@ export const providerSessionSchema = z.object({
|
||||
});
|
||||
|
||||
export const providerSessionStartInputSchema = z.object({
|
||||
uiThreadId: z.string().trim().min(1).optional(),
|
||||
provider: providerKindSchema.default("codex"),
|
||||
threadId: z.string().trim().min(1).optional(),
|
||||
cwd: z.string().min(1).optional(),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
resumeThreadId: z.string().trim().min(1).optional(),
|
||||
@@ -81,8 +81,9 @@ export const providerSendTurnAttachmentInputSchema = z.discriminatedUnion("type"
|
||||
|
||||
export const providerSendTurnInputSchema = z
|
||||
.object({
|
||||
uiThreadId: z.string().trim().min(1).optional(),
|
||||
sessionId: z.string().min(1),
|
||||
clientMessageId: z.string().trim().min(1).optional(),
|
||||
clientMessageText: z.string().max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS).optional(),
|
||||
input: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS).optional(),
|
||||
attachments: z
|
||||
.array(providerSendTurnAttachmentInputSchema)
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
stateBootstrapResultSchema,
|
||||
stateCatchUpInputSchema,
|
||||
stateListMessagesInputSchema,
|
||||
stateListMessagesResultSchema,
|
||||
stateMessageSchema,
|
||||
stateThreadSchema,
|
||||
threadsCreateInputSchema,
|
||||
threadsUpdateTerminalStateInputSchema,
|
||||
threadsUpdateTitleInputSchema,
|
||||
} from "./state";
|
||||
|
||||
describe("state schemas", () => {
|
||||
it("applies defaults for state thread records", () => {
|
||||
const parsed = stateThreadSchema.parse({
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
createdAt: "2026-02-19T00:00:00.000Z",
|
||||
updatedAt: "2026-02-19T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(parsed.codexThreadId).toBeNull();
|
||||
expect(parsed.terminalIds).toEqual(["default"]);
|
||||
expect(parsed.activeTerminalId).toBe("default");
|
||||
expect(parsed.turnDiffSummaries).toEqual([]);
|
||||
});
|
||||
|
||||
it("validates bootstrap payloads", () => {
|
||||
const parsed = stateBootstrapResultSchema.parse({
|
||||
projects: [
|
||||
{
|
||||
id: "project-1",
|
||||
cwd: "/repo",
|
||||
name: "repo",
|
||||
scripts: [],
|
||||
createdAt: "2026-02-19T00:00:00.000Z",
|
||||
updatedAt: "2026-02-19T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
createdAt: "2026-02-19T00:00:00.000Z",
|
||||
updatedAt: "2026-02-19T00:00:00.000Z",
|
||||
messages: [],
|
||||
},
|
||||
],
|
||||
lastStateSeq: 12,
|
||||
});
|
||||
|
||||
expect(parsed.lastStateSeq).toBe(12);
|
||||
expect(parsed.threads[0]?.messages).toEqual([]);
|
||||
});
|
||||
|
||||
it("validates message pagination result payloads", () => {
|
||||
const message = stateMessageSchema.parse({
|
||||
id: "msg-1",
|
||||
threadId: "thread-1",
|
||||
role: "assistant",
|
||||
text: "Hello",
|
||||
createdAt: "2026-02-19T00:00:00.000Z",
|
||||
updatedAt: "2026-02-19T00:00:00.000Z",
|
||||
streaming: false,
|
||||
});
|
||||
|
||||
const result = stateListMessagesResultSchema.parse({
|
||||
messages: [message],
|
||||
total: 1,
|
||||
nextOffset: null,
|
||||
});
|
||||
|
||||
expect(result.total).toBe(1);
|
||||
expect(result.nextOffset).toBeNull();
|
||||
});
|
||||
|
||||
it("enforces at least one terminal field on terminal updates", () => {
|
||||
expect(() =>
|
||||
threadsUpdateTerminalStateInputSchema.parse({
|
||||
threadId: "thread-1",
|
||||
}),
|
||||
).toThrow();
|
||||
|
||||
const parsed = threadsUpdateTerminalStateInputSchema.parse({
|
||||
threadId: "thread-1",
|
||||
terminalOpen: true,
|
||||
});
|
||||
expect(parsed.terminalOpen).toBe(true);
|
||||
});
|
||||
|
||||
it("parses thread create/title inputs and state pagination defaults", () => {
|
||||
const created = threadsCreateInputSchema.parse({
|
||||
projectId: "project-1",
|
||||
});
|
||||
expect(created.projectId).toBe("project-1");
|
||||
|
||||
const titled = threadsUpdateTitleInputSchema.parse({
|
||||
threadId: "thread-1",
|
||||
title: "New title",
|
||||
});
|
||||
expect(titled.title).toBe("New title");
|
||||
|
||||
const listInput = stateListMessagesInputSchema.parse({
|
||||
threadId: "thread-1",
|
||||
});
|
||||
expect(listInput.offset).toBe(0);
|
||||
expect(listInput.limit).toBe(200);
|
||||
});
|
||||
|
||||
it("parses state catch-up payloads", () => {
|
||||
const catchUp = stateCatchUpInputSchema.parse({});
|
||||
expect(catchUp.afterSeq).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
import { z } from "zod";
|
||||
import { projectScriptSchema } from "./project";
|
||||
|
||||
export const STATE_DEFAULT_TERMINAL_ID = "default";
|
||||
export const STATE_DEFAULT_TERMINAL_HEIGHT = 280;
|
||||
|
||||
export const stateThreadTerminalGroupSchema = z.object({
|
||||
id: z.string().trim().min(1),
|
||||
terminalIds: z.array(z.string().trim().min(1)).min(1).max(4),
|
||||
});
|
||||
|
||||
export const stateMessageImageAttachmentSchema = z.object({
|
||||
type: z.literal("image"),
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
mimeType: z.string().min(1),
|
||||
sizeBytes: z.number().int().min(1),
|
||||
});
|
||||
|
||||
export const stateMessageAttachmentSchema = z.discriminatedUnion("type", [
|
||||
stateMessageImageAttachmentSchema,
|
||||
]);
|
||||
|
||||
export const stateMessageSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
threadId: z.string().min(1),
|
||||
role: z.enum(["user", "assistant"]),
|
||||
text: z.string(),
|
||||
attachments: z.array(stateMessageAttachmentSchema).optional(),
|
||||
createdAt: z.string().datetime(),
|
||||
updatedAt: z.string().datetime(),
|
||||
streaming: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export const stateTurnDiffFileChangeSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
kind: z.string().min(1).optional(),
|
||||
additions: z.number().int().min(0).optional(),
|
||||
deletions: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
export const stateTurnSummarySchema = z.object({
|
||||
turnId: z.string().min(1),
|
||||
completedAt: z.string().datetime(),
|
||||
status: z.string().min(1).optional(),
|
||||
files: z.array(stateTurnDiffFileChangeSchema).default([]),
|
||||
assistantMessageId: z.string().min(1).optional(),
|
||||
checkpointTurnCount: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
export const stateProjectSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
cwd: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
scripts: z.array(projectScriptSchema).default([]),
|
||||
createdAt: z.string().datetime(),
|
||||
updatedAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const stateThreadSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
codexThreadId: z.string().min(1).nullable().default(null),
|
||||
projectId: z.string().min(1),
|
||||
title: z.string().min(1),
|
||||
model: z.string().min(1),
|
||||
terminalOpen: z.boolean().default(false),
|
||||
terminalHeight: z.number().int().min(120).max(4_096).default(STATE_DEFAULT_TERMINAL_HEIGHT),
|
||||
terminalIds: z
|
||||
.array(z.string().trim().min(1))
|
||||
.max(4)
|
||||
.default([STATE_DEFAULT_TERMINAL_ID]),
|
||||
runningTerminalIds: z.array(z.string().trim().min(1)).max(4).default([]),
|
||||
activeTerminalId: z.string().trim().min(1).default(STATE_DEFAULT_TERMINAL_ID),
|
||||
terminalGroups: z.array(stateThreadTerminalGroupSchema).default([]),
|
||||
activeTerminalGroupId: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.default(`group-${STATE_DEFAULT_TERMINAL_ID}`),
|
||||
createdAt: z.string().datetime(),
|
||||
updatedAt: z.string().datetime(),
|
||||
lastVisitedAt: z.string().datetime().optional(),
|
||||
latestTurnId: z.string().min(1).optional(),
|
||||
latestTurnStartedAt: z.string().datetime().optional(),
|
||||
latestTurnCompletedAt: z.string().datetime().optional(),
|
||||
latestTurnDurationMs: z.number().int().min(0).optional(),
|
||||
branch: z.string().min(1).nullable().default(null),
|
||||
worktreePath: z.string().min(1).nullable().default(null),
|
||||
turnDiffSummaries: z.array(stateTurnSummarySchema).default([]),
|
||||
});
|
||||
|
||||
export const stateBootstrapThreadSchema = stateThreadSchema.extend({
|
||||
messages: z.array(stateMessageSchema).default([]),
|
||||
});
|
||||
|
||||
export const stateBootstrapResultSchema = z.object({
|
||||
projects: z.array(stateProjectSchema),
|
||||
threads: z.array(stateBootstrapThreadSchema),
|
||||
lastStateSeq: z.number().int().min(0),
|
||||
});
|
||||
|
||||
export const stateCatchUpInputSchema = z.object({
|
||||
afterSeq: z.number().int().min(0).default(0),
|
||||
});
|
||||
|
||||
export const stateEventSchema = z.object({
|
||||
seq: z.number().int().positive(),
|
||||
eventType: z.string().min(1),
|
||||
entityId: z.string().min(1),
|
||||
payload: z.unknown(),
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const stateCatchUpResultSchema = z.object({
|
||||
events: z.array(stateEventSchema),
|
||||
lastStateSeq: z.number().int().min(0),
|
||||
});
|
||||
|
||||
export const stateListMessagesInputSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(200),
|
||||
});
|
||||
|
||||
export const stateListMessagesResultSchema = z.object({
|
||||
messages: z.array(stateMessageSchema),
|
||||
total: z.number().int().min(0),
|
||||
nextOffset: z.number().int().min(0).nullable(),
|
||||
});
|
||||
|
||||
export const threadsCreateInputSchema = z.object({
|
||||
projectId: z.string().min(1),
|
||||
title: z.string().trim().min(1).optional(),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
branch: z.string().trim().min(1).nullable().optional(),
|
||||
worktreePath: z.string().trim().min(1).nullable().optional(),
|
||||
terminalOpen: z.boolean().optional(),
|
||||
terminalHeight: z.number().int().min(120).max(4_096).optional(),
|
||||
terminalIds: z.array(z.string().trim().min(1)).max(4).optional(),
|
||||
activeTerminalId: z.string().trim().min(1).optional(),
|
||||
terminalGroups: z.array(stateThreadTerminalGroupSchema).optional(),
|
||||
activeTerminalGroupId: z.string().trim().min(1).optional(),
|
||||
});
|
||||
|
||||
export const threadsUpdateTitleInputSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
title: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
export const threadsUpdateModelInputSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
model: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
export const threadsDeleteInputSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const threadsMarkVisitedInputSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
visitedAt: z.string().datetime().optional(),
|
||||
});
|
||||
|
||||
export const threadsUpdateBranchInputSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
branch: z.string().trim().min(1).nullable(),
|
||||
worktreePath: z.string().trim().min(1).nullable(),
|
||||
});
|
||||
|
||||
export const threadsUpdateTerminalStateInputSchema = z
|
||||
.object({
|
||||
threadId: z.string().min(1),
|
||||
terminalOpen: z.boolean().optional(),
|
||||
terminalHeight: z.number().int().min(120).max(4_096).optional(),
|
||||
terminalIds: z.array(z.string().trim().min(1)).max(4).optional(),
|
||||
runningTerminalIds: z.array(z.string().trim().min(1)).max(4).optional(),
|
||||
activeTerminalId: z.string().trim().min(1).optional(),
|
||||
terminalGroups: z.array(stateThreadTerminalGroupSchema).optional(),
|
||||
activeTerminalGroupId: z.string().trim().min(1).optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
const hasAnyUpdate = Object.keys(value).some((key) => key !== "threadId");
|
||||
if (!hasAnyUpdate) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "At least one terminal field must be provided",
|
||||
path: ["threadId"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const threadsUpdateResultSchema = z.object({
|
||||
thread: stateThreadSchema,
|
||||
});
|
||||
|
||||
export type StateThreadTerminalGroup = z.infer<typeof stateThreadTerminalGroupSchema>;
|
||||
export type StateMessageImageAttachment = z.infer<typeof stateMessageImageAttachmentSchema>;
|
||||
export type StateMessageAttachment = z.infer<typeof stateMessageAttachmentSchema>;
|
||||
export type StateMessage = z.infer<typeof stateMessageSchema>;
|
||||
export type StateTurnDiffFileChange = z.infer<typeof stateTurnDiffFileChangeSchema>;
|
||||
export type StateTurnSummary = z.infer<typeof stateTurnSummarySchema>;
|
||||
export type StateProject = z.infer<typeof stateProjectSchema>;
|
||||
export type StateThread = z.infer<typeof stateThreadSchema>;
|
||||
export type StateBootstrapThread = z.infer<typeof stateBootstrapThreadSchema>;
|
||||
export type StateBootstrapResult = z.infer<typeof stateBootstrapResultSchema>;
|
||||
export type StateCatchUpInput = z.input<typeof stateCatchUpInputSchema>;
|
||||
export type StateEvent = z.infer<typeof stateEventSchema>;
|
||||
export type StateCatchUpResult = z.infer<typeof stateCatchUpResultSchema>;
|
||||
export type StateListMessagesInput = z.input<typeof stateListMessagesInputSchema>;
|
||||
export type StateListMessagesResult = z.infer<typeof stateListMessagesResultSchema>;
|
||||
export type ThreadsCreateInput = z.input<typeof threadsCreateInputSchema>;
|
||||
export type ThreadsUpdateTitleInput = z.input<typeof threadsUpdateTitleInputSchema>;
|
||||
export type ThreadsUpdateModelInput = z.input<typeof threadsUpdateModelInputSchema>;
|
||||
export type ThreadsDeleteInput = z.input<typeof threadsDeleteInputSchema>;
|
||||
export type ThreadsMarkVisitedInput = z.input<typeof threadsMarkVisitedInputSchema>;
|
||||
export type ThreadsUpdateBranchInput = z.input<typeof threadsUpdateBranchInputSchema>;
|
||||
export type ThreadsUpdateTerminalStateInput = z.input<typeof threadsUpdateTerminalStateInputSchema>;
|
||||
export type ThreadsUpdateResult = z.infer<typeof threadsUpdateResultSchema>;
|
||||
@@ -0,0 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { WS_METHODS } from "./ws";
|
||||
|
||||
describe("WS thread methods", () => {
|
||||
it("exposes only canonical terminal state update method", () => {
|
||||
expect(WS_METHODS.threadsUpdateTerminalState).toBe("threads.updateTerminalState");
|
||||
expect("threadsUpdate" in WS_METHODS).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,22 @@ import { z } from "zod";
|
||||
// ── WebSocket RPC Method Names ───────────────────────────────────────
|
||||
|
||||
export const WS_METHODS = {
|
||||
// State methods
|
||||
stateBootstrap: "state.bootstrap",
|
||||
stateListMessages: "state.listMessages",
|
||||
stateCatchUp: "state.catchUp",
|
||||
appSettingsGet: "appSettings.get",
|
||||
appSettingsUpdate: "appSettings.update",
|
||||
|
||||
// Thread methods
|
||||
threadsCreate: "threads.create",
|
||||
threadsDelete: "threads.delete",
|
||||
threadsMarkVisited: "threads.markVisited",
|
||||
threadsUpdateTerminalState: "threads.updateTerminalState",
|
||||
threadsUpdateModel: "threads.updateModel",
|
||||
threadsUpdateTitle: "threads.updateTitle",
|
||||
threadsUpdateBranch: "threads.updateBranch",
|
||||
|
||||
// Provider methods (mirrors NativeApi.providers)
|
||||
providersStartSession: "providers.startSession",
|
||||
providersSendTurn: "providers.sendTurn",
|
||||
@@ -46,22 +62,15 @@ export const WS_METHODS = {
|
||||
// Server meta
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
||||
|
||||
// Server-authoritative state
|
||||
stateGetSnapshot: "state.getSnapshot",
|
||||
stateCreateThread: "state.createThread",
|
||||
stateDeleteThread: "state.deleteThread",
|
||||
stateMarkThreadVisited: "state.markThreadVisited",
|
||||
stateSetRuntimeMode: "state.setRuntimeMode",
|
||||
} as const;
|
||||
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
|
||||
export const WS_CHANNELS = {
|
||||
providerEvent: "providers.event",
|
||||
stateEvent: "state.event",
|
||||
terminalEvent: "terminal.event",
|
||||
serverWelcome: "server.welcome",
|
||||
stateUpdated: "state.updated",
|
||||
} as const;
|
||||
|
||||
// ── Client → Server (request) ────────────────────────────────────────
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@t3tools/core",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"effect": "^3.18.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import type { AnyDomainCommand } from "../domain/commands";
|
||||
import type { NewDomainEvent } from "../domain/events";
|
||||
import type { AppViewState } from "../domain/models";
|
||||
|
||||
function eventFromCommand(
|
||||
command: AnyDomainCommand,
|
||||
eventType: NewDomainEvent["type"],
|
||||
payload: NewDomainEvent["payload"],
|
||||
streamId: string,
|
||||
): NewDomainEvent {
|
||||
return {
|
||||
streamId,
|
||||
type: eventType,
|
||||
payload,
|
||||
occurredAt: command.issuedAt,
|
||||
...(command.id ? { causationId: command.id } : {}),
|
||||
...(command.correlationId ? { correlationId: command.correlationId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function streamIdFromCommand(command: AnyDomainCommand): string {
|
||||
switch (command.type) {
|
||||
case "app.bootstrap":
|
||||
case "runtime.setMode":
|
||||
return "app";
|
||||
case "project.add":
|
||||
case "project.remove":
|
||||
case "project.updateScripts":
|
||||
return `project:${command.payload.id}`;
|
||||
case "thread.create":
|
||||
case "thread.delete":
|
||||
return `thread:${command.payload.id}`;
|
||||
case "thread.addUserMessage":
|
||||
case "thread.updateProviderSession":
|
||||
case "thread.recordProviderEvent":
|
||||
case "thread.setBranch":
|
||||
case "thread.setTerminalActivity":
|
||||
case "thread.markVisited":
|
||||
return `thread:${command.payload.threadId}`;
|
||||
default:
|
||||
return "app";
|
||||
}
|
||||
}
|
||||
|
||||
export function decide(command: AnyDomainCommand, currentState: AppViewState): ReadonlyArray<NewDomainEvent> {
|
||||
switch (command.type) {
|
||||
case "app.bootstrap": {
|
||||
if (currentState.projects.length > 0) return [];
|
||||
return [eventFromCommand(command, "app.bootstrapped", command.payload, streamIdFromCommand(command))];
|
||||
}
|
||||
case "project.add":
|
||||
return [eventFromCommand(command, "project.added", command.payload, streamIdFromCommand(command))];
|
||||
case "project.remove":
|
||||
return [eventFromCommand(command, "project.removed", command.payload, streamIdFromCommand(command))];
|
||||
case "project.updateScripts":
|
||||
return [eventFromCommand(command, "project.scriptsUpdated", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.create":
|
||||
return [eventFromCommand(command, "thread.created", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.delete":
|
||||
return [eventFromCommand(command, "thread.deleted", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.addUserMessage":
|
||||
return [eventFromCommand(command, "thread.userMessageAdded", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.updateProviderSession":
|
||||
return [eventFromCommand(command, "thread.providerSessionUpdated", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.recordProviderEvent":
|
||||
return [eventFromCommand(command, "thread.providerEventRecorded", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.setBranch":
|
||||
return [eventFromCommand(command, "thread.branchSet", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.setTerminalActivity":
|
||||
return [eventFromCommand(command, "thread.terminalActivitySet", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.markVisited":
|
||||
return [eventFromCommand(command, "thread.markVisited", command.payload, streamIdFromCommand(command))];
|
||||
case "runtime.setMode":
|
||||
return [eventFromCommand(command, "runtime.modeSet", command.payload, streamIdFromCommand(command))];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import { emptyAppViewState, type AppViewState } from "../domain/models";
|
||||
import type { AnyDomainCommand } from "../domain/commands";
|
||||
import { decide } from "./decide";
|
||||
import type { EventStorePort, ProjectionStorePort } from "../ports";
|
||||
import { QueueProjector } from "./projector";
|
||||
import { reduceEvents } from "../projections/reducer";
|
||||
|
||||
export class OrchestrationEngine {
|
||||
constructor(
|
||||
private readonly eventStore: EventStorePort,
|
||||
projectionStore: ProjectionStorePort,
|
||||
private readonly projector: QueueProjector,
|
||||
) {
|
||||
this.projectionStore = projectionStore;
|
||||
}
|
||||
|
||||
private readonly projectionStore: ProjectionStorePort;
|
||||
|
||||
async start(): Promise<void> {
|
||||
const state = await this.projectionStore.readState();
|
||||
if (!state) {
|
||||
const allEvents = await this.eventStore.loadAll();
|
||||
const next = allEvents.length === 0 ? emptyAppViewState() : reduceEvents(allEvents, emptyAppViewState());
|
||||
await this.projectionStore.writeState(next);
|
||||
}
|
||||
await this.projector.start();
|
||||
const pending = await this.eventStore.loadAfterPosition((await this.currentState()).lastPosition);
|
||||
if (pending.length > 0) {
|
||||
await this.projector.enqueue(pending);
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await this.projector.stop();
|
||||
}
|
||||
|
||||
async execute(command: AnyDomainCommand): Promise<AppViewState> {
|
||||
const current = await this.currentState();
|
||||
const pending = decide(command, current);
|
||||
if (pending.length === 0) return current;
|
||||
const appended = await this.eventStore.append(pending);
|
||||
await this.projector.enqueue(appended);
|
||||
return this.currentState();
|
||||
}
|
||||
|
||||
async currentState(): Promise<AppViewState> {
|
||||
return this.projector.readState();
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import type { StateUpdatedNotification } from "../domain/events";
|
||||
import type { FanoutPort } from "../ports";
|
||||
|
||||
interface Sink<T> {
|
||||
push(value: T): void;
|
||||
close(): void;
|
||||
iterable: AsyncIterable<T>;
|
||||
}
|
||||
|
||||
function createSink<T>(): Sink<T> {
|
||||
const queue: T[] = [];
|
||||
const waiters: Array<(value: IteratorResult<T>) => void> = [];
|
||||
let closed = false;
|
||||
const push = (value: T) => {
|
||||
if (closed) return;
|
||||
const waiter = waiters.shift();
|
||||
if (waiter) {
|
||||
waiter({ value, done: false });
|
||||
return;
|
||||
}
|
||||
queue.push(value);
|
||||
};
|
||||
const close = () => {
|
||||
closed = true;
|
||||
while (waiters.length > 0) {
|
||||
const waiter = waiters.shift();
|
||||
waiter?.({ value: undefined as never, done: true });
|
||||
}
|
||||
};
|
||||
const iterable: AsyncIterable<T> = {
|
||||
[Symbol.asyncIterator]() {
|
||||
return {
|
||||
async next() {
|
||||
if (queue.length > 0) {
|
||||
return { value: queue.shift() as T, done: false };
|
||||
}
|
||||
if (closed) {
|
||||
return { value: undefined as never, done: true };
|
||||
}
|
||||
return new Promise<IteratorResult<T>>((resolve) => {
|
||||
waiters.push(resolve);
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
return { push, close, iterable };
|
||||
}
|
||||
|
||||
export class EffectFanout implements FanoutPort {
|
||||
private readonly sinks = new Set<Sink<StateUpdatedNotification>>();
|
||||
|
||||
async publish(notification: StateUpdatedNotification): Promise<void> {
|
||||
for (const sink of this.sinks) {
|
||||
sink.push(notification);
|
||||
}
|
||||
}
|
||||
|
||||
async subscribe(): Promise<AsyncIterable<StateUpdatedNotification>> {
|
||||
const sink = createSink<StateUpdatedNotification>();
|
||||
this.sinks.add(sink);
|
||||
return sink.iterable;
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import type { DomainEventEnvelope } from "../domain/events";
|
||||
import { emptyAppViewState, type AppViewState } from "../domain/models";
|
||||
import type { FanoutPort, ProjectionStorePort } from "../ports";
|
||||
import { reduceEvents } from "../projections/reducer";
|
||||
|
||||
export class QueueProjector {
|
||||
private readonly queue: ReadonlyArray<DomainEventEnvelope>[] = [];
|
||||
private processing = false;
|
||||
private stopSignal = false;
|
||||
|
||||
constructor(
|
||||
private readonly projectionStore: ProjectionStorePort,
|
||||
private readonly fanout: FanoutPort,
|
||||
) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.processing) return;
|
||||
this.stopSignal = false;
|
||||
this.processing = true;
|
||||
void this.drain();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.stopSignal = true;
|
||||
this.processing = false;
|
||||
}
|
||||
|
||||
async enqueue(events: ReadonlyArray<DomainEventEnvelope>): Promise<void> {
|
||||
if (events.length === 0) return;
|
||||
this.queue.push(events);
|
||||
if (this.processing) {
|
||||
void this.drain();
|
||||
}
|
||||
}
|
||||
|
||||
async readState(): Promise<AppViewState> {
|
||||
return (await this.projectionStore.readState()) ?? emptyAppViewState();
|
||||
}
|
||||
|
||||
private async drain(): Promise<void> {
|
||||
if (!this.processing) return;
|
||||
while (!this.stopSignal && this.queue.length > 0) {
|
||||
const chunk = this.queue.shift();
|
||||
if (!chunk || chunk.length === 0) continue;
|
||||
const current = (await this.projectionStore.readState()) ?? emptyAppViewState();
|
||||
const next = reduceEvents(chunk, current);
|
||||
await this.projectionStore.writeState(next);
|
||||
await this.fanout.publish({ state: next, events: chunk });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { ProjectScriptSchema, ProviderEventSchema, ProviderSessionViewSchema, RuntimeModeSchema } from "./models";
|
||||
|
||||
export const CommandTypeSchema = Schema.Literal(
|
||||
"app.bootstrap",
|
||||
"project.add",
|
||||
"project.remove",
|
||||
"project.updateScripts",
|
||||
"thread.create",
|
||||
"thread.delete",
|
||||
"thread.addUserMessage",
|
||||
"thread.updateProviderSession",
|
||||
"thread.recordProviderEvent",
|
||||
"thread.setBranch",
|
||||
"thread.setTerminalActivity",
|
||||
"thread.markVisited",
|
||||
"runtime.setMode",
|
||||
);
|
||||
export type CommandType = Schema.Schema.Type<typeof CommandTypeSchema>;
|
||||
|
||||
export interface DomainCommand<TPayload> {
|
||||
readonly id: string;
|
||||
readonly type: CommandType;
|
||||
readonly payload: TPayload;
|
||||
readonly issuedAt: string;
|
||||
readonly correlationId?: string;
|
||||
}
|
||||
|
||||
export interface AppBootstrapCommand
|
||||
extends DomainCommand<{
|
||||
cwd: string;
|
||||
projectName: string;
|
||||
}> {
|
||||
readonly type: "app.bootstrap";
|
||||
}
|
||||
|
||||
export interface ProjectAddCommand
|
||||
extends DomainCommand<{
|
||||
id: string;
|
||||
name: string;
|
||||
cwd: string;
|
||||
model: string;
|
||||
scripts: Schema.Schema.Type<typeof ProjectScriptSchema>[];
|
||||
}> {
|
||||
readonly type: "project.add";
|
||||
}
|
||||
|
||||
export interface ProjectRemoveCommand extends DomainCommand<{ id: string }> {
|
||||
readonly type: "project.remove";
|
||||
}
|
||||
|
||||
export interface ProjectUpdateScriptsCommand
|
||||
extends DomainCommand<{
|
||||
id: string;
|
||||
scripts: Schema.Schema.Type<typeof ProjectScriptSchema>[];
|
||||
}> {
|
||||
readonly type: "project.updateScripts";
|
||||
}
|
||||
|
||||
export interface ThreadCreateCommand
|
||||
extends DomainCommand<{
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}> {
|
||||
readonly type: "thread.create";
|
||||
}
|
||||
|
||||
export interface ThreadDeleteCommand extends DomainCommand<{ id: string }> {
|
||||
readonly type: "thread.delete";
|
||||
}
|
||||
|
||||
export interface ThreadAddUserMessageCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
messageId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
attachments?: Array<{
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
previewUrl?: string;
|
||||
}>;
|
||||
}> {
|
||||
readonly type: "thread.addUserMessage";
|
||||
}
|
||||
|
||||
export interface ThreadUpdateProviderSessionCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
session: Schema.Schema.Type<typeof ProviderSessionViewSchema> | null;
|
||||
}> {
|
||||
readonly type: "thread.updateProviderSession";
|
||||
}
|
||||
|
||||
export interface ThreadRecordProviderEventCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
event: Schema.Schema.Type<typeof ProviderEventSchema>;
|
||||
}> {
|
||||
readonly type: "thread.recordProviderEvent";
|
||||
}
|
||||
|
||||
export interface ThreadSetBranchCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}> {
|
||||
readonly type: "thread.setBranch";
|
||||
}
|
||||
|
||||
export interface ThreadSetTerminalActivityCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
running: boolean;
|
||||
}> {
|
||||
readonly type: "thread.setTerminalActivity";
|
||||
}
|
||||
|
||||
export interface ThreadMarkVisitedCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
visitedAt: string;
|
||||
}> {
|
||||
readonly type: "thread.markVisited";
|
||||
}
|
||||
|
||||
export interface RuntimeSetModeCommand
|
||||
extends DomainCommand<{
|
||||
mode: Schema.Schema.Type<typeof RuntimeModeSchema>;
|
||||
}> {
|
||||
readonly type: "runtime.setMode";
|
||||
}
|
||||
|
||||
export type AnyDomainCommand =
|
||||
| AppBootstrapCommand
|
||||
| ProjectAddCommand
|
||||
| ProjectRemoveCommand
|
||||
| ProjectUpdateScriptsCommand
|
||||
| ThreadCreateCommand
|
||||
| ThreadDeleteCommand
|
||||
| ThreadAddUserMessageCommand
|
||||
| ThreadUpdateProviderSessionCommand
|
||||
| ThreadRecordProviderEventCommand
|
||||
| ThreadSetBranchCommand
|
||||
| ThreadSetTerminalActivityCommand
|
||||
| ThreadMarkVisitedCommand
|
||||
| RuntimeSetModeCommand;
|
||||
@@ -1,149 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
import {
|
||||
type AppViewState,
|
||||
ProjectScriptSchema,
|
||||
ProviderEventSchema,
|
||||
ProviderSessionViewSchema,
|
||||
RuntimeModeSchema,
|
||||
} from "./models";
|
||||
|
||||
export const DomainEventTypeSchema = Schema.Literal(
|
||||
"app.bootstrapped",
|
||||
"project.added",
|
||||
"project.removed",
|
||||
"project.scriptsUpdated",
|
||||
"thread.created",
|
||||
"thread.deleted",
|
||||
"thread.userMessageAdded",
|
||||
"thread.providerSessionUpdated",
|
||||
"thread.providerEventRecorded",
|
||||
"thread.branchSet",
|
||||
"thread.terminalActivitySet",
|
||||
"thread.markVisited",
|
||||
"runtime.modeSet",
|
||||
);
|
||||
export type DomainEventType = Schema.Schema.Type<typeof DomainEventTypeSchema>;
|
||||
|
||||
const AppBootstrappedPayloadSchema = Schema.Struct({
|
||||
cwd: Schema.String,
|
||||
projectName: Schema.String,
|
||||
});
|
||||
|
||||
const ProjectAddedPayloadSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
cwd: Schema.String,
|
||||
model: Schema.String,
|
||||
scripts: Schema.Array(ProjectScriptSchema),
|
||||
});
|
||||
|
||||
const ProjectRemovedPayloadSchema = Schema.Struct({ id: Schema.String });
|
||||
|
||||
const ProjectScriptsUpdatedPayloadSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
scripts: Schema.Array(ProjectScriptSchema),
|
||||
});
|
||||
|
||||
const ThreadCreatedPayloadSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
projectId: Schema.String,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ThreadDeletedPayloadSchema = Schema.Struct({ id: Schema.String });
|
||||
|
||||
const ThreadUserMessageAddedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
messageId: Schema.String,
|
||||
text: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
attachments: Schema.optional(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("image"),
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
previewUrl: Schema.optional(Schema.String),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const ThreadProviderSessionUpdatedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
session: Schema.NullOr(ProviderSessionViewSchema),
|
||||
});
|
||||
|
||||
const ThreadProviderEventRecordedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
event: ProviderEventSchema,
|
||||
});
|
||||
|
||||
const ThreadBranchSetPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ThreadTerminalActivitySetPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
running: Schema.Boolean,
|
||||
});
|
||||
|
||||
const ThreadMarkVisitedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
visitedAt: Schema.String,
|
||||
});
|
||||
|
||||
const RuntimeModeSetPayloadSchema = Schema.Struct({
|
||||
mode: RuntimeModeSchema,
|
||||
});
|
||||
|
||||
export type DomainEventPayload =
|
||||
| Schema.Schema.Type<typeof AppBootstrappedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ProjectAddedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ProjectRemovedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ProjectScriptsUpdatedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadCreatedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadDeletedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadUserMessageAddedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadProviderSessionUpdatedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadProviderEventRecordedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadBranchSetPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadTerminalActivitySetPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadMarkVisitedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof RuntimeModeSetPayloadSchema>;
|
||||
|
||||
export interface DomainEventEnvelope {
|
||||
readonly eventId: string;
|
||||
readonly streamId: string;
|
||||
readonly sequence: number;
|
||||
readonly position: number;
|
||||
readonly type: DomainEventType;
|
||||
readonly occurredAt: string;
|
||||
readonly payload: DomainEventPayload;
|
||||
readonly causationId?: string;
|
||||
readonly correlationId?: string;
|
||||
}
|
||||
|
||||
export interface NewDomainEvent {
|
||||
readonly streamId: string;
|
||||
readonly type: DomainEventType;
|
||||
readonly payload: DomainEventPayload;
|
||||
readonly occurredAt: string;
|
||||
readonly causationId?: string;
|
||||
readonly correlationId?: string;
|
||||
}
|
||||
|
||||
export interface StateUpdatedNotification {
|
||||
readonly state: AppViewState;
|
||||
readonly events: readonly DomainEventEnvelope[];
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export const RuntimeModeSchema = Schema.Literal("approval-required", "full-access");
|
||||
export type RuntimeMode = Schema.Schema.Type<typeof RuntimeModeSchema>;
|
||||
|
||||
export const ProjectScriptSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
command: Schema.String,
|
||||
keybinding: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ProjectScript = Schema.Schema.Type<typeof ProjectScriptSchema>;
|
||||
|
||||
export const ProjectViewSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
cwd: Schema.String,
|
||||
model: Schema.String,
|
||||
expanded: Schema.Boolean,
|
||||
scripts: Schema.Array(ProjectScriptSchema),
|
||||
});
|
||||
export type ProjectView = Schema.Schema.Type<typeof ProjectViewSchema>;
|
||||
|
||||
export const ChatAttachmentSchema = Schema.Struct({
|
||||
type: Schema.Literal("image"),
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
previewUrl: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ChatAttachment = Schema.Schema.Type<typeof ChatAttachmentSchema>;
|
||||
|
||||
export const ChatMessageSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
role: Schema.Literal("user", "assistant"),
|
||||
text: Schema.String,
|
||||
attachments: Schema.optional(Schema.Array(ChatAttachmentSchema)),
|
||||
createdAt: Schema.String,
|
||||
streaming: Schema.Boolean,
|
||||
});
|
||||
export type ChatMessage = Schema.Schema.Type<typeof ChatMessageSchema>;
|
||||
|
||||
export const SessionStatusSchema = Schema.Literal(
|
||||
"connecting",
|
||||
"ready",
|
||||
"running",
|
||||
"error",
|
||||
"closed",
|
||||
);
|
||||
export type SessionStatus = Schema.Schema.Type<typeof SessionStatusSchema>;
|
||||
|
||||
export const ProviderSessionViewSchema = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
provider: Schema.Literal("codex", "claudeCode"),
|
||||
status: SessionStatusSchema,
|
||||
cwd: Schema.optional(Schema.String),
|
||||
model: Schema.optional(Schema.String),
|
||||
threadId: Schema.optional(Schema.String),
|
||||
activeTurnId: Schema.optional(Schema.String),
|
||||
createdAt: Schema.String,
|
||||
updatedAt: Schema.String,
|
||||
lastError: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ProviderSessionView = Schema.Schema.Type<typeof ProviderSessionViewSchema>;
|
||||
|
||||
export const ProviderEventSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
kind: Schema.Literal("session", "notification", "request", "error"),
|
||||
method: Schema.String,
|
||||
payload: Schema.optional(Schema.Unknown),
|
||||
createdAt: Schema.String,
|
||||
sessionId: Schema.String,
|
||||
threadId: Schema.optional(Schema.String),
|
||||
turnId: Schema.optional(Schema.String),
|
||||
itemId: Schema.optional(Schema.String),
|
||||
textDelta: Schema.optional(Schema.String),
|
||||
requestId: Schema.optional(Schema.String),
|
||||
requestKind: Schema.optional(Schema.String),
|
||||
message: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ProviderEvent = Schema.Schema.Type<typeof ProviderEventSchema>;
|
||||
|
||||
export const TurnDiffFileChangeSchema = Schema.Struct({
|
||||
path: Schema.String,
|
||||
kind: Schema.optional(Schema.String),
|
||||
additions: Schema.optional(Schema.Number),
|
||||
deletions: Schema.optional(Schema.Number),
|
||||
});
|
||||
export type TurnDiffFileChange = Schema.Schema.Type<typeof TurnDiffFileChangeSchema>;
|
||||
|
||||
export const TurnDiffSummarySchema = Schema.Struct({
|
||||
turnId: Schema.String,
|
||||
completedAt: Schema.String,
|
||||
status: Schema.optional(Schema.String),
|
||||
files: Schema.Array(TurnDiffFileChangeSchema),
|
||||
assistantMessageId: Schema.optional(Schema.String),
|
||||
checkpointTurnCount: Schema.optional(Schema.Number),
|
||||
});
|
||||
export type TurnDiffSummary = Schema.Schema.Type<typeof TurnDiffSummarySchema>;
|
||||
|
||||
export const ThreadTerminalGroupSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
terminalIds: Schema.Array(Schema.String),
|
||||
});
|
||||
export type ThreadTerminalGroup = Schema.Schema.Type<typeof ThreadTerminalGroupSchema>;
|
||||
|
||||
export const ThreadViewSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
codexThreadId: Schema.NullOr(Schema.String),
|
||||
projectId: Schema.String,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
terminalOpen: Schema.Boolean,
|
||||
terminalHeight: Schema.Number,
|
||||
terminalIds: Schema.Array(Schema.String),
|
||||
runningTerminalIds: Schema.Array(Schema.String),
|
||||
activeTerminalId: Schema.String,
|
||||
terminalGroups: Schema.Array(ThreadTerminalGroupSchema),
|
||||
activeTerminalGroupId: Schema.String,
|
||||
session: Schema.NullOr(ProviderSessionViewSchema),
|
||||
messages: Schema.Array(ChatMessageSchema),
|
||||
events: Schema.Array(ProviderEventSchema),
|
||||
error: Schema.NullOr(Schema.String),
|
||||
createdAt: Schema.String,
|
||||
latestTurnId: Schema.optional(Schema.String),
|
||||
latestTurnStartedAt: Schema.optional(Schema.String),
|
||||
latestTurnCompletedAt: Schema.optional(Schema.String),
|
||||
latestTurnDurationMs: Schema.optional(Schema.Number),
|
||||
lastVisitedAt: Schema.optional(Schema.String),
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
turnDiffSummaries: Schema.Array(TurnDiffSummarySchema),
|
||||
});
|
||||
export type ThreadView = Schema.Schema.Type<typeof ThreadViewSchema>;
|
||||
|
||||
export const AppViewStateSchema = Schema.Struct({
|
||||
projects: Schema.Array(ProjectViewSchema),
|
||||
threads: Schema.Array(ThreadViewSchema),
|
||||
threadsHydrated: Schema.Boolean,
|
||||
runtimeMode: RuntimeModeSchema,
|
||||
lastPosition: Schema.Number,
|
||||
});
|
||||
export type AppViewState = Schema.Schema.Type<typeof AppViewStateSchema>;
|
||||
|
||||
export const emptyAppViewState = (): AppViewState => ({
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
runtimeMode: "full-access",
|
||||
lastPosition: 0,
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { AppViewState } from "./models";
|
||||
|
||||
export type DomainQuery = { readonly type: "app.getState" };
|
||||
|
||||
export interface QueryResultMap {
|
||||
"app.getState": AppViewState;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
export * from "./domain/models";
|
||||
export * from "./domain/commands";
|
||||
export * from "./domain/events";
|
||||
export * from "./domain/queries";
|
||||
export * from "./ports";
|
||||
export * from "./projections/reducer";
|
||||
export * from "./application/decide";
|
||||
export * from "./application/fanout";
|
||||
export * from "./application/projector";
|
||||
export * from "./application/engine";
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { AnyDomainCommand } from "../domain/commands";
|
||||
import type { DomainEventEnvelope, NewDomainEvent, StateUpdatedNotification } from "../domain/events";
|
||||
import type { AppViewState } from "../domain/models";
|
||||
|
||||
export interface EventStorePort {
|
||||
append(events: ReadonlyArray<NewDomainEvent>): Promise<ReadonlyArray<DomainEventEnvelope>>;
|
||||
loadAll(): Promise<ReadonlyArray<DomainEventEnvelope>>;
|
||||
loadAfterPosition(position: number): Promise<ReadonlyArray<DomainEventEnvelope>>;
|
||||
}
|
||||
|
||||
export interface ProjectionStorePort {
|
||||
readState(): Promise<AppViewState | null>;
|
||||
writeState(state: AppViewState): Promise<void>;
|
||||
}
|
||||
|
||||
export interface FanoutPort {
|
||||
publish(notification: StateUpdatedNotification): Promise<void>;
|
||||
subscribe(): Promise<AsyncIterable<StateUpdatedNotification>>;
|
||||
}
|
||||
|
||||
export interface DeterministicProjectorPort {
|
||||
start(): Promise<void>;
|
||||
stop(): Promise<void>;
|
||||
enqueue(events: ReadonlyArray<DomainEventEnvelope>): Promise<void>;
|
||||
}
|
||||
|
||||
export interface CoreApplicationPort {
|
||||
execute(command: AnyDomainCommand): Promise<AppViewState>;
|
||||
currentState(): Promise<AppViewState>;
|
||||
}
|
||||
@@ -1,436 +0,0 @@
|
||||
import type { DomainEventEnvelope } from "../domain/events";
|
||||
import type {
|
||||
AppViewState,
|
||||
ChatMessage,
|
||||
ProviderEvent,
|
||||
ProviderSessionView,
|
||||
ThreadView,
|
||||
} from "../domain/models";
|
||||
import { emptyAppViewState } from "../domain/models";
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function eventTurnId(event: ProviderEvent): string | undefined {
|
||||
if (event.turnId) return event.turnId;
|
||||
const turn = asObject(asObject(event.payload)?.turn);
|
||||
return asString(turn?.id);
|
||||
}
|
||||
|
||||
function durationMs(startIso: string, endIso: string): number | undefined {
|
||||
const start = Date.parse(startIso);
|
||||
const end = Date.parse(endIso);
|
||||
if (Number.isNaN(start) || Number.isNaN(end) || end < start) return undefined;
|
||||
return end - start;
|
||||
}
|
||||
|
||||
function evolveSession(previous: ProviderSessionView, event: ProviderEvent): ProviderSessionView {
|
||||
const payload = asObject(event.payload);
|
||||
if (event.method === "thread/started") {
|
||||
const thread = asObject(payload?.thread);
|
||||
return {
|
||||
...previous,
|
||||
threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
if (event.method === "turn/started") {
|
||||
const turn = asObject(payload?.turn);
|
||||
return {
|
||||
...previous,
|
||||
status: "running",
|
||||
activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
if (event.method === "turn/completed") {
|
||||
const turn = asObject(payload?.turn);
|
||||
const status = asString(turn?.status);
|
||||
const turnError = asObject(turn?.error);
|
||||
return {
|
||||
...previous,
|
||||
status: status === "failed" ? "error" : "ready",
|
||||
activeTurnId: undefined,
|
||||
lastError: asString(turnError?.message) ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
if (event.kind === "error") {
|
||||
return {
|
||||
...previous,
|
||||
status: "error",
|
||||
lastError: event.message ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
if (event.method === "session/closed" || event.method === "session/exited") {
|
||||
return {
|
||||
...previous,
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: event.message ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
return { ...previous, updatedAt: event.createdAt };
|
||||
}
|
||||
|
||||
function applyEventToMessages(
|
||||
previous: ReadonlyArray<ChatMessage>,
|
||||
event: ProviderEvent,
|
||||
): ChatMessage[] {
|
||||
const payload = asObject(event.payload);
|
||||
if (event.method === "item/started") {
|
||||
const item = asObject(payload?.item);
|
||||
if (asString(item?.type) !== "agentMessage") return [...previous];
|
||||
const itemId = asString(item?.id);
|
||||
if (!itemId) return [...previous];
|
||||
const seedText = asString(item?.text) ?? "";
|
||||
return [
|
||||
...previous.filter((entry) => entry.id !== itemId),
|
||||
{
|
||||
id: itemId,
|
||||
role: "assistant",
|
||||
text: seedText,
|
||||
createdAt: event.createdAt,
|
||||
streaming: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (event.method === "item/agentMessage/delta") {
|
||||
const itemId = event.itemId ?? asString(payload?.itemId);
|
||||
const delta = event.textDelta ?? asString(payload?.delta) ?? "";
|
||||
if (!itemId || !delta) return [...previous];
|
||||
const idx = previous.findIndex((entry) => entry.id === itemId);
|
||||
if (idx < 0) {
|
||||
return [
|
||||
...previous,
|
||||
{ id: itemId, role: "assistant", text: delta, createdAt: event.createdAt, streaming: true },
|
||||
];
|
||||
}
|
||||
const next = [...previous];
|
||||
const current = next[idx];
|
||||
if (!current) return [...previous];
|
||||
next[idx] = { ...current, text: `${current.text}${delta}`, streaming: true };
|
||||
return next;
|
||||
}
|
||||
if (event.method === "item/completed") {
|
||||
const item = asObject(payload?.item);
|
||||
if (asString(item?.type) !== "agentMessage") return [...previous];
|
||||
const itemId = asString(item?.id);
|
||||
if (!itemId) return [...previous];
|
||||
const fullText = asString(item?.text);
|
||||
const idx = previous.findIndex((entry) => entry.id === itemId);
|
||||
if (idx < 0) {
|
||||
return [
|
||||
...previous,
|
||||
{
|
||||
id: itemId,
|
||||
role: "assistant",
|
||||
text: fullText ?? "",
|
||||
createdAt: event.createdAt,
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
const next = [...previous];
|
||||
const current = next[idx];
|
||||
if (!current) return [...previous];
|
||||
next[idx] = { ...current, text: fullText ?? current.text, streaming: false };
|
||||
return next;
|
||||
}
|
||||
if (event.method === "turn/completed") {
|
||||
return previous.map((entry) => ({ ...entry, streaming: false }));
|
||||
}
|
||||
return [...previous];
|
||||
}
|
||||
|
||||
function defaultThread(payload: {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}): ThreadView {
|
||||
return {
|
||||
id: payload.id,
|
||||
codexThreadId: null,
|
||||
projectId: payload.projectId,
|
||||
title: payload.title,
|
||||
model: payload.model,
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: payload.createdAt,
|
||||
branch: payload.branch,
|
||||
worktreePath: payload.worktreePath,
|
||||
turnDiffSummaries: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function applyDomainEvent(state: AppViewState, event: DomainEventEnvelope): AppViewState {
|
||||
switch (event.type) {
|
||||
case "app.bootstrapped": {
|
||||
const payload = event.payload as { cwd: string; projectName: string };
|
||||
if (state.projects.length > 0)
|
||||
return { ...state, threadsHydrated: true, lastPosition: event.position };
|
||||
return {
|
||||
...state,
|
||||
projects: [
|
||||
{
|
||||
id: "bootstrap-project",
|
||||
name: payload.projectName,
|
||||
cwd: payload.cwd,
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threadsHydrated: true,
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "project.added": {
|
||||
const payload = event.payload as {
|
||||
id: string;
|
||||
name: string;
|
||||
cwd: string;
|
||||
model: string;
|
||||
scripts: Array<{ id: string; name: string; command: string; keybinding?: string }>;
|
||||
};
|
||||
if (
|
||||
state.projects.some((project) => project.id === payload.id || project.cwd === payload.cwd)
|
||||
) {
|
||||
return { ...state, lastPosition: event.position };
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
projects: [...state.projects, { ...payload, expanded: true }],
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "project.removed": {
|
||||
const payload = event.payload as { id: string };
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.filter((project) => project.id !== payload.id),
|
||||
threads: state.threads.filter((thread) => thread.projectId !== payload.id),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "project.scriptsUpdated": {
|
||||
const payload = event.payload as {
|
||||
id: string;
|
||||
scripts: Array<{ id: string; name: string; command: string; keybinding?: string }>;
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((project) =>
|
||||
project.id === payload.id ? { ...project, scripts: payload.scripts } : project,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.created": {
|
||||
const payload = event.payload as {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
};
|
||||
if (state.threads.some((thread) => thread.id === payload.id)) {
|
||||
return { ...state, lastPosition: event.position };
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: [...state.threads, defaultThread(payload)],
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.deleted": {
|
||||
const payload = event.payload as { id: string };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.filter((thread) => thread.id !== payload.id),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.userMessageAdded": {
|
||||
const payload = event.payload as {
|
||||
threadId: string;
|
||||
messageId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
attachments?: Array<{
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
previewUrl?: string;
|
||||
}>;
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId
|
||||
? {
|
||||
...thread,
|
||||
messages: [
|
||||
...thread.messages,
|
||||
{
|
||||
id: payload.messageId,
|
||||
role: "user",
|
||||
text: payload.text,
|
||||
attachments: payload.attachments ? [...payload.attachments] : undefined,
|
||||
createdAt: payload.createdAt,
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
}
|
||||
: thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.providerSessionUpdated": {
|
||||
const payload = event.payload as { threadId: string; session: ProviderSessionView | null };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId
|
||||
? {
|
||||
...thread,
|
||||
session: payload.session,
|
||||
codexThreadId: payload.session?.threadId ?? thread.codexThreadId,
|
||||
...(payload.session ? {} : { events: [], messages: [], turnDiffSummaries: [] }),
|
||||
}
|
||||
: thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.providerEventRecorded": {
|
||||
const payload = event.payload as { threadId: string; event: ProviderEvent };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) => {
|
||||
if (thread.id !== payload.threadId) return thread;
|
||||
const nextEvents = [payload.event, ...thread.events];
|
||||
const nextSession = thread.session
|
||||
? evolveSession(thread.session, payload.event)
|
||||
: thread.session;
|
||||
const nextMessages = applyEventToMessages(thread.messages, payload.event);
|
||||
const nextTurnId =
|
||||
payload.event.method === "turn/started"
|
||||
? (eventTurnId(payload.event) ?? thread.latestTurnId)
|
||||
: thread.latestTurnId;
|
||||
const nextTurnStartedAt =
|
||||
payload.event.method === "turn/started"
|
||||
? payload.event.createdAt
|
||||
: thread.latestTurnStartedAt;
|
||||
const nextTurnCompletedAt =
|
||||
payload.event.method === "turn/completed"
|
||||
? payload.event.createdAt
|
||||
: thread.latestTurnCompletedAt;
|
||||
const nextTurnDuration =
|
||||
payload.event.method === "turn/completed" && thread.latestTurnStartedAt
|
||||
? durationMs(thread.latestTurnStartedAt, payload.event.createdAt)
|
||||
: thread.latestTurnDurationMs;
|
||||
return {
|
||||
...thread,
|
||||
events: nextEvents,
|
||||
messages: nextMessages,
|
||||
session: nextSession,
|
||||
error:
|
||||
payload.event.kind === "error" && payload.event.message
|
||||
? payload.event.message
|
||||
: thread.error,
|
||||
latestTurnId: nextTurnId,
|
||||
latestTurnStartedAt: nextTurnStartedAt,
|
||||
latestTurnCompletedAt: nextTurnCompletedAt,
|
||||
latestTurnDurationMs: nextTurnDuration,
|
||||
};
|
||||
}),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.branchSet": {
|
||||
const payload = event.payload as {
|
||||
threadId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId
|
||||
? { ...thread, branch: payload.branch, worktreePath: payload.worktreePath }
|
||||
: thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.terminalActivitySet": {
|
||||
const payload = event.payload as { threadId: string; terminalId: string; running: boolean };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) => {
|
||||
if (thread.id !== payload.threadId) return thread;
|
||||
const running = new Set(thread.runningTerminalIds);
|
||||
if (payload.running) running.add(payload.terminalId);
|
||||
else running.delete(payload.terminalId);
|
||||
const terminalIds = thread.terminalIds.includes(payload.terminalId)
|
||||
? thread.terminalIds
|
||||
: [...thread.terminalIds, payload.terminalId];
|
||||
return { ...thread, terminalIds, runningTerminalIds: [...running] };
|
||||
}),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.markVisited": {
|
||||
const payload = event.payload as { threadId: string; visitedAt: string };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId ? { ...thread, lastVisitedAt: payload.visitedAt } : thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "runtime.modeSet": {
|
||||
const payload = event.payload as { mode: "approval-required" | "full-access" };
|
||||
return { ...state, runtimeMode: payload.mode, lastPosition: event.position };
|
||||
}
|
||||
default:
|
||||
return { ...state, lastPosition: event.position };
|
||||
}
|
||||
}
|
||||
|
||||
export function reduceEvents(
|
||||
events: ReadonlyArray<DomainEventEnvelope>,
|
||||
seed?: AppViewState,
|
||||
): AppViewState {
|
||||
return events.reduce(
|
||||
(state, event) => applyDomainEvent(state, event),
|
||||
seed ?? emptyAppViewState(),
|
||||
);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@t3tools/infra-sqlite",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/sql": "^0.49.0",
|
||||
"@effect/sql-sqlite-node": "^0.50.1",
|
||||
"@t3tools/core": "workspace:*",
|
||||
"effect": "^3.18.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./sqliteStore";
|
||||
@@ -1,175 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import crypto from "node:crypto";
|
||||
|
||||
import type { AppViewState, DomainEventEnvelope, EventStorePort, NewDomainEvent, ProjectionStorePort } from "@t3tools/core";
|
||||
|
||||
interface EventRow {
|
||||
event_id: string;
|
||||
stream_id: string;
|
||||
sequence: number;
|
||||
position: number;
|
||||
type: string;
|
||||
occurred_at: string;
|
||||
payload_json: string;
|
||||
causation_id: string | null;
|
||||
correlation_id: string | null;
|
||||
}
|
||||
|
||||
function ensureDir(filePath: string): void {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
}
|
||||
|
||||
function parseState(raw: string | null): AppViewState | null {
|
||||
if (!raw) return null;
|
||||
return JSON.parse(raw) as AppViewState;
|
||||
}
|
||||
|
||||
export class SqliteEventStore implements EventStorePort {
|
||||
constructor(private readonly db: DatabaseSync) {}
|
||||
|
||||
async append(events: ReadonlyArray<NewDomainEvent>): Promise<ReadonlyArray<DomainEventEnvelope>> {
|
||||
if (events.length === 0) return [];
|
||||
const out: DomainEventEnvelope[] = [];
|
||||
this.db.exec("BEGIN IMMEDIATE TRANSACTION");
|
||||
try {
|
||||
for (const event of events) {
|
||||
const sequenceStmt = this.db.prepare(
|
||||
"SELECT COALESCE(MAX(sequence), 0) + 1 AS nextSequence FROM events WHERE stream_id = ?",
|
||||
);
|
||||
const sequenceRow = sequenceStmt.get(event.streamId) as { nextSequence: number };
|
||||
const insert = this.db.prepare(
|
||||
[
|
||||
"INSERT INTO events(",
|
||||
"event_id, stream_id, sequence, type, occurred_at, payload_json, causation_id, correlation_id",
|
||||
") VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
].join(" "),
|
||||
);
|
||||
const eventId = crypto.randomUUID();
|
||||
insert.run(
|
||||
eventId,
|
||||
event.streamId,
|
||||
sequenceRow.nextSequence,
|
||||
event.type,
|
||||
event.occurredAt,
|
||||
JSON.stringify(event.payload),
|
||||
event.causationId ?? null,
|
||||
event.correlationId ?? null,
|
||||
);
|
||||
const positionRow = this.db
|
||||
.prepare("SELECT position FROM events WHERE event_id = ?")
|
||||
.get(eventId) as { position: number };
|
||||
out.push({
|
||||
eventId,
|
||||
streamId: event.streamId,
|
||||
sequence: sequenceRow.nextSequence,
|
||||
position: positionRow.position,
|
||||
type: event.type,
|
||||
occurredAt: event.occurredAt,
|
||||
payload: event.payload,
|
||||
...(event.causationId ? { causationId: event.causationId } : {}),
|
||||
...(event.correlationId ? { correlationId: event.correlationId } : {}),
|
||||
});
|
||||
}
|
||||
this.db.exec("COMMIT");
|
||||
return out;
|
||||
} catch (error) {
|
||||
this.db.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async loadAll(): Promise<ReadonlyArray<DomainEventEnvelope>> {
|
||||
const stmt = this.db.prepare(
|
||||
"SELECT event_id, stream_id, sequence, position, type, occurred_at, payload_json, causation_id, correlation_id FROM events ORDER BY position ASC",
|
||||
);
|
||||
const rows = stmt.all() as unknown as EventRow[];
|
||||
return rows.map(mapEventRow);
|
||||
}
|
||||
|
||||
async loadAfterPosition(position: number): Promise<ReadonlyArray<DomainEventEnvelope>> {
|
||||
const stmt = this.db.prepare(
|
||||
"SELECT event_id, stream_id, sequence, position, type, occurred_at, payload_json, causation_id, correlation_id FROM events WHERE position > ? ORDER BY position ASC",
|
||||
);
|
||||
const rows = stmt.all(position) as unknown as EventRow[];
|
||||
return rows.map(mapEventRow);
|
||||
}
|
||||
}
|
||||
|
||||
function mapEventRow(row: EventRow): DomainEventEnvelope {
|
||||
return {
|
||||
eventId: row.event_id,
|
||||
streamId: row.stream_id,
|
||||
sequence: row.sequence,
|
||||
position: row.position,
|
||||
type: row.type as DomainEventEnvelope["type"],
|
||||
occurredAt: row.occurred_at,
|
||||
payload: JSON.parse(row.payload_json) as DomainEventEnvelope["payload"],
|
||||
...(row.causation_id ? { causationId: row.causation_id } : {}),
|
||||
...(row.correlation_id ? { correlationId: row.correlation_id } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export class SqliteProjectionStore implements ProjectionStorePort {
|
||||
constructor(private readonly db: DatabaseSync) {}
|
||||
|
||||
async readState(): Promise<AppViewState | null> {
|
||||
const row = this.db
|
||||
.prepare("SELECT state_json FROM projection_state WHERE projection_name = 'app_state'")
|
||||
.get() as { state_json: string } | undefined;
|
||||
return parseState(row?.state_json ?? null);
|
||||
}
|
||||
|
||||
async writeState(state: AppViewState): Promise<void> {
|
||||
this.db
|
||||
.prepare(
|
||||
[
|
||||
"INSERT INTO projection_state(projection_name, state_json, updated_at)",
|
||||
"VALUES('app_state', ?, ?)",
|
||||
"ON CONFLICT(projection_name) DO UPDATE SET",
|
||||
"state_json = excluded.state_json,",
|
||||
"updated_at = excluded.updated_at",
|
||||
].join(" "),
|
||||
)
|
||||
.run(JSON.stringify(state), new Date().toISOString());
|
||||
}
|
||||
}
|
||||
|
||||
export function createSqliteStores(dbPath: string): {
|
||||
db: DatabaseSync;
|
||||
eventStore: SqliteEventStore;
|
||||
projectionStore: SqliteProjectionStore;
|
||||
} {
|
||||
ensureDir(dbPath);
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec("PRAGMA journal_mode = WAL;");
|
||||
db.exec("PRAGMA foreign_keys = ON;");
|
||||
db.exec(
|
||||
[
|
||||
"CREATE TABLE IF NOT EXISTS events(",
|
||||
"position INTEGER PRIMARY KEY AUTOINCREMENT,",
|
||||
"event_id TEXT NOT NULL UNIQUE,",
|
||||
"stream_id TEXT NOT NULL,",
|
||||
"sequence INTEGER NOT NULL,",
|
||||
"type TEXT NOT NULL,",
|
||||
"occurred_at TEXT NOT NULL,",
|
||||
"payload_json TEXT NOT NULL,",
|
||||
"causation_id TEXT,",
|
||||
"correlation_id TEXT,",
|
||||
"UNIQUE(stream_id, sequence)",
|
||||
");",
|
||||
"CREATE INDEX IF NOT EXISTS idx_events_stream_position ON events(stream_id, position);",
|
||||
"CREATE TABLE IF NOT EXISTS projection_state(",
|
||||
"projection_name TEXT PRIMARY KEY,",
|
||||
"state_json TEXT NOT NULL,",
|
||||
"updated_at TEXT NOT NULL",
|
||||
");",
|
||||
].join(" "),
|
||||
);
|
||||
return {
|
||||
db,
|
||||
eventStore: new SqliteEventStore(db),
|
||||
projectionStore: new SqliteProjectionStore(db),
|
||||
};
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
+26
-3
@@ -58,6 +58,19 @@ function resolveOffset() {
|
||||
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
|
||||
}
|
||||
|
||||
function resolvePublicHost() {
|
||||
const rawHost = process.env.T3CODE_PUBLIC_HOST?.trim();
|
||||
if (!rawHost) return undefined;
|
||||
|
||||
if (rawHost.includes("://") || rawHost.includes("/")) {
|
||||
throw new Error(
|
||||
`Invalid T3CODE_PUBLIC_HOST: ${rawHost}. Use only a host or IP (no protocol/path).`,
|
||||
);
|
||||
}
|
||||
|
||||
return rawHost;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const mode = process.argv[2];
|
||||
const isDryRun = process.argv.includes("--dry-run");
|
||||
@@ -69,6 +82,9 @@ function main() {
|
||||
const { offset, source } = resolveOffset();
|
||||
const serverPort = BASE_SERVER_PORT + offset;
|
||||
const webPort = BASE_WEB_PORT + offset;
|
||||
const publicHost = resolvePublicHost();
|
||||
const wsHost = publicHost ?? "localhost";
|
||||
const webHost = publicHost ?? "localhost";
|
||||
|
||||
if (serverPort > 65535 || webPort > 65535) {
|
||||
throw new Error(
|
||||
@@ -81,15 +97,22 @@ function main() {
|
||||
T3CODE_PORT: String(serverPort),
|
||||
PORT: String(webPort),
|
||||
ELECTRON_RENDERER_PORT: String(webPort),
|
||||
VITE_WS_URL: `ws://localhost:${serverPort}`,
|
||||
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
|
||||
VITE_WS_URL: `ws://${wsHost}:${serverPort}`,
|
||||
VITE_DEV_SERVER_URL: `http://${webHost}:${webPort}`,
|
||||
};
|
||||
|
||||
if (publicHost) {
|
||||
env.VITE_DEV_SERVER_HOST = "0.0.0.0";
|
||||
env.VITE_HMR_HOST = publicHost;
|
||||
}
|
||||
|
||||
if (mode === "dev" && !env.T3CODE_LOG_WS_EVENTS) {
|
||||
env.T3CODE_LOG_WS_EVENTS = "1";
|
||||
}
|
||||
|
||||
console.info(
|
||||
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort}`,
|
||||
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort}` +
|
||||
`${publicHost ? ` publicHost=${publicHost}` : ""}`,
|
||||
);
|
||||
|
||||
if (isDryRun) {
|
||||
|
||||
Reference in new issue
Block a user