Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8aadcff89 | ||
|
|
b9bb89cf52 | ||
|
|
c03bb95282 | ||
|
|
05aa27a0d9 | ||
|
|
e81c2acb78 | ||
|
|
fda3073e0c | ||
|
|
7214778b64 | ||
|
|
27bd9192ad | ||
|
|
0da96d5c93 | ||
|
|
25dbfa7bc7 | ||
|
|
781006f005 | ||
|
|
78b7070042 | ||
|
|
d8412eca9f | ||
|
|
1332c488ad | ||
|
|
384878a3f1 | ||
|
|
749a2076d8 | ||
|
|
f039878edd | ||
|
|
632c1417ea | ||
|
|
c00354c0b1 | ||
|
|
a002239fc4 | ||
|
|
70a13c298f | ||
|
|
8a72a2a91d | ||
|
|
842e327583 | ||
|
|
891eb02d49 | ||
|
|
8cea075a1e | ||
|
|
84fc3e96e6 | ||
|
|
2c9121553e | ||
|
|
48bf123d0c | ||
|
|
f8883d0495 | ||
|
|
8cb2b3fcfe | ||
|
|
cc3e1db22a | ||
|
|
daf8e5f53b | ||
|
|
c89798ecb1 | ||
|
|
b253d1f8ca | ||
|
|
bf9f653331 | ||
|
|
a32701ef8d | ||
|
|
f3b773f1f0 | ||
|
|
e7e289f4ba | ||
|
|
efbab1b104 | ||
|
|
564474f927 | ||
|
|
47fcd16003 | ||
|
|
24c617d32e | ||
|
|
22e1a4cf92 | ||
|
|
79382b272c | ||
|
|
90e199d6a7 | ||
|
|
9a8a5b3935 | ||
|
|
58a8d653a8 | ||
|
|
eecb53498a | ||
|
|
5cf140b0ee | ||
|
|
85085491da | ||
|
|
6356b3ca6d | ||
|
|
978c810139 | ||
|
|
1a315235b7 | ||
|
|
bcf8b14f38 | ||
|
|
fe69e96942 | ||
|
|
e9d40e4481 | ||
|
|
ed9f561dc3 | ||
|
|
7de054fa49 | ||
|
|
bb9371d3c9 | ||
|
|
bd1c7e1d9a | ||
|
|
453fb4992e | ||
|
|
5cfab38f31 | ||
|
|
ba1a2dbcf7 | ||
|
|
b441875731 | ||
|
|
8e744269a2 | ||
|
|
c90e245038 | ||
|
|
200e43e44c | ||
|
|
6aea858ed8 | ||
|
|
f07b6ac8e6 | ||
|
|
3afbf93d5e | ||
|
|
ec5c3c32cd | ||
|
|
5209967a7e | ||
|
|
867c122082 | ||
|
|
cf8a2f03fc | ||
|
|
582615971e | ||
|
|
d2e6cfe109 | ||
|
|
351736baa1 | ||
|
|
b236dccca3 | ||
|
|
ac05ddc0f9 | ||
|
|
0e73dc1527 | ||
|
|
1a94fcbd29 | ||
|
|
ed40fd3364 | ||
|
|
88f31d2f65 | ||
|
|
c8c0dc6c3c | ||
|
|
e52db0bbc2 | ||
|
|
71d8f74143 | ||
|
|
dfeb673b6d | ||
|
|
4d886b99f5 | ||
|
|
4e791759cf | ||
|
|
9799b42dcd | ||
|
|
a999933297 | ||
|
|
648a6ac372 | ||
|
|
3537d47702 | ||
|
|
9e877f592b | ||
|
|
f719aea047 | ||
|
|
f6136bd4c2 | ||
|
|
385d77d0c2 | ||
|
|
ee2f6bd742 | ||
|
|
e1ba603605 | ||
|
|
5d61b8b14f | ||
|
|
2743e45dbe | ||
|
|
1b409c3946 | ||
|
|
60ed67e5e1 | ||
|
|
bd6a5c85e6 | ||
|
|
9cce509013 | ||
|
|
9f48564d84 | ||
|
|
e8556bcff9 | ||
|
|
a1532d5b2d | ||
|
|
ba4a62eb03 | ||
|
|
09ac18db82 | ||
|
|
376efdd340 | ||
|
|
7a5dd62d2f | ||
|
|
f64c26e708 | ||
|
|
6d8d39a5d1 | ||
|
|
afdfe16931 | ||
|
|
73fa2d66c7 | ||
|
|
51dcb547ed | ||
|
|
228862ac56 | ||
|
|
bc22a71f10 | ||
|
|
c42d6a6a64 | ||
|
|
5242bbbade | ||
|
|
05b47e748f | ||
|
|
3863901085 | ||
|
|
f864ef189d | ||
|
|
765f4cd00b | ||
|
|
748ea2ae20 | ||
|
|
56a09ad1aa | ||
|
|
be1c8c4656 | ||
|
|
b7fb0b8fed | ||
|
|
5656f294d0 | ||
|
|
dd23bd73d9 | ||
|
|
8dd107429e | ||
|
|
1269b52580 | ||
|
|
fe79c8e9ee | ||
|
|
0a5aaf3e0e | ||
|
|
3d7ef8a833 | ||
|
|
66ebadb448 | ||
|
|
6667992753 | ||
|
|
41ba1ec7a8 | ||
|
|
3db020a683 | ||
|
|
20d3ad5d50 | ||
|
|
54fa15c72e | ||
|
|
370127760a | ||
|
|
dd3babdcad | ||
|
|
7aa717c5c2 | ||
|
|
8beba3e16b | ||
|
|
38c93a2abd | ||
|
|
ef4ce2e1ec | ||
|
|
61e9ba4b19 | ||
|
|
ad6247577e | ||
|
|
f1cd76c17a | ||
|
|
31aa32b83b | ||
|
|
53c367420c | ||
|
|
ace5803581 | ||
|
|
645b037c9e | ||
|
|
7fc53dadc7 |
No files matched your search
@@ -10,3 +10,4 @@ packages/*/dist
|
||||
.env.local
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
@@ -1,6 +1,13 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"],
|
||||
"ignorePatterns": [
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts"
|
||||
],
|
||||
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
|
||||
"categories": {
|
||||
"correctness": "warn",
|
||||
|
||||
@@ -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`
|
||||
@@ -0,0 +1,101 @@
|
||||
# Keybindings
|
||||
|
||||
T3 Code reads keybindings from:
|
||||
|
||||
- `~/.t3/keybindings.json`
|
||||
|
||||
The file must be a JSON array of rules:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "key": "mod+g", "command": "terminal.toggle" },
|
||||
{ "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" }
|
||||
]
|
||||
```
|
||||
|
||||
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
|
||||
|
||||
## Defaults
|
||||
|
||||
```json
|
||||
[
|
||||
{ "key": "mod+j", "command": "terminal.toggle" },
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
|
||||
{ "key": "mod+o", "command": "editor.openFavorite" }
|
||||
]
|
||||
```
|
||||
|
||||
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
|
||||
|
||||
## Configuration
|
||||
|
||||
### Rule Shape
|
||||
|
||||
Each entry supports:
|
||||
|
||||
- `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d`
|
||||
- `command` (required): action ID
|
||||
- `when` (optional): boolean expression controlling when the shortcut is active
|
||||
|
||||
Invalid rules are ignored. Invalid config files are ignored. Warnings are logged by the server.
|
||||
|
||||
### Available Commands
|
||||
|
||||
- `terminal.toggle`: open/close terminal drawer
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
|
||||
|
||||
### Key Syntax
|
||||
|
||||
Supported modifiers:
|
||||
|
||||
- `mod` (`cmd` on macOS, `ctrl` on non-macOS)
|
||||
- `cmd` / `meta`
|
||||
- `ctrl` / `control`
|
||||
- `shift`
|
||||
- `alt` / `option`
|
||||
|
||||
Examples:
|
||||
|
||||
- `mod+j`
|
||||
- `mod+shift+d`
|
||||
- `ctrl+l`
|
||||
- `cmd+k`
|
||||
|
||||
### `when` Conditions
|
||||
|
||||
Currently available context keys:
|
||||
|
||||
- `terminalFocus`
|
||||
- `terminalOpen`
|
||||
|
||||
Supported operators:
|
||||
|
||||
- `!` (not)
|
||||
- `&&` (and)
|
||||
- `||` (or)
|
||||
- parentheses: `(` `)`
|
||||
|
||||
Examples:
|
||||
|
||||
- `"when": "terminalFocus"`
|
||||
- `"when": "terminalOpen && !terminalFocus"`
|
||||
- `"when": "terminalFocus || terminalOpen"`
|
||||
|
||||
Unknown condition keys evaluate to `false`.
|
||||
|
||||
### Precedence
|
||||
|
||||
- Rules are evaluated in array order.
|
||||
- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
|
||||
- That means precedence is across commands, not only within the same command.
|
||||
@@ -56,10 +56,26 @@ T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
|
||||
bun run build
|
||||
bun run start
|
||||
|
||||
# Build a shareable macOS .dmg (arm64 by default)
|
||||
bun run dist:desktop:dmg
|
||||
|
||||
# Or from any project directory after publishing:
|
||||
npx t3
|
||||
```
|
||||
|
||||
## 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.
|
||||
@@ -69,6 +85,17 @@ npx t3
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
|
||||
### Running multiple dev instances
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
## Small things
|
||||
|
||||
- [ ] Plan mode
|
||||
- [ ] Submitting new messages should scroll to bottom
|
||||
- [ ] 1 click copy in codeblocks
|
||||
- [x] Pasting/adding images to submit with prompts
|
||||
- [ ] Only show last 10 threads for a given project
|
||||
@@ -12,7 +14,7 @@
|
||||
- [x] "Response" bar should ONLY appear on work completed
|
||||
- [x] "Response" bar should ONLY appear above the FINAL message in a series
|
||||
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
|
||||
- [ ] Insta focus input on new thread creation
|
||||
- [x] Insta focus input on new thread creation
|
||||
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||
- [x] Making new thread should auto-focus input box
|
||||
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
@@ -2,19 +2,20 @@
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"productName": "T3 Code (Alpha)",
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "electron dist-electron/main.js",
|
||||
"start": "bun run scripts/start-electron.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"electron": "33.4.11"
|
||||
"electron": "40.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.2",
|
||||
|
||||
|
After Width: | Height: | Size: 279 KiB |
|
After Width: | Height: | Size: 313 KiB |
@@ -1,7 +1,10 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import electronmon from "electronmon";
|
||||
import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
|
||||
@@ -14,18 +17,57 @@ await waitOn({
|
||||
],
|
||||
});
|
||||
|
||||
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(command, ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
const monitor = await electronmon({
|
||||
cwd: desktopDir,
|
||||
args: ["dist-electron/main.js"],
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
electronPath: resolveElectronPath(),
|
||||
});
|
||||
|
||||
child.on("exit", (code) => {
|
||||
process.exit(code ?? 0);
|
||||
let shuttingDown = false;
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
async function shutdown(exitCode) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
try {
|
||||
await Promise.race([
|
||||
monitor.destroy(),
|
||||
new Promise((resolve) => setTimeout(resolve, 1_500)),
|
||||
]);
|
||||
} catch {
|
||||
// Best effort only; fallback process kill below handles stubborn children.
|
||||
}
|
||||
|
||||
killChildTree("TERM");
|
||||
setTimeout(() => {
|
||||
killChildTree("KILL");
|
||||
}, 1_200).unref();
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void shutdown(130);
|
||||
});
|
||||
process.once("SIGTERM", () => {
|
||||
void shutdown(143);
|
||||
});
|
||||
process.once("SIGHUP", () => {
|
||||
void shutdown(129);
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
copyFileSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 1;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = spawnSync(
|
||||
"plutil",
|
||||
["-replace", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (replaceResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertResult = spawnSync(
|
||||
"plutil",
|
||||
["-insert", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (insertResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const details = [replaceResult.stderr, insertResult.stderr]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
throw new Error(
|
||||
`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
|
||||
|
||||
const resourcesDir = join(appBundlePath, "Contents", "Resources");
|
||||
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
|
||||
if (!existsSync(frameworksDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
|
||||
continue;
|
||||
}
|
||||
if (!entry.name.startsWith("Electron Helper")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const helperPlistPath = join(
|
||||
frameworksDir,
|
||||
entry.name,
|
||||
"Contents",
|
||||
"Info.plist",
|
||||
);
|
||||
if (!existsSync(helperPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suffix = entry.name
|
||||
.replace("Electron Helper", "")
|
||||
.replace(".app", "")
|
||||
.trim();
|
||||
const helperName = suffix
|
||||
? `${APP_DISPLAY_NAME} Helper ${suffix}`
|
||||
: `${APP_DISPLAY_NAME} Helper`;
|
||||
const helperIdSuffix = suffix
|
||||
.replace(/[()]/g, "")
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, "-");
|
||||
const helperBundleId = helperIdSuffix
|
||||
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
|
||||
: `${APP_BUNDLE_ID}.helper`;
|
||||
|
||||
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = resolve(electronBinaryPath, "../../..");
|
||||
const runtimeDir = join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = join(
|
||||
targetAppBundlePath,
|
||||
"Contents",
|
||||
"MacOS",
|
||||
"Electron",
|
||||
);
|
||||
const iconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
const expectedMetadata = {
|
||||
launcherVersion: LAUNCHER_VERSION,
|
||||
sourceAppBundlePath,
|
||||
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
|
||||
iconMtimeMs: statSync(iconPath).mtimeMs,
|
||||
};
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
existsSync(targetBinaryPath) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
process.kill(process.pid, signal);
|
||||
return;
|
||||
}
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
@@ -5,7 +5,16 @@ import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
dialog,
|
||||
ipcMain,
|
||||
Menu,
|
||||
type MenuItemConstructorOptions,
|
||||
protocol,
|
||||
shell,
|
||||
} from "electron";
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { fixPath } from "./fixPath";
|
||||
@@ -16,11 +25,13 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
|
||||
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess | null = null;
|
||||
@@ -30,6 +41,235 @@ let backendWsUrl = "";
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
let desktopProtocolRegistered = false;
|
||||
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
function resolveAppRoot(): string {
|
||||
if (!app.isPackaged) {
|
||||
return ROOT_DIR;
|
||||
}
|
||||
return app.getAppPath();
|
||||
}
|
||||
|
||||
function resolveBackendEntry(): string {
|
||||
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
}
|
||||
|
||||
function resolveBackendCwd(): string {
|
||||
if (!app.isPackaged) {
|
||||
return resolveAppRoot();
|
||||
}
|
||||
return os.homedir();
|
||||
}
|
||||
|
||||
function resolveDesktopStaticDir(): string | null {
|
||||
const appRoot = resolveAppRoot();
|
||||
const candidates = [
|
||||
path.join(appRoot, "apps/server/dist/client"),
|
||||
path.join(appRoot, "apps/web/dist"),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(path.join(candidate, "index.html"))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
|
||||
const url = new URL(requestUrl);
|
||||
const rawPath = decodeURIComponent(url.pathname);
|
||||
const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
|
||||
if (normalizedPath.includes("..")) {
|
||||
return path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
|
||||
const resolvedPath = path.join(staticRoot, requestedPath);
|
||||
|
||||
if (path.extname(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
const nestedIndex = path.join(resolvedPath, "index.html");
|
||||
if (fs.existsSync(nestedIndex)) {
|
||||
return nestedIndex;
|
||||
}
|
||||
|
||||
return path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function registerDesktopProtocol(): void {
|
||||
if (isDevelopment || desktopProtocolRegistered) return;
|
||||
|
||||
const staticRoot = resolveDesktopStaticDir();
|
||||
if (!staticRoot) {
|
||||
throw new Error("Desktop static bundle missing. Build apps/server (with bundled client) first.");
|
||||
}
|
||||
|
||||
const staticRootResolved = path.resolve(staticRoot);
|
||||
const staticRootPrefix = `${staticRootResolved}${path.sep}`;
|
||||
const fallbackIndex = path.join(staticRootResolved, "index.html");
|
||||
|
||||
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
|
||||
try {
|
||||
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
|
||||
const resolvedCandidate = path.resolve(candidate);
|
||||
const isInRoot =
|
||||
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
|
||||
const isAssetRequest = isStaticAssetRequest(request.url);
|
||||
|
||||
if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
|
||||
if (isAssetRequest) {
|
||||
callback({ error: -6 });
|
||||
return;
|
||||
}
|
||||
callback({ path: fallbackIndex });
|
||||
return;
|
||||
}
|
||||
|
||||
callback({ path: resolvedCandidate });
|
||||
} catch {
|
||||
callback({ path: fallbackIndex });
|
||||
}
|
||||
});
|
||||
|
||||
desktopProtocolRegistered = true;
|
||||
}
|
||||
|
||||
function dispatchMenuAction(action: string): void {
|
||||
const existingWindow = BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
|
||||
const targetWindow = existingWindow ?? createWindow();
|
||||
if (!existingWindow) {
|
||||
mainWindow = targetWindow;
|
||||
}
|
||||
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
|
||||
if (!targetWindow.isVisible()) {
|
||||
targetWindow.show();
|
||||
}
|
||||
targetWindow.focus();
|
||||
};
|
||||
|
||||
if (targetWindow.webContents.isLoadingMainFrame()) {
|
||||
targetWindow.webContents.once("did-finish-load", send);
|
||||
return;
|
||||
}
|
||||
|
||||
send();
|
||||
}
|
||||
|
||||
function configureApplicationMenu(): void {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
template.push({
|
||||
label: app.name,
|
||||
submenu: [
|
||||
{ role: "about" },
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => dispatchMenuAction("open-settings"),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ role: "services" },
|
||||
{ type: "separator" },
|
||||
{ role: "hide" },
|
||||
{ role: "hideOthers" },
|
||||
{ role: "unhide" },
|
||||
{ type: "separator" },
|
||||
{ role: "quit" },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
template.push(
|
||||
{
|
||||
label: "File",
|
||||
submenu: [
|
||||
...(process.platform === "darwin"
|
||||
? []
|
||||
: [
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => dispatchMenuAction("open-settings"),
|
||||
},
|
||||
{ type: "separator" as const },
|
||||
]),
|
||||
{ role: process.platform === "darwin" ? "close" : "quit" },
|
||||
],
|
||||
},
|
||||
{ role: "editMenu" },
|
||||
{ role: "viewMenu" },
|
||||
{ role: "windowMenu" },
|
||||
);
|
||||
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||
}
|
||||
|
||||
function resolveResourcePath(fileName: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, "../resources", fileName),
|
||||
path.join(process.resourcesPath, "resources", fileName),
|
||||
path.join(process.resourcesPath, fileName),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
|
||||
return resolveResourcePath(`icon.${ext}`);
|
||||
}
|
||||
|
||||
function configureAppIdentity(): void {
|
||||
app.setName(APP_DISPLAY_NAME);
|
||||
app.setAboutPanelOptions({
|
||||
applicationName: APP_DISPLAY_NAME,
|
||||
});
|
||||
|
||||
if (process.platform === "win32") {
|
||||
app.setAppUserModelId(APP_USER_MODEL_ID);
|
||||
}
|
||||
|
||||
if (process.platform === "darwin" && app.dock) {
|
||||
const iconPath = resolveIconPath("png");
|
||||
if (iconPath) {
|
||||
app.dock.setIcon(iconPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -60,6 +300,42 @@ function backendEnv(): NodeJS.ProcessEnv {
|
||||
};
|
||||
}
|
||||
|
||||
function resolveBackendLaunch(backendEntry: string): {
|
||||
command: string;
|
||||
args: string[];
|
||||
env: NodeJS.ProcessEnv;
|
||||
} {
|
||||
const runtimeOverride = process.env.T3CODE_BACKEND_RUNTIME?.trim();
|
||||
if (runtimeOverride && runtimeOverride.length > 0) {
|
||||
if (runtimeOverride === "electron-node") {
|
||||
return {
|
||||
command: process.execPath,
|
||||
args: [backendEntry],
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
command: runtimeOverride,
|
||||
args: [backendEntry],
|
||||
env: backendEnv(),
|
||||
};
|
||||
}
|
||||
|
||||
// Default to Node-mode execution under Electron in both dev and production.
|
||||
// This matches main and avoids runtime-specific PTY behavior differences.
|
||||
return {
|
||||
command: process.execPath,
|
||||
args: [backendEntry],
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleBackendRestart(reason: string): void {
|
||||
if (isQuitting || restartTimer) return;
|
||||
|
||||
@@ -76,19 +352,16 @@ function scheduleBackendRestart(reason: string): void {
|
||||
function startBackend(): void {
|
||||
if (isQuitting || backendProcess) return;
|
||||
|
||||
if (!fs.existsSync(BACKEND_ENTRY)) {
|
||||
scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`);
|
||||
const backendEntry = resolveBackendEntry();
|
||||
if (!fs.existsSync(backendEntry)) {
|
||||
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const child = spawn(process.execPath, [BACKEND_ENTRY], {
|
||||
cwd: ROOT_DIR,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
const launch = resolveBackendLaunch(backendEntry);
|
||||
const child = spawn(launch.command, launch.args, {
|
||||
cwd: resolveBackendCwd(),
|
||||
env: launch.env,
|
||||
stdio: "inherit",
|
||||
});
|
||||
backendProcess = child;
|
||||
@@ -124,10 +397,10 @@ function stopBackend(): void {
|
||||
backendProcess = null;
|
||||
if (!child) return;
|
||||
|
||||
if (!child.killed) {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => {
|
||||
if (!child.killed) {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, 2_000).unref();
|
||||
@@ -204,6 +477,13 @@ function registerIpcHandlers(): void {
|
||||
});
|
||||
}
|
||||
|
||||
function getIconOption(): { icon: string } | Record<string, never> {
|
||||
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = process.platform === "win32" ? "ico" : "png";
|
||||
const iconPath = resolveIconPath(ext);
|
||||
return iconPath ? { icon: iconPath } : {};
|
||||
}
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
width: 1100,
|
||||
@@ -212,6 +492,8 @@ function createWindow(): BrowserWindow {
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
webPreferences: {
|
||||
@@ -223,6 +505,13 @@ function createWindow(): BrowserWindow {
|
||||
});
|
||||
|
||||
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
|
||||
window.on("page-title-updated", (event) => {
|
||||
event.preventDefault();
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
});
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
});
|
||||
window.once("ready-to-show", () => {
|
||||
window.show();
|
||||
});
|
||||
@@ -231,10 +520,7 @@ function createWindow(): BrowserWindow {
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
if (!fs.existsSync(WEB_ENTRY)) {
|
||||
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
|
||||
}
|
||||
void window.loadFile(WEB_ENTRY);
|
||||
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -246,6 +532,8 @@ function createWindow(): BrowserWindow {
|
||||
return window;
|
||||
}
|
||||
|
||||
configureAppIdentity();
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
backendPort = await reserveLoopbackPort();
|
||||
backendAuthToken = randomBytes(24).toString("hex");
|
||||
@@ -263,6 +551,9 @@ app.on("before-quit", () => {
|
||||
});
|
||||
|
||||
app.whenReady().then(() => {
|
||||
configureAppIdentity();
|
||||
configureApplicationMenu();
|
||||
registerDesktopProtocol();
|
||||
void bootstrap();
|
||||
|
||||
app.on("activate", () => {
|
||||
@@ -277,3 +568,19 @@ app.on("window-all-closed", () => {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
if (process.platform !== "win32") {
|
||||
process.on("SIGINT", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
stopBackend();
|
||||
app.quit();
|
||||
});
|
||||
|
||||
process.on("SIGTERM", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
stopBackend();
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
@@ -4,6 +4,7 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
@@ -13,4 +14,15 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
showContextMenu: (items: { id: string; label: string }[]) =>
|
||||
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
|
||||
onMenuAction: (listener: (action: string) => void) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
if (typeof action !== "string") return;
|
||||
listener(action);
|
||||
};
|
||||
|
||||
ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -17,6 +17,7 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
|
||||
@@ -43,6 +43,36 @@ function createSendTurnHarness() {
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
function createThreadControlHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as { requireSession: (sessionId: string) => unknown },
|
||||
"requireSession",
|
||||
)
|
||||
.mockReturnValue(context);
|
||||
const sendRequest = vi.spyOn(
|
||||
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
|
||||
"sendRequest",
|
||||
);
|
||||
const updateSession = vi
|
||||
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
describe("classifyCodexStderrLine", () => {
|
||||
it("ignores empty lines", () => {
|
||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||
@@ -113,6 +143,40 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
method: event.method,
|
||||
kind: event.kind,
|
||||
...(event.message ? { message: event.message } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
|
||||
throw new Error("cwd missing");
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
provider: "codex",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toEqual({
|
||||
method: "session/startFailed",
|
||||
kind: "error",
|
||||
message: "cwd missing",
|
||||
});
|
||||
} finally {
|
||||
processCwd.mockRestore();
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendTurn", () => {
|
||||
it("sends text and image user input items to turn/start", async () => {
|
||||
const { manager, context, requireSession, sendRequest, updateSession } =
|
||||
@@ -198,3 +262,91 @@ describe("sendTurn", () => {
|
||||
).rejects.toThrow("Turn input must include text or attachments.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread checkpoint control", () => {
|
||||
it("reads thread turns from thread/read", async () => {
|
||||
const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
thread: {
|
||||
id: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.readThread("sess_1");
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
includeTurns: true,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reads thread turns from flat thread/read responses", async () => {
|
||||
const { manager, context, sendRequest } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
threadId: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await manager.readThread("sess_1");
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
includeTurns: true,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("rolls back turns via thread/rollback and resets session running state", async () => {
|
||||
const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
thread: {
|
||||
id: "thread_1",
|
||||
turns: [],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.rollbackThread("sess_1", 2);
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
|
||||
threadId: "thread_1",
|
||||
numTurns: 2,
|
||||
});
|
||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
||||
status: "ready",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -65,6 +65,16 @@ interface JsonRpcNotification {
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export interface CodexThreadTurnSnapshot {
|
||||
id: string;
|
||||
items: unknown[];
|
||||
}
|
||||
|
||||
export interface CodexThreadSnapshot {
|
||||
threadId: string;
|
||||
turns: CodexThreadTurnSnapshot[];
|
||||
}
|
||||
|
||||
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
|
||||
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
|
||||
const CODEX_STDERR_LOG_REGEX =
|
||||
@@ -138,40 +148,48 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const sessionId = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "connecting",
|
||||
model: normalizeCodexModelSlug(input.model),
|
||||
cwd: input.cwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const child = spawn("codex", ["app-server"], {
|
||||
cwd: input.cwd,
|
||||
env: process.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
const context: CodexSessionContext = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
let context: CodexSessionContext | undefined;
|
||||
|
||||
try {
|
||||
const resolvedCwd = input.cwd ?? process.cwd();
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "connecting",
|
||||
model: normalizeCodexModelSlug(input.model),
|
||||
cwd: resolvedCwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const codexBinaryPath = input.codexBinaryPath?.trim() || "codex";
|
||||
const codexHomePath = input.codexHomePath?.trim();
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
context = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
|
||||
await this.sendRequest(context, "initialize", {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
@@ -241,12 +259,24 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return { ...context.session };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to start Codex session.";
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "session/startFailed", message);
|
||||
this.stopSession(sessionId);
|
||||
if (context) {
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "session/startFailed", message);
|
||||
this.stopSession(sessionId);
|
||||
} else {
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "session/startFailed",
|
||||
message,
|
||||
});
|
||||
}
|
||||
throw new Error(message, { cause: error });
|
||||
}
|
||||
}
|
||||
@@ -331,6 +361,41 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
async readThread(sessionId: string): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "thread/read", {
|
||||
threadId,
|
||||
includeTurns: true,
|
||||
});
|
||||
return this.parseThreadSnapshot("thread/read", response);
|
||||
}
|
||||
|
||||
async rollbackThread(sessionId: string, numTurns: number): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
throw new Error("numTurns must be an integer >= 1.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "thread/rollback", {
|
||||
threadId,
|
||||
numTurns,
|
||||
});
|
||||
this.updateSession(context, {
|
||||
status: "ready",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
return this.parseThreadSnapshot("thread/rollback", response);
|
||||
}
|
||||
|
||||
async respondToRequest(
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
@@ -742,6 +807,31 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot {
|
||||
const responseRecord = this.readObject(response);
|
||||
const thread = this.readObject(responseRecord, "thread");
|
||||
const threadId = this.readString(thread, "id") ?? this.readString(responseRecord, "threadId");
|
||||
if (!threadId) {
|
||||
throw new Error(`${method} response did not include a thread id.`);
|
||||
}
|
||||
|
||||
const turnsRaw = this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
|
||||
const turns = turnsRaw.map((turnValue, index) => {
|
||||
const turn = this.readObject(turnValue);
|
||||
const turnId = this.readString(turn, "id") ?? `${threadId}:turn:${index + 1}`;
|
||||
const items = this.readArray(turn, "items") ?? [];
|
||||
return {
|
||||
id: turnId,
|
||||
items,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
threadId,
|
||||
turns,
|
||||
};
|
||||
}
|
||||
|
||||
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
@@ -823,6 +913,16 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return target as Record<string, unknown>;
|
||||
}
|
||||
|
||||
private readArray(value: unknown, key?: string): unknown[] | undefined {
|
||||
const target =
|
||||
key === undefined
|
||||
? value
|
||||
: value && typeof value === "object"
|
||||
? (value as Record<string, unknown>)[key]
|
||||
: undefined;
|
||||
return Array.isArray(target) ? target : undefined;
|
||||
}
|
||||
|
||||
private readString(value: unknown, key: string): string | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { checkpointRefForThreadTurn, FilesystemCheckpointStore } from "./filesystemCheckpointStore";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
async function runGit(cwd: string, args: readonly string[]): Promise<string> {
|
||||
const result = await runProcess("git", args, {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr.trim() || `git ${args.join(" ")} failed`);
|
||||
}
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
function exists(filePath: string): boolean {
|
||||
return fs.existsSync(filePath);
|
||||
}
|
||||
|
||||
async function createRepo(): Promise<string> {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-test-"));
|
||||
await runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
await runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
await runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
await writeFile(path.join(cwd, "README.md"), "v1\n");
|
||||
await writeFile(path.join(cwd, "tracked.txt"), "tracked-v1\n");
|
||||
await runGit(cwd, ["add", "."]);
|
||||
await runGit(cwd, ["commit", "-m", "Initial"]);
|
||||
return cwd;
|
||||
}
|
||||
|
||||
async function createRepoWithoutHead(): Promise<string> {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-empty-test-"));
|
||||
await runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
return cwd;
|
||||
}
|
||||
|
||||
describe("FilesystemCheckpointStore", () => {
|
||||
it("captures refs without mutating branch history and restores workspace state", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_1";
|
||||
|
||||
try {
|
||||
const headBefore = await runGit(cwd, ["rev-parse", "HEAD"]);
|
||||
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
const rootRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const rootCommit = await runGit(cwd, ["rev-parse", "--verify", `${rootRef}^{commit}`]);
|
||||
expect(rootCommit.length).toBeGreaterThan(0);
|
||||
expect(await runGit(cwd, ["rev-parse", "HEAD"])).toBe(headBefore);
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await rm(path.join(cwd, "tracked.txt"));
|
||||
await writeFile(path.join(cwd, "notes.md"), "notes\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v3\n");
|
||||
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
|
||||
await writeFile(path.join(cwd, "tracked.txt"), "tracked-new\n");
|
||||
|
||||
const restoredRoot = await store.restoreCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
expect(restoredRoot).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
|
||||
expect(await readFile(path.join(cwd, "tracked.txt"), "utf8")).toBe("tracked-v1\n");
|
||||
expect(exists(path.join(cwd, "notes.md"))).toBe(false);
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
|
||||
const restoredTurn1 = await store.restoreCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
expect(restoredTurn1).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v2\n");
|
||||
expect(exists(path.join(cwd, "tracked.txt"))).toBe(false);
|
||||
expect(await readFile(path.join(cwd, "notes.md"), "utf8")).toBe("notes\n");
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns false when restoring a missing checkpoint", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
|
||||
try {
|
||||
const restored = await store.restoreCheckpoint({
|
||||
cwd,
|
||||
threadId: "thr_2",
|
||||
turnCount: 999,
|
||||
});
|
||||
expect(restored).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to HEAD when restoring turn 0 and root checkpoint ref is missing", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_2b";
|
||||
|
||||
try {
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v3\n");
|
||||
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
|
||||
|
||||
const restored = await store.restoreCheckpoint({
|
||||
cwd,
|
||||
threadId,
|
||||
turnCount: 0,
|
||||
});
|
||||
|
||||
expect(restored).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("prunes refs newer than the retained turn", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_3";
|
||||
|
||||
try {
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
await writeFile(path.join(cwd, "README.md"), "turn1\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
await writeFile(path.join(cwd, "README.md"), "turn2\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 2 });
|
||||
|
||||
await store.pruneAfterTurn({
|
||||
cwd,
|
||||
threadId,
|
||||
maxTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 0 })).toBe(true);
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 1 })).toBe(true);
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 2 })).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns a unified patch between checkpoint turns", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_4";
|
||||
|
||||
try {
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await writeFile(path.join(cwd, "new.txt"), "new file\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
const diff = await store.diffCheckpoints({
|
||||
cwd,
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git a/README.md b/README.md");
|
||||
expect(diff).toContain("diff --git a/new.txt b/new.txt");
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to HEAD as diff base when turn 0 checkpoint is missing", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_5";
|
||||
|
||||
try {
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await writeFile(path.join(cwd, "new.txt"), "new file\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
const diff = await store.diffCheckpoints({
|
||||
cwd,
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git a/README.md b/README.md");
|
||||
expect(diff).toContain("diff --git a/new.txt b/new.txt");
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("detects non-repo folders", async () => {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-nonrepo-"));
|
||||
const store = new FilesystemCheckpointStore();
|
||||
|
||||
try {
|
||||
expect(await store.isGitRepository(cwd)).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns false when repository path does not exist", async () => {
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const cwd = path.join(os.tmpdir(), `t3-fs-checkpoints-missing-${Date.now()}`);
|
||||
|
||||
expect(await store.isGitRepository(cwd)).toBe(false);
|
||||
});
|
||||
|
||||
it("restores checkpoint without reset when repository has no HEAD commit", async () => {
|
||||
const cwd = await createRepoWithoutHead();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr-no-head";
|
||||
|
||||
try {
|
||||
await writeFile(path.join(cwd, "README.md"), "first\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "second\n");
|
||||
const restored = await store.restoreCheckpoint({
|
||||
cwd,
|
||||
threadId,
|
||||
turnCount: 0,
|
||||
});
|
||||
|
||||
expect(restored).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("first\n");
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,322 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
|
||||
function quoteGitCommand(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function checkpointRefThreadSegment(threadId: string): string {
|
||||
return Buffer.from(threadId, "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
export function checkpointRefForThreadTurn(threadId: string, turnCount: number): string {
|
||||
if (!Number.isInteger(turnCount) || turnCount < 0) {
|
||||
throw new Error(`Invalid checkpoint turn count: ${turnCount}`);
|
||||
}
|
||||
return `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/${turnCount}`;
|
||||
}
|
||||
|
||||
interface GitOptions {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
stdin?: string;
|
||||
allowNonZeroExit?: boolean;
|
||||
}
|
||||
|
||||
export class FilesystemCheckpointStore {
|
||||
async isGitRepository(cwd: string): Promise<boolean> {
|
||||
try {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--is-inside-work-tree"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
return result.code === 0 && result.stdout.trim() === "true";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async captureCheckpoint(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}): Promise<void> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoint-"));
|
||||
|
||||
try {
|
||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||
const commitEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_INDEX_FILE: tempIndexPath,
|
||||
GIT_AUTHOR_NAME: "T3 Code",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
|
||||
const hasHead = await this.hasHeadCommit(cwd);
|
||||
if (hasHead) {
|
||||
await this.runGit(cwd, ["read-tree", "HEAD"], { env: commitEnv });
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["add", "-A", "--", "."], { env: commitEnv });
|
||||
const writeTreeResult = await this.runGit(cwd, ["write-tree"], { env: commitEnv });
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (!treeOid) {
|
||||
throw new Error("git write-tree returned an empty tree oid.");
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint thread=${threadId} turn=${turnCount}`;
|
||||
const commitTreeResult = await this.runGit(cwd, ["commit-tree", treeOid], {
|
||||
env: commitEnv,
|
||||
stdin: `${message}\n`,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (!commitOid) {
|
||||
throw new Error("git commit-tree returned an empty commit oid.");
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["update-ref", ref, commitOid]);
|
||||
} finally {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async hasCheckpoint(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}): Promise<boolean> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
const commit = await this.resolveCheckpointCommit(cwd, ref);
|
||||
return commit !== null;
|
||||
}
|
||||
|
||||
async ensureRootCheckpoint(input: { cwd: string; threadId: string }): Promise<boolean> {
|
||||
const { cwd, threadId } = input;
|
||||
const rootRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const existing = await this.resolveCheckpointCommit(cwd, rootRef);
|
||||
if (existing) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const headCommit = await this.resolveHeadCommit(cwd);
|
||||
if (!headCommit) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["update-ref", rootRef, headCommit]);
|
||||
return true;
|
||||
}
|
||||
|
||||
async restoreCheckpoint(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}): Promise<boolean> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
let commitOid = await this.resolveCheckpointCommit(cwd, ref);
|
||||
if (!commitOid && turnCount === 0) {
|
||||
commitOid = await this.resolveHeadCommit(cwd);
|
||||
}
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."]);
|
||||
await this.runGit(cwd, ["clean", "-fd", "--", "."]);
|
||||
if (await this.hasHeadCommit(cwd)) {
|
||||
await this.runGit(cwd, ["reset", "--quiet", "--", "."]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async diffCheckpoints(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
fromTurnCount: number;
|
||||
toTurnCount: number;
|
||||
}): Promise<string> {
|
||||
const { cwd, threadId, fromTurnCount, toTurnCount } = input;
|
||||
if (!Number.isInteger(fromTurnCount) || fromTurnCount < 0) {
|
||||
throw new Error(`Invalid from turn count: ${fromTurnCount}`);
|
||||
}
|
||||
if (!Number.isInteger(toTurnCount) || toTurnCount < 0) {
|
||||
throw new Error(`Invalid to turn count: ${toTurnCount}`);
|
||||
}
|
||||
if (fromTurnCount > toTurnCount) {
|
||||
throw new Error(`Invalid checkpoint range: ${fromTurnCount}..${toTurnCount}`);
|
||||
}
|
||||
|
||||
const fromRef = checkpointRefForThreadTurn(threadId, fromTurnCount);
|
||||
const toRef = checkpointRefForThreadTurn(threadId, toTurnCount);
|
||||
let fromCommitOid = await this.resolveCheckpointCommit(cwd, fromRef);
|
||||
const toCommitOid = await this.resolveCheckpointCommit(cwd, toRef);
|
||||
if (!fromCommitOid && fromTurnCount === 0) {
|
||||
const headCommit = await this.resolveHeadCommit(cwd);
|
||||
if (headCommit) {
|
||||
fromCommitOid = headCommit;
|
||||
}
|
||||
}
|
||||
if (!fromCommitOid) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${fromTurnCount} in thread ${threadId}.`,
|
||||
);
|
||||
}
|
||||
if (!toCommitOid) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${toTurnCount} in thread ${threadId}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await this.runGit(cwd, [
|
||||
"diff",
|
||||
"--patch",
|
||||
"--minimal",
|
||||
"--no-color",
|
||||
fromCommitOid,
|
||||
toCommitOid,
|
||||
]);
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
private async resolveHeadCommit(cwd: string): Promise<string | null> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}
|
||||
|
||||
async pruneAfterTurn(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
maxTurnCount: number;
|
||||
}): Promise<void> {
|
||||
const { cwd, threadId, maxTurnCount } = input;
|
||||
if (!Number.isInteger(maxTurnCount) || maxTurnCount < 0) {
|
||||
throw new Error(`Invalid max turn count: ${maxTurnCount}`);
|
||||
}
|
||||
|
||||
const threadRefPrefix = `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/`;
|
||||
const result = await this.runGit(
|
||||
cwd,
|
||||
["for-each-ref", "--format=%(refname)", threadRefPrefix],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const refsToDelete = result.stdout
|
||||
.split(/\r?\n/g)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.filter((refName) => {
|
||||
const turn = this.readRefTurnCount(refName);
|
||||
return turn !== null && turn > maxTurnCount;
|
||||
});
|
||||
|
||||
const batchSize = 32;
|
||||
const batches = Array.from(
|
||||
{ length: Math.ceil(refsToDelete.length / batchSize) },
|
||||
(_, index) => refsToDelete.slice(index * batchSize, (index + 1) * batchSize),
|
||||
);
|
||||
await batches.reduce<Promise<void>>((pending, batch) => {
|
||||
return pending.then(async () => {
|
||||
await Promise.all(
|
||||
batch.map((refName) =>
|
||||
this.runGit(cwd, ["update-ref", "-d", refName], { allowNonZeroExit: true }),
|
||||
),
|
||||
);
|
||||
});
|
||||
}, Promise.resolve());
|
||||
}
|
||||
|
||||
private async hasHeadCommit(cwd: string): Promise<boolean> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "HEAD"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
return result.code === 0;
|
||||
}
|
||||
|
||||
private async resolveCheckpointCommit(cwd: string, ref: string): Promise<string | null> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}
|
||||
|
||||
private readRefTurnCount(ref: string): number | null {
|
||||
const segments = ref.split("/");
|
||||
const rawTurn = segments.at(-1);
|
||||
if (!rawTurn) {
|
||||
return null;
|
||||
}
|
||||
const turn = Number.parseInt(rawTurn, 10);
|
||||
return Number.isInteger(turn) && turn >= 0 ? turn : null;
|
||||
}
|
||||
|
||||
private async runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: GitOptions = {},
|
||||
): Promise<Awaited<ReturnType<typeof runProcess>>> {
|
||||
let result: Awaited<ReturnType<typeof runProcess>>;
|
||||
try {
|
||||
result = await runProcess("git", args, {
|
||||
cwd,
|
||||
env: options.env,
|
||||
stdin: options.stdin,
|
||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Failed to run ${quoteGitCommand(args)}: ${message}`, { cause: error });
|
||||
}
|
||||
|
||||
if (result.timedOut) {
|
||||
throw new Error(`${quoteGitCommand(args)} timed out.`);
|
||||
}
|
||||
|
||||
if (result.stdoutTruncated || result.stderrTruncated) {
|
||||
throw new Error(
|
||||
`${quoteGitCommand(args)} output exceeded ${DEFAULT_MAX_OUTPUT_BYTES} bytes and was truncated.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!options.allowNonZeroExit && result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
throw new Error(
|
||||
stderr.length > 0
|
||||
? `${quoteGitCommand(args)} failed: ${stderr}`
|
||||
: `${quoteGitCommand(args)} failed with code ${result.code ?? "null"}.`,
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -617,6 +617,32 @@ describe("git integration", () => {
|
||||
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
|
||||
expect(existsSync(wtPath)).toBe(false);
|
||||
});
|
||||
|
||||
it("removeGitWorktree force removes a dirty worktree", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
const wtPath = path.join(tmp.path, "wt-dirty-dir");
|
||||
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(b) => b.current,
|
||||
)!.name;
|
||||
|
||||
await createGitWorktree({
|
||||
cwd: tmp.path,
|
||||
branch: currentBranch,
|
||||
newBranch: "wt-dirty",
|
||||
path: wtPath,
|
||||
});
|
||||
expect(existsSync(wtPath)).toBe(true);
|
||||
|
||||
await writeFile(path.join(wtPath, "README.md"), "dirty change\n");
|
||||
|
||||
await expect(removeGitWorktree({ cwd: tmp.path, path: wtPath })).rejects.toThrow();
|
||||
expect(existsSync(wtPath)).toBe(true);
|
||||
|
||||
await removeGitWorktree({ cwd: tmp.path, path: wtPath, force: true });
|
||||
expect(existsSync(wtPath)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Full flow: local branch checkout ──
|
||||
@@ -760,6 +786,53 @@ describe("git integration", () => {
|
||||
expect(dirty.hasWorkingTreeChanges).toBe(true);
|
||||
});
|
||||
|
||||
it("includes command context when worktree removal fails", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const core = new GitCoreService();
|
||||
const missingWorktreePath = path.join(tmp.path, "missing-worktree");
|
||||
|
||||
const error = await core
|
||||
.removeWorktree({ cwd: tmp.path, path: missingWorktreePath })
|
||||
.then(() => null)
|
||||
.catch((err: unknown) => err);
|
||||
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
const message = (error as Error).message;
|
||||
expect(message).toContain("git worktree remove");
|
||||
expect(message).toContain(`cwd: ${tmp.path}`);
|
||||
expect(message).toContain(missingWorktreePath);
|
||||
});
|
||||
|
||||
it("refreshes upstream before statusDetails so behind count reflects remote updates", async () => {
|
||||
await using remote = await makeTmpDir();
|
||||
await using source = await makeTmpDir();
|
||||
await using clone = await makeTmpDir();
|
||||
await git(remote.path, "init --bare");
|
||||
|
||||
await initRepoWithCommit(source.path);
|
||||
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
||||
await git(source.path, `push -u origin ${initialBranch}`);
|
||||
|
||||
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
|
||||
await git(clone.path, "config user.email '[email protected]'");
|
||||
await git(clone.path, "config user.name 'Test'");
|
||||
await git(clone.path, `checkout -B ${initialBranch} --track origin/${initialBranch}`);
|
||||
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
|
||||
await git(clone.path, "add CHANGELOG.md");
|
||||
await git(clone.path, "commit -m 'remote update'");
|
||||
await git(clone.path, `push origin ${initialBranch}`);
|
||||
|
||||
const core = new GitCoreService();
|
||||
const details = await core.statusDetails(source.path);
|
||||
expect(details.branch).toBe(initialBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
});
|
||||
|
||||
it("prepares commit context by auto-staging and creates commit", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
@@ -65,6 +65,8 @@ interface ExecuteGitOptions {
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL_MS = 15_000;
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** Spawn git directly with an argv array — no shell, no quoting needed. */
|
||||
function runGit(
|
||||
@@ -216,6 +218,8 @@ async function executeGit(
|
||||
}
|
||||
|
||||
export class GitCoreService {
|
||||
private readonly lastUpstreamRefreshAt = new Map<string, number>();
|
||||
|
||||
async status(raw: GitStatusInput): Promise<GitStatusResult> {
|
||||
const input = gitStatusInputSchema.parse(raw);
|
||||
const details = await this.statusDetails(input.cwd);
|
||||
@@ -231,6 +235,8 @@ export class GitCoreService {
|
||||
}
|
||||
|
||||
async statusDetails(cwd: string): Promise<GitStatusDetails> {
|
||||
await this.refreshStatusUpstreamIfStale(cwd).catch(() => undefined);
|
||||
|
||||
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
|
||||
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
|
||||
this.gitStdout(cwd, ["diff", "--numstat"]),
|
||||
@@ -540,10 +546,22 @@ export class GitCoreService {
|
||||
}
|
||||
|
||||
async removeWorktree(input: GitRemoveWorktreeInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["worktree", "remove", input.path], {
|
||||
timeoutMs: 15_000,
|
||||
fallbackErrorMessage: "git worktree remove failed",
|
||||
});
|
||||
const args = ["worktree", "remove"];
|
||||
if (input.force) {
|
||||
args.push("--force");
|
||||
}
|
||||
args.push(input.path);
|
||||
try {
|
||||
await executeGit(input.cwd, args, {
|
||||
timeoutMs: 15_000,
|
||||
fallbackErrorMessage: "git worktree remove failed",
|
||||
});
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`${commandLabel(args)} failed (cwd: ${input.cwd}): ${detail}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async createBranch(input: GitCreateBranchInput): Promise<void> {
|
||||
@@ -553,7 +571,9 @@ export class GitCoreService {
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
||||
private async resolveCurrentUpstream(
|
||||
cwd: string,
|
||||
): Promise<{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null> {
|
||||
const upstreamRef = trimStdout(
|
||||
await this.gitStdout(
|
||||
cwd,
|
||||
@@ -562,24 +582,72 @@ export class GitCoreService {
|
||||
),
|
||||
);
|
||||
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const separatorIndex = upstreamRef.indexOf("/");
|
||||
if (separatorIndex <= 0) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
const remoteName = upstreamRef.slice(0, separatorIndex);
|
||||
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
|
||||
if (remoteName.length === 0) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
if (upstreamBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName,
|
||||
upstreamBranch,
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchUpstreamRef(
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Promise<void> {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
await this.git(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], true);
|
||||
}
|
||||
|
||||
private async fetchUpstreamRefForStatus(
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Promise<void> {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
await executeGit(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: STATUS_UPSTREAM_REFRESH_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshStatusUpstreamIfStale(cwd: string): Promise<void> {
|
||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
||||
if (!upstream) {
|
||||
return;
|
||||
}
|
||||
|
||||
const refspec = `+refs/heads/${upstreamBranch}:refs/remotes/${upstreamRef}`;
|
||||
await this.git(cwd, ["fetch", "--quiet", "--no-tags", remoteName, refspec], true);
|
||||
const cacheKey = `${cwd}\u0000${upstream.upstreamRef}`;
|
||||
const now = Date.now();
|
||||
const lastRefreshAt = this.lastUpstreamRefreshAt.get(cacheKey) ?? 0;
|
||||
if (now - lastRefreshAt < STATUS_UPSTREAM_REFRESH_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Record attempt time first to avoid repeated fetch spikes when status is polled often.
|
||||
this.lastUpstreamRefreshAt.set(cacheKey, now);
|
||||
await this.fetchUpstreamRefForStatus(cwd, upstream);
|
||||
}
|
||||
|
||||
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
||||
if (!upstream) {
|
||||
return;
|
||||
}
|
||||
await this.fetchUpstreamRef(cwd, upstream);
|
||||
}
|
||||
|
||||
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
|
||||
|
||||
@@ -6,7 +6,7 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
import { fixPath } from "./fixPath";
|
||||
import { createLogger } from "./logger";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { PersistenceService } from "./persistenceService";
|
||||
import { createServer } from "./wsServer";
|
||||
|
||||
fixPath();
|
||||
@@ -49,6 +49,13 @@ function resolveStateDir(raw: string | undefined): string {
|
||||
return path.resolve(expandHomePath(raw.trim()));
|
||||
}
|
||||
|
||||
function resolveStateDbPath(raw: string | undefined): string {
|
||||
if (!raw || raw.trim().length === 0) {
|
||||
return path.join(os.homedir(), ".t3", "state.sqlite");
|
||||
}
|
||||
return path.resolve(expandHomePath(raw.trim()));
|
||||
}
|
||||
|
||||
async function findAvailablePort(preferred: number): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
@@ -101,8 +108,12 @@ async function main() {
|
||||
const requestedPort = parsePort(process.env.T3CODE_PORT);
|
||||
const port =
|
||||
requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
|
||||
const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
|
||||
const projectRegistry = new ProjectRegistry(stateDir);
|
||||
const legacyStateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
|
||||
const stateDbPath = resolveStateDbPath(process.env.T3CODE_STATE_DB_PATH);
|
||||
const persistenceService = new PersistenceService({
|
||||
dbPath: stateDbPath,
|
||||
legacyProjectsJsonPath: path.join(legacyStateDir, "projects.json"),
|
||||
});
|
||||
const devUrl = process.env.VITE_DEV_SERVER_URL;
|
||||
const noBrowser = parseBooleanEnv(process.env.T3CODE_NO_BROWSER) ?? mode === "desktop";
|
||||
const authToken = process.env.T3CODE_AUTH_TOKEN;
|
||||
@@ -120,7 +131,7 @@ async function main() {
|
||||
cwd,
|
||||
staticDir,
|
||||
devUrl,
|
||||
projectRegistry,
|
||||
persistenceService,
|
||||
authToken,
|
||||
});
|
||||
await server.start();
|
||||
@@ -130,7 +141,8 @@ async function main() {
|
||||
url,
|
||||
cwd,
|
||||
mode,
|
||||
stateDir,
|
||||
stateDbPath,
|
||||
legacyStateDir,
|
||||
authEnabled: Boolean(authToken),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { assert, afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
compileResolvedKeybindingRule,
|
||||
parseKeybindingShortcut,
|
||||
upsertKeybindingRule,
|
||||
} from "./keybindings";
|
||||
|
||||
describe("server keybindings", () => {
|
||||
const tempDirs: string[] = [];
|
||||
const logger = {
|
||||
warn: vi.fn(),
|
||||
};
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
logger.warn.mockReset();
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("parses shortcuts including plus key", () => {
|
||||
assert.deepEqual(parseKeybindingShortcut("mod+j"), {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
});
|
||||
assert.deepEqual(parseKeybindingShortcut("mod++"), {
|
||||
key: "+",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("compiles valid rule with parsed when AST", () => {
|
||||
const compiled = compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: "terminalOpen && !terminalFocus",
|
||||
});
|
||||
|
||||
assert.deepEqual(compiled, {
|
||||
command: "terminal.split",
|
||||
shortcut: {
|
||||
key: "d",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
whenAst: {
|
||||
type: "and",
|
||||
left: { type: "identifier", name: "terminalOpen" },
|
||||
right: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects invalid rules", () => {
|
||||
assert.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+shift+d+o",
|
||||
command: "terminal.new",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: "terminalFocus && (",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: `${"!".repeat(300)}terminalFocus`,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("upserts custom keybindings to ~/.t3/keybindings.json", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-upsert-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(
|
||||
configPath,
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
const resolved = upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
|
||||
key: string;
|
||||
command: string;
|
||||
}>;
|
||||
|
||||
expect(persisted).toEqual([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
expect(resolved.some((entry) => entry.command === "script.run-tests.run")).toBe(true);
|
||||
});
|
||||
|
||||
it("replaces existing custom keybinding for the same command", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-upsert-replace-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(
|
||||
configPath,
|
||||
JSON.stringify([{ key: "mod+r", command: "script.run-tests.run" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
|
||||
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
|
||||
key: string;
|
||||
command: string;
|
||||
}>;
|
||||
expect(persisted).toEqual([{ key: "mod+shift+r", command: "script.run-tests.run" }]);
|
||||
});
|
||||
|
||||
it("refuses to overwrite malformed keybindings config", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-malformed-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(configPath, "{ not-json", "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).toThrow(/Unable to parse keybindings config/);
|
||||
|
||||
expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
|
||||
});
|
||||
|
||||
it("reports non-array config parse errors without duplicate prefix", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-non-array-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(configPath, JSON.stringify({ key: "mod+j", command: "terminal.toggle" }), "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).toThrow(new RegExp(`Unable to parse keybindings config at ${configPath}: expected JSON array`));
|
||||
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).not.toThrow(
|
||||
new RegExp(`Unable to parse keybindings config at ${configPath}: Unable to parse keybindings config at`),
|
||||
);
|
||||
});
|
||||
|
||||
it("cleans up temp files when atomic keybinding write fails", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-atomic-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(configPath, JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]), "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
vi.spyOn(fs, "renameSync").mockImplementation(() => {
|
||||
throw new Error("rename failed");
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).toThrow(/rename failed/);
|
||||
|
||||
expect(fs.readFileSync(configPath, "utf8")).toBe(
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
);
|
||||
const tempFiles = fs
|
||||
.readdirSync(configDir)
|
||||
.filter((file) => file.includes("keybindings.json.") && file.endsWith(".tmp"));
|
||||
expect(tempFiles).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,447 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type {
|
||||
KeybindingRule,
|
||||
KeybindingsConfig,
|
||||
KeybindingShortcut,
|
||||
KeybindingWhenNode,
|
||||
ResolvedKeybindingRule,
|
||||
ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { keybindingRuleSchema } from "@t3tools/contracts";
|
||||
|
||||
interface KeybindingsLogger {
|
||||
warn(message: string, context?: Record<string, unknown>): void;
|
||||
}
|
||||
|
||||
type WhenToken =
|
||||
| { type: "identifier"; value: string }
|
||||
| { type: "not" }
|
||||
| { type: "and" }
|
||||
| { type: "or" }
|
||||
| { type: "lparen" }
|
||||
| { type: "rparen" };
|
||||
|
||||
const MAX_WHEN_EXPRESSION_DEPTH = 256;
|
||||
|
||||
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
{ key: "mod+o", command: "editor.openFavorite" },
|
||||
];
|
||||
|
||||
function normalizeKeyToken(token: string): string {
|
||||
if (token === "space") return " ";
|
||||
if (token === "esc") return "escape";
|
||||
return token;
|
||||
}
|
||||
|
||||
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
|
||||
const rawTokens = value
|
||||
.toLowerCase()
|
||||
.split("+")
|
||||
.map((token) => token.trim());
|
||||
const tokens = [...rawTokens];
|
||||
let trailingEmptyCount = 0;
|
||||
while (tokens[tokens.length - 1] === "") {
|
||||
trailingEmptyCount += 1;
|
||||
tokens.pop();
|
||||
}
|
||||
if (trailingEmptyCount > 0) {
|
||||
tokens.push("+");
|
||||
}
|
||||
if (tokens.some((token) => token.length === 0)) {
|
||||
return null;
|
||||
}
|
||||
if (tokens.length === 0) return null;
|
||||
|
||||
let key: string | null = null;
|
||||
let metaKey = false;
|
||||
let ctrlKey = false;
|
||||
let shiftKey = false;
|
||||
let altKey = false;
|
||||
let modKey = false;
|
||||
|
||||
for (const token of tokens) {
|
||||
switch (token) {
|
||||
case "cmd":
|
||||
case "meta":
|
||||
metaKey = true;
|
||||
break;
|
||||
case "ctrl":
|
||||
case "control":
|
||||
ctrlKey = true;
|
||||
break;
|
||||
case "shift":
|
||||
shiftKey = true;
|
||||
break;
|
||||
case "alt":
|
||||
case "option":
|
||||
altKey = true;
|
||||
break;
|
||||
case "mod":
|
||||
modKey = true;
|
||||
break;
|
||||
default: {
|
||||
if (key !== null) return null;
|
||||
key = normalizeKeyToken(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (key === null) return null;
|
||||
return {
|
||||
key,
|
||||
metaKey,
|
||||
ctrlKey,
|
||||
shiftKey,
|
||||
altKey,
|
||||
modKey,
|
||||
};
|
||||
}
|
||||
|
||||
function tokenizeWhenExpression(expression: string): WhenToken[] | null {
|
||||
const tokens: WhenToken[] = [];
|
||||
let index = 0;
|
||||
|
||||
while (index < expression.length) {
|
||||
const current = expression[index];
|
||||
if (!current) break;
|
||||
|
||||
if (/\s/.test(current)) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (expression.startsWith("&&", index)) {
|
||||
tokens.push({ type: "and" });
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
if (expression.startsWith("||", index)) {
|
||||
tokens.push({ type: "or" });
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
if (current === "!") {
|
||||
tokens.push({ type: "not" });
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (current === "(") {
|
||||
tokens.push({ type: "lparen" });
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (current === ")") {
|
||||
tokens.push({ type: "rparen" });
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
|
||||
if (!identifier) {
|
||||
return null;
|
||||
}
|
||||
tokens.push({ type: "identifier", value: identifier[0] });
|
||||
index += identifier[0].length;
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
|
||||
const tokens = tokenizeWhenExpression(expression);
|
||||
if (!tokens || tokens.length === 0) return null;
|
||||
let index = 0;
|
||||
|
||||
const parsePrimary = (depth: number): KeybindingWhenNode | null => {
|
||||
if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
|
||||
return null;
|
||||
}
|
||||
const token = tokens[index];
|
||||
if (!token) return null;
|
||||
|
||||
if (token.type === "identifier") {
|
||||
index += 1;
|
||||
return { type: "identifier", name: token.value };
|
||||
}
|
||||
|
||||
if (token.type === "lparen") {
|
||||
index += 1;
|
||||
const expressionNode = parseOr(depth + 1);
|
||||
const closeToken = tokens[index];
|
||||
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
|
||||
return null;
|
||||
}
|
||||
index += 1;
|
||||
return expressionNode;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const parseUnary = (depth: number): KeybindingWhenNode | null => {
|
||||
let notCount = 0;
|
||||
while (tokens[index]?.type === "not") {
|
||||
index += 1;
|
||||
notCount += 1;
|
||||
if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let node = parsePrimary(depth);
|
||||
if (!node) return null;
|
||||
|
||||
while (notCount > 0) {
|
||||
node = { type: "not", node };
|
||||
notCount -= 1;
|
||||
}
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
const parseAnd = (depth: number): KeybindingWhenNode | null => {
|
||||
let left = parseUnary(depth);
|
||||
if (!left) return null;
|
||||
|
||||
while (tokens[index]?.type === "and") {
|
||||
index += 1;
|
||||
const right = parseUnary(depth);
|
||||
if (!right) return null;
|
||||
left = { type: "and", left, right };
|
||||
}
|
||||
|
||||
return left;
|
||||
};
|
||||
|
||||
const parseOr = (depth: number): KeybindingWhenNode | null => {
|
||||
let left = parseAnd(depth);
|
||||
if (!left) return null;
|
||||
|
||||
while (tokens[index]?.type === "or") {
|
||||
index += 1;
|
||||
const right = parseAnd(depth);
|
||||
if (!right) return null;
|
||||
left = { type: "or", left, right };
|
||||
}
|
||||
|
||||
return left;
|
||||
};
|
||||
|
||||
const ast = parseOr(0);
|
||||
if (!ast || index !== tokens.length) return null;
|
||||
return ast;
|
||||
}
|
||||
|
||||
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
|
||||
const key = rule.key.trim();
|
||||
if (key.length === 0) return null;
|
||||
const shortcut = parseKeybindingShortcut(key);
|
||||
if (!shortcut) return null;
|
||||
|
||||
const when = rule.when?.trim();
|
||||
if (when && when.length > 0) {
|
||||
const whenAst = parseKeybindingWhenExpression(when);
|
||||
if (!whenAst) return null;
|
||||
return {
|
||||
command: rule.command,
|
||||
shortcut,
|
||||
whenAst,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
command: rule.command,
|
||||
shortcut,
|
||||
};
|
||||
}
|
||||
|
||||
export function compileResolvedKeybindingsConfig(
|
||||
config: KeybindingsConfig,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const compiled: ResolvedKeybindingsConfig = [];
|
||||
for (const rule of config) {
|
||||
const resolved = compileResolvedKeybindingRule(rule);
|
||||
if (!resolved) continue;
|
||||
compiled.push(resolved);
|
||||
}
|
||||
return compiled;
|
||||
}
|
||||
|
||||
function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
|
||||
const resolved: ResolvedKeybindingsConfig = [];
|
||||
for (const rule of DEFAULT_KEYBINDINGS) {
|
||||
const compiled = compileResolvedKeybindingRule(rule);
|
||||
if (!compiled) {
|
||||
throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`);
|
||||
}
|
||||
resolved.push(compiled);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
|
||||
const KEYBINDINGS_CONFIG_PATH = path.join(".t3", "keybindings.json");
|
||||
const MAX_KEYBINDINGS = 256;
|
||||
|
||||
class KeybindingsConfigParseError extends Error {
|
||||
constructor(configPath: string, detail: string, options?: { cause?: unknown }) {
|
||||
super(`Unable to parse keybindings config at ${configPath}: ${detail}`, options);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveKeybindingsConfigPath(): string {
|
||||
return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
|
||||
}
|
||||
|
||||
function loadCustomKeybindingsConfig(
|
||||
logger: KeybindingsLogger,
|
||||
options?: {
|
||||
throwOnUnreadableConfig?: boolean;
|
||||
},
|
||||
): KeybindingsConfig {
|
||||
const configPath = resolveKeybindingsConfigPath();
|
||||
try {
|
||||
const raw = fs.readFileSync(configPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) {
|
||||
if (options?.throwOnUnreadableConfig) {
|
||||
throw new KeybindingsConfigParseError(configPath, "expected JSON array");
|
||||
}
|
||||
logger.warn("ignoring keybindings config with unsupported format; expected array", {
|
||||
path: configPath,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
|
||||
const sanitized: KeybindingsConfig = [];
|
||||
let invalidEntries = 0;
|
||||
for (const entry of parsed) {
|
||||
const result = keybindingRuleSchema.safeParse(entry);
|
||||
if (result.success) {
|
||||
if (!compileResolvedKeybindingRule(result.data)) {
|
||||
invalidEntries += 1;
|
||||
continue;
|
||||
}
|
||||
sanitized.push(result.data);
|
||||
continue;
|
||||
}
|
||||
invalidEntries += 1;
|
||||
}
|
||||
if (invalidEntries > 0) {
|
||||
logger.warn("ignoring invalid keybinding entries", {
|
||||
path: configPath,
|
||||
invalidEntries,
|
||||
totalEntries: parsed.length,
|
||||
});
|
||||
}
|
||||
return sanitized;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
|
||||
return [];
|
||||
}
|
||||
if (options?.throwOnUnreadableConfig) {
|
||||
if (error instanceof KeybindingsConfigParseError) {
|
||||
throw error;
|
||||
}
|
||||
throw new KeybindingsConfigParseError(
|
||||
configPath,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
logger.warn("ignoring malformed keybindings config", {
|
||||
path: configPath,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeConfigAtomically(configPath: string, config: KeybindingsConfig): void {
|
||||
const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
try {
|
||||
fs.writeFileSync(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
||||
fs.renameSync(tempPath, configPath);
|
||||
} catch (error) {
|
||||
fs.rmSync(tempPath, { force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
if (custom.length === 0) {
|
||||
return [...DEFAULT_RESOLVED_KEYBINDINGS];
|
||||
}
|
||||
|
||||
const overriddenCommands = new Set(custom.map((binding) => binding.command));
|
||||
const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
|
||||
(binding) => !overriddenCommands.has(binding.command),
|
||||
);
|
||||
const merged = [...retainedDefaults, ...custom];
|
||||
|
||||
if (merged.length <= MAX_KEYBINDINGS) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
|
||||
return merged.slice(-MAX_KEYBINDINGS);
|
||||
}
|
||||
|
||||
export function loadResolvedKeybindingsConfig(
|
||||
logger: KeybindingsLogger,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const customConfig = loadCustomKeybindingsConfig(logger);
|
||||
const compiledCustomConfig = compileResolvedKeybindingsConfig(customConfig);
|
||||
const overriddenCommands = new Set(compiledCustomConfig.map((entry) => entry.command));
|
||||
const mergedBeforeCapLength =
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
|
||||
.length + compiledCustomConfig.length;
|
||||
const merged = mergeWithDefaultKeybindings(compiledCustomConfig);
|
||||
if (mergedBeforeCapLength > MAX_KEYBINDINGS) {
|
||||
logger.warn("truncating merged keybindings config to max entries", {
|
||||
path: resolveKeybindingsConfigPath(),
|
||||
maxEntries: MAX_KEYBINDINGS,
|
||||
});
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function upsertKeybindingRule(
|
||||
logger: KeybindingsLogger,
|
||||
rawRule: unknown,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const rule = keybindingRuleSchema.parse(rawRule);
|
||||
if (!compileResolvedKeybindingRule(rule)) {
|
||||
throw new Error(`Invalid keybinding shortcut: "${rule.key}"`);
|
||||
}
|
||||
|
||||
const configPath = resolveKeybindingsConfigPath();
|
||||
const customConfig = loadCustomKeybindingsConfig(logger, {
|
||||
throwOnUnreadableConfig: true,
|
||||
});
|
||||
const nextConfig = [...customConfig.filter((entry) => entry.command !== rule.command), rule];
|
||||
const cappedConfig =
|
||||
nextConfig.length > MAX_KEYBINDINGS ? nextConfig.slice(-MAX_KEYBINDINGS) : nextConfig;
|
||||
|
||||
if (nextConfig.length > MAX_KEYBINDINGS) {
|
||||
logger.warn("truncating keybindings config to max entries", {
|
||||
path: configPath,
|
||||
maxEntries: MAX_KEYBINDINGS,
|
||||
});
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
||||
writeConfigAtomically(configPath, cappedConfig);
|
||||
|
||||
const compiledCustomConfig = compileResolvedKeybindingsConfig(cappedConfig);
|
||||
return mergeWithDefaultKeybindings(compiledCustomConfig);
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
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",
|
||||
};
|
||||
|
||||
const event1 = service.ingestProviderEvent({
|
||||
...baseEvent,
|
||||
id: "evt-1",
|
||||
createdAt: iso(10),
|
||||
method: "item/started",
|
||||
payload: {
|
||||
item: {
|
||||
type: "agentMessage",
|
||||
id: "assistant-msg-1",
|
||||
text: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(event1?.seq).toBeGreaterThan(0);
|
||||
|
||||
const event2 = 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",
|
||||
},
|
||||
});
|
||||
expect((event2?.seq ?? 0) > (event1?.seq ?? 0)).toBe(true);
|
||||
|
||||
const event3 = service.ingestProviderEvent({
|
||||
...baseEvent,
|
||||
id: "evt-3",
|
||||
createdAt: iso(30),
|
||||
method: "item/completed",
|
||||
payload: {
|
||||
item: {
|
||||
type: "agentMessage",
|
||||
id: "assistant-msg-1",
|
||||
text: "hi there",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect((event3?.seq ?? 0) > (event2?.seq ?? 0)).toBe(true);
|
||||
|
||||
const event4 = service.ingestProviderEvent({
|
||||
...baseEvent,
|
||||
id: "evt-4",
|
||||
createdAt: iso(40),
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect((event4?.seq ?? 0) > (event3?.seq ?? 0)).toBe(true);
|
||||
|
||||
const snapshot = service.loadSnapshot();
|
||||
expect(snapshot.projects).toHaveLength(1);
|
||||
expect(snapshot.threads).toHaveLength(1);
|
||||
const thread = snapshot.threads[0];
|
||||
expect(thread?.messages.map((message) => message.id)).toEqual([
|
||||
"msg-user-1",
|
||||
"assistant-msg-1",
|
||||
]);
|
||||
expect(thread?.messages[1]?.text).toBe("hi there");
|
||||
expect(thread?.turnDiffSummaries[0]?.turnId).toBe("turn-1");
|
||||
expect(thread?.turnDiffSummaries[0]?.assistantMessageId).toBe("assistant-msg-1");
|
||||
|
||||
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);
|
||||
|
||||
const providerCatchUp = service.providerCatchUp({ afterSeq: 0 });
|
||||
expect(providerCatchUp.lastProviderSeq).toBe(event4?.seq ?? 0);
|
||||
expect(providerCatchUp.events.map((event) => event.id)).toEqual([
|
||||
"evt-1",
|
||||
"evt-2",
|
||||
"evt-3",
|
||||
"evt-4",
|
||||
]);
|
||||
const providerSeqs = providerCatchUp.events.map((event) => event.seq ?? 0);
|
||||
for (let index = 1; index < providerSeqs.length; index += 1) {
|
||||
expect(providerSeqs[index]).toBeGreaterThan(providerSeqs[index - 1] ?? Number.NEGATIVE_INFINITY);
|
||||
}
|
||||
|
||||
const providerCatchUpAfterSecond = service.providerCatchUp({
|
||||
afterSeq: event2?.seq ?? 0,
|
||||
});
|
||||
expect(providerCatchUpAfterSecond.events.map((event) => event.id)).toEqual(["evt-3", "evt-4"]);
|
||||
} 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();
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("ProjectRegistry scripts", () => {
|
||||
it("stores and reloads project scripts", () => {
|
||||
const stateDir = makeTempDir("t3code-project-registry-state-");
|
||||
const projectDir = makeTempDir("t3code-project-registry-project-");
|
||||
const registry = new ProjectRegistry(stateDir);
|
||||
|
||||
const created = registry.add({ cwd: projectDir }).project;
|
||||
const updated = registry.updateScripts({
|
||||
id: created.id,
|
||||
scripts: [
|
||||
{
|
||||
id: "run",
|
||||
name: "Run",
|
||||
command: "bun run dev",
|
||||
icon: "play",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(updated.project.scripts).toHaveLength(2);
|
||||
expect(updated.project.scripts[1]?.id).toBe("setup");
|
||||
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(true);
|
||||
|
||||
const reloaded = new ProjectRegistry(stateDir);
|
||||
const listed = reloaded.list();
|
||||
expect(listed).toHaveLength(1);
|
||||
expect(listed[0]?.scripts).toHaveLength(2);
|
||||
expect(listed[0]?.scripts[0]?.id).toBe("run");
|
||||
expect(listed[0]?.scripts[1]?.id).toBe("setup");
|
||||
registry.close();
|
||||
reloaded.close();
|
||||
});
|
||||
|
||||
it("deduplicates script ids and allows only one setup script", () => {
|
||||
const stateDir = makeTempDir("t3code-project-registry-state-");
|
||||
const projectDir = makeTempDir("t3code-project-registry-project-");
|
||||
const registry = new ProjectRegistry(stateDir);
|
||||
const created = registry.add({ cwd: projectDir }).project;
|
||||
|
||||
const updated = registry.updateScripts({
|
||||
id: created.id,
|
||||
scripts: [
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "echo setup",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup Duplicate",
|
||||
command: "echo duplicate",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
{
|
||||
id: "another",
|
||||
name: "Another Setup",
|
||||
command: "echo another",
|
||||
icon: "play",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(updated.project.scripts).toHaveLength(2);
|
||||
expect(updated.project.scripts[0]?.id).toBe("setup");
|
||||
expect(updated.project.scripts[0]?.runOnWorktreeCreate).toBe(true);
|
||||
expect(updated.project.scripts[1]?.id).toBe("another");
|
||||
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(false);
|
||||
registry.close();
|
||||
});
|
||||
|
||||
it("throws when updating scripts for an unknown project id", () => {
|
||||
const stateDir = makeTempDir("t3code-project-registry-state-");
|
||||
const registry = new ProjectRegistry(stateDir);
|
||||
|
||||
expect(() =>
|
||||
registry.updateScripts({
|
||||
id: "missing-project",
|
||||
scripts: [],
|
||||
}),
|
||||
).toThrowError("Project not found");
|
||||
registry.close();
|
||||
});
|
||||
});
|
||||
@@ -1,172 +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,
|
||||
projectAddInputSchema,
|
||||
projectRecordSchema,
|
||||
projectRemoveInputSchema,
|
||||
import type {
|
||||
ProjectAddInput,
|
||||
ProjectAddResult,
|
||||
ProjectListResult,
|
||||
ProjectRemoveInput,
|
||||
ProjectUpdateScriptsInput,
|
||||
ProjectUpdateScriptsResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
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 }));
|
||||
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 }, created: false };
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const project: ProjectRecord = {
|
||||
id: randomUUID(),
|
||||
cwd: normalizedCwd,
|
||||
name: inferProjectName(normalizedCwd),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.projects = [project, ...this.projects];
|
||||
this.persist();
|
||||
return { project: { ...project }, 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);
|
||||
}
|
||||
|
||||
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),
|
||||
};
|
||||
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 ||
|
||||
source.createdAt !== project.createdAt ||
|
||||
source.updatedAt !== project.updatedAt
|
||||
);
|
||||
});
|
||||
|
||||
if (changed) {
|
||||
this.projects = normalizedProjects;
|
||||
this.persist();
|
||||
}
|
||||
|
||||
return normalizedProjects;
|
||||
updateScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
|
||||
return this.persistenceService.updateProjectScripts(raw);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,60 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ProviderManager } from "./providerManager";
|
||||
|
||||
describe("ProviderManager", () => {
|
||||
it("emits persisted provider events with durable sequence metadata when available", () => {
|
||||
const ingestProviderEvent = vi.fn((event: {
|
||||
id: string;
|
||||
kind: "notification";
|
||||
provider: "codex";
|
||||
sessionId: string;
|
||||
createdAt: string;
|
||||
method: string;
|
||||
threadId: string;
|
||||
}) => ({
|
||||
...event,
|
||||
seq: 11,
|
||||
}));
|
||||
const persistenceService = {
|
||||
ingestProviderEvent,
|
||||
unbindSession: vi.fn(),
|
||||
};
|
||||
const manager = new ProviderManager({
|
||||
persistenceService: persistenceService as never,
|
||||
});
|
||||
const events: Array<{ id: string; seq?: number }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({ id: event.id, seq: event.seq });
|
||||
});
|
||||
|
||||
const internals = manager as unknown as {
|
||||
onCodexEvent: (event: {
|
||||
id: string;
|
||||
kind: "notification";
|
||||
provider: "codex";
|
||||
sessionId: string;
|
||||
createdAt: string;
|
||||
method: string;
|
||||
threadId: string;
|
||||
}) => void;
|
||||
};
|
||||
|
||||
internals.onCodexEvent({
|
||||
id: "evt-seq-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "turn/started",
|
||||
threadId: "thread-1",
|
||||
});
|
||||
|
||||
expect(ingestProviderEvent).toHaveBeenCalledTimes(1);
|
||||
expect(events).toEqual([{ id: "evt-seq-1", seq: 11 }]);
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("detaches provider event listener and ends thread log streams on dispose", () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
@@ -59,4 +111,821 @@ describe("ProviderManager", () => {
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("rejects checkpoint operations for unknown sessions", async () => {
|
||||
const manager = new ProviderManager();
|
||||
|
||||
await expect(
|
||||
manager.listCheckpoints({
|
||||
sessionId: "missing-session",
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
await expect(
|
||||
manager.revertToCheckpoint({
|
||||
sessionId: "missing-session",
|
||||
turnCount: 0,
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
await expect(
|
||||
manager.getCheckpointDiff({
|
||||
sessionId: "missing-session",
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("derives checkpoints from thread turns", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const codex = (
|
||||
manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
).codex;
|
||||
|
||||
codex.hasSession = () => true;
|
||||
codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [
|
||||
{
|
||||
type: "userMessage",
|
||||
content: [{ type: "text", text: "Refactor the logger" }],
|
||||
},
|
||||
{
|
||||
type: "agentMessage",
|
||||
text: "I refactored it.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await manager.listCheckpoints({
|
||||
sessionId: "sess_1",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
threadId: "thr_1",
|
||||
checkpoints: [
|
||||
{
|
||||
id: "root",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
label: "Start of conversation",
|
||||
isCurrent: false,
|
||||
},
|
||||
{
|
||||
id: "turn_1",
|
||||
turnCount: 1,
|
||||
messageCount: 2,
|
||||
label: "Turn 1",
|
||||
preview: "Refactor the logger",
|
||||
isCurrent: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("rolls back from a selected checkpoint turn count", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (
|
||||
sessionId: string,
|
||||
numTurns: number,
|
||||
) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
hasCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
restoreCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
pruneAfterTurn: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
maxTurnCount: number;
|
||||
}) => Promise<void>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
const rollbackCalls: Array<{ sessionId: string; numTurns: number }> = [];
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
{ id: "turn_3", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = async (sessionId, numTurns) => {
|
||||
rollbackCalls.push({ sessionId, numTurns });
|
||||
return {
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
};
|
||||
};
|
||||
const hasCheckpoint = vi.fn(async () => true);
|
||||
const restoreCheckpoint = vi.fn(async () => true);
|
||||
const pruneAfterTurn = vi.fn(async () => undefined);
|
||||
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
|
||||
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
|
||||
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
const result = await manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
|
||||
expect(rollbackCalls).toEqual([{ sessionId: "sess_1", numTurns: 2 }]);
|
||||
expect(result.threadId).toBe("thr_1");
|
||||
expect(result.turnCount).toBe(1);
|
||||
expect(result.messageCount).toBe(0);
|
||||
expect(result.rolledBackTurns).toBe(2);
|
||||
expect(result.checkpoints).toHaveLength(2);
|
||||
expect(hasCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(restoreCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(pruneAfterTurn).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
maxTurnCount: 1,
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("returns diff text for a checkpoint range", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
diffCheckpoints: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
fromTurnCount: number;
|
||||
toTurnCount: number;
|
||||
}) => Promise<string>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
|
||||
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
const result = await manager.getCheckpointDiff({
|
||||
sessionId: "sess_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
threadId: "thr_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
diff: "diff --git a/a.ts b/a.ts",
|
||||
});
|
||||
expect(diffCheckpoints).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("emits checkpoint/captured after turn completion checkpoint capture", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const events: Array<{ method: string; payload?: unknown; threadId?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
method: event.method,
|
||||
...(event.payload !== undefined ? { payload: event.payload } : {}),
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const internals = manager as unknown as {
|
||||
onCodexEvent: (event: {
|
||||
id: string;
|
||||
kind: "notification";
|
||||
provider: "codex";
|
||||
sessionId: string;
|
||||
createdAt: string;
|
||||
method: string;
|
||||
threadId: string;
|
||||
}) => void;
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
captureCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<void>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
});
|
||||
const captureCheckpoint = vi.fn(async () => undefined);
|
||||
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
internals.onCodexEvent({
|
||||
id: "evt-turn-complete",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess_1",
|
||||
createdAt: "2026-02-19T00:00:00.000Z",
|
||||
method: "turn/completed",
|
||||
threadId: "thr_1",
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(captureCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(events.some((event) => event.method === "checkpoint/captured")).toBe(true);
|
||||
});
|
||||
|
||||
const checkpointCapturedEvent = events.find((event) => event.method === "checkpoint/captured");
|
||||
expect(checkpointCapturedEvent?.threadId).toBe("thr_1");
|
||||
expect(checkpointCapturedEvent?.payload).toEqual({
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("lazily initializes filesystem checkpoints before diffing when cache is missing", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
listSessions: () => Array<{
|
||||
sessionId: string;
|
||||
provider: "codex";
|
||||
status: "ready";
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
cwd?: string;
|
||||
}>;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
||||
ensureRootCheckpoint: (input: { cwd: string; threadId: string }) => Promise<boolean>;
|
||||
captureCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<void>;
|
||||
diffCheckpoints: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
fromTurnCount: number;
|
||||
toTurnCount: number;
|
||||
}) => Promise<string>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.listSessions = () => [
|
||||
{
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-18T00:00:00.000Z",
|
||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
||||
cwd: "/repo",
|
||||
},
|
||||
];
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
const isGitRepository = vi.fn(async () => true);
|
||||
const ensureRootCheckpoint = vi.fn(async () => true);
|
||||
const captureCheckpoint = vi.fn(async () => undefined);
|
||||
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
|
||||
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
|
||||
internals.filesystemCheckpointStore.ensureRootCheckpoint = ensureRootCheckpoint;
|
||||
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
|
||||
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
|
||||
internals.sessionCheckpointCwds.delete("sess_1");
|
||||
|
||||
const result = await manager.getCheckpointDiff({
|
||||
sessionId: "sess_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
});
|
||||
|
||||
expect(result.diff).toBe("diff --git a/a.ts b/a.ts");
|
||||
expect(isGitRepository).toHaveBeenCalledWith("/repo");
|
||||
expect(captureCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 2,
|
||||
});
|
||||
expect(ensureRootCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
});
|
||||
expect(diffCheckpoints).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
});
|
||||
expect(internals.sessionCheckpointCwds.get("sess_1")).toBe("/repo");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("falls back to process cwd for lazy checkpoint init when session cwd is missing", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
listSessions: () => Array<{
|
||||
sessionId: string;
|
||||
provider: "codex";
|
||||
status: "ready";
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
cwd?: string;
|
||||
}>;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
||||
ensureRootCheckpoint: (input: { cwd: string; threadId: string }) => Promise<boolean>;
|
||||
captureCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<void>;
|
||||
diffCheckpoints: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
fromTurnCount: number;
|
||||
toTurnCount: number;
|
||||
}) => Promise<string>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
const processCwd = vi.spyOn(process, "cwd").mockReturnValue("/fallback-repo");
|
||||
try {
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.listSessions = () => [
|
||||
{
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-18T00:00:00.000Z",
|
||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
});
|
||||
const isGitRepository = vi.fn(async (cwd: string) => cwd === "/fallback-repo");
|
||||
const ensureRootCheckpoint = vi.fn(async () => true);
|
||||
const captureCheckpoint = vi.fn(async () => undefined);
|
||||
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
|
||||
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
|
||||
internals.filesystemCheckpointStore.ensureRootCheckpoint = ensureRootCheckpoint;
|
||||
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
|
||||
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
|
||||
internals.sessionCheckpointCwds.delete("sess_1");
|
||||
|
||||
const result = await manager.getCheckpointDiff({
|
||||
sessionId: "sess_1",
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(result.diff).toBe("diff --git a/a.ts b/a.ts");
|
||||
expect(isGitRepository).toHaveBeenCalledWith("/fallback-repo");
|
||||
expect(captureCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/fallback-repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(ensureRootCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/fallback-repo",
|
||||
threadId: "thr_1",
|
||||
});
|
||||
expect(diffCheckpoints).toHaveBeenCalledWith({
|
||||
cwd: "/fallback-repo",
|
||||
threadId: "thr_1",
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
expect(internals.sessionCheckpointCwds.get("sess_1")).toBe("/fallback-repo");
|
||||
} finally {
|
||||
processCwd.mockRestore();
|
||||
manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not fall back to process cwd when a session cwd exists but is not a git repo", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
listSessions: () => Array<{
|
||||
sessionId: string;
|
||||
provider: "codex";
|
||||
status: "ready";
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
cwd?: string;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
const processCwd = vi.spyOn(process, "cwd").mockReturnValue("/fallback-repo");
|
||||
try {
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.listSessions = () => [
|
||||
{
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-18T00:00:00.000Z",
|
||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
||||
cwd: "/session-cwd",
|
||||
},
|
||||
];
|
||||
const isGitRepository = vi.fn(async (cwd: string) => cwd === "/fallback-repo");
|
||||
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
|
||||
internals.sessionCheckpointCwds.delete("sess_1");
|
||||
|
||||
await expect(
|
||||
manager.getCheckpointDiff({
|
||||
sessionId: "sess_1",
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
}),
|
||||
).rejects.toThrow("Filesystem checkpoints are unavailable for this session.");
|
||||
expect(isGitRepository).toHaveBeenCalledWith("/session-cwd");
|
||||
expect(isGitRepository).not.toHaveBeenCalledWith("/fallback-repo");
|
||||
} finally {
|
||||
processCwd.mockRestore();
|
||||
manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("fails revert when filesystem checkpoints are unavailable for the session", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
listSessions: () => Array<{
|
||||
sessionId: string;
|
||||
provider: "codex";
|
||||
status: "ready";
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
cwd?: string;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.listSessions = () => [
|
||||
{
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-18T00:00:00.000Z",
|
||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
internals.filesystemCheckpointStore.isGitRepository = async () => false;
|
||||
internals.sessionCheckpointCwds.delete("sess_1");
|
||||
|
||||
await expect(
|
||||
manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
}),
|
||||
).rejects.toThrow("Filesystem checkpoints are unavailable for this session.");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("restores filesystem checkpoint when reverting and checkpointing is enabled", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (
|
||||
sessionId: string,
|
||||
numTurns: number,
|
||||
) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
hasCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
restoreCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
pruneAfterTurn: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
maxTurnCount: number;
|
||||
}) => Promise<void>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
const callOrder: string[] = [];
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = async () => {
|
||||
callOrder.push("rollback");
|
||||
return {
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
};
|
||||
};
|
||||
const hasCheckpoint = vi.fn(async () => true);
|
||||
const restoreCheckpoint = vi.fn(async () => {
|
||||
callOrder.push("restore");
|
||||
return true;
|
||||
});
|
||||
const pruneAfterTurn = vi.fn(async () => {
|
||||
callOrder.push("prune");
|
||||
return undefined;
|
||||
});
|
||||
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
|
||||
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
|
||||
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
const result = await manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
|
||||
expect(result.turnCount).toBe(1);
|
||||
expect(hasCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(restoreCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(pruneAfterTurn).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
maxTurnCount: 1,
|
||||
});
|
||||
expect(callOrder).toEqual(["restore", "rollback", "prune"]);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("reverts to turn 0 without requiring an explicit turn 0 checkpoint ref", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (
|
||||
sessionId: string,
|
||||
numTurns: number,
|
||||
) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
hasCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
restoreCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
pruneAfterTurn: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
maxTurnCount: number;
|
||||
}) => Promise<void>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [],
|
||||
});
|
||||
const hasCheckpoint = vi.fn(async () => false);
|
||||
const restoreCheckpoint = vi.fn(async () => true);
|
||||
const pruneAfterTurn = vi.fn(async () => undefined);
|
||||
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
|
||||
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
|
||||
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
const result = await manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 0,
|
||||
});
|
||||
|
||||
expect(result.turnCount).toBe(0);
|
||||
expect(hasCheckpoint).not.toHaveBeenCalled();
|
||||
expect(restoreCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 0,
|
||||
});
|
||||
expect(pruneAfterTurn).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
maxTurnCount: 0,
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("fails before rollback when filesystem checkpoint is missing", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (
|
||||
sessionId: string,
|
||||
numTurns: number,
|
||||
) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
hasCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
const rollbackSpy = vi.fn(async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
}));
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = rollbackSpy;
|
||||
internals.filesystemCheckpointStore.hasCheckpoint = async () => false;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
await expect(
|
||||
manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
}),
|
||||
).rejects.toThrow("Filesystem checkpoint is unavailable for turn 1 in thread thr_1.");
|
||||
expect(rollbackSpy).not.toHaveBeenCalled();
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,18 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import {
|
||||
type ProviderCheckpoint,
|
||||
type ProviderEvent,
|
||||
type ProviderGetCheckpointDiffInput,
|
||||
type ProviderGetCheckpointDiffResult,
|
||||
type ProviderInterruptTurnInput,
|
||||
type ProviderListCheckpointsInput,
|
||||
type ProviderListCheckpointsResult,
|
||||
type ProviderRevertToCheckpointInput,
|
||||
type ProviderRevertToCheckpointResult,
|
||||
type ProviderRespondToRequestInput,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
@@ -12,35 +20,176 @@ import {
|
||||
type ProviderStopSessionInput,
|
||||
type ProviderTurnStartResult,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerGetCheckpointDiffInputSchema,
|
||||
providerListCheckpointsInputSchema,
|
||||
providerRevertToCheckpointInputSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
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];
|
||||
}
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function asArray(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
|
||||
function trimToPreview(value: string): string {
|
||||
const normalized = value.replace(/\s+/g, " ").trim();
|
||||
if (normalized.length <= 120) {
|
||||
return normalized;
|
||||
}
|
||||
return `${normalized.slice(0, 117)}...`;
|
||||
}
|
||||
|
||||
function summarizeUserMessageContent(content: unknown[]): string | undefined {
|
||||
const segments: string[] = [];
|
||||
|
||||
for (const part of content) {
|
||||
const record = asObject(part);
|
||||
const type = asString(record?.type);
|
||||
if (!type) continue;
|
||||
|
||||
if (type === "text") {
|
||||
const text = asString(record?.text);
|
||||
if (text && text.trim().length > 0) {
|
||||
segments.push(text.trim());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type === "image") {
|
||||
segments.push("[Image attachment]");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type === "localImage") {
|
||||
segments.push("[Local image attachment]");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (segments.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return trimToPreview(segments.join(" "));
|
||||
}
|
||||
|
||||
function summarizeTurn(turn: CodexThreadTurnSnapshot): {
|
||||
messageCountDelta: number;
|
||||
preview?: string;
|
||||
} {
|
||||
let messageCountDelta = 0;
|
||||
let preview: string | undefined;
|
||||
|
||||
for (const item of turn.items) {
|
||||
const record = asObject(item);
|
||||
const type = asString(record?.type);
|
||||
if (!type) continue;
|
||||
|
||||
if (type === "userMessage") {
|
||||
messageCountDelta += 1;
|
||||
if (!preview) {
|
||||
const content = asArray(record?.content);
|
||||
preview = summarizeUserMessageContent(content);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type === "agentMessage") {
|
||||
messageCountDelta += 1;
|
||||
if (!preview) {
|
||||
const text = asString(record?.text);
|
||||
if (text && text.trim().length > 0) {
|
||||
preview = trimToPreview(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
messageCountDelta,
|
||||
...(preview ? { preview } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function buildCheckpoints(turns: CodexThreadTurnSnapshot[]): ProviderCheckpoint[] {
|
||||
const checkpoints: ProviderCheckpoint[] = [];
|
||||
let messageCount = 0;
|
||||
const isEmpty = turns.length === 0;
|
||||
checkpoints.push({
|
||||
id: "root",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
label: "Start of conversation",
|
||||
isCurrent: isEmpty,
|
||||
});
|
||||
|
||||
for (let index = 0; index < turns.length; index += 1) {
|
||||
const turn = turns[index];
|
||||
if (!turn) continue;
|
||||
const turnSummary = summarizeTurn(turn);
|
||||
messageCount += turnSummary.messageCountDelta;
|
||||
checkpoints.push({
|
||||
id: turn.id,
|
||||
turnCount: index + 1,
|
||||
messageCount,
|
||||
label: `Turn ${index + 1}`,
|
||||
...(turnSummary.preview ? { preview: turnSummary.preview } : {}),
|
||||
isCurrent: index === turns.length - 1,
|
||||
});
|
||||
}
|
||||
|
||||
return checkpoints;
|
||||
}
|
||||
|
||||
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>();
|
||||
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>();
|
||||
private readonly sessionCheckpointCwds = new Map<string, string>();
|
||||
private readonly filesystemLocks = new Map<string, Promise<void>>();
|
||||
private disposed = false;
|
||||
private readonly onCodexEvent = (event: ProviderEvent) => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.routeEventToThreadLog(event);
|
||||
this.emit("event", event);
|
||||
const emittedEvent = this.publishProviderEvent(event);
|
||||
if (!emittedEvent) {
|
||||
return;
|
||||
}
|
||||
this.maybeCaptureFilesystemCheckpoint(emittedEvent);
|
||||
};
|
||||
|
||||
constructor() {
|
||||
constructor(options: ProviderManagerOptions = {}) {
|
||||
super();
|
||||
this.persistenceService = options.persistenceService;
|
||||
|
||||
const logsDir = path.resolve(process.cwd(), ".logs");
|
||||
this.threadLogsDir = path.join(logsDir, "threads");
|
||||
@@ -56,10 +205,26 @@ 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);
|
||||
}
|
||||
await this.initializeFilesystemCheckpointing(session, input.cwd).catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(session.sessionId, message, session.threadId);
|
||||
});
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -69,6 +234,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);
|
||||
}
|
||||
|
||||
@@ -93,14 +263,141 @@ 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);
|
||||
this.filesystemLocks.delete(input.sessionId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
return this.codex.listSessions();
|
||||
}
|
||||
|
||||
async listCheckpoints(raw: ProviderListCheckpointsInput): Promise<ProviderListCheckpointsResult> {
|
||||
const input = providerListCheckpointsInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
const snapshot = await this.codex.readThread(input.sessionId);
|
||||
return {
|
||||
threadId: snapshot.threadId,
|
||||
checkpoints: buildCheckpoints(snapshot.turns),
|
||||
};
|
||||
}
|
||||
|
||||
async getCheckpointDiff(
|
||||
raw: ProviderGetCheckpointDiffInput,
|
||||
): Promise<ProviderGetCheckpointDiffResult> {
|
||||
const input = providerGetCheckpointDiffInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId);
|
||||
if (!checkpointCwd) {
|
||||
throw new Error("Filesystem checkpoints are unavailable for this session.");
|
||||
}
|
||||
|
||||
return this.withFilesystemLock(input.sessionId, async () => {
|
||||
const snapshot = await this.codex.readThread(input.sessionId);
|
||||
if (input.toTurnCount > snapshot.turns.length) {
|
||||
throw new Error(
|
||||
`Checkpoint turn count ${input.toTurnCount} exceeds current turn count ${snapshot.turns.length}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const diff = await this.filesystemCheckpointStore.diffCheckpoints({
|
||||
cwd: checkpointCwd,
|
||||
threadId: snapshot.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
});
|
||||
|
||||
return {
|
||||
threadId: snapshot.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async revertToCheckpoint(
|
||||
raw: ProviderRevertToCheckpointInput,
|
||||
): Promise<ProviderRevertToCheckpointResult> {
|
||||
const input = providerRevertToCheckpointInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId);
|
||||
if (!checkpointCwd) {
|
||||
throw new Error("Filesystem checkpoints are unavailable for this session.");
|
||||
}
|
||||
return this.withFilesystemLock(input.sessionId, async () => {
|
||||
const beforeSnapshot = await this.codex.readThread(input.sessionId);
|
||||
const currentTurnCount = beforeSnapshot.turns.length;
|
||||
if (input.turnCount > currentTurnCount) {
|
||||
throw new Error(
|
||||
`Checkpoint turn count ${input.turnCount} exceeds current turn count ${currentTurnCount}.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (checkpointCwd && input.turnCount > 0) {
|
||||
const hasCheckpoint = await this.filesystemCheckpointStore.hasCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: beforeSnapshot.threadId,
|
||||
turnCount: input.turnCount,
|
||||
});
|
||||
if (!hasCheckpoint) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const restored = await this.filesystemCheckpointStore.restoreCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: beforeSnapshot.threadId,
|
||||
turnCount: input.turnCount,
|
||||
});
|
||||
if (!restored) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const requestedRollbackTurns = currentTurnCount - input.turnCount;
|
||||
const afterSnapshot =
|
||||
requestedRollbackTurns > 0
|
||||
? await this.codex.rollbackThread(input.sessionId, requestedRollbackTurns)
|
||||
: beforeSnapshot;
|
||||
|
||||
await this.filesystemCheckpointStore.pruneAfterTurn({
|
||||
cwd: checkpointCwd,
|
||||
threadId: afterSnapshot.threadId,
|
||||
maxTurnCount: afterSnapshot.turns.length,
|
||||
});
|
||||
|
||||
const checkpoints = buildCheckpoints(afterSnapshot.turns);
|
||||
const currentCheckpoint =
|
||||
checkpoints.find((checkpoint) => checkpoint.isCurrent) ??
|
||||
checkpoints[checkpoints.length - 1] ??
|
||||
checkpoints[0];
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - afterSnapshot.turns.length);
|
||||
|
||||
return {
|
||||
threadId: afterSnapshot.threadId,
|
||||
turnCount: currentCheckpoint?.turnCount ?? 0,
|
||||
messageCount: currentCheckpoint?.messageCount ?? 0,
|
||||
rolledBackTurns,
|
||||
checkpoints,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
stopAll(): void {
|
||||
this.codex.stopAll();
|
||||
}
|
||||
@@ -118,6 +415,196 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.threadLogStreams.clear();
|
||||
this.sessionThreadIds.clear();
|
||||
this.pendingEventsBySession.clear();
|
||||
this.sessionCheckpointCwds.clear();
|
||||
this.filesystemLocks.clear();
|
||||
}
|
||||
|
||||
private async initializeFilesystemCheckpointing(
|
||||
session: ProviderSession,
|
||||
preferredCwd?: string,
|
||||
): Promise<void> {
|
||||
const cwd = preferredCwd ?? session.cwd ?? process.cwd();
|
||||
|
||||
await this.withFilesystemLock(session.sessionId, async () => {
|
||||
const supportsGit = await this.filesystemCheckpointStore.isGitRepository(cwd);
|
||||
if (!supportsGit) {
|
||||
this.sessionCheckpointCwds.delete(session.sessionId);
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = await this.codex.readThread(session.sessionId);
|
||||
await this.filesystemCheckpointStore.ensureRootCheckpoint({
|
||||
cwd,
|
||||
threadId: snapshot.threadId,
|
||||
});
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
if (this.codex.hasSession(session.sessionId)) {
|
||||
this.sessionCheckpointCwds.set(session.sessionId, cwd);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async getOrInitializeFilesystemCheckpointCwd(sessionId: string): Promise<string | null> {
|
||||
const existingCwd = this.sessionCheckpointCwds.get(sessionId);
|
||||
if (existingCwd) {
|
||||
return existingCwd;
|
||||
}
|
||||
|
||||
const session = this.codex
|
||||
.listSessions()
|
||||
.find((candidate) => candidate.sessionId === sessionId);
|
||||
const candidateCwds = session?.cwd ? [session.cwd] : [process.cwd()];
|
||||
|
||||
await this.withFilesystemLock(sessionId, async () => {
|
||||
const currentCwd = this.sessionCheckpointCwds.get(sessionId);
|
||||
if (currentCwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cwdSupport = await Promise.all(
|
||||
candidateCwds.map(async (cwd) => ({
|
||||
cwd,
|
||||
supportsGit: await this.filesystemCheckpointStore.isGitRepository(cwd),
|
||||
})),
|
||||
);
|
||||
const supportedCwd = cwdSupport.find((entry) => entry.supportsGit)?.cwd;
|
||||
if (supportedCwd) {
|
||||
const snapshot = await this.codex.readThread(sessionId);
|
||||
await this.filesystemCheckpointStore.ensureRootCheckpoint({
|
||||
cwd: supportedCwd,
|
||||
threadId: snapshot.threadId,
|
||||
});
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd: supportedCwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
if (this.codex.hasSession(sessionId)) {
|
||||
this.sessionCheckpointCwds.set(sessionId, supportedCwd);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.sessionCheckpointCwds.delete(sessionId);
|
||||
});
|
||||
|
||||
return this.sessionCheckpointCwds.get(sessionId) ?? null;
|
||||
}
|
||||
|
||||
private maybeCaptureFilesystemCheckpoint(event: ProviderEvent): void {
|
||||
if (event.kind !== "notification" || event.method !== "turn/completed") {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
|
||||
if (!checkpointCwd) {
|
||||
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId)
|
||||
.then(async (initializedCwd) => {
|
||||
if (!initializedCwd || !this.codex.hasSession(event.sessionId)) {
|
||||
return;
|
||||
}
|
||||
const snapshot = await this.codex.readThread(event.sessionId);
|
||||
await this.persistCheckpointSummaryForTurn(event, initializedCwd, snapshot.threadId, snapshot.turns);
|
||||
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
|
||||
})
|
||||
.catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void this.withFilesystemLock(event.sessionId, async () => {
|
||||
if (!this.codex.hasSession(event.sessionId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = await this.codex.readThread(event.sessionId);
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
await this.persistCheckpointSummaryForTurn(event, checkpointCwd, snapshot.threadId, snapshot.turns);
|
||||
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
|
||||
}).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
}
|
||||
|
||||
private emitCheckpointCaptured(sessionId: string, threadId: string, turnCount: number): void {
|
||||
this.publishProviderEvent({
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "checkpoint/captured",
|
||||
threadId,
|
||||
payload: {
|
||||
threadId,
|
||||
turnCount,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private emitFilesystemCheckpointError(
|
||||
sessionId: string,
|
||||
message: string,
|
||||
threadId?: string,
|
||||
): void {
|
||||
this.publishProviderEvent({
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "checkpoint/filesystemError",
|
||||
message,
|
||||
...(threadId ? { threadId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
private publishProviderEvent(event: ProviderEvent): ProviderEvent | null {
|
||||
let emittedEvent = event;
|
||||
try {
|
||||
const persistedEvent = this.persistenceService?.ingestProviderEvent(event);
|
||||
if (this.persistenceService && !persistedEvent) {
|
||||
return null;
|
||||
}
|
||||
emittedEvent = persistedEvent ?? event;
|
||||
} catch {
|
||||
// Persistence failures should not break provider streaming.
|
||||
}
|
||||
|
||||
this.routeEventToThreadLog(emittedEvent);
|
||||
if (emittedEvent.method === "session/closed" || emittedEvent.method === "session/exited") {
|
||||
this.persistenceService?.unbindSession(emittedEvent.sessionId);
|
||||
}
|
||||
this.emit("event", emittedEvent);
|
||||
return emittedEvent;
|
||||
}
|
||||
|
||||
private withFilesystemLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
|
||||
const previous = this.filesystemLocks.get(sessionId) ?? Promise.resolve();
|
||||
const next = previous.catch(() => undefined).then(fn);
|
||||
const completion = next.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
this.filesystemLocks.set(sessionId, completion);
|
||||
return next.finally(() => {
|
||||
const tracked = this.filesystemLocks.get(sessionId);
|
||||
if (tracked === completion) {
|
||||
this.filesystemLocks.delete(sessionId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private routeEventToThreadLog(event: ProviderEvent): void {
|
||||
@@ -199,4 +686,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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ export interface PtyProcess {
|
||||
|
||||
export interface PtySpawnInput {
|
||||
shell: string;
|
||||
args?: string[];
|
||||
cwd: string;
|
||||
cols: number;
|
||||
rows: number;
|
||||
@@ -118,7 +119,7 @@ class NodePtyProcess implements PtyProcess {
|
||||
export class NodePtyAdapter implements PtyAdapter {
|
||||
spawn(input: PtySpawnInput): PtyProcess {
|
||||
ensureNodePtySpawnHelperExecutable();
|
||||
const ptyProcess = nodePty.spawn(input.shell, [], {
|
||||
const ptyProcess = nodePty.spawn(input.shell, input.args ?? [], {
|
||||
cwd: input.cwd,
|
||||
cols: input.cols,
|
||||
rows: input.rows,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -196,6 +196,65 @@ describe("TerminalManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("resizes running terminal on open when a different size is requested", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput({ cols: 100, rows: 24 }));
|
||||
const process = ptyAdapter.processes[0];
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
|
||||
await manager.open(openInput({ cols: 140, rows: 40 }));
|
||||
|
||||
expect(process.resizeCalls).toEqual([{ cols: 140, rows: 40 }]);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("preserves existing terminal size on open when size is omitted", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput({ cols: 100, rows: 24 }));
|
||||
const ptyProcess = ptyAdapter.processes[0];
|
||||
expect(ptyProcess).toBeDefined();
|
||||
if (!ptyProcess) return;
|
||||
|
||||
await manager.open({
|
||||
threadId: "thread-1",
|
||||
cwd: globalThis.process.cwd(),
|
||||
});
|
||||
|
||||
expect(ptyProcess.resizeCalls).toEqual([]);
|
||||
|
||||
ptyProcess.emitExit({ exitCode: 0, signal: 0 });
|
||||
await manager.open({
|
||||
threadId: "thread-1",
|
||||
cwd: globalThis.process.cwd(),
|
||||
});
|
||||
|
||||
const resumedSpawn = ptyAdapter.spawnInputs[1];
|
||||
expect(resumedSpawn).toBeDefined();
|
||||
if (!resumedSpawn) return;
|
||||
expect(resumedSpawn.cols).toBe(100);
|
||||
expect(resumedSpawn.rows).toBe(24);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("uses default dimensions when opening a new terminal without size hints", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open({
|
||||
threadId: "thread-1",
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
|
||||
const spawned = ptyAdapter.spawnInputs[0];
|
||||
expect(spawned).toBeDefined();
|
||||
if (!spawned) return;
|
||||
expect(spawned.cols).toBe(120);
|
||||
expect(spawned.rows).toBe(30);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("supports multiple terminals per thread with isolated sessions", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput({ terminalId: "default" }));
|
||||
@@ -466,4 +525,42 @@ describe("TerminalManager", () => {
|
||||
restoreEnv();
|
||||
}
|
||||
});
|
||||
|
||||
it("injects runtime env overrides into spawned terminals", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(
|
||||
openInput({
|
||||
env: {
|
||||
T3CODE_PROJECT_ROOT: "/repo",
|
||||
T3CODE_WORKTREE_PATH: "/repo/worktree-a",
|
||||
CUSTOM_FLAG: "1",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const spawnInput = ptyAdapter.spawnInputs[0];
|
||||
expect(spawnInput).toBeDefined();
|
||||
if (!spawnInput) return;
|
||||
|
||||
expect(spawnInput.env.T3CODE_PROJECT_ROOT).toBe("/repo");
|
||||
expect(spawnInput.env.T3CODE_WORKTREE_PATH).toBe("/repo/worktree-a");
|
||||
expect(spawnInput.env.CUSTOM_FLAG).toBe("1");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("starts zsh with prompt spacer disabled to avoid `%` end markers", async () => {
|
||||
if (process.platform === "win32") return;
|
||||
const { manager, ptyAdapter } = makeManager(5, {
|
||||
shellResolver: () => "/bin/zsh",
|
||||
});
|
||||
await manager.open(openInput());
|
||||
const spawnInput = ptyAdapter.spawnInputs[0];
|
||||
expect(spawnInput).toBeDefined();
|
||||
if (!spawnInput) return;
|
||||
|
||||
expect(spawnInput.shell).toBe("/bin/zsh");
|
||||
expect(spawnInput.args).toEqual(["-o", "nopromptsp"]);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,8 @@ import { runProcess } from "./processRunner";
|
||||
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
|
||||
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
|
||||
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
|
||||
const DEFAULT_OPEN_COLS = 120;
|
||||
const DEFAULT_OPEN_ROWS = 30;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||
|
||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
@@ -59,8 +61,16 @@ interface TerminalSessionState {
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runtimeEnv: Record<string, string> | null;
|
||||
}
|
||||
|
||||
interface ShellCandidate {
|
||||
shell: string;
|
||||
args?: string[];
|
||||
}
|
||||
|
||||
type TerminalStartInput = TerminalOpenInput & { cols: number; rows: number };
|
||||
|
||||
function defaultShellResolver(): string {
|
||||
if (process.platform === "win32") {
|
||||
return process.env.ComSpec ?? "cmd.exe";
|
||||
@@ -82,34 +92,54 @@ function normalizeShellCommand(value: string | undefined): string | null {
|
||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||
}
|
||||
|
||||
function uniqueShells(shells: Array<string | null>): string[] {
|
||||
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
|
||||
if (!command || command.length === 0) return null;
|
||||
const shellName = path.basename(command).toLowerCase();
|
||||
if (process.platform !== "win32" && shellName === "zsh") {
|
||||
return { shell: command, args: ["-o", "nopromptsp"] };
|
||||
}
|
||||
return { shell: command };
|
||||
}
|
||||
|
||||
function formatShellCandidate(candidate: ShellCandidate): string {
|
||||
if (!candidate.args || candidate.args.length === 0) return candidate.shell;
|
||||
return `${candidate.shell} ${candidate.args.join(" ")}`;
|
||||
}
|
||||
|
||||
function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellCandidate[] {
|
||||
const seen = new Set<string>();
|
||||
const ordered: string[] = [];
|
||||
for (const shell of shells) {
|
||||
if (!shell || shell.length === 0) continue;
|
||||
if (seen.has(shell)) continue;
|
||||
seen.add(shell);
|
||||
ordered.push(shell);
|
||||
const ordered: ShellCandidate[] = [];
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) continue;
|
||||
const key = formatShellCandidate(candidate);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
ordered.push(candidate);
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
function resolveShellCandidates(shellResolver: () => string): string[] {
|
||||
const requested = normalizeShellCommand(shellResolver());
|
||||
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
|
||||
|
||||
if (process.platform === "win32") {
|
||||
return uniqueShells([requested, process.env.ComSpec ?? null, "powershell.exe", "cmd.exe"]);
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null),
|
||||
shellCandidateFromCommand("powershell.exe"),
|
||||
shellCandidateFromCommand("cmd.exe"),
|
||||
]);
|
||||
}
|
||||
|
||||
return uniqueShells([
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
normalizeShellCommand(process.env.SHELL),
|
||||
"/bin/zsh",
|
||||
"/bin/bash",
|
||||
"/bin/sh",
|
||||
"zsh",
|
||||
"bash",
|
||||
"sh",
|
||||
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
|
||||
shellCandidateFromCommand("/bin/zsh"),
|
||||
shellCandidateFromCommand("/bin/bash"),
|
||||
shellCandidateFromCommand("/bin/sh"),
|
||||
shellCandidateFromCommand("zsh"),
|
||||
shellCandidateFromCommand("bash"),
|
||||
shellCandidateFromCommand("sh"),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -241,16 +271,33 @@ function shouldExcludeTerminalEnvKey(key: string): boolean {
|
||||
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
|
||||
}
|
||||
|
||||
function createTerminalSpawnEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||
function createTerminalSpawnEnv(
|
||||
baseEnv: NodeJS.ProcessEnv,
|
||||
runtimeEnv?: Record<string, string> | null,
|
||||
): NodeJS.ProcessEnv {
|
||||
const spawnEnv: NodeJS.ProcessEnv = {};
|
||||
for (const [key, value] of Object.entries(baseEnv)) {
|
||||
if (value === undefined) continue;
|
||||
if (shouldExcludeTerminalEnvKey(key)) continue;
|
||||
spawnEnv[key] = value;
|
||||
}
|
||||
if (runtimeEnv) {
|
||||
for (const [key, value] of Object.entries(runtimeEnv)) {
|
||||
spawnEnv[key] = value;
|
||||
}
|
||||
}
|
||||
return spawnEnv;
|
||||
}
|
||||
|
||||
function normalizedRuntimeEnv(
|
||||
env: Record<string, string> | undefined,
|
||||
): Record<string, string> | null {
|
||||
if (!env) return null;
|
||||
const entries = Object.entries(env);
|
||||
if (entries.length === 0) return null;
|
||||
return Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right)));
|
||||
}
|
||||
|
||||
export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
private readonly sessions = new Map<string, TerminalSessionState>();
|
||||
private readonly logsDir: string;
|
||||
@@ -291,6 +338,8 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
if (!existing) {
|
||||
await this.flushPersistQueue(input.threadId, input.terminalId);
|
||||
const history = await this.readHistory(input.threadId, input.terminalId);
|
||||
const cols = input.cols ?? DEFAULT_OPEN_COLS;
|
||||
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
|
||||
const session: TerminalSessionState = {
|
||||
threadId: input.threadId,
|
||||
terminalId: input.terminalId,
|
||||
@@ -301,37 +350,49 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
cols: input.cols,
|
||||
rows: input.rows,
|
||||
cols,
|
||||
rows,
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
this.startSession(session, input, "started");
|
||||
this.startSession(session, { ...input, cols, rows }, "started");
|
||||
return this.snapshot(session);
|
||||
}
|
||||
|
||||
if (existing.cwd !== input.cwd) {
|
||||
const nextRuntimeEnv = normalizedRuntimeEnv(input.env);
|
||||
const currentRuntimeEnv = existing.runtimeEnv;
|
||||
const targetCols = input.cols ?? existing.cols;
|
||||
const targetRows = input.rows ?? existing.rows;
|
||||
const runtimeEnvChanged =
|
||||
JSON.stringify(currentRuntimeEnv) !== JSON.stringify(nextRuntimeEnv);
|
||||
|
||||
if (existing.cwd !== input.cwd || runtimeEnvChanged) {
|
||||
this.stopProcess(existing);
|
||||
existing.cwd = input.cwd;
|
||||
existing.runtimeEnv = nextRuntimeEnv;
|
||||
existing.history = "";
|
||||
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
|
||||
} else if (existing.status === "exited" || existing.status === "error") {
|
||||
existing.runtimeEnv = nextRuntimeEnv;
|
||||
existing.history = "";
|
||||
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
|
||||
} else if (currentRuntimeEnv !== nextRuntimeEnv) {
|
||||
existing.runtimeEnv = nextRuntimeEnv;
|
||||
}
|
||||
|
||||
if (!existing.process) {
|
||||
this.startSession(existing, input, "started");
|
||||
this.startSession(existing, { ...input, cols: targetCols, rows: targetRows }, "started");
|
||||
return this.snapshot(existing);
|
||||
}
|
||||
|
||||
if (existing.cols !== input.cols || existing.rows !== input.rows) {
|
||||
existing.cols = input.cols;
|
||||
existing.rows = input.rows;
|
||||
existing.process.resize(input.cols, input.rows);
|
||||
if (existing.cols !== targetCols || existing.rows !== targetRows) {
|
||||
existing.cols = targetCols;
|
||||
existing.rows = targetRows;
|
||||
existing.process.resize(targetCols, targetRows);
|
||||
existing.updatedAt = new Date().toISOString();
|
||||
}
|
||||
|
||||
@@ -388,6 +449,8 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
const sessionKey = toSessionKey(input.threadId, input.terminalId);
|
||||
let session = this.sessions.get(sessionKey);
|
||||
if (!session) {
|
||||
const cols = input.cols ?? DEFAULT_OPEN_COLS;
|
||||
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
|
||||
session = {
|
||||
threadId: input.threadId,
|
||||
terminalId: input.terminalId,
|
||||
@@ -398,22 +461,27 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
cols: input.cols,
|
||||
rows: input.rows,
|
||||
cols,
|
||||
rows,
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
} else {
|
||||
this.stopProcess(session);
|
||||
session.cwd = input.cwd;
|
||||
session.runtimeEnv = normalizedRuntimeEnv(input.env);
|
||||
}
|
||||
|
||||
const cols = input.cols ?? session.cols;
|
||||
const rows = input.rows ?? session.rows;
|
||||
|
||||
session.history = "";
|
||||
await this.persistHistory(input.threadId, input.terminalId, session.history);
|
||||
this.startSession(session, input, "restarted");
|
||||
this.startSession(session, { ...input, cols, rows }, "restarted");
|
||||
return this.snapshot(session);
|
||||
});
|
||||
}
|
||||
@@ -462,7 +530,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
|
||||
private startSession(
|
||||
session: TerminalSessionState,
|
||||
input: TerminalOpenInput,
|
||||
input: TerminalStartInput,
|
||||
eventType: "started" | "restarted",
|
||||
): void {
|
||||
this.stopProcess(session);
|
||||
@@ -480,19 +548,20 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
let startedShell: string | null = null;
|
||||
try {
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
||||
const terminalEnv = createTerminalSpawnEnv(process.env);
|
||||
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
|
||||
let lastSpawnError: unknown = null;
|
||||
|
||||
for (const shell of shellCandidates) {
|
||||
for (const candidate of shellCandidates) {
|
||||
try {
|
||||
ptyProcess = this.ptyAdapter.spawn({
|
||||
shell,
|
||||
shell: candidate.shell,
|
||||
...(candidate.args ? { args: candidate.args } : {}),
|
||||
cwd: session.cwd,
|
||||
cols: session.cols,
|
||||
rows: session.rows,
|
||||
env: terminalEnv,
|
||||
});
|
||||
startedShell = shell;
|
||||
startedShell = formatShellCandidate(candidate);
|
||||
break;
|
||||
} catch (error) {
|
||||
lastSpawnError = error;
|
||||
@@ -506,7 +575,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
const detail =
|
||||
lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
|
||||
const tried =
|
||||
shellCandidates.length > 0 ? ` Tried shells: ${shellCandidates.join(", ")}.` : "";
|
||||
shellCandidates.length > 0
|
||||
? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.`
|
||||
: "";
|
||||
throw new Error(`${detail}.${tried}`.trim());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { assert, beforeEach, describe, it, vi } from "vitest";
|
||||
import type { ProcessRunOptions, ProcessRunResult } from "./processRunner";
|
||||
|
||||
const { runProcessMock } = vi.hoisted(() => ({
|
||||
runProcessMock: vi.fn<
|
||||
(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>
|
||||
>(),
|
||||
}));
|
||||
|
||||
vi.mock("./processRunner", () => ({
|
||||
runProcess: runProcessMock,
|
||||
}));
|
||||
|
||||
function processResult(
|
||||
overrides: Partial<ProcessRunResult> & Pick<ProcessRunResult, "stdout" | "code">,
|
||||
): ProcessRunResult {
|
||||
return {
|
||||
stdout: overrides.stdout,
|
||||
code: overrides.code,
|
||||
stderr: overrides.stderr ?? "",
|
||||
signal: overrides.signal ?? null,
|
||||
timedOut: overrides.timedOut ?? false,
|
||||
stdoutTruncated: overrides.stdoutTruncated ?? false,
|
||||
stderrTruncated: overrides.stderrTruncated ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("searchWorkspaceEntries git-ignore chunking", () => {
|
||||
beforeEach(() => {
|
||||
runProcessMock.mockReset();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("chunks git check-ignore stdin to avoid building giant strings", async () => {
|
||||
const ignoredPaths = Array.from(
|
||||
{ length: 5000 },
|
||||
(_, index) => `ignored/${index.toString().padStart(5, "0")}/${"x".repeat(80)}.ts`,
|
||||
);
|
||||
const keptPaths = ["src/keep.ts", "docs/readme.md"];
|
||||
const listedPaths = [...ignoredPaths, ...keptPaths];
|
||||
let checkIgnoreCalls = 0;
|
||||
|
||||
runProcessMock.mockImplementation(async (_command, args, options) => {
|
||||
if (args[0] === "rev-parse") {
|
||||
return processResult({ code: 0, stdout: "true\n" });
|
||||
}
|
||||
|
||||
if (args[0] === "ls-files") {
|
||||
return processResult({ code: 0, stdout: `${listedPaths.join("\0")}\0` });
|
||||
}
|
||||
|
||||
if (args[0] === "check-ignore") {
|
||||
checkIgnoreCalls += 1;
|
||||
const chunkPaths = (options?.stdin ?? "").split("\0").filter((value) => value.length > 0);
|
||||
const chunkIgnored = chunkPaths.filter((value) => value.startsWith("ignored/"));
|
||||
return processResult({
|
||||
code: chunkIgnored.length > 0 ? 0 : 1,
|
||||
stdout: chunkIgnored.length > 0 ? `${chunkIgnored.join("\0")}\0` : "",
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected command: git ${args.join(" ")}`);
|
||||
});
|
||||
|
||||
const { searchWorkspaceEntries } = await import("./workspaceEntries");
|
||||
const result = await searchWorkspaceEntries({
|
||||
cwd: "/virtual/workspace",
|
||||
query: "",
|
||||
limit: 100,
|
||||
});
|
||||
|
||||
assert.isAbove(checkIgnoreCalls, 1);
|
||||
assert.isFalse(result.entries.some((entry) => entry.path.startsWith("ignored/")));
|
||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/keep.ts"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import fs from "node:fs";
|
||||
import fsPromises from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import { afterEach, assert, describe, it, vi } from "vitest";
|
||||
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
function writeFile(cwd: string, relativePath: string, contents = ""): void {
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
|
||||
fs.writeFileSync(absolutePath, contents, "utf8");
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: string[]): void {
|
||||
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr || `git ${args.join(" ")} failed`);
|
||||
}
|
||||
}
|
||||
|
||||
describe("searchWorkspaceEntries", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns files and directories relative to cwd", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-entries-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/index.ts");
|
||||
writeFile(cwd, "README.md");
|
||||
writeFile(cwd, ".git/HEAD");
|
||||
writeFile(cwd, "node_modules/pkg/index.js");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/components");
|
||||
assert.include(paths, "src/components/Composer.tsx");
|
||||
assert.include(paths, "README.md");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".git")));
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("node_modules")));
|
||||
assert.isFalse(result.truncated);
|
||||
});
|
||||
|
||||
it("filters and ranks entries by query", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-query-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "compo", limit: 5 });
|
||||
|
||||
assert.isAbove(result.entries.length, 0);
|
||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/components"));
|
||||
assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo")));
|
||||
});
|
||||
|
||||
it("excludes gitignored paths for git repositories", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
writeFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
writeFile(cwd, "ignored.txt", "ignore me");
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.notInclude(paths, "ignored.txt");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("convex/")));
|
||||
});
|
||||
|
||||
it("excludes tracked paths that match ignore rules", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-tracked-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
runGit(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
|
||||
writeFile(cwd, ".gitignore", ".convex/\n");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
});
|
||||
|
||||
it("excludes .convex in non-git workspaces", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-non-git-convex-");
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
});
|
||||
|
||||
it("deduplicates concurrent index builds for the same cwd", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-concurrent-build-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
|
||||
let rootReadCount = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation(
|
||||
(async (...args: Parameters<typeof fsPromises.readdir>) => {
|
||||
if (args[0] === cwd) {
|
||||
rootReadCount += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir,
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
|
||||
]);
|
||||
|
||||
assert.equal(rootReadCount, 1);
|
||||
});
|
||||
|
||||
it("limits concurrent directory reads while walking the filesystem", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-read-concurrency-");
|
||||
for (let index = 0; index < 80; index += 1) {
|
||||
writeFile(cwd, `group-${index}/entry-${index}.ts`, "export {};");
|
||||
}
|
||||
|
||||
let activeReads = 0;
|
||||
let peakReads = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation(
|
||||
(async (...args: Parameters<typeof fsPromises.readdir>) => {
|
||||
const target = args[0];
|
||||
if (typeof target === "string" && target.startsWith(cwd)) {
|
||||
activeReads += 1;
|
||||
peakReads = Math.max(peakReads, activeReads);
|
||||
await new Promise((resolve) => setTimeout(resolve, 4));
|
||||
try {
|
||||
return await originalReaddir(...args);
|
||||
} finally {
|
||||
activeReads -= 1;
|
||||
}
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir,
|
||||
);
|
||||
|
||||
await searchWorkspaceEntries({ cwd, query: "", limit: 200 });
|
||||
|
||||
assert.isAtMost(peakReads, 32);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,433 @@
|
||||
import fs from "node:fs/promises";
|
||||
import type { Dirent } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
import {
|
||||
projectSearchEntriesInputSchema,
|
||||
type ProjectEntry,
|
||||
type ProjectSearchEntriesInput,
|
||||
type ProjectSearchEntriesResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const WORKSPACE_CACHE_TTL_MS = 15_000;
|
||||
const WORKSPACE_CACHE_MAX_KEYS = 4;
|
||||
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
|
||||
const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const IGNORED_DIRECTORY_NAMES = new Set([
|
||||
".git",
|
||||
".convex",
|
||||
"node_modules",
|
||||
".next",
|
||||
".turbo",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".cache",
|
||||
]);
|
||||
|
||||
interface WorkspaceIndex {
|
||||
scannedAt: number;
|
||||
entries: ProjectEntry[];
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
|
||||
const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
|
||||
|
||||
function toPosixPath(input: string): string {
|
||||
return input.split(path.sep).join("/");
|
||||
}
|
||||
|
||||
function parentPathOf(input: string): string | undefined {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return undefined;
|
||||
}
|
||||
return input.slice(0, separatorIndex);
|
||||
}
|
||||
|
||||
function basenameOf(input: string): string {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return input;
|
||||
}
|
||||
return input.slice(separatorIndex + 1);
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^[@./]+/, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreEntry(entry: ProjectEntry, query: string): number {
|
||||
if (!query) {
|
||||
return entry.kind === "directory" ? 0 : 1;
|
||||
}
|
||||
|
||||
const normalizedPath = entry.path.toLowerCase();
|
||||
const normalizedName = basenameOf(normalizedPath);
|
||||
|
||||
if (normalizedName === query) return 0;
|
||||
if (normalizedPath === query) return 1;
|
||||
if (normalizedName.startsWith(query)) return 2;
|
||||
if (normalizedPath.startsWith(query)) return 3;
|
||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
||||
return 5;
|
||||
}
|
||||
|
||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
||||
const firstSegment = relativePath.split("/")[0];
|
||||
if (!firstSegment) return false;
|
||||
return IGNORED_DIRECTORY_NAMES.has(firstSegment);
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
// If output was truncated, the final token can be partial.
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function directoryAncestorsOf(relativePath: string): string[] {
|
||||
const segments = relativePath.split("/").filter((segment) => segment.length > 0);
|
||||
if (segments.length <= 1) return [];
|
||||
const directories: string[] = [];
|
||||
for (let index = 1; index < segments.length; index += 1) {
|
||||
directories.push(segments.slice(0, index).join("/"));
|
||||
}
|
||||
return directories;
|
||||
}
|
||||
|
||||
async function mapWithConcurrency<TInput, TOutput>(
|
||||
items: readonly TInput[],
|
||||
concurrency: number,
|
||||
mapper: (item: TInput, index: number) => Promise<TOutput>,
|
||||
): Promise<TOutput[]> {
|
||||
if (items.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length));
|
||||
const results = Array.from({ length: items.length }) as TOutput[];
|
||||
let nextIndex = 0;
|
||||
|
||||
const workers = Array.from({ length: boundedConcurrency }, async () => {
|
||||
while (nextIndex < items.length) {
|
||||
const currentIndex = nextIndex;
|
||||
nextIndex += 1;
|
||||
results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(workers);
|
||||
return results;
|
||||
}
|
||||
|
||||
async function isInsideGitWorkTree(cwd: string): Promise<boolean> {
|
||||
const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxBufferBytes: 4_096,
|
||||
}).catch(() => null);
|
||||
return Boolean(
|
||||
insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true",
|
||||
);
|
||||
}
|
||||
|
||||
async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise<string[]> {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const ignoredPaths = new Set<string>();
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
const flushChunk = async (): Promise<boolean> => {
|
||||
if (chunk.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
}).catch(() => null);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
|
||||
if (!checkIgnore) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// git-check-ignore exits with 1 when no paths match.
|
||||
if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const matchedIgnoredPaths = splitNullSeparatedPaths(
|
||||
checkIgnore.stdout,
|
||||
Boolean(checkIgnore.stdoutTruncated),
|
||||
);
|
||||
for (const ignoredPath of matchedIgnoredPaths) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (
|
||||
chunk.length > 0 &&
|
||||
chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES &&
|
||||
!(await flushChunk())
|
||||
) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) {
|
||||
return relativePaths;
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await flushChunk())) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
|
||||
if (!(await isInsideGitWorkTree(cwd))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedFiles = await runProcess(
|
||||
"git",
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
{
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
).catch(() => null);
|
||||
if (!listedFiles || listedFiles.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedPaths = splitNullSeparatedPaths(
|
||||
listedFiles.stdout,
|
||||
Boolean(listedFiles.stdoutTruncated),
|
||||
)
|
||||
.map((entry) => toPosixPath(entry))
|
||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
||||
const filePaths = await filterGitIgnoredPaths(cwd, listedPaths);
|
||||
|
||||
const directorySet = new Set<string>();
|
||||
for (const filePath of filePaths) {
|
||||
for (const directoryPath of directoryAncestorsOf(filePath)) {
|
||||
if (!isPathInIgnoredDirectory(directoryPath)) {
|
||||
directorySet.add(directoryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const directoryEntries: ProjectEntry[] = [...directorySet]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map((directoryPath) => ({
|
||||
path: directoryPath,
|
||||
kind: "directory",
|
||||
parentPath: parentPathOf(directoryPath),
|
||||
}));
|
||||
const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map((filePath) => ({
|
||||
path: filePath,
|
||||
kind: "file",
|
||||
parentPath: parentPathOf(filePath),
|
||||
}));
|
||||
|
||||
const entries = [...directoryEntries, ...fileEntries];
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
|
||||
truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
|
||||
if (gitIndexed) {
|
||||
return gitIndexed;
|
||||
}
|
||||
const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
|
||||
|
||||
let pendingDirectories: string[] = [""];
|
||||
const entries: ProjectEntry[] = [];
|
||||
let truncated = false;
|
||||
|
||||
while (pendingDirectories.length > 0 && !truncated) {
|
||||
const currentDirectories = pendingDirectories;
|
||||
pendingDirectories = [];
|
||||
const directoryEntries = await mapWithConcurrency(
|
||||
currentDirectories,
|
||||
WORKSPACE_SCAN_READDIR_CONCURRENCY,
|
||||
async (relativeDir) => {
|
||||
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
|
||||
try {
|
||||
const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
|
||||
return { relativeDir, dirents };
|
||||
} catch (error) {
|
||||
if (!relativeDir) {
|
||||
throw new Error(
|
||||
`Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
return { relativeDir, dirents: null };
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
|
||||
const { relativeDir, dirents } = directoryEntry;
|
||||
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
|
||||
|
||||
dirents.sort((left, right) => left.name.localeCompare(right.name));
|
||||
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
|
||||
for (const dirent of dirents) {
|
||||
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
|
||||
continue;
|
||||
}
|
||||
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
|
||||
continue;
|
||||
}
|
||||
if (!dirent.isDirectory() && !dirent.isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const relativePath = toPosixPath(
|
||||
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
|
||||
);
|
||||
if (isPathInIgnoredDirectory(relativePath)) {
|
||||
continue;
|
||||
}
|
||||
candidates.push({ dirent, relativePath });
|
||||
}
|
||||
return candidates;
|
||||
});
|
||||
|
||||
const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
|
||||
candidateEntries.map((entry) => entry.relativePath),
|
||||
);
|
||||
const allowedPathSet = shouldFilterWithGitIgnore
|
||||
? new Set(await filterGitIgnoredPaths(cwd, candidatePaths))
|
||||
: null;
|
||||
|
||||
for (const candidateEntries of candidateEntriesByDirectory) {
|
||||
for (const candidate of candidateEntries) {
|
||||
if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry: ProjectEntry = {
|
||||
path: candidate.relativePath,
|
||||
kind: candidate.dirent.isDirectory() ? "directory" : "file",
|
||||
parentPath: parentPathOf(candidate.relativePath),
|
||||
};
|
||||
entries.push(entry);
|
||||
|
||||
if (candidate.dirent.isDirectory()) {
|
||||
pendingDirectories.push(candidate.relativePath);
|
||||
}
|
||||
|
||||
if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (truncated) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries,
|
||||
truncated,
|
||||
};
|
||||
}
|
||||
|
||||
async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const cached = workspaceIndexCache.get(cwd);
|
||||
if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
|
||||
if (inFlight) {
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
const nextPromise = buildWorkspaceIndex(cwd)
|
||||
.then((next) => {
|
||||
workspaceIndexCache.set(cwd, next);
|
||||
while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
|
||||
const oldestKey = workspaceIndexCache.keys().next().value;
|
||||
if (!oldestKey) break;
|
||||
workspaceIndexCache.delete(oldestKey);
|
||||
}
|
||||
return next;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightWorkspaceIndexBuilds.delete(cwd);
|
||||
});
|
||||
inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);
|
||||
return nextPromise;
|
||||
}
|
||||
|
||||
export async function searchWorkspaceEntries(
|
||||
input: ProjectSearchEntriesInput,
|
||||
): Promise<ProjectSearchEntriesResult> {
|
||||
const parsed = projectSearchEntriesInputSchema.parse(input);
|
||||
const index = await getWorkspaceIndex(parsed.cwd);
|
||||
const normalizedQuery = normalizeQuery(parsed.query);
|
||||
const candidates = normalizedQuery
|
||||
? index.entries.filter((entry) => entry.path.toLowerCase().includes(normalizedQuery))
|
||||
: index.entries;
|
||||
|
||||
const ranked = candidates.toSorted((left, right) => {
|
||||
const scoreDelta = scoreEntry(left, normalizedQuery) - scoreEntry(right, normalizedQuery);
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.path.localeCompare(right.path);
|
||||
});
|
||||
|
||||
return {
|
||||
entries: ranked.slice(0, parsed.limit),
|
||||
truncated: index.truncated || ranked.length > parsed.limit,
|
||||
};
|
||||
}
|
||||
@@ -11,10 +11,13 @@ import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
WS_CHANNELS,
|
||||
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,
|
||||
TerminalCloseInput,
|
||||
@@ -25,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[];
|
||||
@@ -192,10 +197,46 @@ async function sendRequest(ws: WebSocket, method: string, params?: unknown): Pro
|
||||
}
|
||||
}
|
||||
|
||||
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
const resolved: ResolvedKeybindingsConfig = [];
|
||||
for (const binding of bindings) {
|
||||
const compiled = compileResolvedKeybindingRule(binding);
|
||||
if (!compiled) {
|
||||
throw new Error(`Unexpected invalid keybinding in test setup: ${binding.command}`);
|
||||
}
|
||||
resolved.push(compiled);
|
||||
}
|
||||
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 {
|
||||
if (custom.length === 0) {
|
||||
return DEFAULT_RESOLVED_KEYBINDINGS;
|
||||
}
|
||||
|
||||
const overriddenCommands = new Set(custom.map((binding) => binding.command));
|
||||
const retainedDefaults = DEFAULT_KEYBINDINGS.filter(
|
||||
(binding) => !overriddenCommands.has(binding.command),
|
||||
);
|
||||
return compileKeybindings([...retainedDefaults, ...custom].slice(-256));
|
||||
}
|
||||
|
||||
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));
|
||||
@@ -214,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 } : {}),
|
||||
});
|
||||
@@ -237,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 });
|
||||
}
|
||||
@@ -294,6 +346,8 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("responds to server.getConfig", async () => {
|
||||
const fakeHome = makeTempDir("t3code-home-");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
@@ -307,7 +361,278 @@ describe("WebSocket Server", () => {
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({ cwd: "/my/workspace" });
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
});
|
||||
});
|
||||
|
||||
it("reads keybindings from ~/.t3/keybindings.json", async () => {
|
||||
const fakeHome = makeTempDir("t3code-home-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, "keybindings.json"),
|
||||
JSON.stringify([
|
||||
{ key: "cmd+j", command: "terminal.toggle" },
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
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.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: mergeWithDefaultsForTest([
|
||||
{ key: "cmd+j", command: "terminal.toggle" },
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("warns and ignores invalid keybinding entries", async () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const fakeHome = makeTempDir("t3code-home-invalid-entry-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, "keybindings.json"),
|
||||
JSON.stringify([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+z", command: "invalid.command", when: "terminalFocus" },
|
||||
]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
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.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: mergeWithDefaultsForTest([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
});
|
||||
expect(
|
||||
warnSpy.mock.calls.some(([message]) =>
|
||||
String(message).includes("ignoring invalid keybinding entries"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("warns and ignores keybindings with malformed when expressions", async () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const fakeHome = makeTempDir("t3code-home-invalid-when-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, "keybindings.json"),
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle", when: "terminalFocus && (" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
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.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
});
|
||||
expect(
|
||||
warnSpy.mock.calls.some(([message]) =>
|
||||
String(message).includes("ignoring invalid keybinding entries"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("reads keybindings once at startup and caches the resolved config", async () => {
|
||||
const fakeHome = makeTempDir("t3code-home-cached-config-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const keybindingsPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(
|
||||
keybindingsPath,
|
||||
JSON.stringify([{ key: "cmd+j", command: "terminal.toggle" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
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 firstResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(firstResponse.error).toBeUndefined();
|
||||
expect(firstResponse.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: mergeWithDefaultsForTest([{ key: "cmd+j", command: "terminal.toggle" }]),
|
||||
});
|
||||
|
||||
fs.writeFileSync(
|
||||
keybindingsPath,
|
||||
JSON.stringify([{ key: "cmd+k", command: "terminal.toggle" }]),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const secondResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(secondResponse.error).toBeUndefined();
|
||||
expect(secondResponse.result).toEqual(firstResponse.result);
|
||||
});
|
||||
|
||||
it("upserts keybinding rules and updates cached server config", async () => {
|
||||
const fakeHome = makeTempDir("t3code-home-upsert-keybinding-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const keybindingsPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(
|
||||
keybindingsPath,
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
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 upsertResponse = await sendRequest(ws, WS_METHODS.serverUpsertKeybinding, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
expect(upsertResponse.error).toBeUndefined();
|
||||
expect(upsertResponse.result).toEqual({
|
||||
keybindings: mergeWithDefaultsForTest([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]),
|
||||
});
|
||||
|
||||
const persistedConfig = JSON.parse(fs.readFileSync(keybindingsPath, "utf8")) as Array<{
|
||||
key: string;
|
||||
command: string;
|
||||
}>;
|
||||
expect(persistedConfig).toEqual([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
|
||||
const configResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(configResponse.error).toBeUndefined();
|
||||
expect(configResponse.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: mergeWithDefaultsForTest([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("warns and ignores unsupported keybindings config format", async () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const fakeHome = makeTempDir("t3code-home-unsupported-format-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, "keybindings.json"),
|
||||
JSON.stringify({ "terminal.toggle": "mod+j" }),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
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.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
});
|
||||
expect(
|
||||
warnSpy.mock.calls.some(([message]) =>
|
||||
String(message).includes("unsupported format; expected array"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("warns and ignores malformed keybindings config files", async () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const fakeHome = makeTempDir("t3code-home-invalid-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(configDir, "keybindings.json"), "{not-json", "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
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.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
});
|
||||
expect(
|
||||
warnSpy.mock.calls.some(([message]) =>
|
||||
String(message).includes("ignoring malformed keybindings config"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns error for unknown methods", async () => {
|
||||
@@ -344,6 +669,304 @@ describe("WebSocket Server", () => {
|
||||
expect(response.result).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns durable provider catch-up events ordered by seq", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-provider-catchup-");
|
||||
const persistenceService = new PersistenceService({
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
|
||||
});
|
||||
|
||||
const first = persistenceService.ingestProviderEvent({
|
||||
id: "provider-evt-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: "2026-02-20T00:00:00.000Z",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
payload: { turn: { id: "turn-1" } },
|
||||
});
|
||||
const second = persistenceService.ingestProviderEvent({
|
||||
id: "provider-evt-2",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: "2026-02-20T00:00:01.000Z",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
});
|
||||
|
||||
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.providersCatchUp, {
|
||||
afterSeq: first?.seq ?? 0,
|
||||
});
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
events: [
|
||||
expect.objectContaining({
|
||||
id: "provider-evt-2",
|
||||
seq: second?.seq,
|
||||
}),
|
||||
],
|
||||
lastProviderSeq: second?.seq ?? 0,
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
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 listResponse = await sendRequest(ws, WS_METHODS.providersListCheckpoints, {
|
||||
sessionId: "missing-session",
|
||||
});
|
||||
expect(listResponse.result).toBeUndefined();
|
||||
expect(listResponse.error?.message).toContain("Unknown provider session");
|
||||
|
||||
const revertResponse = await sendRequest(ws, WS_METHODS.providersRevertToCheckpoint, {
|
||||
sessionId: "missing-session",
|
||||
turnCount: 0,
|
||||
});
|
||||
expect(revertResponse.result).toBeUndefined();
|
||||
expect(revertResponse.error?.message).toContain("Unknown provider session");
|
||||
|
||||
const diffResponse = await sendRequest(ws, WS_METHODS.providersGetCheckpointDiff, {
|
||||
sessionId: "missing-session",
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
expect(diffResponse.result).toBeUndefined();
|
||||
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();
|
||||
@@ -432,6 +1055,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();
|
||||
@@ -509,6 +1169,42 @@ describe("WebSocket Server", () => {
|
||||
expect(projectId).toBeTruthy();
|
||||
if (!projectId) return;
|
||||
|
||||
const updatedScripts = await sendRequest(ws, WS_METHODS.projectsUpdateScripts, {
|
||||
id: projectId,
|
||||
scripts: [
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(updatedScripts.error).toBeUndefined();
|
||||
const scriptPayload = (
|
||||
updatedScripts.result as {
|
||||
project: {
|
||||
scripts: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
command: string;
|
||||
icon: string;
|
||||
runOnWorktreeCreate: boolean;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
).project.scripts;
|
||||
expect(scriptPayload).toEqual([
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]);
|
||||
|
||||
const removed = await sendRequest(ws, WS_METHODS.projectsRemove, {
|
||||
id: projectId,
|
||||
});
|
||||
@@ -519,6 +1215,38 @@ describe("WebSocket Server", () => {
|
||||
expect(afterRemove.result).toEqual([]);
|
||||
});
|
||||
|
||||
it("supports projects.searchEntries", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-workspace-entries-");
|
||||
fs.mkdirSync(path.join(workspace, "src", "components"), { recursive: true });
|
||||
fs.writeFileSync(path.join(workspace, "src", "components", "Composer.tsx"), "export {};", "utf8");
|
||||
fs.writeFileSync(path.join(workspace, "README.md"), "# test", "utf8");
|
||||
fs.mkdirSync(path.join(workspace, ".git"), { recursive: true });
|
||||
fs.writeFileSync(path.join(workspace, ".git", "HEAD"), "ref: refs/heads/main\n", "utf8");
|
||||
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
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.projectsSearchEntries, {
|
||||
cwd: workspace,
|
||||
query: "comp",
|
||||
limit: 10,
|
||||
});
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
entries: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "src/components", kind: "directory" }),
|
||||
expect.objectContaining({ path: "src/components/Composer.tsx", kind: "file" }),
|
||||
]),
|
||||
truncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("supports git methods over websocket", async () => {
|
||||
const repoCwd = makeTempDir("t3code-ws-git-project-");
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
import { GitManager } from "./gitManager";
|
||||
import {
|
||||
@@ -31,6 +30,9 @@ import {
|
||||
removeGitWorktree,
|
||||
} from "./git";
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
import { PersistenceService } from "./persistenceService";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -54,7 +56,8 @@ export interface ServerOptions {
|
||||
staticDir?: string | undefined;
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
projectRegistry?: ProjectRegistry | undefined;
|
||||
persistenceService?: PersistenceService | undefined;
|
||||
stateDbPath?: string | undefined;
|
||||
gitManager?: GitManager | undefined;
|
||||
terminalManager?: TerminalManager | undefined;
|
||||
authToken?: string | undefined;
|
||||
@@ -76,20 +79,26 @@ export function createServer(options: ServerOptions) {
|
||||
staticDir,
|
||||
devUrl,
|
||||
logWebSocketEvents: explicitLogWsEvents,
|
||||
projectRegistry: providedRegistry,
|
||||
persistenceService: providedPersistenceService,
|
||||
stateDbPath,
|
||||
gitManager: providedGitManager,
|
||||
terminalManager: providedTerminalManager,
|
||||
authToken,
|
||||
} = options;
|
||||
const providerManager = new ProviderManager();
|
||||
const persistenceService =
|
||||
providedPersistenceService ??
|
||||
new PersistenceService({
|
||||
dbPath: stateDbPath ?? path.join(os.homedir(), ".t3", "state.sqlite"),
|
||||
});
|
||||
const 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 clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
const logWebSocketEvents =
|
||||
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
|
||||
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
|
||||
|
||||
function logOutgoingPush(push: WsPush, recipients: number) {
|
||||
if (!logWebSocketEvents) return;
|
||||
@@ -118,6 +127,24 @@ export function createServer(options: ServerOptions) {
|
||||
logOutgoingPush(push, recipients);
|
||||
});
|
||||
|
||||
const onStateEvent = (event: unknown) => {
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.stateEvent,
|
||||
data: event,
|
||||
};
|
||||
const message = JSON.stringify(push);
|
||||
let recipients = 0;
|
||||
for (const client of clients) {
|
||||
if (client.readyState === client.OPEN) {
|
||||
client.send(message);
|
||||
recipients += 1;
|
||||
}
|
||||
}
|
||||
logOutgoingPush(push, recipients);
|
||||
};
|
||||
persistenceService.on("stateEvent", onStateEvent);
|
||||
|
||||
const onTerminalEvent = (event: TerminalEvent) => {
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
@@ -307,16 +334,96 @@ export function createServer(options: ServerOptions) {
|
||||
case WS_METHODS.providersListSessions:
|
||||
return providerManager.listSessions();
|
||||
|
||||
case WS_METHODS.providersCatchUp:
|
||||
return persistenceService.providerCatchUp(request.params as never);
|
||||
|
||||
case WS_METHODS.providersListCheckpoints:
|
||||
return providerManager.listCheckpoints(request.params as never);
|
||||
|
||||
case WS_METHODS.providersGetCheckpointDiff:
|
||||
return providerManager.getCheckpointDiff(request.params as never);
|
||||
|
||||
case WS_METHODS.providersRevertToCheckpoint:
|
||||
{
|
||||
const 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:
|
||||
return projectRegistry.add(request.params as never);
|
||||
return persistenceService.addProject(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsRemove:
|
||||
projectRegistry.remove(request.params as never);
|
||||
persistenceService.removeProject(request.params as never);
|
||||
return undefined;
|
||||
|
||||
case WS_METHODS.projectsSearchEntries:
|
||||
return searchWorkspaceEntries(request.params as never);
|
||||
case WS_METHODS.projectsUpdateScripts:
|
||||
return persistenceService.updateProjectScripts(request.params as never);
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const params = request.params as {
|
||||
cwd: string;
|
||||
@@ -410,7 +517,16 @@ export function createServer(options: ServerOptions) {
|
||||
return undefined;
|
||||
|
||||
case WS_METHODS.serverGetConfig:
|
||||
return { cwd };
|
||||
return {
|
||||
cwd,
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding:
|
||||
keybindingsConfig = upsertKeybindingRule(logger, request.params);
|
||||
return {
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown method: ${request.method}`);
|
||||
@@ -438,9 +554,13 @@ export function createServer(options: ServerOptions) {
|
||||
|
||||
async function stop(): Promise<void> {
|
||||
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();
|
||||
|
||||
@@ -3,13 +3,15 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300..800;1,9..40,300..800&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<title>T3 Code</title>
|
||||
<title>T3 Code (Alpha)</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -12,8 +12,12 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"@tanstack/react-virtual": "^3.13.18",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
@@ -29,6 +33,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"@tanstack/router-plugin": "^1.161.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
|
||||
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 2.3 KiB |
|
After Width: | Height: | Size: 279 KiB |
@@ -0,0 +1,4 @@
|
||||
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M0 10C0 4.47715 4.47715 0 10 0H118C123.523 0 128 4.47715 128 10V118C128 123.523 123.523 128 118 128H10C4.47715 128 0 123.523 0 118V10Z" fill="black"/>
|
||||
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -1,215 +0,0 @@
|
||||
import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import ChatView from "./components/ChatView";
|
||||
import DiffPanel from "./components/DiffPanel";
|
||||
import Sidebar from "./components/Sidebar";
|
||||
import { isElectron } from "./env";
|
||||
import { DEFAULT_MODEL } from "./model-logic";
|
||||
import { StoreProvider, useStore } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import { onServerWelcome } from "./wsNativeApi";
|
||||
import { useNativeApi } from "./hooks/useNativeApi";
|
||||
import { AnchoredToastProvider, ToastProvider } from "./components/ui/toast";
|
||||
import { invalidateGitQueries } from "./lib/gitReactQuery";
|
||||
|
||||
function EventRouter() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
const activeAssistantItemRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.providers.onEvent((event) => {
|
||||
if (event.method === "turn/completed") {
|
||||
void invalidateGitQueries(queryClient);
|
||||
}
|
||||
dispatch({
|
||||
type: "APPLY_EVENT",
|
||||
event,
|
||||
activeAssistantItemRef,
|
||||
});
|
||||
});
|
||||
}, [api, dispatch, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.terminal.onEvent((event) => {
|
||||
dispatch({
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event,
|
||||
});
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function AutoProjectBootstrap() {
|
||||
const { state, dispatch } = useStore();
|
||||
const bootstrappedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Browser mode bootstraps from server welcome.
|
||||
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
|
||||
if (isElectron) return;
|
||||
|
||||
return onServerWelcome((payload) => {
|
||||
if (bootstrappedRef.current) return;
|
||||
|
||||
// Don't create duplicate projects for the same cwd
|
||||
const existing = state.projects.find((p) => p.cwd === payload.cwd);
|
||||
if (existing) {
|
||||
bootstrappedRef.current = true;
|
||||
// Ensure a thread is active
|
||||
const existingThread = state.threads.find((t) => t.projectId === existing.id);
|
||||
if (existingThread && !state.activeThreadId) {
|
||||
dispatch({
|
||||
type: "SET_ACTIVE_THREAD",
|
||||
threadId: existingThread.id,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
bootstrappedRef.current = true;
|
||||
|
||||
// Create project + thread from server cwd
|
||||
const projectId = crypto.randomUUID();
|
||||
dispatch({
|
||||
type: "ADD_PROJECT",
|
||||
project: {
|
||||
id: projectId,
|
||||
name: payload.projectName,
|
||||
cwd: payload.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
},
|
||||
});
|
||||
dispatch({
|
||||
type: "ADD_THREAD",
|
||||
thread: {
|
||||
id: crypto.randomUUID(),
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "New thread",
|
||||
model: DEFAULT_MODEL,
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
}, [state.projects, state.threads, state.activeThreadId, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function DesktopProjectBootstrap() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
const bootstrappedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isElectron || !api || bootstrappedRef.current) return;
|
||||
|
||||
let disposed = false;
|
||||
let retryDelayMs = 500;
|
||||
let retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const attemptBootstrap = async () => {
|
||||
try {
|
||||
const projects = await api.projects.list();
|
||||
if (disposed) return;
|
||||
dispatch({
|
||||
type: "SYNC_PROJECTS",
|
||||
projects: projects.map((project) => ({
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
cwd: project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
})),
|
||||
});
|
||||
bootstrappedRef.current = true;
|
||||
} catch {
|
||||
if (disposed) return;
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
void attemptBootstrap();
|
||||
}, retryDelayMs);
|
||||
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
|
||||
}
|
||||
};
|
||||
|
||||
void attemptBootstrap();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
if (retryTimer) {
|
||||
clearTimeout(retryTimer);
|
||||
}
|
||||
};
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function Layout() {
|
||||
const api = useNativeApi();
|
||||
const { state } = useStore();
|
||||
|
||||
if (!api) {
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background text-foreground">
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground">Connecting to T3 Code server...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-background text-foreground isolate">
|
||||
<EventRouter />
|
||||
<AutoProjectBootstrap />
|
||||
<DesktopProjectBootstrap />
|
||||
<Sidebar />
|
||||
<ChatView />
|
||||
{state.diffOpen && <DiffPanel />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<StoreProvider>
|
||||
<ToastProvider>
|
||||
<AnchoredToastProvider>
|
||||
<Layout />
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
</StoreProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
@@ -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 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,319 @@
|
||||
import {
|
||||
type AppSettings as BackendAppSettings,
|
||||
appSettingsSchema as backendAppSettingsSchema,
|
||||
appSettingsUpdateInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
import { readNativeApi } from "./session-logic";
|
||||
|
||||
const LOCAL_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:local:v1";
|
||||
const LEGACY_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
|
||||
const localAppSettingsSchema = z.object({
|
||||
confirmThreadDelete: z.boolean().default(true),
|
||||
});
|
||||
|
||||
const legacyAppSettingsSchema = backendAppSettingsSchema.extend({
|
||||
confirmThreadDelete: z.boolean().default(true),
|
||||
});
|
||||
|
||||
const appSettingsSchema = backendAppSettingsSchema.extend({
|
||||
confirmThreadDelete: z.boolean().default(true),
|
||||
});
|
||||
|
||||
export type AppSettings = z.infer<typeof appSettingsSchema>;
|
||||
|
||||
const DEFAULT_BACKEND_APP_SETTINGS: BackendAppSettings = backendAppSettingsSchema.parse({});
|
||||
const DEFAULT_LOCAL_APP_SETTINGS = localAppSettingsSchema.parse({});
|
||||
const DEFAULT_APP_SETTINGS: AppSettings = {
|
||||
...DEFAULT_BACKEND_APP_SETTINGS,
|
||||
...DEFAULT_LOCAL_APP_SETTINGS,
|
||||
};
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let cachedBackendSettings: BackendAppSettings = DEFAULT_BACKEND_APP_SETTINGS;
|
||||
let cachedBackendCacheKey = JSON.stringify(DEFAULT_BACKEND_APP_SETTINGS);
|
||||
let cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
|
||||
let cachedLocalCacheKey: string | undefined;
|
||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||
let cachedSnapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
|
||||
let backendHydrationPromise: Promise<void> | null = null;
|
||||
let backendHydrated = false;
|
||||
let backendUpdateSequence = 0;
|
||||
let optimisticWriteSequence = 0;
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
function setCachedBackendSettings(next: BackendAppSettings): void {
|
||||
cachedBackendSettings = next;
|
||||
cachedBackendCacheKey = JSON.stringify(next);
|
||||
}
|
||||
|
||||
function parseLegacySettings(value: string | null): z.infer<typeof legacyAppSettingsSchema> | null {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(value) as unknown;
|
||||
return legacyAppSettingsSchema.parse(parsed);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readLegacySettingsSnapshot(): z.infer<typeof legacyAppSettingsSchema> | null {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
return parseLegacySettings(window.localStorage.getItem(LEGACY_APP_SETTINGS_STORAGE_KEY));
|
||||
}
|
||||
|
||||
function readLocalSettingsSnapshot() {
|
||||
if (typeof window === "undefined") {
|
||||
return DEFAULT_LOCAL_APP_SETTINGS;
|
||||
}
|
||||
|
||||
const rawLocal = window.localStorage.getItem(LOCAL_APP_SETTINGS_STORAGE_KEY);
|
||||
const rawLegacy = rawLocal === null ? window.localStorage.getItem(LEGACY_APP_SETTINGS_STORAGE_KEY) : null;
|
||||
const cacheKey = rawLocal !== null ? `local:${rawLocal}` : `legacy:${rawLegacy ?? ""}`;
|
||||
if (cacheKey === cachedLocalCacheKey) {
|
||||
return cachedLocalSettings;
|
||||
}
|
||||
|
||||
if (rawLocal !== null) {
|
||||
try {
|
||||
const parsed = JSON.parse(rawLocal) as unknown;
|
||||
cachedLocalSettings = localAppSettingsSchema.parse(parsed);
|
||||
} catch {
|
||||
cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
|
||||
}
|
||||
} else {
|
||||
const legacySettings = parseLegacySettings(rawLegacy);
|
||||
cachedLocalSettings = localAppSettingsSchema.parse({
|
||||
confirmThreadDelete: legacySettings?.confirmThreadDelete ?? DEFAULT_LOCAL_APP_SETTINGS.confirmThreadDelete,
|
||||
});
|
||||
}
|
||||
|
||||
cachedLocalCacheKey = cacheKey;
|
||||
return cachedLocalSettings;
|
||||
}
|
||||
|
||||
function persistLocalSettings(next: z.infer<typeof localAppSettingsSchema>): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const normalized = localAppSettingsSchema.parse(next);
|
||||
const raw = JSON.stringify(normalized);
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(LOCAL_APP_SETTINGS_STORAGE_KEY, raw);
|
||||
} catch {
|
||||
// Best-effort persistence only.
|
||||
}
|
||||
|
||||
cachedLocalSettings = normalized;
|
||||
cachedLocalCacheKey = `local:${raw}`;
|
||||
}
|
||||
|
||||
function normalizeBackendSettings(value: unknown): BackendAppSettings {
|
||||
const parsed = backendAppSettingsSchema.safeParse(value);
|
||||
if (parsed.success) {
|
||||
return parsed.data;
|
||||
}
|
||||
return DEFAULT_BACKEND_APP_SETTINGS;
|
||||
}
|
||||
|
||||
async function hydrateBackendSettings(): Promise<void> {
|
||||
if (typeof window === "undefined" || backendHydrated) {
|
||||
return;
|
||||
}
|
||||
if (backendHydrationPromise) {
|
||||
await backendHydrationPromise;
|
||||
return;
|
||||
}
|
||||
|
||||
const hydrationSequence = optimisticWriteSequence;
|
||||
const hasOptimisticWriteSinceHydration = () => hydrationSequence !== optimisticWriteSequence;
|
||||
|
||||
backendHydrationPromise = (async () => {
|
||||
const api = readNativeApi();
|
||||
if (!api?.appSettings || typeof api.appSettings.get !== "function") {
|
||||
backendHydrated = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const legacySettings = readLegacySettingsSnapshot();
|
||||
let next = normalizeBackendSettings(await api.appSettings.get());
|
||||
if (!hasOptimisticWriteSinceHydration()) {
|
||||
const migrationPatch = appSettingsUpdateInputSchema.parse({
|
||||
...(next.codexBinaryPath.length === 0 && legacySettings?.codexBinaryPath
|
||||
? { codexBinaryPath: legacySettings.codexBinaryPath }
|
||||
: {}),
|
||||
...(next.codexHomePath.length === 0 && legacySettings?.codexHomePath
|
||||
? { codexHomePath: legacySettings.codexHomePath }
|
||||
: {}),
|
||||
});
|
||||
const hasMigrationPatch =
|
||||
migrationPatch.codexBinaryPath !== undefined || migrationPatch.codexHomePath !== undefined;
|
||||
if (hasMigrationPatch) {
|
||||
next = normalizeBackendSettings(await api.appSettings.update(migrationPatch));
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasOptimisticWriteSinceHydration()) {
|
||||
setCachedBackendSettings(next);
|
||||
|
||||
if (legacySettings) {
|
||||
persistLocalSettings({
|
||||
confirmThreadDelete: legacySettings.confirmThreadDelete,
|
||||
});
|
||||
}
|
||||
|
||||
emitChange();
|
||||
}
|
||||
|
||||
backendHydrated = true;
|
||||
if (legacySettings) {
|
||||
try {
|
||||
window.localStorage.removeItem(LEGACY_APP_SETTINGS_STORAGE_KEY);
|
||||
} catch {
|
||||
// Best-effort legacy cleanup only.
|
||||
}
|
||||
}
|
||||
})()
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
backendHydrationPromise = null;
|
||||
});
|
||||
|
||||
await backendHydrationPromise;
|
||||
}
|
||||
|
||||
export function getAppSettingsSnapshot(): AppSettings {
|
||||
const localSettings = readLocalSettingsSnapshot();
|
||||
const snapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
|
||||
if (snapshotKey === cachedSnapshotKey) {
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
cachedSnapshot = appSettingsSchema.parse({
|
||||
...cachedBackendSettings,
|
||||
...localSettings,
|
||||
});
|
||||
cachedSnapshotKey = snapshotKey;
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
export function ensureAppSettingsHydrated(): Promise<void> {
|
||||
return hydrateBackendSettings();
|
||||
}
|
||||
|
||||
export function updateAppSettings(patch: Partial<AppSettings>): void {
|
||||
const parsedPatch = appSettingsSchema.partial().parse(patch);
|
||||
let didChange = false;
|
||||
let didOptimisticWrite = false;
|
||||
const markOptimisticWrite = () => {
|
||||
if (didOptimisticWrite) return;
|
||||
didOptimisticWrite = true;
|
||||
optimisticWriteSequence += 1;
|
||||
};
|
||||
|
||||
if (parsedPatch.confirmThreadDelete !== undefined) {
|
||||
markOptimisticWrite();
|
||||
persistLocalSettings({
|
||||
...readLocalSettingsSnapshot(),
|
||||
confirmThreadDelete: parsedPatch.confirmThreadDelete,
|
||||
});
|
||||
didChange = true;
|
||||
}
|
||||
|
||||
const backendPatch = appSettingsUpdateInputSchema.parse({
|
||||
...(parsedPatch.codexBinaryPath !== undefined
|
||||
? { codexBinaryPath: parsedPatch.codexBinaryPath }
|
||||
: {}),
|
||||
...(parsedPatch.codexHomePath !== undefined ? { codexHomePath: parsedPatch.codexHomePath } : {}),
|
||||
});
|
||||
const hasBackendPatch =
|
||||
backendPatch.codexBinaryPath !== undefined || backendPatch.codexHomePath !== undefined;
|
||||
if (hasBackendPatch) {
|
||||
markOptimisticWrite();
|
||||
const previous = cachedBackendSettings;
|
||||
const optimisticNext = backendAppSettingsSchema.parse({
|
||||
...cachedBackendSettings,
|
||||
...backendPatch,
|
||||
});
|
||||
setCachedBackendSettings(optimisticNext);
|
||||
backendHydrated = true;
|
||||
didChange = true;
|
||||
|
||||
const updateSequence = ++backendUpdateSequence;
|
||||
const api = readNativeApi();
|
||||
if (api?.appSettings && typeof api.appSettings.update === "function") {
|
||||
void api.appSettings
|
||||
.update(backendPatch)
|
||||
.then((response) => {
|
||||
if (updateSequence !== backendUpdateSequence) return;
|
||||
setCachedBackendSettings(normalizeBackendSettings(response));
|
||||
emitChange();
|
||||
})
|
||||
.catch(() => {
|
||||
if (updateSequence !== backendUpdateSequence) return;
|
||||
setCachedBackendSettings(previous);
|
||||
emitChange();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (didChange) {
|
||||
emitChange();
|
||||
}
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.push(listener);
|
||||
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (
|
||||
event.key === null ||
|
||||
event.key === LOCAL_APP_SETTINGS_STORAGE_KEY ||
|
||||
event.key === LEGACY_APP_SETTINGS_STORAGE_KEY
|
||||
) {
|
||||
emitChange();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => {
|
||||
listeners = listeners.filter((entry) => entry !== listener);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
};
|
||||
}
|
||||
|
||||
export function useAppSettings() {
|
||||
const settings = useSyncExternalStore(subscribe, getAppSettingsSnapshot, () => DEFAULT_APP_SETTINGS);
|
||||
|
||||
useEffect(() => {
|
||||
void ensureAppSettingsHydrated();
|
||||
}, []);
|
||||
|
||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||
updateAppSettings(patch);
|
||||
}, []);
|
||||
|
||||
const resetSettings = useCallback(() => {
|
||||
updateSettings(DEFAULT_APP_SETTINGS);
|
||||
}, [updateSettings]);
|
||||
|
||||
return {
|
||||
settings,
|
||||
updateSettings,
|
||||
resetSettings,
|
||||
defaults: DEFAULT_APP_SETTINGS,
|
||||
} as const;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export const APP_BASE_NAME = "T3 Code";
|
||||
export const APP_STAGE_LABEL = import.meta.env.DEV ? "Dev" : "Alpha";
|
||||
export const APP_DISPLAY_NAME = `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
|
||||
|
||||
describe("isScrollContainerNearBottom", () => {
|
||||
it("returns true when already at bottom", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 600,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true when within the auto-scroll threshold", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 540,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when the user is meaningfully above the bottom", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom({
|
||||
scrollTop: 520,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("clamps negative thresholds to zero", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom(
|
||||
{
|
||||
scrollTop: 539,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
},
|
||||
-1,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to the default threshold for non-finite values", () => {
|
||||
expect(
|
||||
isScrollContainerNearBottom(
|
||||
{
|
||||
scrollTop: 540,
|
||||
clientHeight: 400,
|
||||
scrollHeight: 1_000,
|
||||
},
|
||||
Number.NaN,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(AUTO_SCROLL_BOTTOM_THRESHOLD_PX).toBe(64);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
export const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 64;
|
||||
|
||||
interface ScrollPosition {
|
||||
scrollTop: number;
|
||||
clientHeight: number;
|
||||
scrollHeight: number;
|
||||
}
|
||||
|
||||
export function isScrollContainerNearBottom(
|
||||
position: ScrollPosition,
|
||||
thresholdPx = AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
|
||||
): boolean {
|
||||
const threshold = Number.isFinite(thresholdPx)
|
||||
? Math.max(0, thresholdPx)
|
||||
: AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
|
||||
|
||||
const { scrollTop, clientHeight, scrollHeight } = position;
|
||||
if (![scrollTop, clientHeight, scrollHeight].every(Number.isFinite)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const distanceFromBottom = scrollHeight - clientHeight - scrollTop;
|
||||
return distanceFromBottom <= threshold;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("deriveSyncedLocalBranch", () => {
|
||||
it("syncs to git current branch in local mode", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBe("main");
|
||||
});
|
||||
|
||||
it("does not sync when creating a new worktree", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "worktree",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("does not sync when thread already targets a worktree path", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
|
||||
interface DeriveSyncedLocalBranchInput {
|
||||
activeThreadId: string | undefined;
|
||||
activeWorktreePath: string | null;
|
||||
envMode: "local" | "worktree";
|
||||
activeThreadBranch: string | null;
|
||||
queryBranches: GitBranch[] | undefined;
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
}: DeriveSyncedLocalBranchInput): string | null {
|
||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return currentBranch.name;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
|
||||
interface BranchToolbarProps {
|
||||
threadId: string;
|
||||
envMode: "local" | "worktree";
|
||||
onEnvModeChange: (mode: "local" | "worktree") => void;
|
||||
envLocked: boolean;
|
||||
@@ -29,6 +31,7 @@ interface BranchToolbarProps {
|
||||
}
|
||||
|
||||
export default function BranchToolbar({
|
||||
threadId,
|
||||
envMode,
|
||||
onEnvModeChange,
|
||||
envLocked,
|
||||
@@ -41,7 +44,7 @@ export default function BranchToolbar({
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
|
||||
const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId);
|
||||
const activeThread = state.threads.find((thread) => thread.id === threadId);
|
||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||
const activeThreadId = activeThread?.id;
|
||||
const activeThreadBranch = activeThread?.branch ?? null;
|
||||
@@ -67,36 +70,35 @@ export default function BranchToolbar({
|
||||
: branchNames;
|
||||
// ── Mutations ─────────────────────────────────────────────────────────
|
||||
|
||||
const checkoutMutation = useMutation({
|
||||
...gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
const checkoutMutation = useMutation(
|
||||
gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
);
|
||||
|
||||
const createBranchMutation = useMutation({
|
||||
...gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
onError: (error) =>
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch."),
|
||||
});
|
||||
const createBranchMutation = useMutation(
|
||||
gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
);
|
||||
|
||||
// ── Effects ───────────────────────────────────────────────────────────
|
||||
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || activeWorktreePath) return;
|
||||
const current = queryBranches?.find((branch) => branch.current);
|
||||
if (!current) return;
|
||||
if (current.name === activeThreadBranch) return;
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: current.name,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
@@ -153,6 +155,10 @@ export default function BranchToolbar({
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -167,13 +173,16 @@ export default function BranchToolbar({
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
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">
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { memo } from "react";
|
||||
import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import rehypeHighlight from "rehype-highlight";
|
||||
@@ -13,7 +14,7 @@ const markdownComponents: Components = {
|
||||
},
|
||||
};
|
||||
|
||||
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
|
||||
function ChatMarkdown({ text }: ChatMarkdownProps) {
|
||||
return (
|
||||
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
|
||||
<ReactMarkdown
|
||||
@@ -26,3 +27,5 @@ export default function ChatMarkdown({ text }: ChatMarkdownProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(ChatMarkdown);
|
||||
@@ -1,58 +1,476 @@
|
||||
import { XIcon } from "lucide-react";
|
||||
import { parsePatchFiles } from "@pierre/diffs";
|
||||
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { isElectron } from "../env";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useStore } from "../store";
|
||||
import { Button } from "./ui/button";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
|
||||
export default function DiffPanel() {
|
||||
const { dispatch } = useStore();
|
||||
type DiffRenderMode = "stacked" | "split";
|
||||
type DiffThemeType = "light" | "dark" | "system";
|
||||
|
||||
type RenderablePatch =
|
||||
| {
|
||||
kind: "files";
|
||||
files: FileDiffMetadata[];
|
||||
}
|
||||
| {
|
||||
kind: "raw";
|
||||
text: string;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
function getRenderablePatch(patch: string | undefined): RenderablePatch | null {
|
||||
if (!patch) return null;
|
||||
const normalizedPatch = patch.trim();
|
||||
if (normalizedPatch.length === 0) return null;
|
||||
|
||||
try {
|
||||
const parsedPatches = parsePatchFiles(normalizedPatch, buildPatchCacheKey(normalizedPatch));
|
||||
const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
|
||||
if (files.length > 0) {
|
||||
return { kind: "files", files };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "raw",
|
||||
text: normalizedPatch,
|
||||
reason: "Unsupported diff format. Showing raw patch.",
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
kind: "raw",
|
||||
text: normalizedPatch,
|
||||
reason: "Failed to parse patch. Showing raw patch.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
|
||||
const raw = fileDiff.name ?? fileDiff.prevName ?? "";
|
||||
if (raw.startsWith("a/") || raw.startsWith("b/")) {
|
||||
return raw.slice(2);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
|
||||
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
|
||||
}
|
||||
|
||||
function formatTurnChipTimestamp(isoDate: string): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
}).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
interface DiffPanelProps {
|
||||
mode?: "inline" | "sheet";
|
||||
}
|
||||
|
||||
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const api = useNativeApi();
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { state } = useStore();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
|
||||
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
|
||||
const params = useParams({ strict: false });
|
||||
const rawSearch = useSearch({ strict: false });
|
||||
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
|
||||
const diffSearch = useMemo(
|
||||
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
|
||||
[rawSearch],
|
||||
);
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||
const activeThreadRuntimeId =
|
||||
activeThread?.codexThreadId ?? activeThread?.session?.threadId ?? null;
|
||||
const activeSessionId = activeThread?.session?.sessionId ?? null;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
|
||||
const selectedTurnId = diffSearch.diffTurnId ?? null;
|
||||
const selectedFilePath = selectedTurnId !== null ? (diffSearch.diffFilePath ?? null) : null;
|
||||
const selectedTurn =
|
||||
selectedTurnId === null
|
||||
? undefined
|
||||
: (turnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
|
||||
turnDiffSummaries[0]);
|
||||
const selectedCheckpointTurnCount =
|
||||
selectedTurn &&
|
||||
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
|
||||
const selectedCheckpointRange = useMemo(
|
||||
() =>
|
||||
typeof selectedCheckpointTurnCount === "number"
|
||||
? {
|
||||
fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
|
||||
toTurnCount: selectedCheckpointTurnCount,
|
||||
}
|
||||
: null,
|
||||
[selectedCheckpointTurnCount],
|
||||
);
|
||||
const conversationCheckpointTurnCount = useMemo(() => {
|
||||
const turnCounts = turnDiffSummaries
|
||||
.map(
|
||||
(summary) =>
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId],
|
||||
)
|
||||
.filter((value): value is number => typeof value === "number");
|
||||
if (turnCounts.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const latest = Math.max(...turnCounts);
|
||||
return latest > 0 ? latest : undefined;
|
||||
}, [inferredCheckpointTurnCountByTurnId, turnDiffSummaries]);
|
||||
const conversationCheckpointRange = useMemo(
|
||||
() =>
|
||||
!selectedTurn && typeof conversationCheckpointTurnCount === "number"
|
||||
? {
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: conversationCheckpointTurnCount,
|
||||
}
|
||||
: null,
|
||||
[conversationCheckpointTurnCount, selectedTurn],
|
||||
);
|
||||
const activeCheckpointRange = selectedTurn
|
||||
? selectedCheckpointRange
|
||||
: conversationCheckpointRange;
|
||||
const conversationCacheScope = useMemo(() => {
|
||||
if (selectedTurn || turnDiffSummaries.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return `conversation:${turnDiffSummaries.map((summary) => summary.turnId).join(",")}`;
|
||||
}, [selectedTurn, turnDiffSummaries]);
|
||||
const activeCheckpointDiffQuery = useQuery(
|
||||
checkpointDiffQueryOptions(api, {
|
||||
sessionId: activeSessionId,
|
||||
threadRuntimeId: activeThreadRuntimeId,
|
||||
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
|
||||
}),
|
||||
);
|
||||
const selectedTurnCheckpointDiff = selectedTurn
|
||||
? activeCheckpointDiffQuery.data?.diff
|
||||
: undefined;
|
||||
const conversationCheckpointDiff = selectedTurn
|
||||
? undefined
|
||||
: activeCheckpointDiffQuery.data?.diff;
|
||||
const isLoadingCheckpointDiff = activeCheckpointDiffQuery.isLoading;
|
||||
const checkpointDiffError =
|
||||
activeCheckpointDiffQuery.error instanceof Error
|
||||
? activeCheckpointDiffQuery.error.message
|
||||
: activeCheckpointDiffQuery.error
|
||||
? "Failed to load checkpoint diff."
|
||||
: null;
|
||||
|
||||
const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
|
||||
const renderablePatch = useMemo(() => getRenderablePatch(selectedPatch), [selectedPatch]);
|
||||
const renderableFiles = useMemo(() => {
|
||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
||||
return [];
|
||||
}
|
||||
return renderablePatch.files.toSorted((left, right) =>
|
||||
resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
|
||||
numeric: true,
|
||||
sensitivity: "base",
|
||||
}),
|
||||
);
|
||||
}, [renderablePatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath || !patchViewportRef.current) {
|
||||
return;
|
||||
}
|
||||
const target = Array.from(
|
||||
patchViewportRef.current.querySelectorAll<HTMLElement>("[data-diff-file-path]"),
|
||||
).find((element) => element.dataset.diffFilePath === selectedFilePath);
|
||||
target?.scrollIntoView({ block: "nearest" });
|
||||
}, [selectedFilePath, renderableFiles]);
|
||||
|
||||
const selectTurn = (turnId: string) => {
|
||||
if (!activeThread) return;
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: activeThread.id },
|
||||
search: (previous) => {
|
||||
const rest = stripDiffSearchParams(previous);
|
||||
return { ...rest, diff: "1", diffTurnId: turnId };
|
||||
},
|
||||
});
|
||||
};
|
||||
const selectWholeConversation = () => {
|
||||
if (!activeThread) return;
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: activeThread.id },
|
||||
search: (previous) => {
|
||||
const rest = stripDiffSearchParams(previous);
|
||||
return { ...rest, diff: "1" };
|
||||
},
|
||||
});
|
||||
};
|
||||
const updateTurnStripScrollState = useCallback(() => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) {
|
||||
setCanScrollTurnStripLeft(false);
|
||||
setCanScrollTurnStripRight(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
|
||||
setCanScrollTurnStripLeft(element.scrollLeft > 4);
|
||||
setCanScrollTurnStripRight(element.scrollLeft < maxScrollLeft - 4);
|
||||
}, []);
|
||||
const scrollTurnStripBy = useCallback((offset: number) => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
element.scrollBy({ left: offset, behavior: "smooth" });
|
||||
}, []);
|
||||
const onTurnStripWheel = useCallback((event: WheelEvent) => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
if (element.scrollWidth <= element.clientWidth + 1) return;
|
||||
if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
|
||||
|
||||
event.preventDefault();
|
||||
element.scrollBy({ left: event.deltaY, behavior: "auto" });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
|
||||
updateTurnStripScrollState();
|
||||
const onScroll = () => updateTurnStripScrollState();
|
||||
|
||||
element.addEventListener("scroll", onScroll, { passive: true });
|
||||
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
|
||||
resizeObserver.observe(element);
|
||||
|
||||
return () => {
|
||||
element.removeEventListener("scroll", onScroll);
|
||||
element.removeEventListener("wheel", onTurnStripWheel);
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [updateTurnStripScrollState, onTurnStripWheel]);
|
||||
|
||||
useEffect(() => {
|
||||
updateTurnStripScrollState();
|
||||
}, [turnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
|
||||
|
||||
useEffect(() => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
|
||||
const selectedChip = element.querySelector<HTMLElement>("[data-turn-chip-selected='true']");
|
||||
selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
|
||||
}, [selectedTurn?.turnId, selectedTurnId]);
|
||||
|
||||
const shouldUseDragRegion = isElectron && mode === "inline";
|
||||
|
||||
return (
|
||||
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
|
||||
{/* Header */}
|
||||
<aside
|
||||
className={cn(
|
||||
"flex h-full min-w-0 flex-col bg-card",
|
||||
mode === "inline"
|
||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||
: "w-full",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-2 border-b border-border px-4",
|
||||
shouldUseDragRegion ? "drag-region h-[52px]" : "py-3",
|
||||
)}
|
||||
>
|
||||
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Placeholder content */}
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<span className="rounded bg-emerald-500/20 px-1.5 py-0.5 text-[9px] font-medium text-emerald-400">
|
||||
M
|
||||
</span>
|
||||
<span className="font-mono text-xs text-muted-foreground/80">src/App.tsx</span>
|
||||
</div>
|
||||
<div className="space-y-0.5 font-mono text-[11px]">
|
||||
<div className="text-red-400/60">- const oldValue = "hello";</div>
|
||||
<div className="text-emerald-400/60">+ const newValue = "world";</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="rounded bg-blue-500/20 px-1.5 py-0.5 text-[9px] font-medium text-blue-400">
|
||||
A
|
||||
</span>
|
||||
<span className="font-mono text-xs text-muted-foreground/80">src/utils.ts</span>
|
||||
</div>
|
||||
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
|
||||
{canScrollTurnStripLeft && (
|
||||
<div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-gradient-to-r from-card to-transparent" />
|
||||
)}
|
||||
{canScrollTurnStripRight && (
|
||||
<div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-gradient-to-l from-card to-transparent" />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"absolute left-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
|
||||
canScrollTurnStripLeft
|
||||
? "border-border/70 hover:border-border hover:text-foreground"
|
||||
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
|
||||
)}
|
||||
onClick={() => scrollTurnStripBy(-180)}
|
||||
disabled={!canScrollTurnStripLeft}
|
||||
aria-label="Scroll turn list left"
|
||||
>
|
||||
<ChevronLeftIcon className="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"absolute right-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
|
||||
canScrollTurnStripRight
|
||||
? "border-border/70 hover:border-border hover:text-foreground"
|
||||
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
|
||||
)}
|
||||
onClick={() => scrollTurnStripBy(180)}
|
||||
disabled={!canScrollTurnStripRight}
|
||||
aria-label="Scroll turn list right"
|
||||
>
|
||||
<ChevronRightIcon className="size-3.5" />
|
||||
</button>
|
||||
<div
|
||||
ref={turnStripRef}
|
||||
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 rounded-md"
|
||||
onClick={selectWholeConversation}
|
||||
data-turn-chip-selected={selectedTurnId === null}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
selectedTurnId === null
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
||||
)}
|
||||
>
|
||||
<div className="text-[10px] leading-tight font-medium">All turns</div>
|
||||
</div>
|
||||
</button>
|
||||
{turnDiffSummaries.map((summary, index) => (
|
||||
<button
|
||||
key={summary.turnId}
|
||||
type="button"
|
||||
className="shrink-0 rounded-md"
|
||||
onClick={() => selectTurn(summary.turnId)}
|
||||
title={summary.turnId}
|
||||
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
summary.turnId === selectedTurn?.turnId
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-[10px] leading-tight font-medium">
|
||||
Turn {turnDiffSummaries.length - index}
|
||||
</span>
|
||||
<span className="text-[9px] leading-tight opacity-70">
|
||||
{formatTurnChipTimestamp(summary.completedAt)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-center text-[10px] text-muted-foreground/30">
|
||||
Diff integration coming soon
|
||||
</p>
|
||||
<ToggleGroup
|
||||
className="shrink-0 [-webkit-app-region:no-drag]"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
value={[diffRenderMode]}
|
||||
onValueChange={(value) => {
|
||||
const next = value[0];
|
||||
if (next === "stacked" || next === "split") {
|
||||
setDiffRenderMode(next);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Toggle aria-label="Stacked diff view" value="stacked">
|
||||
<Rows3Icon className="size-3" />
|
||||
</Toggle>
|
||||
<Toggle aria-label="Split diff view" value="split">
|
||||
<Columns2Icon className="size-3" />
|
||||
</Toggle>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
|
||||
{!activeThread ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Select a thread to inspect turn diffs.
|
||||
</div>
|
||||
) : turnDiffSummaries.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
No completed turns yet.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
||||
{checkpointDiffError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||
</div>
|
||||
)}
|
||||
{!renderablePatch ? (
|
||||
<div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
|
||||
<p>
|
||||
{isLoadingCheckpointDiff
|
||||
? "Loading checkpoint diff..."
|
||||
: "No patch available for this selection."}
|
||||
</p>
|
||||
</div>
|
||||
) : renderablePatch.kind === "files" ? (
|
||||
<Virtualizer
|
||||
className="h-full min-h-0 overflow-auto px-3 py-2"
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
}}
|
||||
>
|
||||
{renderableFiles.map((fileDiff) => {
|
||||
const filePath = resolveFileDiffPath(fileDiff);
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
return (
|
||||
<div key={fileKey} data-diff-file-path={filePath} className="rounded-md">
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
options={{
|
||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||
lineDiffType: "none",
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Virtualizer>
|
||||
) : (
|
||||
<div className="h-full overflow-auto px-3 py-2">
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
||||
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
|
||||
{renderablePatch.text}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
|
||||
import { useMemo, type ReactNode } from "react";
|
||||
|
||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
const workerPoolSize = useMemo(() => {
|
||||
const cores = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
||||
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<WorkerPoolContextProvider
|
||||
poolOptions={{
|
||||
workerFactory: () =>
|
||||
new Worker(new URL("../workers/diffs.worker.ts", import.meta.url), { type: "module" }),
|
||||
poolSize: workerPoolSize,
|
||||
totalASTLRUCacheSize: 240,
|
||||
}}
|
||||
highlighterOptions={{
|
||||
tokenizeMaxLineLength: 1_000,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</WorkerPoolContextProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -67,13 +67,13 @@ export function buildGitActionProgressStages(input: {
|
||||
return [...commitStages, pushStage, "Creating PR..."];
|
||||
}
|
||||
|
||||
const withDescription = (title: string, description: string | undefined) =>
|
||||
description ? { title, description } : { title };
|
||||
|
||||
export function summarizeGitResult(result: GitRunStackedActionResult): {
|
||||
title: string;
|
||||
description?: string;
|
||||
} {
|
||||
const withDescription = (title: string, description: string | undefined) =>
|
||||
description ? { title, description } : { title };
|
||||
|
||||
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
|
||||
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
|
||||
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
|
||||
|
||||
@@ -38,12 +38,12 @@ import {
|
||||
gitStatusQueryOptions,
|
||||
invalidateGitQueries,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { useStore } from "~/store";
|
||||
import { preferredTerminalEditor, resolvePathLinkTarget } from "~/terminal-links";
|
||||
|
||||
interface GitActionsControlProps {
|
||||
api: NativeApi | undefined;
|
||||
gitCwd: string | null;
|
||||
activeThreadId: string | null;
|
||||
}
|
||||
|
||||
function getMenuActionDisabledReason(
|
||||
@@ -136,9 +136,11 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
|
||||
return <InfoIcon className={iconClassName} />;
|
||||
}
|
||||
|
||||
export default function GitActionsControl({ api, gitCwd }: GitActionsControlProps) {
|
||||
const { state } = useStore();
|
||||
const activeThreadId = state.activeThreadId;
|
||||
export default function GitActionsControl({
|
||||
api,
|
||||
gitCwd,
|
||||
activeThreadId,
|
||||
}: GitActionsControlProps) {
|
||||
const threadToastData = useMemo(
|
||||
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
|
||||
[activeThreadId],
|
||||
@@ -226,17 +228,14 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
});
|
||||
return;
|
||||
}
|
||||
const promise = api.shell.openExternal(prUrl);
|
||||
toastManager.promise(promise, {
|
||||
loading: { title: "Opening PR...", data: threadToastData },
|
||||
success: { title: "PR opened", data: threadToastData },
|
||||
error: (err) => ({
|
||||
void api.shell.openExternal(prUrl).catch((err) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
data: threadToastData,
|
||||
}),
|
||||
});
|
||||
});
|
||||
void promise.catch(() => undefined);
|
||||
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
|
||||
|
||||
const runGitActionWithToast = useCallback(
|
||||
@@ -312,7 +311,10 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
title: resultToast.title,
|
||||
description: resultToast.description,
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
data: {
|
||||
...threadToastData,
|
||||
dismissAfterVisibleMs: 10_000,
|
||||
},
|
||||
...(shouldOfferPushCta
|
||||
? {
|
||||
actionProps: {
|
||||
@@ -627,7 +629,8 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
: gitStatusForActions.aheadCount === 0 &&
|
||||
gitStatusForActions.behindCount === 0
|
||||
? "Up to date"
|
||||
: gitStatusForActions.aheadCount > 0 && gitStatusForActions.behindCount > 0
|
||||
: gitStatusForActions.aheadCount > 0 &&
|
||||
gitStatusForActions.behindCount > 0
|
||||
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
|
||||
: gitStatusForActions.aheadCount > 0
|
||||
? `Ahead by ${gitStatusForActions.aheadCount}`
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
import type {
|
||||
ProjectScript,
|
||||
ProjectScriptIcon,
|
||||
ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
BugIcon,
|
||||
ChevronDownIcon,
|
||||
FlaskConicalIcon,
|
||||
HammerIcon,
|
||||
ListChecksIcon,
|
||||
PlayIcon,
|
||||
PlusIcon,
|
||||
SettingsIcon,
|
||||
WrenchIcon,
|
||||
} from "lucide-react";
|
||||
import React, { type FormEvent, type KeyboardEvent, useMemo, useState } from "react";
|
||||
|
||||
import { commandForProjectScript, primaryProjectScript } from "~/projectScripts";
|
||||
import { shortcutLabelForCommand } from "~/keybindings";
|
||||
import { isMacPlatform } from "~/lib/utils";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "./ui/dialog";
|
||||
import { Group, GroupSeparator } from "./ui/group";
|
||||
import { Input } from "./ui/input";
|
||||
import { Label } from "./ui/label";
|
||||
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
|
||||
import { Switch } from "./ui/switch";
|
||||
import { Textarea } from "./ui/textarea";
|
||||
|
||||
const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
|
||||
{ id: "play", label: "Play" },
|
||||
{ id: "test", label: "Test" },
|
||||
{ id: "lint", label: "Lint" },
|
||||
{ id: "configure", label: "Configure" },
|
||||
{ id: "build", label: "Build" },
|
||||
{ id: "debug", label: "Debug" },
|
||||
];
|
||||
|
||||
function ScriptIcon({
|
||||
icon,
|
||||
className = "size-3.5",
|
||||
}: {
|
||||
icon: ProjectScriptIcon;
|
||||
className?: string;
|
||||
}) {
|
||||
if (icon === "test") return <FlaskConicalIcon className={className} />;
|
||||
if (icon === "lint") return <ListChecksIcon className={className} />;
|
||||
if (icon === "configure") return <WrenchIcon className={className} />;
|
||||
if (icon === "build") return <HammerIcon className={className} />;
|
||||
if (icon === "debug") return <BugIcon className={className} />;
|
||||
return <PlayIcon className={className} />;
|
||||
}
|
||||
|
||||
export interface NewProjectScriptInput {
|
||||
name: string;
|
||||
command: string;
|
||||
icon: ProjectScriptIcon;
|
||||
runOnWorktreeCreate: boolean;
|
||||
keybinding: string | null;
|
||||
}
|
||||
|
||||
interface ProjectScriptsControlProps {
|
||||
scripts: ProjectScript[];
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
preferredScriptId?: string | null;
|
||||
onRunScript: (script: ProjectScript) => void;
|
||||
onAddScript: (input: NewProjectScriptInput) => Promise<void> | void;
|
||||
onUpdateScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void> | void;
|
||||
}
|
||||
|
||||
function normalizeShortcutKeyToken(key: string): string | null {
|
||||
const normalized = key.toLowerCase();
|
||||
if (
|
||||
normalized === "meta" ||
|
||||
normalized === "control" ||
|
||||
normalized === "ctrl" ||
|
||||
normalized === "shift" ||
|
||||
normalized === "alt" ||
|
||||
normalized === "option"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (normalized === " ") return "space";
|
||||
if (normalized === "escape") return "esc";
|
||||
if (normalized === "arrowup") return "arrowup";
|
||||
if (normalized === "arrowdown") return "arrowdown";
|
||||
if (normalized === "arrowleft") return "arrowleft";
|
||||
if (normalized === "arrowright") return "arrowright";
|
||||
if (normalized.length === 1) return normalized;
|
||||
if (normalized.startsWith("f") && normalized.length <= 3) return normalized;
|
||||
if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "delete" || normalized === "home" || normalized === "end") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "pageup" || normalized === "pagedown") return normalized;
|
||||
return null;
|
||||
}
|
||||
|
||||
function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | null {
|
||||
const keyToken = normalizeShortcutKeyToken(event.key);
|
||||
if (!keyToken) return null;
|
||||
|
||||
const parts: string[] = [];
|
||||
if (isMacPlatform(navigator.platform)) {
|
||||
if (event.metaKey) parts.push("mod");
|
||||
if (event.ctrlKey) parts.push("ctrl");
|
||||
} else {
|
||||
if (event.ctrlKey) parts.push("mod");
|
||||
if (event.metaKey) parts.push("meta");
|
||||
}
|
||||
if (event.altKey) parts.push("alt");
|
||||
if (event.shiftKey) parts.push("shift");
|
||||
if (parts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
parts.push(keyToken);
|
||||
return parts.join("+");
|
||||
}
|
||||
|
||||
function keybindingValueForCommand(
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
command: string,
|
||||
): string | null {
|
||||
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
|
||||
const binding = keybindings[index];
|
||||
if (!binding || binding.command !== command) continue;
|
||||
|
||||
const parts: string[] = [];
|
||||
if (binding.shortcut.modKey) parts.push("mod");
|
||||
if (binding.shortcut.ctrlKey) parts.push("ctrl");
|
||||
if (binding.shortcut.metaKey) parts.push("meta");
|
||||
if (binding.shortcut.altKey) parts.push("alt");
|
||||
if (binding.shortcut.shiftKey) parts.push("shift");
|
||||
const keyToken =
|
||||
binding.shortcut.key === " "
|
||||
? "space"
|
||||
: binding.shortcut.key === "escape"
|
||||
? "esc"
|
||||
: binding.shortcut.key;
|
||||
parts.push(keyToken);
|
||||
return parts.join("+");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function ProjectScriptsControl({
|
||||
scripts,
|
||||
keybindings,
|
||||
preferredScriptId = null,
|
||||
onRunScript,
|
||||
onAddScript,
|
||||
onUpdateScript,
|
||||
}: ProjectScriptsControlProps) {
|
||||
const addScriptFormId = React.useId();
|
||||
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [command, setCommand] = useState("");
|
||||
const [icon, setIcon] = useState<ProjectScriptIcon>("play");
|
||||
const [iconPickerOpen, setIconPickerOpen] = useState(false);
|
||||
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
|
||||
const [keybinding, setKeybinding] = useState("");
|
||||
const [validationError, setValidationError] = useState<string | null>(null);
|
||||
|
||||
const primaryScript = useMemo(() => {
|
||||
if (preferredScriptId) {
|
||||
const preferred = scripts.find((script) => script.id === preferredScriptId);
|
||||
if (preferred) return preferred;
|
||||
}
|
||||
return primaryProjectScript(scripts);
|
||||
}, [preferredScriptId, scripts]);
|
||||
const isEditing = editingScriptId !== null;
|
||||
const dropdownItemClassName =
|
||||
"data-highlighted:bg-transparent data-highlighted:text-foreground hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground data-highlighted:hover:bg-accent data-highlighted:hover:text-accent-foreground data-highlighted:focus-visible:bg-accent data-highlighted:focus-visible:text-accent-foreground";
|
||||
|
||||
const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (event.key === "Tab") return;
|
||||
event.preventDefault();
|
||||
if (event.key === "Backspace" || event.key === "Delete") {
|
||||
setKeybinding("");
|
||||
return;
|
||||
}
|
||||
const next = keybindingFromEvent(event);
|
||||
if (!next) return;
|
||||
setKeybinding(next);
|
||||
};
|
||||
|
||||
const submitAddScript = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
const trimmedName = name.trim();
|
||||
const trimmedCommand = command.trim();
|
||||
if (trimmedName.length === 0) {
|
||||
setValidationError("Name is required.");
|
||||
return;
|
||||
}
|
||||
if (trimmedCommand.length === 0) {
|
||||
setValidationError("Command is required.");
|
||||
return;
|
||||
}
|
||||
|
||||
setValidationError(null);
|
||||
try {
|
||||
const payload = {
|
||||
name: trimmedName,
|
||||
command: trimmedCommand,
|
||||
icon,
|
||||
runOnWorktreeCreate,
|
||||
keybinding: keybinding.trim() || null,
|
||||
} satisfies NewProjectScriptInput;
|
||||
if (editingScriptId) {
|
||||
await onUpdateScript(editingScriptId, payload);
|
||||
} else {
|
||||
await onAddScript(payload);
|
||||
}
|
||||
setDialogOpen(false);
|
||||
setIconPickerOpen(false);
|
||||
} catch (error) {
|
||||
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
|
||||
}
|
||||
};
|
||||
|
||||
const openAddDialog = () => {
|
||||
setEditingScriptId(null);
|
||||
setName("");
|
||||
setCommand("");
|
||||
setIcon("play");
|
||||
setIconPickerOpen(false);
|
||||
setRunOnWorktreeCreate(false);
|
||||
setKeybinding("");
|
||||
setValidationError(null);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const openEditDialog = (script: ProjectScript) => {
|
||||
setEditingScriptId(script.id);
|
||||
setName(script.name);
|
||||
setCommand(script.command);
|
||||
setIcon(script.icon);
|
||||
setIconPickerOpen(false);
|
||||
setRunOnWorktreeCreate(script.runOnWorktreeCreate);
|
||||
setKeybinding(keybindingValueForCommand(keybindings, commandForProjectScript(script.id)) ?? "");
|
||||
setValidationError(null);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{primaryScript ? (
|
||||
<Group aria-label="Project scripts">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onRunScript(primaryScript)}
|
||||
title={`Run ${primaryScript.name}`}
|
||||
>
|
||||
<ScriptIcon icon={primaryScript.icon} />
|
||||
<span className="ml-0.5">{primaryScript.name}</span>
|
||||
</Button>
|
||||
<GroupSeparator />
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<MenuTrigger
|
||||
render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end">
|
||||
{scripts.map((script) => {
|
||||
const shortcutLabel = shortcutLabelForCommand(
|
||||
keybindings,
|
||||
commandForProjectScript(script.id),
|
||||
);
|
||||
return (
|
||||
<MenuItem
|
||||
key={script.id}
|
||||
className={`group ${dropdownItemClassName}`}
|
||||
onClick={() => onRunScript(script)}
|
||||
>
|
||||
<ScriptIcon icon={script.icon} className="size-4" />
|
||||
<span className="truncate">
|
||||
{script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
|
||||
</span>
|
||||
<span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
|
||||
{shortcutLabel && (
|
||||
<MenuShortcut className="ms-0 transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
|
||||
{shortcutLabel}
|
||||
</MenuShortcut>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="absolute right-0 top-1/2 size-6 -translate-y-1/2 opacity-0 pointer-events-none transition-opacity group-hover:opacity-100 group-hover:pointer-events-auto group-focus-visible:opacity-100 group-focus-visible:pointer-events-auto"
|
||||
aria-label={`Edit ${script.name}`}
|
||||
onPointerDown={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
openEditDialog(script);
|
||||
}}
|
||||
>
|
||||
<SettingsIcon className="size-3.5" />
|
||||
</Button>
|
||||
</span>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
<MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
|
||||
<PlusIcon className="size-4" />
|
||||
Add action
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
</Group>
|
||||
) : (
|
||||
<Button size="xs" variant="outline" onClick={openAddDialog}>
|
||||
<PlusIcon className="size-3.5" />
|
||||
Add action
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
onOpenChange={(open) => {
|
||||
setDialogOpen(open);
|
||||
if (!open) {
|
||||
setIconPickerOpen(false);
|
||||
}
|
||||
}}
|
||||
onOpenChangeComplete={(open) => {
|
||||
if (open) return;
|
||||
setEditingScriptId(null);
|
||||
setName("");
|
||||
setCommand("");
|
||||
setIcon("play");
|
||||
setRunOnWorktreeCreate(false);
|
||||
setKeybinding("");
|
||||
setValidationError(null);
|
||||
}}
|
||||
open={dialogOpen}
|
||||
>
|
||||
<DialogPopup>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Actions are project-scoped commands you can run from the top bar or keybindings.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel>
|
||||
<form id={addScriptFormId} className="space-y-4" onSubmit={submitAddScript}>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="script-name">Name</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)]"
|
||||
aria-label="Choose icon"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ScriptIcon icon={icon} className="size-4.5" />
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup align="start">
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{SCRIPT_ICONS.map((entry) => {
|
||||
const isSelected = entry.id === icon;
|
||||
return (
|
||||
<button
|
||||
key={entry.id}
|
||||
type="button"
|
||||
className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs ${
|
||||
isSelected
|
||||
? "border-primary/70 bg-primary/10"
|
||||
: "border-border/70 hover:bg-accent/60"
|
||||
}`}
|
||||
onClick={() => {
|
||||
setIcon(entry.id);
|
||||
setIconPickerOpen(false);
|
||||
}}
|
||||
>
|
||||
<ScriptIcon icon={entry.id} className="size-4" />
|
||||
<span>{entry.label}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
<Input
|
||||
id="script-name"
|
||||
placeholder="Test"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="script-keybinding">Keybinding</Label>
|
||||
<Input
|
||||
id="script-keybinding"
|
||||
placeholder="Press shortcut"
|
||||
value={keybinding}
|
||||
readOnly
|
||||
onKeyDown={captureKeybinding}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Press a shortcut. Use <code>Backspace</code> to clear.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="script-command">Command</Label>
|
||||
<Textarea
|
||||
id="script-command"
|
||||
placeholder="bun test"
|
||||
value={command}
|
||||
onChange={(event) => setCommand(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm">
|
||||
<span>Run automatically on worktree creation</span>
|
||||
<Switch
|
||||
checked={runOnWorktreeCreate}
|
||||
onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
|
||||
/>
|
||||
</label>
|
||||
{validationError && <p className="text-sm text-destructive">{validationError}</p>}
|
||||
</form>
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setDialogOpen(false);
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button form={addScriptFormId} type="submit">
|
||||
{isEditing ? "Save changes" : "Save action"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -1,22 +1,25 @@
|
||||
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
|
||||
import { TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { APP_STAGE_LABEL } from "../branding";
|
||||
import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
type Project,
|
||||
type Thread,
|
||||
} from "../types";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||
import { type Project, type Thread } from "../types";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { createLocalThreadForProject } from "./Sidebar.logic";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
|
||||
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
|
||||
function formatRelativeTime(iso: string): string {
|
||||
const diff = Date.now() - new Date(iso).getTime();
|
||||
const minutes = Math.floor(diff / 60_000);
|
||||
@@ -109,12 +112,25 @@ 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();
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
const params = useParams({ strict: false });
|
||||
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
|
||||
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
|
||||
...serverConfigQueryOptions(api),
|
||||
select: (config) => config.keybindings,
|
||||
});
|
||||
const queryClient = useQueryClient();
|
||||
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ api, queryClient }));
|
||||
const { theme, setTheme } = useTheme();
|
||||
const removeWorktreeMutation = useMutation(
|
||||
gitRemoveWorktreeMutationOptions({ api, queryClient }),
|
||||
);
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
@@ -128,38 +144,78 @@ export default function Sidebar() {
|
||||
}, [state.threads]);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(projectId: string) => {
|
||||
dispatch({
|
||||
type: "ADD_THREAD",
|
||||
thread: {
|
||||
id: crypto.randomUUID(),
|
||||
codexThreadId: null,
|
||||
(
|
||||
projectId: string,
|
||||
options?: {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
},
|
||||
) => {
|
||||
if (!api) {
|
||||
const localThread = createLocalThreadForProject({
|
||||
projectId,
|
||||
title: "New thread",
|
||||
model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
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 ?? [],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: result.thread.id },
|
||||
});
|
||||
} catch {
|
||||
// Ignore thread creation errors here; caller surfaces project-level failures.
|
||||
}
|
||||
})();
|
||||
},
|
||||
[dispatch, state.projects],
|
||||
[api, dispatch, navigate, state.projects],
|
||||
);
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
@@ -173,12 +229,12 @@ export default function Sidebar() {
|
||||
})[0];
|
||||
if (!latestThread) return;
|
||||
|
||||
dispatch({
|
||||
type: "SET_ACTIVE_THREAD",
|
||||
threadId: latestThread.id,
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: latestThread.id },
|
||||
});
|
||||
},
|
||||
[dispatch, state.threads],
|
||||
[navigate, state.threads],
|
||||
);
|
||||
|
||||
const addProjectFromPath = useCallback(
|
||||
@@ -188,28 +244,7 @@ export default function Sidebar() {
|
||||
|
||||
setIsAddingProject(true);
|
||||
try {
|
||||
if (isElectron && api) {
|
||||
const result = await api.projects.add({ cwd });
|
||||
const project: Project = {
|
||||
id: result.project.id,
|
||||
name: result.project.name,
|
||||
cwd: result.project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
};
|
||||
const existingById = state.projects.find((p) => p.id === project.id);
|
||||
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
|
||||
if (!existingById && !existingByCwd) {
|
||||
dispatch({ type: "ADD_PROJECT", project });
|
||||
}
|
||||
const resolvedProjectId = existingByCwd?.id ?? project.id;
|
||||
|
||||
if (result.created) {
|
||||
handleNewThread(resolvedProjectId);
|
||||
} else {
|
||||
focusMostRecentThreadForProject(resolvedProjectId);
|
||||
}
|
||||
} else {
|
||||
if (!api) {
|
||||
const existing = state.projects.find((project) => project.cwd === cwd);
|
||||
if (existing) {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
@@ -223,9 +258,33 @@ export default function Sidebar() {
|
||||
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);
|
||||
@@ -267,6 +326,17 @@ export default function Sidebar() {
|
||||
|
||||
const thread = state.threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
if (appSettings.confirmThreadDelete) {
|
||||
const confirmed = await api.dialogs.confirm(
|
||||
[
|
||||
`Delete thread \"${thread.title}\"?`,
|
||||
"This permanently clears conversation history for this thread.",
|
||||
].join("\n"),
|
||||
);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const threadProject = state.projects.find((project) => project.id === thread.projectId);
|
||||
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
|
||||
const displayWorktreePath = orphanedWorktreePath
|
||||
@@ -304,7 +374,21 @@ export default function Sidebar() {
|
||||
// Terminal may already be closed
|
||||
}
|
||||
|
||||
const shouldNavigateToFallback = routeThreadId === threadId;
|
||||
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
||||
void api.threads.delete({ threadId }).catch(() => undefined);
|
||||
dispatch({ type: "DELETE_THREAD", threadId });
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: fallbackThreadId },
|
||||
replace: true,
|
||||
});
|
||||
} else {
|
||||
void navigate({ to: "/", replace: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
|
||||
return;
|
||||
@@ -314,62 +398,127 @@ export default function Sidebar() {
|
||||
await removeWorktreeMutation.mutateAsync({
|
||||
cwd: threadProject.cwd,
|
||||
path: orphanedWorktreePath,
|
||||
force: true,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
|
||||
console.error("Failed to remove orphaned worktree after thread deletion", {
|
||||
threadId,
|
||||
projectCwd: threadProject.cwd,
|
||||
worktreePath: orphanedWorktreePath,
|
||||
error,
|
||||
});
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Thread deleted, but worktree removal failed",
|
||||
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
|
||||
});
|
||||
} catch {
|
||||
// Worktree deletion is best-effort and should not block thread deletion.
|
||||
}
|
||||
},
|
||||
[api, dispatch, removeWorktreeMutation, state.projects, state.threads],
|
||||
[
|
||||
api,
|
||||
appSettings.confirmThreadDelete,
|
||||
dispatch,
|
||||
navigate,
|
||||
removeWorktreeMutation,
|
||||
routeThreadId,
|
||||
state.projects,
|
||||
state.threads,
|
||||
],
|
||||
);
|
||||
|
||||
const handleProjectContextMenu = useCallback(
|
||||
async (projectId: string, position: { x: number; y: number }) => {
|
||||
if (!api) return;
|
||||
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
|
||||
if (clicked !== "delete") return;
|
||||
|
||||
const project = state.projects.find((entry) => entry.id === projectId);
|
||||
if (!project) return;
|
||||
|
||||
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
|
||||
if (projectThreads.length > 0) {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Project is not empty",
|
||||
description: "Delete all threads in this project before deleting it.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const confirmed = await api.dialogs.confirm(
|
||||
[`Delete project "${project.name}"?`, "This action cannot be undone."].join("\n"),
|
||||
);
|
||||
if (!confirmed) 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],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
const isNewThreadShortcut =
|
||||
event.metaKey &&
|
||||
event.shiftKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.altKey &&
|
||||
event.key.toLowerCase() === "o";
|
||||
if (!isNewThreadShortcut) return;
|
||||
const activeThread = routeThreadId
|
||||
? state.threads.find((thread) => thread.id === routeThreadId)
|
||||
: undefined;
|
||||
if (isChatNewLocalShortcut(event, keybindings)) {
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
handleNewThread(projectId);
|
||||
return;
|
||||
}
|
||||
|
||||
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
|
||||
if (!isChatNewShortcut(event, keybindings)) return;
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
|
||||
event.preventDefault();
|
||||
handleNewThread(projectId);
|
||||
handleNewThread(projectId, {
|
||||
branch: activeThread?.branch ?? null,
|
||||
worktreePath: activeThread?.worktreePath ?? null,
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
};
|
||||
}, [handleNewThread, state.activeThreadId, state.projects, state.threads]);
|
||||
}, [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"}`}
|
||||
>
|
||||
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
|
||||
T3 <span className="font-normal text-muted-foreground">Code</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1.5 text-muted-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-muted-foreground"
|
||||
onClick={() => setTheme(THEME_CYCLE[theme])}
|
||||
aria-label={`Theme: ${theme}`}
|
||||
title={`Theme: ${theme}`}
|
||||
>
|
||||
{theme === "system" ? (
|
||||
<MonitorIcon className="size-3.5" />
|
||||
) : theme === "light" ? (
|
||||
<SunIcon className="size-3.5" />
|
||||
) : (
|
||||
<MoonIcon className="size-3.5" />
|
||||
)}
|
||||
</button>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<span className="truncate text-sm font-semibold tracking-tight text-foreground">
|
||||
T3 <span className="font-normal text-muted-foreground">Code</span>
|
||||
</span>
|
||||
<span className="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>
|
||||
</div>
|
||||
|
||||
{/* New thread (global) */}
|
||||
@@ -408,6 +557,13 @@ export default function Sidebar() {
|
||||
type="button"
|
||||
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
|
||||
onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
void handleProjectContextMenu(project.id, {
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<span className="text-[10px] text-muted-foreground/70">
|
||||
{project.expanded ? "▼" : "▶"}
|
||||
@@ -415,14 +571,16 @@ 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 */}
|
||||
{project.expanded && (
|
||||
<div className="ml-2 border-l border-border/80 pl-2">
|
||||
{threads.map((thread) => {
|
||||
const isActive = state.activeThreadId === thread.id;
|
||||
const isActive = routeThreadId === thread.id;
|
||||
const threadStatus = threadStatusPill(
|
||||
thread,
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
@@ -437,12 +595,12 @@ export default function Sidebar() {
|
||||
? "bg-accent text-foreground"
|
||||
: "text-muted-foreground hover:bg-secondary"
|
||||
}`}
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "SET_ACTIVE_THREAD",
|
||||
threadId: thread.id,
|
||||
})
|
||||
}
|
||||
onClick={() => {
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: thread.id },
|
||||
});
|
||||
}}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
void handleThreadContextMenu(thread.id, {
|
||||
@@ -479,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>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
|
||||
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
|
||||
import { type NativeApi } from "@t3tools/contracts";
|
||||
import { Terminal, type ITheme } from "@xterm/xterm";
|
||||
import {
|
||||
@@ -18,10 +18,11 @@ import {
|
||||
preferredTerminalEditor,
|
||||
resolvePathLinkTarget,
|
||||
} from "../terminal-links";
|
||||
import { isTerminalClearShortcut } from "../terminal-shortcuts";
|
||||
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ThreadTerminalGroup,
|
||||
} from "../types";
|
||||
|
||||
@@ -110,6 +111,7 @@ interface TerminalViewportProps {
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
focusRequestId: number;
|
||||
autoFocus: boolean;
|
||||
resizeEpoch: number;
|
||||
@@ -121,6 +123,7 @@ function TerminalViewport({
|
||||
threadId,
|
||||
terminalId,
|
||||
cwd,
|
||||
runtimeEnv,
|
||||
focusRequestId,
|
||||
autoFocus,
|
||||
resizeEpoch,
|
||||
@@ -152,24 +155,29 @@ function TerminalViewport({
|
||||
terminalRef.current = terminal;
|
||||
fitAddonRef.current = fitAddon;
|
||||
|
||||
const sendClearShortcut = async () => {
|
||||
const sendTerminalInput = async (data: string, fallbackError: string) => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) return;
|
||||
try {
|
||||
await api.terminal.write({ threadId, terminalId, data: "\u000c" });
|
||||
await api.terminal.write({ threadId, terminalId, data });
|
||||
} catch (error) {
|
||||
writeSystemMessage(
|
||||
activeTerminal,
|
||||
error instanceof Error ? error.message : "Failed to clear terminal",
|
||||
);
|
||||
writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
|
||||
}
|
||||
};
|
||||
|
||||
terminal.attachCustomKeyEventHandler((event) => {
|
||||
const navigationData = terminalNavigationShortcutData(event);
|
||||
if (navigationData !== null) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void sendTerminalInput(navigationData, "Failed to move cursor");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isTerminalClearShortcut(event)) return true;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void sendClearShortcut();
|
||||
void sendTerminalInput("\u000c", "Failed to clear terminal");
|
||||
return false;
|
||||
});
|
||||
|
||||
@@ -244,6 +252,7 @@ function TerminalViewport({
|
||||
),
|
||||
);
|
||||
});
|
||||
let didReceiveRenderableEventSinceOpen = false;
|
||||
|
||||
const themeObserver = new MutationObserver(() => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
@@ -268,11 +277,17 @@ function TerminalViewport({
|
||||
cwd,
|
||||
cols: activeTerminal.cols,
|
||||
rows: activeTerminal.rows,
|
||||
...(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(() => {
|
||||
@@ -293,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;
|
||||
@@ -363,7 +382,7 @@ function TerminalViewport({
|
||||
fitAddonRef.current = null;
|
||||
terminal.dispose();
|
||||
};
|
||||
}, [api, cwd, terminalId, threadId]);
|
||||
}, [api, cwd, runtimeEnv, terminalId, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoFocus) return;
|
||||
@@ -408,6 +427,7 @@ interface ThreadTerminalDrawerProps {
|
||||
api: NativeApi;
|
||||
threadId: string;
|
||||
cwd: string;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
height: number;
|
||||
terminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
@@ -416,6 +436,9 @@ interface ThreadTerminalDrawerProps {
|
||||
focusRequestId: number;
|
||||
onSplitTerminal: () => void;
|
||||
onNewTerminal: () => void;
|
||||
splitShortcutLabel?: string | undefined;
|
||||
newShortcutLabel?: string | undefined;
|
||||
closeShortcutLabel?: string | undefined;
|
||||
onActiveTerminalChange: (terminalId: string) => void;
|
||||
onCloseTerminal: (terminalId: string) => void;
|
||||
onHeightChange: (height: number) => void;
|
||||
@@ -431,15 +454,9 @@ interface TerminalActionButtonProps {
|
||||
function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger openOnHover
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className={className}
|
||||
onClick={onClick}
|
||||
aria-label={label}
|
||||
/>
|
||||
}
|
||||
<PopoverTrigger
|
||||
openOnHover
|
||||
render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
|
||||
>
|
||||
{children}
|
||||
</PopoverTrigger>
|
||||
@@ -460,6 +477,7 @@ export default function ThreadTerminalDrawer({
|
||||
api,
|
||||
threadId,
|
||||
cwd,
|
||||
runtimeEnv,
|
||||
height,
|
||||
terminalIds,
|
||||
activeTerminalId,
|
||||
@@ -468,6 +486,9 @@ export default function ThreadTerminalDrawer({
|
||||
focusRequestId,
|
||||
onSplitTerminal,
|
||||
onNewTerminal,
|
||||
splitShortcutLabel,
|
||||
newShortcutLabel,
|
||||
closeShortcutLabel,
|
||||
onActiveTerminalChange,
|
||||
onCloseTerminal,
|
||||
onHeightChange,
|
||||
@@ -576,6 +597,7 @@ export default function ThreadTerminalDrawer({
|
||||
const showGroupHeaders =
|
||||
resolvedTerminalGroups.length > 1 ||
|
||||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
|
||||
const hasReachedTerminalLimit = normalizedTerminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
|
||||
const terminalLabelById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
@@ -583,6 +605,23 @@ export default function ThreadTerminalDrawer({
|
||||
),
|
||||
[normalizedTerminalIds],
|
||||
);
|
||||
const splitTerminalActionLabel = hasReachedTerminalLimit
|
||||
? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
||||
: (splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal");
|
||||
const newTerminalActionLabel = hasReachedTerminalLimit
|
||||
? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
||||
: (newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal");
|
||||
const closeTerminalActionLabel = closeShortcutLabel
|
||||
? `Close Terminal (${closeShortcutLabel})`
|
||||
: "Close Terminal";
|
||||
const onSplitTerminalAction = useCallback(() => {
|
||||
if (hasReachedTerminalLimit) return;
|
||||
onSplitTerminal();
|
||||
}, [hasReachedTerminalLimit, onSplitTerminal]);
|
||||
const onNewTerminalAction = useCallback(() => {
|
||||
if (hasReachedTerminalLimit) return;
|
||||
onNewTerminal();
|
||||
}, [hasReachedTerminalLimit, onNewTerminal]);
|
||||
|
||||
useEffect(() => {
|
||||
onHeightChangeRef.current = onHeightChange;
|
||||
@@ -677,7 +716,7 @@ export default function ThreadTerminalDrawer({
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
|
||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
||||
style={{ height: `${drawerHeight}px` }}
|
||||
>
|
||||
<div
|
||||
@@ -692,17 +731,25 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="pointer-events-none absolute right-2 top-2 z-20">
|
||||
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
|
||||
<TerminalActionButton
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onSplitTerminal}
|
||||
label="Split Terminal"
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
onClick={onSplitTerminalAction}
|
||||
label={splitTerminalActionLabel}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<div className="h-4 w-px bg-border/80" />
|
||||
<TerminalActionButton
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onNewTerminal}
|
||||
label="New Terminal"
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -710,7 +757,7 @@ export default function ThreadTerminalDrawer({
|
||||
<TerminalActionButton
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||
label="Close Terminal"
|
||||
label={closeTerminalActionLabel}
|
||||
>
|
||||
<Trash2 className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -723,9 +770,9 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="min-w-0 flex-1">
|
||||
{isSplitView ? (
|
||||
<div
|
||||
className="grid h-full w-full gap-0 overflow-x-auto"
|
||||
className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
|
||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
|
||||
}}
|
||||
>
|
||||
{visibleTerminalIds.map((terminalId) => (
|
||||
@@ -746,6 +793,7 @@ export default function ThreadTerminalDrawer({
|
||||
threadId={threadId}
|
||||
terminalId={terminalId}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus={terminalId === resolvedActiveTerminalId}
|
||||
resizeEpoch={resizeEpoch}
|
||||
@@ -763,6 +811,7 @@ export default function ThreadTerminalDrawer({
|
||||
threadId={threadId}
|
||||
terminalId={resolvedActiveTerminalId}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus
|
||||
resizeEpoch={resizeEpoch}
|
||||
@@ -777,23 +826,31 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
|
||||
<div className="inline-flex h-full items-stretch">
|
||||
<TerminalActionButton
|
||||
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onSplitTerminal}
|
||||
label="Split Terminal"
|
||||
className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
onClick={onSplitTerminalAction}
|
||||
label={splitTerminalActionLabel}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<TerminalActionButton
|
||||
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onNewTerminal}
|
||||
label="New Terminal"
|
||||
className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<TerminalActionButton
|
||||
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||
label="Close Terminal"
|
||||
label={closeTerminalActionLabel}
|
||||
>
|
||||
<Trash2 className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -831,6 +888,9 @@ export default function ThreadTerminalDrawer({
|
||||
>
|
||||
{terminalGroup.terminalIds.map((terminalId) => {
|
||||
const isActive = terminalId === resolvedActiveTerminalId;
|
||||
const closeTerminalLabel = `Close ${
|
||||
terminalLabelById.get(terminalId) ?? "terminal"
|
||||
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
|
||||
return (
|
||||
<div
|
||||
key={terminalId}
|
||||
@@ -854,18 +914,30 @@ export default function ThreadTerminalDrawer({
|
||||
</span>
|
||||
</button>
|
||||
{normalizedTerminalIds.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onCloseTerminal(terminalId);
|
||||
}}
|
||||
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
|
||||
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
openOnHover
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
|
||||
onClick={() => onCloseTerminal(terminalId)}
|
||||
aria-label={closeTerminalLabel}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<XIcon className="size-2.5" />
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup
|
||||
tooltipStyle
|
||||
side="bottom"
|
||||
sideOffset={6}
|
||||
align="center"
|
||||
className="pointer-events-none select-none"
|
||||
>
|
||||
{closeTerminalLabel}
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -60,16 +60,18 @@ function SheetPopup({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
keepMounted = false,
|
||||
side = "right",
|
||||
variant = "default",
|
||||
...props
|
||||
}: SheetPrimitive.Popup.Props & {
|
||||
showCloseButton?: boolean;
|
||||
keepMounted?: boolean;
|
||||
side?: "right" | "left" | "top" | "bottom";
|
||||
variant?: "default" | "inset";
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetPortal keepMounted={keepMounted}>
|
||||
<SheetBackdrop />
|
||||
<SheetViewport side={side} variant={variant}>
|
||||
<SheetPrimitive.Popup
|
||||
|
||||
@@ -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,16 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
import { shouldHideCollapsedToastContent } from "./toast.logic";
|
||||
|
||||
describe("shouldHideCollapsedToastContent", () => {
|
||||
it("keeps a single visible toast readable", () => {
|
||||
assert.equal(shouldHideCollapsedToastContent(0, 1), false);
|
||||
});
|
||||
|
||||
it("keeps the front-most toast readable in a visible stack", () => {
|
||||
assert.equal(shouldHideCollapsedToastContent(0, 3), false);
|
||||
});
|
||||
|
||||
it("hides non-front toasts until the stack is expanded", () => {
|
||||
assert.equal(shouldHideCollapsedToastContent(1, 3), true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
export function shouldHideCollapsedToastContent(
|
||||
visibleToastIndex: number,
|
||||
visibleToastCount: number,
|
||||
): boolean {
|
||||
// Keep the front-most toast readable even if Base UI marks it as "behind"
|
||||
// due to toasts hidden by thread filtering.
|
||||
if (visibleToastCount <= 1) return false;
|
||||
return visibleToastIndex > 0;
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { Toast } from "@base-ui/react/toast";
|
||||
import { useEffect } from "react";
|
||||
import { useParams } from "@tanstack/react-router";
|
||||
import {
|
||||
CircleAlertIcon,
|
||||
CircleCheckIcon,
|
||||
@@ -11,15 +13,18 @@ import {
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { buttonVariants } from "~/components/ui/button";
|
||||
import { useStore } from "~/store";
|
||||
import { shouldHideCollapsedToastContent } from "./toast.logic";
|
||||
|
||||
type ThreadToastData = {
|
||||
threadId?: string | null;
|
||||
tooltipStyle?: boolean;
|
||||
dismissAfterVisibleMs?: number;
|
||||
};
|
||||
|
||||
const toastManager = Toast.createToastManager<ThreadToastData>();
|
||||
const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
|
||||
type ToastId = ReturnType<typeof toastManager.add>;
|
||||
const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
|
||||
|
||||
const TOAST_ICONS = {
|
||||
error: CircleAlertIcon,
|
||||
@@ -50,6 +55,91 @@ function shouldRenderForActiveThread(
|
||||
return toastThreadId === activeThreadId;
|
||||
}
|
||||
|
||||
function useActiveThreadIdFromRoute(): string | null {
|
||||
return useParams({
|
||||
strict: false,
|
||||
select: (params) => params.threadId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
function ThreadToastVisibleAutoDismiss({
|
||||
toastId,
|
||||
dismissAfterVisibleMs,
|
||||
}: {
|
||||
toastId: ToastId;
|
||||
dismissAfterVisibleMs: number | undefined;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
if (!dismissAfterVisibleMs || dismissAfterVisibleMs <= 0) return;
|
||||
if (typeof window === "undefined" || typeof document === "undefined") return;
|
||||
|
||||
let remainingMs = threadToastVisibleTimeoutRemainingMs.get(toastId) ?? dismissAfterVisibleMs;
|
||||
let startedAtMs: number | null = null;
|
||||
let timeoutId: number | null = null;
|
||||
let closed = false;
|
||||
|
||||
const clearTimer = () => {
|
||||
if (timeoutId === null) return;
|
||||
window.clearTimeout(timeoutId);
|
||||
timeoutId = null;
|
||||
};
|
||||
|
||||
const closeToast = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
threadToastVisibleTimeoutRemainingMs.delete(toastId);
|
||||
toastManager.close(toastId);
|
||||
};
|
||||
|
||||
const pause = () => {
|
||||
if (startedAtMs === null) return;
|
||||
remainingMs = Math.max(0, remainingMs - (Date.now() - startedAtMs));
|
||||
startedAtMs = null;
|
||||
clearTimer();
|
||||
threadToastVisibleTimeoutRemainingMs.set(toastId, remainingMs);
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
if (closed || startedAtMs !== null) return;
|
||||
if (remainingMs <= 0) {
|
||||
closeToast();
|
||||
return;
|
||||
}
|
||||
startedAtMs = Date.now();
|
||||
clearTimer();
|
||||
timeoutId = window.setTimeout(() => {
|
||||
remainingMs = 0;
|
||||
startedAtMs = null;
|
||||
closeToast();
|
||||
}, remainingMs);
|
||||
};
|
||||
|
||||
const syncTimer = () => {
|
||||
const shouldRun = document.visibilityState === "visible" && document.hasFocus();
|
||||
if (shouldRun) {
|
||||
start();
|
||||
return;
|
||||
}
|
||||
pause();
|
||||
};
|
||||
|
||||
syncTimer();
|
||||
document.addEventListener("visibilitychange", syncTimer);
|
||||
window.addEventListener("focus", syncTimer);
|
||||
window.addEventListener("blur", syncTimer);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", syncTimer);
|
||||
window.removeEventListener("focus", syncTimer);
|
||||
window.removeEventListener("blur", syncTimer);
|
||||
pause();
|
||||
clearTimer();
|
||||
};
|
||||
}, [dismissAfterVisibleMs, toastId]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) {
|
||||
return (
|
||||
<Toast.Provider toastManager={toastManager} {...props}>
|
||||
@@ -60,10 +150,21 @@ function ToastProvider({ children, position = "top-right", ...props }: ToastProv
|
||||
}
|
||||
|
||||
function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
const { state } = useStore();
|
||||
const { toasts } = Toast.useToastManager<ThreadToastData>();
|
||||
const activeThreadId = state.activeThreadId;
|
||||
const activeThreadId = useActiveThreadIdFromRoute();
|
||||
const isTop = position.startsWith("top");
|
||||
const visibleToasts = toasts.filter((toast) =>
|
||||
shouldRenderForActiveThread(toast.data, activeThreadId),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const activeToastIds = new Set(toasts.map((toast) => toast.id));
|
||||
for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) {
|
||||
if (!activeToastIds.has(toastId)) {
|
||||
threadToastVisibleTimeoutRemainingMs.delete(toastId);
|
||||
}
|
||||
}
|
||||
}, [toasts]);
|
||||
|
||||
return (
|
||||
<Toast.Portal data-slot="toast-portal">
|
||||
@@ -81,96 +182,107 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
data-position={position}
|
||||
data-slot="toast-viewport"
|
||||
>
|
||||
{toasts
|
||||
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
|
||||
.map((toast) => {
|
||||
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
|
||||
{visibleToasts.map((toast, visibleIndex) => {
|
||||
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
|
||||
const hideCollapsedContent = shouldHideCollapsedToastContent(
|
||||
visibleIndex,
|
||||
visibleToasts.length,
|
||||
);
|
||||
|
||||
return (
|
||||
<Toast.Root
|
||||
return (
|
||||
<Toast.Root
|
||||
className={cn(
|
||||
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
// Base positioning using data-position
|
||||
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
|
||||
"data-[position*=left]:right-auto data-[position*=left]:left-0",
|
||||
"data-[position*=center]:right-0 data-[position*=center]:left-0",
|
||||
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
|
||||
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
|
||||
// Gap fill for hover
|
||||
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
|
||||
"data-[position*=top]:after:top-full",
|
||||
"data-[position*=bottom]:after:bottom-full",
|
||||
// Define some variables
|
||||
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
|
||||
// Define offset-y variable
|
||||
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
|
||||
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
|
||||
// Default state transform
|
||||
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
|
||||
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
|
||||
// Limited state
|
||||
"data-limited:opacity-0",
|
||||
// Expanded state
|
||||
"data-expanded:h-(--toast-height)",
|
||||
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
|
||||
// Starting and ending animations
|
||||
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
|
||||
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
|
||||
"data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:opacity-0",
|
||||
// Ending animations (direction-aware)
|
||||
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
|
||||
"data-[position*=top]:data-[position*=right]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
|
||||
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
|
||||
// Ending animations (expanded)
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
|
||||
)}
|
||||
data-position={position}
|
||||
key={toast.id}
|
||||
swipeDirection={
|
||||
position.includes("center")
|
||||
? [isTop ? "up" : "down"]
|
||||
: position.includes("left")
|
||||
? ["left", isTop ? "up" : "down"]
|
||||
: ["right", isTop ? "up" : "down"]
|
||||
}
|
||||
toast={toast}
|
||||
>
|
||||
<ThreadToastVisibleAutoDismiss
|
||||
dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
|
||||
toastId={toast.id}
|
||||
/>
|
||||
<Toast.Content
|
||||
className={cn(
|
||||
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
// Base positioning using data-position
|
||||
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
|
||||
"data-[position*=left]:right-auto data-[position*=left]:left-0",
|
||||
"data-[position*=center]:right-0 data-[position*=center]:left-0",
|
||||
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
|
||||
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
|
||||
// Gap fill for hover
|
||||
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
|
||||
"data-[position*=top]:after:top-full",
|
||||
"data-[position*=bottom]:after:bottom-full",
|
||||
// Define some variables
|
||||
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
|
||||
// Define offset-y variable
|
||||
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
|
||||
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
|
||||
// Default state transform
|
||||
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
|
||||
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
|
||||
// Limited state
|
||||
"data-limited:opacity-0",
|
||||
// Expanded state
|
||||
"data-expanded:h-(--toast-height)",
|
||||
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
|
||||
// Starting and ending animations
|
||||
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
|
||||
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
|
||||
"data-ending-style:opacity-0",
|
||||
// Ending animations (direction-aware)
|
||||
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
|
||||
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
|
||||
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
|
||||
// Ending animations (expanded)
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
|
||||
"pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-expanded:opacity-100",
|
||||
hideCollapsedContent &&
|
||||
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
|
||||
)}
|
||||
data-position={position}
|
||||
key={toast.id}
|
||||
swipeDirection={
|
||||
position.includes("center")
|
||||
? [isTop ? "up" : "down"]
|
||||
: position.includes("left")
|
||||
? ["left", isTop ? "up" : "down"]
|
||||
: ["right", isTop ? "up" : "down"]
|
||||
}
|
||||
toast={toast}
|
||||
>
|
||||
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-behind:not-data-expanded:pointer-events-none data-behind:opacity-0 data-expanded:opacity-100">
|
||||
<div className="flex gap-2">
|
||||
{Icon && (
|
||||
<div
|
||||
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
|
||||
data-slot="toast-icon"
|
||||
>
|
||||
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Toast.Title className="font-medium" data-slot="toast-title" />
|
||||
<Toast.Description
|
||||
className="text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{toast.actionProps && (
|
||||
<Toast.Action
|
||||
className={buttonVariants({ size: "xs" })}
|
||||
data-slot="toast-action"
|
||||
<div className="flex gap-2">
|
||||
{Icon && (
|
||||
<div
|
||||
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
|
||||
data-slot="toast-icon"
|
||||
>
|
||||
{toast.actionProps.children}
|
||||
</Toast.Action>
|
||||
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
|
||||
</div>
|
||||
)}
|
||||
</Toast.Content>
|
||||
</Toast.Root>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Toast.Title className="font-medium" data-slot="toast-title" />
|
||||
<Toast.Description
|
||||
className="text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{toast.actionProps && (
|
||||
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
|
||||
{toast.actionProps.children}
|
||||
</Toast.Action>
|
||||
)}
|
||||
</Toast.Content>
|
||||
</Toast.Root>
|
||||
);
|
||||
})}
|
||||
</Toast.Viewport>
|
||||
</Toast.Portal>
|
||||
);
|
||||
@@ -186,9 +298,8 @@ function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
|
||||
}
|
||||
|
||||
function AnchoredToasts() {
|
||||
const { state } = useStore();
|
||||
const { toasts } = Toast.useToastManager<ThreadToastData>();
|
||||
const activeThreadId = state.activeThreadId;
|
||||
const activeThreadId = useActiveThreadIdFromRoute();
|
||||
|
||||
return (
|
||||
<Toast.Portal data-slot="toast-portal-anchored">
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"use client";
|
||||
|
||||
import type { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
|
||||
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Separator } from "~/components/ui/separator";
|
||||
import { Toggle as ToggleComponent, type toggleVariants } from "~/components/ui/toggle";
|
||||
|
||||
const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
|
||||
size: "default",
|
||||
variant: "default",
|
||||
});
|
||||
|
||||
function ToggleGroup({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
orientation = "horizontal",
|
||||
children,
|
||||
...props
|
||||
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<ToggleGroupPrimitive
|
||||
className={cn(
|
||||
"flex w-fit *:focus-visible:z-10 dark:*:[[data-slot=separator]:has(+[data-slot=toggle]:hover)]:before:bg-input/64 dark:*:[[data-slot=separator]:has(+[data-slot=toggle][data-pressed])]:before:bg-input dark:*:[[data-slot=toggle]:hover+[data-slot=separator]]:before:bg-input/64 dark:*:[[data-slot=toggle][data-pressed]+[data-slot=separator]]:before:bg-input",
|
||||
orientation === "horizontal"
|
||||
? "*:pointer-coarse:after:min-w-auto"
|
||||
: "*:pointer-coarse:after:min-h-auto",
|
||||
variant === "default"
|
||||
? "gap-0.5"
|
||||
: orientation === "horizontal"
|
||||
? "*:not-first:not-data-[slot=separator]:before:-start-[0.5px] *:not-last:not-data-[slot=separator]:before:-end-[0.5px] *:not-first:rounded-s-none *:not-last:rounded-e-none *:not-first:border-s-0 *:not-last:border-e-0 *:not-first:before:rounded-s-none *:not-last:before:rounded-e-none"
|
||||
: "*:not-first:not-data-[slot=separator]:before:-top-[0.5px] *:not-last:not-data-[slot=separator]:before:-bottom-[0.5px] flex-col *:not-first:rounded-t-none *:not-last:rounded-b-none *:not-first:border-t-0 *:not-last:border-b-0 *:not-first:before:rounded-t-none *:not-last:before:rounded-b-none *:data-[slot=toggle]:not-last:before:hidden dark:*:last:before:hidden dark:*:first:before:block",
|
||||
className,
|
||||
)}
|
||||
data-size={size}
|
||||
data-slot="toggle-group"
|
||||
data-variant={variant}
|
||||
orientation={orientation}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider value={{ size, variant }}>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive>
|
||||
);
|
||||
}
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
children,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
const context = React.useContext(ToggleGroupContext);
|
||||
|
||||
const resolvedVariant = variant ?? context.variant;
|
||||
const resolvedSize = size ?? context.size;
|
||||
|
||||
return (
|
||||
<ToggleComponent
|
||||
className={className}
|
||||
data-size={resolvedSize}
|
||||
data-variant={resolvedVariant}
|
||||
size={resolvedSize}
|
||||
variant={resolvedVariant}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</ToggleComponent>
|
||||
);
|
||||
}
|
||||
|
||||
function ToggleGroupSeparator({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: {
|
||||
className?: string;
|
||||
} & React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
className={cn(
|
||||
"pointer-events-none relative bg-input before:absolute before:inset-0 dark:before:bg-input/32",
|
||||
className,
|
||||
)}
|
||||
orientation={orientation}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { ToggleGroup, Toggle, Toggle as ToggleGroupItem, ToggleGroupSeparator };
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const toggleVariants = cva(
|
||||
"[&_svg]:-mx-0.5 relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center gap-2 whitespace-nowrap rounded-lg border font-medium text-base text-foreground outline-none transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 data-pressed:bg-input/64 data-pressed:text-accent-foreground sm:text-sm [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
variant: "default",
|
||||
},
|
||||
variants: {
|
||||
size: {
|
||||
default: "h-9 min-w-9 px-[calc(--spacing(2)-1px)] sm:h-8 sm:min-w-8",
|
||||
lg: "h-10 min-w-10 px-[calc(--spacing(2.5)-1px)] sm:h-9 sm:min-w-9",
|
||||
sm: "h-8 min-w-8 px-[calc(--spacing(1.5)-1px)] sm:h-7 sm:min-w-7",
|
||||
xs: "h-7 min-w-7 px-[calc(--spacing(1)-1px)] sm:h-6 sm:min-w-6 rounded-md",
|
||||
},
|
||||
variant: {
|
||||
default: "border-transparent",
|
||||
outline:
|
||||
"border-input bg-background not-dark:bg-clip-padding shadow-xs/5 not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:data-pressed:bg-input dark:hover:bg-input/64 dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] dark:not-disabled:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/2%)] [:disabled,:active,[data-pressed]]:shadow-none",
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<TogglePrimitive
|
||||
className={cn(toggleVariants({ className, size, variant }))}
|
||||
data-slot="toggle"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Toggle, toggleVariants };
|
||||
@@ -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,
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { detectComposerTrigger, replaceTextRange } from "./composer-logic";
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
const text = "Please check @src/com";
|
||||
const trigger = detectComposerTrigger(text, text.length);
|
||||
|
||||
expect(trigger).toEqual({
|
||||
kind: "path",
|
||||
query: "src/com",
|
||||
rangeStart: "Please check ".length,
|
||||
rangeEnd: text.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects slash command token while typing command name", () => {
|
||||
const text = "/mo";
|
||||
const trigger = detectComposerTrigger(text, text.length);
|
||||
|
||||
expect(trigger).toEqual({
|
||||
kind: "slash-command",
|
||||
query: "mo",
|
||||
rangeStart: 0,
|
||||
rangeEnd: text.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects slash model query after /model", () => {
|
||||
const text = "/model spark";
|
||||
const trigger = detectComposerTrigger(text, text.length);
|
||||
|
||||
expect(trigger).toEqual({
|
||||
kind: "slash-model",
|
||||
query: "spark",
|
||||
rangeStart: 0,
|
||||
rangeEnd: text.length,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("replaceTextRange", () => {
|
||||
it("replaces a text range and returns new cursor", () => {
|
||||
const replaced = replaceTextRange("hello @src", 6, 10, "");
|
||||
expect(replaced).toEqual({
|
||||
text: "hello ",
|
||||
cursor: 6,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
||||
|
||||
export interface ComposerTrigger {
|
||||
kind: ComposerTriggerKind;
|
||||
query: string;
|
||||
rangeStart: number;
|
||||
rangeEnd: number;
|
||||
}
|
||||
|
||||
function clampCursor(text: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return text.length;
|
||||
return Math.max(0, Math.min(text.length, Math.floor(cursor)));
|
||||
}
|
||||
|
||||
function isWhitespace(char: string): boolean {
|
||||
return char === " " || char === "\n" || char === "\t" || char === "\r";
|
||||
}
|
||||
|
||||
function tokenStartForCursor(text: string, cursor: number): number {
|
||||
let index = cursor - 1;
|
||||
while (index >= 0 && !isWhitespace(text[index] ?? "")) {
|
||||
index -= 1;
|
||||
}
|
||||
return index + 1;
|
||||
}
|
||||
|
||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
||||
const cursor = clampCursor(text, cursorInput);
|
||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
||||
const linePrefix = text.slice(lineStart, cursor);
|
||||
|
||||
if (linePrefix.startsWith("/")) {
|
||||
const commandMatch = /^\/(\S*)$/.exec(linePrefix);
|
||||
if (commandMatch) {
|
||||
const commandQuery = commandMatch[1] ?? "";
|
||||
if (commandQuery.toLowerCase() === "model") {
|
||||
return {
|
||||
kind: "slash-model",
|
||||
query: "",
|
||||
rangeStart: lineStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
if ("model".startsWith(commandQuery.toLowerCase())) {
|
||||
return {
|
||||
kind: "slash-command",
|
||||
query: commandQuery,
|
||||
rangeStart: lineStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const modelMatch = /^\/model(?:\s+(.*))?$/.exec(linePrefix);
|
||||
if (modelMatch) {
|
||||
return {
|
||||
kind: "slash-model",
|
||||
query: (modelMatch[1] ?? "").trim(),
|
||||
rangeStart: lineStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const tokenStart = tokenStartForCursor(text, cursor);
|
||||
const token = text.slice(tokenStart, cursor);
|
||||
if (!token.startsWith("@")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "path",
|
||||
query: token.slice(1),
|
||||
rangeStart: tokenStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
|
||||
export function replaceTextRange(
|
||||
text: string,
|
||||
rangeStart: number,
|
||||
rangeEnd: number,
|
||||
replacement: string,
|
||||
): { text: string; cursor: number } {
|
||||
const safeStart = Math.max(0, Math.min(text.length, rangeStart));
|
||||
const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
|
||||
const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
|
||||
return { text: nextText, cursor: safeStart + replacement.length };
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseDiffRouteSearch } from "./diffRouteSearch";
|
||||
|
||||
describe("parseDiffRouteSearch", () => {
|
||||
it("parses valid diff search values", () => {
|
||||
const parsed = parseDiffRouteSearch({
|
||||
diff: "1",
|
||||
diffTurnId: "turn-1",
|
||||
diffFilePath: "src/app.ts",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
diff: "1",
|
||||
diffTurnId: "turn-1",
|
||||
diffFilePath: "src/app.ts",
|
||||
});
|
||||
});
|
||||
|
||||
it("treats numeric and boolean diff toggles as open", () => {
|
||||
expect(
|
||||
parseDiffRouteSearch({
|
||||
diff: 1,
|
||||
diffTurnId: "turn-1",
|
||||
}),
|
||||
).toEqual({
|
||||
diff: "1",
|
||||
diffTurnId: "turn-1",
|
||||
});
|
||||
|
||||
expect(
|
||||
parseDiffRouteSearch({
|
||||
diff: true,
|
||||
diffTurnId: "turn-1",
|
||||
}),
|
||||
).toEqual({
|
||||
diff: "1",
|
||||
diffTurnId: "turn-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("drops turn and file values when diff is closed", () => {
|
||||
const parsed = parseDiffRouteSearch({
|
||||
diff: "0",
|
||||
diffTurnId: "turn-1",
|
||||
diffFilePath: "src/app.ts",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({});
|
||||
});
|
||||
|
||||
it("drops file value when turn is not selected", () => {
|
||||
const parsed = parseDiffRouteSearch({
|
||||
diff: "1",
|
||||
diffFilePath: "src/app.ts",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
diff: "1",
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes whitespace-only values", () => {
|
||||
const parsed = parseDiffRouteSearch({
|
||||
diff: "1",
|
||||
diffTurnId: " ",
|
||||
diffFilePath: " ",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
diff: "1",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
export interface DiffRouteSearch {
|
||||
diff?: "1";
|
||||
diffTurnId?: string;
|
||||
diffFilePath?: string;
|
||||
}
|
||||
|
||||
function isDiffOpenValue(value: unknown): boolean {
|
||||
return value === "1" || value === 1 || value === true;
|
||||
}
|
||||
|
||||
function normalizeSearchString(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = value.trim();
|
||||
return normalized.length > 0 ? normalized : undefined;
|
||||
}
|
||||
|
||||
export function stripDiffSearchParams<T extends Record<string, unknown>>(
|
||||
params: T,
|
||||
): Omit<T, "diff" | "diffTurnId" | "diffFilePath"> {
|
||||
const { diff: _diff, diffTurnId: _diffTurnId, diffFilePath: _diffFilePath, ...rest } = params;
|
||||
return rest as Omit<T, "diff" | "diffTurnId" | "diffFilePath">;
|
||||
}
|
||||
|
||||
export function parseDiffRouteSearch(search: Record<string, unknown>): DiffRouteSearch {
|
||||
const diff = isDiffOpenValue(search.diff) ? "1" : undefined;
|
||||
const diffTurnId = diff ? normalizeSearchString(search.diffTurnId) : undefined;
|
||||
const diffFilePath = diff && diffTurnId ? normalizeSearchString(search.diffFilePath) : undefined;
|
||||
|
||||
return {
|
||||
...(diff ? { diff } : {}),
|
||||
...(diffTurnId ? { diffTurnId } : {}),
|
||||
...(diffFilePath ? { diffFilePath } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
function getMediaQueryMatch(query: string): boolean {
|
||||
if (typeof window === "undefined") {
|
||||
return false;
|
||||
}
|
||||
return window.matchMedia(query).matches;
|
||||
}
|
||||
|
||||
export function useMediaQuery(query: string): boolean {
|
||||
const [matches, setMatches] = useState(() => getMediaQueryMatch(query));
|
||||
|
||||
useEffect(() => {
|
||||
const mediaQueryList = window.matchMedia(query);
|
||||
const handleChange = () => {
|
||||
setMatches(mediaQueryList.matches);
|
||||
};
|
||||
|
||||
setMatches(mediaQueryList.matches);
|
||||
mediaQueryList.addEventListener("change", handleChange);
|
||||
return () => {
|
||||
mediaQueryList.removeEventListener("change", handleChange);
|
||||
};
|
||||
}, [query]);
|
||||
|
||||
return matches;
|
||||
}
|
||||
@@ -28,6 +28,7 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
if (suppressTransitions) {
|
||||
// Force a reflow so the no-transitions class takes effect before removal
|
||||
// oxlint-disable-next-line no-unused-expressions
|
||||
document.documentElement.offsetHeight;
|
||||
requestAnimationFrame(() => {
|
||||
document.documentElement.classList.remove("no-transitions");
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { ProviderEvent } from "@t3tools/contracts";
|
||||
import { useMemo } from "react";
|
||||
import { deriveTurnDiffSummaries, inferCheckpointTurnCountByTurnId } from "../session-logic";
|
||||
import type { Thread, TurnDiffSummary } from "../types";
|
||||
|
||||
const derivedTurnDiffSummaryCache = new WeakMap<readonly ProviderEvent[], TurnDiffSummary[]>();
|
||||
|
||||
function deriveTurnDiffSummariesCached(events: ProviderEvent[]): TurnDiffSummary[] {
|
||||
const cached = derivedTurnDiffSummaryCache.get(events);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const derived = deriveTurnDiffSummaries(events);
|
||||
derivedTurnDiffSummaryCache.set(events, derived);
|
||||
return derived;
|
||||
}
|
||||
|
||||
export function useTurnDiffSummaries(activeThread: Thread | undefined) {
|
||||
const turnDiffSummaries = useMemo(() => {
|
||||
if (!activeThread) {
|
||||
return [];
|
||||
}
|
||||
if (activeThread.turnDiffSummaries.length > 0) {
|
||||
return activeThread.turnDiffSummaries;
|
||||
}
|
||||
return deriveTurnDiffSummariesCached(activeThread.events);
|
||||
}, [activeThread]);
|
||||
|
||||
const inferredCheckpointTurnCountByTurnId = useMemo(
|
||||
() => inferCheckpointTurnCountByTurnId(turnDiffSummaries),
|
||||
[turnDiffSummaries],
|
||||
);
|
||||
|
||||
return { turnDiffSummaries, inferredCheckpointTurnCountByTurnId };
|
||||
}
|
||||
@@ -190,6 +190,16 @@ input {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
.turn-chip-strip {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
overscroll-behavior-x: contain;
|
||||
}
|
||||
|
||||
.turn-chip-strip::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Terminal drawer scrollbar parity with chat */
|
||||
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical {
|
||||
width: 6px !important;
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
|
||||
import {
|
||||
type KeybindingCommand,
|
||||
type KeybindingShortcut,
|
||||
type KeybindingWhenNode,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
formatShortcutLabel,
|
||||
isChatNewShortcut,
|
||||
isChatNewLocalShortcut,
|
||||
isOpenFavoriteEditorShortcut,
|
||||
isTerminalClearShortcut,
|
||||
isTerminalCloseShortcut,
|
||||
isTerminalNewShortcut,
|
||||
isTerminalSplitShortcut,
|
||||
isTerminalToggleShortcut,
|
||||
resolveShortcutCommand,
|
||||
shortcutLabelForCommand,
|
||||
terminalNavigationShortcutData,
|
||||
type ShortcutEventLike,
|
||||
} from "./keybindings";
|
||||
|
||||
function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
|
||||
return {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function modShortcut(
|
||||
key: string,
|
||||
overrides: Partial<Omit<KeybindingShortcut, "key">> = {},
|
||||
): KeybindingShortcut {
|
||||
return {
|
||||
key,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function whenIdentifier(name: string): KeybindingWhenNode {
|
||||
return { type: "identifier", name };
|
||||
}
|
||||
|
||||
function whenNot(node: KeybindingWhenNode): KeybindingWhenNode {
|
||||
return { type: "not", node };
|
||||
}
|
||||
|
||||
function whenAnd(left: KeybindingWhenNode, right: KeybindingWhenNode): KeybindingWhenNode {
|
||||
return { type: "and", left, right };
|
||||
}
|
||||
|
||||
interface TestBinding {
|
||||
shortcut: KeybindingShortcut;
|
||||
command: KeybindingCommand;
|
||||
whenAst?: KeybindingWhenNode;
|
||||
}
|
||||
|
||||
function compile(bindings: TestBinding[]): ResolvedKeybindingsConfig {
|
||||
return bindings.map((binding) => ({
|
||||
command: binding.command,
|
||||
shortcut: binding.shortcut,
|
||||
...(binding.whenAst ? { whenAst: binding.whenAst } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
const DEFAULT_BINDINGS = compile([
|
||||
{ shortcut: modShortcut("j"), command: "terminal.toggle" },
|
||||
{
|
||||
shortcut: modShortcut("d"),
|
||||
command: "terminal.split",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{
|
||||
shortcut: modShortcut("d", { shiftKey: true }),
|
||||
command: "terminal.new",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{
|
||||
shortcut: modShortcut("w"),
|
||||
command: "terminal.close",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
|
||||
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
|
||||
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
|
||||
]);
|
||||
|
||||
describe("isTerminalToggleShortcut", () => {
|
||||
it("matches Cmd+J on macOS", () => {
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches Ctrl+J on non-macOS", () => {
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ ctrlKey: true }), DEFAULT_BINDINGS, { platform: "Win32" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("split/new/close terminal shortcuts", () => {
|
||||
it("requires terminalFocus for default split/new/close bindings", () => {
|
||||
assert.isFalse(
|
||||
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTerminalNewShortcut(event({ key: "d", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches split/new when terminalFocus is true", () => {
|
||||
assert.isTrue(
|
||||
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isTerminalNewShortcut(event({ key: "d", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("supports when expressions", () => {
|
||||
const keybindings = compile([
|
||||
{
|
||||
shortcut: modShortcut("\\"),
|
||||
command: "terminal.split",
|
||||
whenAst: whenAnd(whenIdentifier("terminalOpen"), whenNot(whenIdentifier("terminalFocus"))),
|
||||
},
|
||||
{
|
||||
shortcut: modShortcut("n", { shiftKey: true }),
|
||||
command: "terminal.new",
|
||||
whenAst: whenAnd(whenIdentifier("terminalOpen"), whenNot(whenIdentifier("terminalFocus"))),
|
||||
},
|
||||
{ shortcut: modShortcut("j"), command: "terminal.toggle" },
|
||||
]);
|
||||
assert.isTrue(
|
||||
isTerminalSplitShortcut(event({ key: "\\", ctrlKey: true }), keybindings, {
|
||||
platform: "Win32",
|
||||
context: { terminalOpen: true, terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTerminalSplitShortcut(event({ key: "\\", ctrlKey: true }), keybindings, {
|
||||
platform: "Win32",
|
||||
context: { terminalOpen: false, terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isTerminalNewShortcut(event({ key: "n", ctrlKey: true, shiftKey: true }), keybindings, {
|
||||
platform: "Win32",
|
||||
context: { terminalOpen: true, terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("supports when boolean literals", () => {
|
||||
const keybindings = compile([
|
||||
{ shortcut: modShortcut("n"), command: "terminal.new", whenAst: whenIdentifier("true") },
|
||||
{ shortcut: modShortcut("m"), command: "terminal.new", whenAst: whenIdentifier("false") },
|
||||
]);
|
||||
|
||||
assert.isTrue(
|
||||
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTerminalNewShortcut(event({ key: "m", ctrlKey: true }), keybindings, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shortcutLabelForCommand", () => {
|
||||
it("returns the most recent binding label", () => {
|
||||
const bindings = compile([
|
||||
{
|
||||
shortcut: modShortcut("\\"),
|
||||
command: "terminal.split",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{
|
||||
shortcut: modShortcut("\\", { shiftKey: true }),
|
||||
command: "terminal.split",
|
||||
whenAst: whenNot(whenIdentifier("terminalFocus")),
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(
|
||||
shortcutLabelForCommand(bindings, "terminal.split", "Linux"),
|
||||
"Ctrl+Shift+\\",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns labels for non-terminal commands", () => {
|
||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
|
||||
assert.strictEqual(
|
||||
shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"),
|
||||
"Ctrl+O",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("chat/editor shortcuts", () => {
|
||||
it("matches chat.new shortcut", () => {
|
||||
assert.isTrue(
|
||||
isChatNewShortcut(event({ key: "o", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isChatNewShortcut(event({ key: "o", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches chat.newLocal shortcut", () => {
|
||||
assert.isTrue(
|
||||
isChatNewLocalShortcut(event({ key: "n", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isChatNewLocalShortcut(event({ key: "n", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches editor.openFavorite shortcut", () => {
|
||||
assert.isTrue(
|
||||
isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isOpenFavoriteEditorShortcut(event({ key: "o", ctrlKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cross-command precedence", () => {
|
||||
it("uses when + order so a later focused rule overrides a global rule", () => {
|
||||
const keybindings = compile([
|
||||
{ shortcut: modShortcut("n"), command: "chat.new" },
|
||||
{
|
||||
shortcut: modShortcut("n"),
|
||||
command: "terminal.new",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
]);
|
||||
|
||||
assert.isTrue(
|
||||
isTerminalNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isChatNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTerminalNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isChatNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("still lets a later global rule win when both rules match", () => {
|
||||
const keybindings = compile([
|
||||
{
|
||||
shortcut: modShortcut("n"),
|
||||
command: "terminal.new",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{ shortcut: modShortcut("n"), command: "chat.new" },
|
||||
]);
|
||||
|
||||
assert.isFalse(
|
||||
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isChatNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveShortcutCommand", () => {
|
||||
it("returns dynamic script commands", () => {
|
||||
const keybindings = compile([
|
||||
{ shortcut: modShortcut("r"), command: "script.setup.run" },
|
||||
]);
|
||||
|
||||
assert.strictEqual(
|
||||
resolveShortcutCommand(event({ key: "r", ctrlKey: true }), keybindings, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
"script.setup.run",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatShortcutLabel", () => {
|
||||
it("formats labels for macOS", () => {
|
||||
assert.strictEqual(
|
||||
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"),
|
||||
"⇧⌘D",
|
||||
);
|
||||
});
|
||||
|
||||
it("formats labels for non-macOS", () => {
|
||||
assert.strictEqual(
|
||||
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"),
|
||||
"Ctrl+Shift+D",
|
||||
);
|
||||
});
|
||||
|
||||
it("formats labels for plus key", () => {
|
||||
assert.strictEqual(formatShortcutLabel(modShortcut("+"), "MacIntel"), "⌘+");
|
||||
assert.strictEqual(formatShortcutLabel(modShortcut("+"), "Linux"), "Ctrl++");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTerminalClearShortcut", () => {
|
||||
it("matches Ctrl+L on all platforms", () => {
|
||||
assert.isTrue(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux"));
|
||||
assert.isTrue(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel"));
|
||||
});
|
||||
|
||||
it("matches Cmd+K on macOS", () => {
|
||||
assert.isTrue(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel"));
|
||||
});
|
||||
|
||||
it("ignores non-keydown events", () => {
|
||||
assert.isFalse(
|
||||
isTerminalClearShortcut(event({ type: "keyup", key: "l", ctrlKey: true }), "Linux"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalNavigationShortcutData", () => {
|
||||
it("maps Option+Arrow on macOS to word movement", () => {
|
||||
assert.strictEqual(
|
||||
terminalNavigationShortcutData(event({ key: "ArrowLeft", altKey: true }), "MacIntel"),
|
||||
"\u001bb",
|
||||
);
|
||||
assert.strictEqual(
|
||||
terminalNavigationShortcutData(event({ key: "ArrowRight", altKey: true }), "MacIntel"),
|
||||
"\u001bf",
|
||||
);
|
||||
});
|
||||
|
||||
it("maps Cmd+Arrow on macOS to line movement", () => {
|
||||
assert.strictEqual(
|
||||
terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "MacIntel"),
|
||||
"\u0001",
|
||||
);
|
||||
assert.strictEqual(
|
||||
terminalNavigationShortcutData(event({ key: "ArrowRight", metaKey: true }), "MacIntel"),
|
||||
"\u0005",
|
||||
);
|
||||
});
|
||||
|
||||
it("maps Ctrl+Arrow on non-macOS to word movement", () => {
|
||||
assert.strictEqual(
|
||||
terminalNavigationShortcutData(event({ key: "ArrowLeft", ctrlKey: true }), "Win32"),
|
||||
"\u001bb",
|
||||
);
|
||||
assert.strictEqual(
|
||||
terminalNavigationShortcutData(event({ key: "ArrowRight", ctrlKey: true }), "Linux"),
|
||||
"\u001bf",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects unsupported combinations", () => {
|
||||
assert.isNull(
|
||||
terminalNavigationShortcutData(
|
||||
event({ key: "ArrowLeft", shiftKey: true, altKey: true }),
|
||||
"MacIntel",
|
||||
),
|
||||
);
|
||||
assert.isNull(
|
||||
terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "Linux"),
|
||||
);
|
||||
assert.isNull(terminalNavigationShortcutData(event({ key: "a", altKey: true }), "MacIntel"));
|
||||
});
|
||||
|
||||
it("ignores non-keydown events", () => {
|
||||
assert.isNull(
|
||||
terminalNavigationShortcutData(
|
||||
event({ type: "keyup", key: "ArrowLeft", altKey: true }),
|
||||
"MacIntel",
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("plus key parsing", () => {
|
||||
it("matches the plus key shortcut", () => {
|
||||
const plusBindings = compile([{ shortcut: modShortcut("+"), command: "terminal.toggle" }]);
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ key: "+", metaKey: true }), plusBindings, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ key: "+", ctrlKey: true }), plusBindings, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,286 @@
|
||||
import {
|
||||
type KeybindingCommand,
|
||||
type KeybindingShortcut,
|
||||
type KeybindingWhenNode,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { isMacPlatform } from "./lib/utils";
|
||||
|
||||
export interface ShortcutEventLike {
|
||||
type?: string;
|
||||
key: string;
|
||||
metaKey: boolean;
|
||||
ctrlKey: boolean;
|
||||
shiftKey: boolean;
|
||||
altKey: boolean;
|
||||
}
|
||||
|
||||
export interface ShortcutMatchContext {
|
||||
terminalFocus: boolean;
|
||||
terminalOpen: boolean;
|
||||
[key: string]: boolean;
|
||||
}
|
||||
|
||||
interface ShortcutMatchOptions {
|
||||
platform?: string;
|
||||
context?: Partial<ShortcutMatchContext>;
|
||||
}
|
||||
|
||||
const TERMINAL_WORD_BACKWARD = "\u001bb";
|
||||
const TERMINAL_WORD_FORWARD = "\u001bf";
|
||||
const TERMINAL_LINE_START = "\u0001";
|
||||
const TERMINAL_LINE_END = "\u0005";
|
||||
|
||||
function normalizeEventKey(key: string): string {
|
||||
const normalized = key.toLowerCase();
|
||||
if (normalized === "esc") return "escape";
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function matchesShortcut(
|
||||
event: ShortcutEventLike,
|
||||
shortcut: KeybindingShortcut,
|
||||
platform = navigator.platform,
|
||||
): boolean {
|
||||
const key = normalizeEventKey(event.key);
|
||||
if (key !== shortcut.key) return false;
|
||||
|
||||
const useMetaForMod = isMacPlatform(platform);
|
||||
const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
|
||||
const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
|
||||
return (
|
||||
event.metaKey === expectedMeta &&
|
||||
event.ctrlKey === expectedCtrl &&
|
||||
event.shiftKey === shortcut.shiftKey &&
|
||||
event.altKey === shortcut.altKey
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
|
||||
return options?.platform ?? navigator.platform;
|
||||
}
|
||||
|
||||
function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
|
||||
return {
|
||||
terminalFocus: false,
|
||||
terminalOpen: false,
|
||||
...options?.context,
|
||||
};
|
||||
}
|
||||
|
||||
function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
|
||||
switch (node.type) {
|
||||
case "identifier":
|
||||
if (node.name === "true") return true;
|
||||
if (node.name === "false") return false;
|
||||
return Boolean(context[node.name]);
|
||||
case "not":
|
||||
return !evaluateWhenNode(node.node, context);
|
||||
case "and":
|
||||
return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
|
||||
case "or":
|
||||
return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
|
||||
}
|
||||
}
|
||||
|
||||
function matchesWhenClause(
|
||||
whenAst: KeybindingWhenNode | undefined,
|
||||
context: ShortcutMatchContext,
|
||||
): boolean {
|
||||
if (!whenAst) return true;
|
||||
return evaluateWhenNode(whenAst, context);
|
||||
}
|
||||
|
||||
function matchesCommandShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
command: KeybindingCommand,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return resolveShortcutCommand(event, keybindings, options) === command;
|
||||
}
|
||||
|
||||
export function resolveShortcutCommand(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): string | null {
|
||||
const platform = resolvePlatform(options);
|
||||
const context = resolveContext(options);
|
||||
|
||||
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
|
||||
const binding = keybindings[index];
|
||||
if (!binding) continue;
|
||||
if (!matchesWhenClause(binding.whenAst, context)) continue;
|
||||
if (!matchesShortcut(event, binding.shortcut, platform)) continue;
|
||||
return binding.command;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatShortcutKeyLabel(key: string): string {
|
||||
if (key === " ") return "Space";
|
||||
if (key.length === 1) return key.toUpperCase();
|
||||
if (key === "escape") return "Esc";
|
||||
if (key === "arrowup") return "Up";
|
||||
if (key === "arrowdown") return "Down";
|
||||
if (key === "arrowleft") return "Left";
|
||||
if (key === "arrowright") return "Right";
|
||||
return key.slice(0, 1).toUpperCase() + key.slice(1);
|
||||
}
|
||||
|
||||
export function formatShortcutLabel(
|
||||
shortcut: KeybindingShortcut,
|
||||
platform = navigator.platform,
|
||||
): string {
|
||||
const keyLabel = formatShortcutKeyLabel(shortcut.key);
|
||||
const useMetaForMod = isMacPlatform(platform);
|
||||
const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
|
||||
const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
|
||||
const showAlt = shortcut.altKey;
|
||||
const showShift = shortcut.shiftKey;
|
||||
|
||||
if (useMetaForMod) {
|
||||
return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
|
||||
}
|
||||
|
||||
const parts: string[] = [];
|
||||
if (showCtrl) parts.push("Ctrl");
|
||||
if (showAlt) parts.push("Alt");
|
||||
if (showShift) parts.push("Shift");
|
||||
if (showMeta) parts.push("Meta");
|
||||
parts.push(keyLabel);
|
||||
return parts.join("+");
|
||||
}
|
||||
|
||||
export function shortcutLabelForCommand(
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
command: KeybindingCommand,
|
||||
platform = navigator.platform,
|
||||
): string | null {
|
||||
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
|
||||
const binding = keybindings[index];
|
||||
if (!binding || binding.command !== command) continue;
|
||||
return formatShortcutLabel(binding.shortcut, platform);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isTerminalToggleShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
|
||||
}
|
||||
|
||||
export function isTerminalSplitShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "terminal.split", options);
|
||||
}
|
||||
|
||||
export function isTerminalNewShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "terminal.new", options);
|
||||
}
|
||||
|
||||
export function isTerminalCloseShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "terminal.close", options);
|
||||
}
|
||||
|
||||
export function isChatNewShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "chat.new", options);
|
||||
}
|
||||
|
||||
export function isChatNewLocalShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "chat.newLocal", options);
|
||||
}
|
||||
|
||||
export function isOpenFavoriteEditorShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "editor.openFavorite", options);
|
||||
}
|
||||
|
||||
export function isTerminalClearShortcut(
|
||||
event: ShortcutEventLike,
|
||||
platform = navigator.platform,
|
||||
): boolean {
|
||||
if (event.type !== undefined && event.type !== "keydown") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const key = event.key.toLowerCase();
|
||||
|
||||
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
isMacPlatform(platform) &&
|
||||
key === "k" &&
|
||||
event.metaKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.altKey &&
|
||||
!event.shiftKey
|
||||
);
|
||||
}
|
||||
|
||||
export function terminalNavigationShortcutData(
|
||||
event: ShortcutEventLike,
|
||||
platform = navigator.platform,
|
||||
): string | null {
|
||||
if (event.type !== undefined && event.type !== "keydown") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (event.shiftKey) return null;
|
||||
|
||||
const key = normalizeEventKey(event.key);
|
||||
if (key !== "arrowleft" && key !== "arrowright") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
|
||||
const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
|
||||
|
||||
if (isMacPlatform(platform)) {
|
||||
if (event.altKey && !event.metaKey && !event.ctrlKey) {
|
||||
return moveWord;
|
||||
}
|
||||
if (event.metaKey && !event.altKey && !event.ctrlKey) {
|
||||
return moveLine;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (event.ctrlKey && !event.metaKey && !event.altKey) {
|
||||
return moveWord;
|
||||
}
|
||||
|
||||
if (event.altKey && !event.metaKey && !event.ctrlKey) {
|
||||
return moveWord;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildPatchCacheKey } from "./diffRendering";
|
||||
|
||||
describe("buildPatchCacheKey", () => {
|
||||
it("returns a stable cache key for identical content", () => {
|
||||
const patch = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
|
||||
|
||||
expect(buildPatchCacheKey(patch)).toBe(buildPatchCacheKey(patch));
|
||||
});
|
||||
|
||||
it("normalizes outer whitespace before hashing", () => {
|
||||
const patch = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
|
||||
|
||||
expect(buildPatchCacheKey(`\n${patch}\n`)).toBe(buildPatchCacheKey(patch));
|
||||
});
|
||||
|
||||
it("changes when diff content changes", () => {
|
||||
const before = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
|
||||
const after = "diff --git a/a.ts b/a.ts\n+console.log('hello world')";
|
||||
|
||||
expect(buildPatchCacheKey(before)).not.toBe(buildPatchCacheKey(after));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
|
||||
const FNV_PRIME_32 = 0x01000193;
|
||||
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
||||
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
||||
|
||||
function fnv1a32(input: string, seed: number, multiplier: number): number {
|
||||
let hash = seed >>> 0;
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
hash ^= input.charCodeAt(index);
|
||||
hash = Math.imul(hash, multiplier) >>> 0;
|
||||
}
|
||||
return hash >>> 0;
|
||||
}
|
||||
|
||||
export function buildPatchCacheKey(patch: string, scope = "diff-panel"): string {
|
||||
const normalizedPatch = patch.trim();
|
||||
const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
|
||||
const secondary = fnv1a32(
|
||||
normalizedPatch,
|
||||
SECONDARY_HASH_SEED,
|
||||
SECONDARY_HASH_MULTIPLIER,
|
||||
).toString(36);
|
||||
return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import type { GitStackedAction, NativeApi } from "@t3tools/contracts";
|
||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||
|
||||
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
||||
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
||||
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
|
||||
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
|
||||
|
||||
export const gitQueryKeys = {
|
||||
all: ["git"] as const,
|
||||
status: (cwd: string | null) => ["git", "status", cwd] as const,
|
||||
@@ -21,6 +26,10 @@ export function gitStatusQueryOptions(api: NativeApi | undefined, cwd: string |
|
||||
return api.git.status({ cwd });
|
||||
},
|
||||
enabled: !!api && !!cwd,
|
||||
staleTime: GIT_STATUS_STALE_TIME_MS,
|
||||
refetchOnWindowFocus: "always",
|
||||
refetchOnReconnect: "always",
|
||||
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -34,6 +43,10 @@ export function gitBranchesQueryOptions(api: NativeApi | undefined, cwd: string
|
||||
return api.git.listBranches({ cwd });
|
||||
},
|
||||
enabled: !!api && !!cwd,
|
||||
staleTime: GIT_BRANCHES_STALE_TIME_MS,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -160,11 +173,11 @@ export function gitRemoveWorktreeMutationOptions(input: {
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationFn: async ({ cwd, path }: { cwd: string; path: string }) => {
|
||||
mutationFn: async ({ cwd, path, force }: { cwd: string; path: string; force?: boolean }) => {
|
||||
if (!input.api) {
|
||||
throw new Error("Git worktree removal is unavailable.");
|
||||
}
|
||||
return input.api.git.removeWorktree({ cwd, path });
|
||||
return input.api.git.removeWorktree({ cwd, path, force });
|
||||
},
|
||||
onSettled: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { NativeApi, ProjectSearchEntriesResult } from "@t3tools/contracts";
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
|
||||
export const projectQueryKeys = {
|
||||
all: ["projects"] as const,
|
||||
searchEntries: (cwd: string | null, query: string, limit: number) =>
|
||||
["projects", "search-entries", cwd, query, limit] as const,
|
||||
};
|
||||
|
||||
const DEFAULT_SEARCH_ENTRIES_LIMIT = 80;
|
||||
const DEFAULT_SEARCH_ENTRIES_STALE_TIME = 15_000;
|
||||
const EMPTY_SEARCH_ENTRIES_RESULT: ProjectSearchEntriesResult = {
|
||||
entries: [],
|
||||
truncated: false,
|
||||
};
|
||||
|
||||
export function projectSearchEntriesQueryOptions(input: {
|
||||
api: NativeApi | undefined;
|
||||
cwd: string | null;
|
||||
query: string;
|
||||
enabled?: boolean;
|
||||
limit?: number;
|
||||
staleTime?: number;
|
||||
}) {
|
||||
const limit = input.limit ?? DEFAULT_SEARCH_ENTRIES_LIMIT;
|
||||
return queryOptions({
|
||||
queryKey: projectQueryKeys.searchEntries(input.cwd, input.query, limit),
|
||||
queryFn: async () => {
|
||||
if (!input.api || !input.cwd) {
|
||||
throw new Error("Workspace entry search is unavailable.");
|
||||
}
|
||||
return input.api.projects.searchEntries({
|
||||
cwd: input.cwd,
|
||||
query: input.query,
|
||||
limit,
|
||||
});
|
||||
},
|
||||
enabled: (input.enabled ?? true) && Boolean(input.api && input.cwd),
|
||||
staleTime: input.staleTime ?? DEFAULT_SEARCH_ENTRIES_STALE_TIME,
|
||||
placeholderData: (previous) => previous ?? EMPTY_SEARCH_ENTRIES_RESULT,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { NativeApi } from "@t3tools/contracts";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { checkpointDiffQueryOptions, providerQueryKeys } from "./providerReactQuery";
|
||||
|
||||
describe("providerQueryKeys.checkpointDiff", () => {
|
||||
it("includes cacheScope so reused turn counts do not collide", () => {
|
||||
const baseInput = {
|
||||
sessionId: "session-id",
|
||||
threadRuntimeId: "thread-id",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
} as const;
|
||||
|
||||
expect(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
...baseInput,
|
||||
cacheScope: "turn:old-turn",
|
||||
}),
|
||||
).not.toEqual(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
...baseInput,
|
||||
cacheScope: "turn:new-turn",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkpointDiffQueryOptions", () => {
|
||||
it("forwards checkpoint range to the provider API", async () => {
|
||||
const getCheckpointDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
||||
const api = {
|
||||
providers: {
|
||||
getCheckpointDiff,
|
||||
},
|
||||
} as unknown as NativeApi;
|
||||
|
||||
const options = checkpointDiffQueryOptions(api, {
|
||||
sessionId: "session-id",
|
||||
threadRuntimeId: "thread-id",
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
await queryClient.fetchQuery(options);
|
||||
|
||||
expect(getCheckpointDiff).toHaveBeenCalledWith({
|
||||
sessionId: "session-id",
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
});
|
||||
});
|
||||
|
||||
it("retries checkpoint-not-ready errors longer than generic failures", () => {
|
||||
const options = checkpointDiffQueryOptions(undefined, {
|
||||
sessionId: "session-id",
|
||||
threadRuntimeId: "thread-id",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
const retry = options.retry;
|
||||
expect(typeof retry).toBe("function");
|
||||
if (typeof retry !== "function") {
|
||||
throw new Error("Expected retry to be a function.");
|
||||
}
|
||||
|
||||
expect(retry(1, new Error("Checkpoint turn count 2 exceeds current turn count 1."))).toBe(true);
|
||||
expect(
|
||||
retry(
|
||||
11,
|
||||
new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1."),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
retry(
|
||||
12,
|
||||
new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1."),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(retry(2, new Error("Something else failed."))).toBe(true);
|
||||
expect(retry(3, new Error("Something else failed."))).toBe(false);
|
||||
});
|
||||
|
||||
it("backs off longer for checkpoint-not-ready errors", () => {
|
||||
const options = checkpointDiffQueryOptions(undefined, {
|
||||
sessionId: "session-id",
|
||||
threadRuntimeId: "thread-id",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
const retryDelay = options.retryDelay;
|
||||
expect(typeof retryDelay).toBe("function");
|
||||
if (typeof retryDelay !== "function") {
|
||||
throw new Error("Expected retryDelay to be a function.");
|
||||
}
|
||||
|
||||
const checkpointDelay = retryDelay(
|
||||
4,
|
||||
new Error("Checkpoint turn count 2 exceeds current turn count 1."),
|
||||
);
|
||||
const genericDelay = retryDelay(4, new Error("Network failure"));
|
||||
|
||||
expect(typeof checkpointDelay).toBe("number");
|
||||
expect(typeof genericDelay).toBe("number");
|
||||
expect((checkpointDelay ?? 0) > (genericDelay ?? 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { NativeApi } from "@t3tools/contracts";
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
|
||||
export interface CheckpointDiffQueryInput {
|
||||
sessionId: string | null;
|
||||
threadRuntimeId: string | null;
|
||||
fromTurnCount: number | null;
|
||||
toTurnCount: number | null;
|
||||
cacheScope?: string | null;
|
||||
}
|
||||
|
||||
export const providerQueryKeys = {
|
||||
all: ["providers"] as const,
|
||||
checkpointDiff: (input: CheckpointDiffQueryInput) =>
|
||||
[
|
||||
"providers",
|
||||
"checkpointDiff",
|
||||
input.sessionId,
|
||||
input.threadRuntimeId,
|
||||
input.fromTurnCount,
|
||||
input.toTurnCount,
|
||||
input.cacheScope ?? null,
|
||||
] as const,
|
||||
};
|
||||
|
||||
function asCheckpointErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
if (typeof error === "string") {
|
||||
return error;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
|
||||
const message = asCheckpointErrorMessage(error).toLowerCase();
|
||||
return (
|
||||
message.includes("exceeds current turn count") ||
|
||||
message.includes("checkpoint is unavailable for turn") ||
|
||||
message.includes("filesystem checkpoint is unavailable")
|
||||
);
|
||||
}
|
||||
|
||||
export function checkpointDiffQueryOptions(
|
||||
api: NativeApi | undefined,
|
||||
input: CheckpointDiffQueryInput,
|
||||
) {
|
||||
const hasValidRange =
|
||||
typeof input.fromTurnCount === "number" &&
|
||||
typeof input.toTurnCount === "number" &&
|
||||
Number.isInteger(input.fromTurnCount) &&
|
||||
Number.isInteger(input.toTurnCount) &&
|
||||
input.fromTurnCount >= 0 &&
|
||||
input.toTurnCount >= 0 &&
|
||||
input.fromTurnCount <= input.toTurnCount;
|
||||
|
||||
return queryOptions({
|
||||
queryKey: providerQueryKeys.checkpointDiff(input),
|
||||
queryFn: async () => {
|
||||
if (!api || !input.sessionId || !hasValidRange) {
|
||||
throw new Error("Checkpoint diff is unavailable.");
|
||||
}
|
||||
const { fromTurnCount, toTurnCount } = input;
|
||||
if (typeof fromTurnCount !== "number" || typeof toTurnCount !== "number") {
|
||||
throw new Error("Checkpoint diff range is invalid.");
|
||||
}
|
||||
return api.providers.getCheckpointDiff({
|
||||
sessionId: input.sessionId,
|
||||
fromTurnCount,
|
||||
toTurnCount,
|
||||
});
|
||||
},
|
||||
enabled: !!api && !!input.sessionId && hasValidRange,
|
||||
staleTime: Infinity,
|
||||
retry: (failureCount, error) => {
|
||||
if (isCheckpointTemporarilyUnavailable(error)) {
|
||||
return failureCount < 12;
|
||||
}
|
||||
return failureCount < 3;
|
||||
},
|
||||
retryDelay: (attempt, error) =>
|
||||
isCheckpointTemporarilyUnavailable(error)
|
||||
? Math.min(5_000, 250 * 2 ** (attempt - 1))
|
||||
: Math.min(1_000, 100 * 2 ** (attempt - 1)),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { NativeApi } from "@t3tools/contracts";
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
|
||||
export const serverQueryKeys = {
|
||||
all: ["server"] as const,
|
||||
config: () => ["server", "config"] as const,
|
||||
};
|
||||
|
||||
export function serverConfigQueryOptions(api: NativeApi | undefined) {
|
||||
return queryOptions({
|
||||
queryKey: serverQueryKeys.config(),
|
||||
queryFn: async () => {
|
||||
if (!api || !api.server || typeof api.server.getConfig !== "function") {
|
||||
throw new Error("Server config is unavailable.");
|
||||
}
|
||||
return api.server.getConfig();
|
||||
},
|
||||
enabled: !!api && !!api.server && typeof api.server.getConfig === "function",
|
||||
staleTime: Infinity,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
|
||||
import { isWindowsPlatform } from "./utils";
|
||||
|
||||
describe("isWindowsPlatform", () => {
|
||||
it("matches Windows platform identifiers", () => {
|
||||
assert.isTrue(isWindowsPlatform("Win32"));
|
||||
assert.isTrue(isWindowsPlatform("Windows"));
|
||||
assert.isTrue(isWindowsPlatform("windows_nt"));
|
||||
});
|
||||
|
||||
it("does not match darwin", () => {
|
||||
assert.isFalse(isWindowsPlatform("darwin"));
|
||||
});
|
||||
});
|
||||