Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex 05f4cb216b chore: restore cursor acp probe artifacts on cursor stack
Co-authored-by: codex <[email protected]>
2026-03-05 22:02:29 -08:00
Julius Marminge e06782cb9f refactor: restore cursor provider surface on stacked branch\n\nCo-authored-by: codex <[email protected]> 2026-03-05 22:02:00 -08:00
Julius Marmingeandcodex e3c98ba52a Restore Cursor adapter on stacked branch
Co-authored-by: codex <[email protected]>
2026-03-05 22:02:00 -08:00
Julius Marmingeandcodex 12d7a5c411 chore: move cursor acp probe artifacts to cursor stack
Co-authored-by: codex <[email protected]>
2026-03-05 22:01:38 -08:00
Julius Marminge daf4b31fbf refactor: move cursor provider surface out of core\n\nCo-authored-by: codex <[email protected]> 2026-03-05 21:55:05 -08:00
Julius Marminge 7d5b896962 sync lock 2026-03-05 21:40:32 -08:00
Julius Marmingeandcodex a535aec704 split: move Claude SDK and plan doc to sibling stack
Co-authored-by: codex <[email protected]>
2026-03-05 21:36:46 -08:00
Julius Marmingeandcodex ef976af7cd split: move Claude provider surface to sibling stack
Co-authored-by: codex <[email protected]>
2026-03-05 21:27:30 -08:00
Julius Marmingeandcodex 02132281da model: move Claude catalogs out of core
Co-authored-by: codex <[email protected]>
2026-03-05 21:16:30 -08:00
Julius Marmingeandcodex 0789b38663 contracts: move Claude schemas out of core
Co-authored-by: codex <[email protected]>
2026-03-05 21:10:33 -08:00
Julius Marminge 8d9bc7c2cf Show unavailable providers as coming-soon placeholders
- Keep Claude Code and Cursor in provider list as disabled options
- Remove unused Claude agent SDK dependency from server
- Delete stale plan-mode deep-dive doc
2026-03-05 21:07:08 -08:00
Julius Marminge a2ee346b78 sync lock 2026-03-05 21:02:12 -08:00
Julius Marminge a01aaa305a rm tmp 2026-03-05 21:01:58 -08:00
Julius Marmingeandcodex 6df3c425f0 test: move Claude coverage out of core PR
Co-authored-by: codex <[email protected]>
2026-03-05 20:54:50 -08:00
Julius Marmingeandcodex d4f823f58d Remove Claude adapter from stack base
Co-authored-by: codex <[email protected]>
2026-03-05 20:00:52 -08:00
Julius Marmingeandcodex bf0712219e Remove Cursor adapter from stack base
Co-authored-by: codex <[email protected]>
2026-03-05 20:00:02 -08:00
Julius Marminge 576dc73d5f Add GPT-5.4 to Codex model options
- include `gpt-5.4` in Codex app model option coverage
- only keep truly custom Cursor models in the custom model option list
2026-03-05 19:51:58 -08:00
Julius Marminge 7d2e2b381d Plumb Codex model options through orchestration and composer
- Replace ad-hoc `effort` handling with provider `modelOptions` across decider/reactor/adapters
- Map Codex `reasoningEffort` and `fastMode` to turn/session params (`effort`, `serviceTier`)
- Persist runtime/interaction/model selections from composer and sync them before sending turns
- Move model normalization/helpers into `@t3tools/shared/model` with updated contracts/tests
2026-03-05 19:40:41 -08:00
Julius Marmingeandcodex 0c4999b764 Fix post-rebase typecheck regressions
Co-authored-by: codex <[email protected]>
2026-03-05 18:20:21 -08:00
Julius Marminge 3f503ccaf0 Prune internal contract exports and remove checkpoint RPC schemas
- Stop exporting internal-only schema constants/types across contracts modules
- Remove unused provider checkpoint list/revert/diff RPC contract schemas
- Keep public contract surface focused on externally consumed types
2026-03-05 18:17:21 -08:00
Julius Marminge da30070d9e style 2026-03-05 18:17:21 -08:00
Julius Marminge ede96cebf0 Persist proposed plans as first-class thread projection data
- Add `thread.proposed-plan-upserted` orchestration flow from ingestion through decider/projector
- Store proposed plans in a dedicated projection table and include them in snapshot queries
- Update provider runtime/web handling and tests to use proposed plans instead of assistant message wrappers
2026-03-05 18:17:21 -08:00
Julius Marminge 8572ca2d05 Add plan interaction mode and user-input request handling
- Wire Codex plan mode through turn start, including collaboration settings
- Track and answer pending `requestUserInput` prompts instead of auto-empty responses
- Persist/project thread `interactionMode` (schema, migration, queries) and update tests/contracts
2026-03-05 18:15:55 -08:00
Julius Marminge 1f9ea614d2 Migrate provider runtime/session flow to thread-scoped IDs
- Replace provider session-id centric plumbing with thread-id based runtime handling across server orchestration and provider layers
- Update persistence repositories/migrations and contracts for threadless runtime semantics
- Refresh integration/unit tests and web session/store types to match the new runtime model
2026-03-05 18:13:42 -08:00
Julius Marminge 13c113fcbb Improve session restart handling and server logging
- add structured lifecycle logs for Codex thread open/resume and provider session restarts
- introduce persistent server file logging layer and tighten WebSocket server startup/finalizer ordering
- preserve env-based boolean overrides in dev runner and stop forcing WS event logging in dev
- enrich provider session listing from persisted bindings and fix Claude rate-limit/task-id event mapping
- update orchestration and dev-runner tests for runtime-mode restart and env-flag behavior
2026-03-05 18:13:42 -08:00
Julius Marmingeandcodex 9a115a8055 Persist thread runtime mode and handle mode-switch session restarts
- Add `thread.runtime-mode.set` -> `thread.runtime-mode-set` flow in decider/reactors/projectors
- Persist runtime mode on thread/session projections with new DB migrations
- Update provider and Codex integration tests to verify thread continuity across mode changes

Co-authored-by: codex <[email protected]>
2026-03-05 18:13:42 -08:00
Julius Marminge 1d4ccdbe45 Clarify Cursor plan-mode semantics and ACP extension mapping
- Define Cursor operating mode as binary `default | plan`
- Document mapping for `cursor/ask_question`, `cursor/create_plan`, and `cursor/update_todos`
- Update capability and fallback guidance based on docs plus probe evidence
2026-03-05 18:13:20 -08:00
Julius Marminge ed2c4bd856 Rewrite plan-mode deep dive as implementation blueprint
- Reframe doc into a provider-agnostic implementation plan for Codex, Claude, and Cursor
- Define canonical mode, plan, and structured user-input models plus capability-driven UI behavior
- Add concrete orchestration, adapter, frontend, and test work items for rollout
2026-03-05 18:13:20 -08:00
Julius Marminge b5d5b3905d Add runtime mode tracking across provider orchestration pipeline
- extend provider and orchestration contracts for runtime mode-aware events
- persist runtime mode fields in projection thread session storage and migration 006
- update adapters, reactors, projections, websocket/web session logic, and tests
- add plan mode deep dive docs and probe artifacts for ACP behavior
2026-03-05 18:13:20 -08:00
Julius Marminge b39480a3fb Handle session.state.changed in provider runtime ingestion
- Map runtime session state transitions to orchestration session status
- Persist error reasons from `session.state.changed` error events
- Add coverage for waiting/error/stopped/ready transition handling
2026-03-05 18:13:20 -08:00
Julius Marminge 0ccc40a4b5 Support provider custom models and fix runtime event mapping
- add per-provider custom model settings/options in web settings and chat picker
- preserve Codex request type on `serverRequest/resolved` events
- validate empty Cursor prompts before turn start and keep tool-call item types consistent
- add tests for new adapter and model-settings behavior
- add PR event review checklist document
2026-03-05 18:13:20 -08:00
Julius Marminge d715c3a03e Inject native event loggers into provider adapters
- allow Claude/Cursor adapters to accept an injected native event logger
- make native event writes effectful/non-blocking so logging cannot break message handling
- update adapter tests to assert native observability events via in-memory loggers
- fix runtime session ID conversion when resolving canonical event thread IDs
2026-03-05 18:13:19 -08:00
Julius Marminge 7c5a543fff Normalize runtime events and tighten orchestration approval flow
- migrate fixtures/tests/adapters to canonical provider runtime event payloads
- route checkpoint capture off `turn.completed` only and drop legacy `checkpoint.captured` path
- stop faking approval resolution when provider reports stale/unknown pending requests
2026-03-05 18:13:19 -08:00
Julius Marminge 196f3312ba Handle stale approval responses and cover Cursor resume IDs
- Catch provider approval response failures and emit `provider.approval.respond.failed`
- Auto-resolve approvals when provider reports unknown pending request IDs
- Add tests for Cursor ACP resume via `resumeCursor.acpSessionId` and legacy `sessionId`
2026-03-05 18:13:19 -08:00
Julius Marminge 78e6125cfe Normalize approval request kinds and persist draft provider state
- map canonical approval request types to `requestKind` across ingestion and web pending approvals
- auto-approve Cursor permission requests when approval policy is `never`
- persist per-thread composer provider selection in draft store and use it in ChatView
- disable Cursor traits picker while model selection is locked
2026-03-05 18:13:19 -08:00
Julius Marminge d096cb85e1 Respect provider model-switch limits and canonical runtime events
- Add provider capability plumbing for `sessionModelSwitch` and use it in session/turn routing
- Keep Cursor sessions stable when in-session model switching is unsupported
- Ingest canonical runtime events (`content.delta`, `item.*`, `request.*`) with legacy-shape compatibility
2026-03-05 18:13:19 -08:00
Julius Marminge 43b64bf17d Fix effort and provider handling in thread turn start
- Only include `effort` in start command when a value is selected
- Persist effort selection via composer draft state and hide picker when unavailable
- Add optional `provider` to `ClientThreadTurnStartCommand`
- Simplify thread model fallback selection in `ChatView`
2026-03-05 18:13:19 -08:00
Julius Marminge 4f47f33ec5 Scope composer draft reasoning effort to Codex options
- Switch draft store types to `CodexReasoningEffort`
- Validate and default effort using Codex-specific option/default constants
2026-03-05 18:13:19 -08:00
Julius Marminge fd65a358e6 Unify provider runtime events and add Cursor adapter layer
- migrate Claude/Codex/registry adapters to canonical runtime event types and payload shapes
- add Cursor layer adapter plus tests and wire it through server layers
- update provider contracts/runtime schemas and related adapter tests
2026-03-05 18:13:19 -08:00
Julius Marminge e80564813e Scope reasoning effort defaults and options by provider
- Replace global reasoning constants with provider-scoped effort options/defaults
- Update ChatView to use Codex-specific reasoning effort types and default lookup
- Expand model contract tests for provider-specific reasoning effort behavior
2026-03-05 18:13:19 -08:00
Julius Marminge 7c0ccb54ff Introduce v2 provider runtime event schema and validation tests
- Restructure runtime events around a shared base plus typed payloads
- Add runtime-branded IDs and new event types (plan, item, request, user-input)
- Remove legacy canonical event names from docs and add schema decode/rejection tests
2026-03-05 18:13:19 -08:00
Julius Marminge cfae88fbc2 Document Cursor ACP mapping in canonical runtime event spec
- Add Cursor ACP raw source types to `RuntimeEventRaw.source`
- Define canonical mappings for ACP lifecycle, updates, permissions, and errors
- Expand cross-provider equivalence table to include Cursor ACP and renumber sections
2026-03-05 18:13:19 -08:00
Julius Marminge b3151013fc Revise Cursor provider plan for ACP JSON-RPC integration
- Switch plan from `agent -p` stream-json to `agent acp` JSON-RPC transport
- Document ACP session, permission, event-mapping, and interrupt/recovery behavior
- Update implementation phases, tests, and delivery checklist for ACP-first design
2026-03-05 18:13:19 -08:00
Julius Marminge f3bbd398f7 Add Cursor ACP probe script and captured session logs
- add `scripts/cursor-acp-probe.mjs` to run ACP protocol probing scenarios
- update `package.json` scripts for probe execution
- include generated probe summaries/transcripts under `.tmp/acp-probe/`
2026-03-05 18:13:19 -08:00
Julius Marminge 0f9f0f241c Add Cursor provider support across backend, contracts, and UI
- Accept `cursor` as a first-class provider in orchestration, persistence, and session directory flows
- Update model/provider inference and normalization to handle Cursor model aliases
- Revamp chat provider/model picker with Cursor-specific trait controls and add coverage in tests
2026-03-05 18:13:19 -08:00
Julius Marmingeandcodex 222294d541 Add Cursor CLI stream event schemas and decoding tests
- define `CursorAdapter` service contract and Cursor stream-json schema types
- add `CursorCliStreamEvent` decoding tests for system/thinking/tool/result/retry events
- add implementation plan for Cursor provider integration

Co-authored-by: codex <[email protected]>
2026-03-05 18:13:19 -08:00
Julius Marminge a5a5246426 Track runtime event sequence and order thread activities by sequence
- add per-session `sessionSequence` on provider runtime events and persist activity `sequence`
- migrate `projection_thread_activities` with nullable `sequence` column + index
- sort server/web activity projections by sequence fallback to timestamp/id
- allow provider sessions/turns to start before a real threadId is emitted
2026-03-05 18:13:19 -08:00
Julius Marminge 13e7249b3b Align Claude permissions and provider-specific reasoning effort
- Default Claude sessions to bypass permissions when approval policy is `never`, while preserving explicit `permissionMode`
- Hide/send reasoning effort only for providers that support it in ChatView
- Add coverage for Claude permission-mode derivation and precedence, and update runtime event model docs
2026-03-05 18:13:19 -08:00
Julius Marminge 9bb6ab317a Stabilize Claude turn event ordering and native event logging
- Preserve active turn state when `session.started`/`thread.started` arrive mid-turn
- Emit `message.delta` from assistant text when stream deltas are missing, then complete the message
- Add Claude native SDK NDJSON observability logging and wire its log path in server layers
- Expand ingestion/adapter tests to cover mid-turn lifecycle and delta fallback behavior
2026-03-05 18:13:19 -08:00
Julius Marmingeandcodex a4cc4d50b5 Fix ProviderService sendTurn recovery expectation after rebase
Co-authored-by: codex <[email protected]>
2026-03-05 18:13:19 -08:00
Julius Marminge 5b7e114d77 Ignore stale resume cursors and Claude placeholder thread IDs
- Do not pass `resumeCursor` when restarting a session after changing providers
- Treat synthetic Claude thread IDs (`claude-thread-*`) as unscoped during runtime ingestion
- Add tests covering provider-switch restart behavior and Claude turn lifecycle acceptance
2026-03-05 18:13:19 -08:00
Julius Marmingeandcodex a32a7aea52 Align orchestration integration tests with latestTurn metadata
Co-authored-by: codex <[email protected]>
2026-03-05 18:13:19 -08:00
Julius Marminge b51fd9496b Fix Claude resume cursor to only persist valid session UUIDs
- Stop synthesizing `resume` from generated thread IDs
- Persist resume session ID from query messages when available
- Validate resume/sessionId values as UUIDs before reuse
- Add tests for valid UUID resume passthrough and no synthesized resume
2026-03-05 18:13:19 -08:00
Julius Marminge f087c61980 Refactor ClaudeCodeAdapter session flow and stream handling
- Replace manual prompt async iterator with `Stream.fromQueue(...).toAsyncIterable`
- Use `Ref` for shared session context in tool approval callbacks
- Simplify timestamp/ID generation and close sessions via queue shutdown
2026-03-05 18:13:19 -08:00
Julius Marminge 94116dab62 Integrate Claude agent SDK into server provider adapter
- add `@anthropic-ai/claude-agent-sdk` dependency for `apps/server`
- replace placeholder Claude adapter with live session/query/event handling
- add comprehensive adapter tests for runtime events, approvals, resume, rollback, and model overrides
2026-03-05 18:13:19 -08:00
Julius Marmingeandcodex 86608b13b3 Include all provider models in /model slash command
Co-authored-by: codex <[email protected]>
2026-03-05 18:12:45 -08:00
Julius Marmingeandcodex 1d640270c9 Fix Claude model fallback in web store sync
Co-authored-by: codex <[email protected]>
2026-03-05 18:12:45 -08:00
Julius Marmingeandcodex 290d098725 Update Claude model catalog to latest 4.6/4.5 gen
Co-authored-by: codex <[email protected]>
2026-03-05 18:12:45 -08:00
Julius Marmingeandcodex a0d86e42ed Show provider logos in composer model trigger
Co-authored-by: codex <[email protected]>
2026-03-05 18:12:45 -08:00
Julius Marmingeandcodex 84892adf1d Use grouped provider/model select in chat composer
Co-authored-by: codex <[email protected]>
2026-03-05 18:12:45 -08:00
Julius Marmingeandcodex 365dd15aad Inline Claude adapter behavior into live layer
Co-authored-by: codex <[email protected]>
2026-03-05 18:12:44 -08:00
Julius Marminge b2ef4795c3 unnecessary catch 2026-03-05 18:12:44 -08:00
Julius Marmingeandcodex d305e9839e Use typed errors for unavailable Claude runtime path
Co-authored-by: codex <[email protected]>
2026-03-05 18:12:44 -08:00
Julius Marmingeandcodex 78cf175145 Make Claude runtime boundary Effect-native
Co-authored-by: codex <[email protected]>
2026-03-05 18:12:44 -08:00
Julius Marmingeandcodex 28f933373d Add Claude integration coverage across orchestration flows
Co-authored-by: codex <[email protected]>
2026-03-05 18:12:44 -08:00
Julius Marmingeandcodex 148b1da274 Add Claude checkpoint and revert reactor coverage
Co-authored-by: codex <[email protected]>
2026-03-05 18:12:44 -08:00
Julius Marmingeandcodex 0b8e994325 Enable Claude provider selection in chat composer
Add provider-aware model options and include provider in turn-start dispatch.

Co-authored-by: codex <[email protected]>
2026-03-05 18:12:44 -08:00
Julius Marmingeandcodex 8ed1217ef8 Support provider-aware session selection in reactor
Add restart semantics when requested provider changes and cover with tests.

Co-authored-by: codex <[email protected]>
2026-03-05 18:12:44 -08:00
Julius Marmingeandcodex a17ea27d10 Wire Claude adapter into registry and server provider layer
Add provider-service routing coverage for explicit claudeCode sessions.

Co-authored-by: codex <[email protected]>
2026-03-05 18:12:44 -08:00
Julius Marminge 0382f4def9 Add Claude Code adapter live layer with error mapping tests
- introduce `ClaudeCodeAdapter` service and live layer wiring
- map runtime/session/request failures into provider adapter error types
- add coverage for validation, session-not-found mapping, lifecycle forwarding, and event passthrough
2026-03-05 18:12:44 -08:00
Julius Marminge 2e06f7c8dc revised plan 2026-03-05 18:12:44 -08:00
Julius Marminge fa0dcca41f redo contracts a bit 2026-03-05 18:12:44 -08:00
Julius Marminge 49a07aeed9 Add provider-specific model resolution and defaults
- Add per-provider model options, defaults, and slug aliases
- Add provider-aware model normalization/resolution helpers
- Preserve Codex-only constants/functions for backward compatibility
- Extend tests to cover Claude aliases and provider-specific fallback behavior
2026-03-05 18:12:44 -08:00
128 changed files with 6035 additions and 4445 deletions

No files matched your search

-21
View File
@@ -1,21 +0,0 @@
# Architecture
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
-6
View File
@@ -1,6 +0,0 @@
# CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
-5
View File
@@ -1,5 +0,0 @@
# Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
-14
View File
@@ -1,14 +0,0 @@
# Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
-22
View File
@@ -1,22 +0,0 @@
# Quick start
```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
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
```
-6
View File
@@ -1,6 +0,0 @@
# Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
-42
View File
@@ -1,42 +0,0 @@
# Scripts
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `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:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
## 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`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
## Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
-6
View File
@@ -1,6 +0,0 @@
# Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
-1
View File
@@ -5,7 +5,6 @@ node_modules
*.log
*.tsbuildinfo
apps/*/dist
.astro
packages/*/dist
.env
.env.local
+327
View File
@@ -0,0 +1,327 @@
# Plan: Cursor ACP (`agent acp`) Provider Integration
## Goal
Add Cursor as a first-class provider in T3 Code using ACP (`agent acp`) over JSON-RPC 2.0 stdio, with robust session lifecycle handling and canonical `ProviderRuntimeEvent` projection.
---
## 1) Exploration Findings (from live ACP probes)
### 1.1 Core invocation and transport
1. Binary is `agent` on PATH (`2026.02.27-e7d2ef6` observed).
2. ACP server command is `agent acp`.
3. Transport is newline-delimited JSON-RPC 2.0 over stdio.
4. Messages:
- client -> server: requests and responses to server-initiated requests
- server -> client: responses, notifications (`session/update`), and server requests (`session/request_permission`)
### 1.2 Handshake and session calls observed
1. `initialize` returns:
- `protocolVersion`
- `agentCapabilities` (`loadSession`, `mcpCapabilities`, `promptCapabilities`)
- `authMethods` (includes `cursor_login`)
2. `authenticate { methodId: "cursor_login" }` returns `{}` when logged in.
3. `session/new` returns:
- `sessionId`
- `modes` (`agent`, `plan`, `ask`)
4. `session/load` works and requires `sessionId`, `cwd`, `mcpServers`.
5. `session/prompt` returns terminal response `{ stopReason: "end_turn" | "cancelled" }`.
Important sequence note:
1. ACP currently allows `session/new` even without explicit `initialize`/`authenticate` when local auth already exists.
2. For adapter consistency and forward compatibility, we should still send `initialize` and `authenticate` during startup.
### 1.3 `session/update` event families observed
Observed `params.update.sessionUpdate` values:
1. `available_commands_update`
2. `agent_thought_chunk`
3. `agent_message_chunk`
4. `tool_call`
5. `tool_call_update`
Observed payload behavior:
1. `agent_*_chunk` provides `content: { type: "text", text: string }`.
2. `tool_call` may be emitted multiple times for same `toolCallId`:
- initial generic form (`title: "Terminal"`, `rawInput: {}`)
- enriched form (`title: "\`pwd\`"`, `rawInput: { command: "pwd" }`)
3. `tool_call_update` statuses observed:
- `in_progress`
- `completed`
4. `tool_call_update` on completion may include `rawOutput`:
- terminal: `{ exitCode, stdout, stderr }`
- search/find: `{ totalFiles, truncated }`
### 1.4 Permission flow observed
1. ACP server sends `session/request_permission` (JSON-RPC request with `id`).
2. Request shape includes:
- `params.sessionId`
- `params.toolCall`
- `params.options` (`allow-once`, `allow-always`, `reject-once`)
3. Client must respond on same `id` with:
- `{ outcome: { outcome: "selected", optionId: "<one-option-id>" } }`
4. Reject path still results in tool lifecycle completion events (`tool_call_update status: completed`), typically without `rawOutput`.
### 1.5 Error and capability quirks
1. `session/cancel` currently returns:
- JSON-RPC error `-32601` Method not found
2. Error shape examples:
- unknown auth method: `-32602`
- `session/load` missing/invalid params: `-32602`
- `session/prompt` unknown session: `-32603` with details
3. Parallel prompts on same session are effectively single-flight:
- second prompt can cause first to complete with `stopReason: "cancelled"`.
4. `session/new` accepts a `model` field (no explicit echo in response).
Probe artifacts:
1. `.tmp/acp-probe/*/transcript.ndjson`
2. `.tmp/acp-probe/*/summary.json`
3. `scripts/cursor-acp-probe.mjs`
---
## 2) Integration Constraints for T3
1. T3 adapter contract still requires:
- `startSession`, `sendTurn`, `interruptTurn`, `respondToRequest`, `readThread`, `rollbackThread`, `stopSession`, `listSessions`, `hasSession`, `stopAll`, `streamEvents`.
2. Orchestration consumes canonical `ProviderRuntimeEvent` only.
3. `ProviderCommandReactor` provider precedence fix remains required (respect explicit provider on turn start).
4. ACP now supports external permission decisions, so Cursor can participate in T3 approval UX via adapter-managed request/response plumbing.
---
## 3) Proposed Architecture
### 3.1 New server components
1. `apps/server/src/provider/Services/CursorAdapter.ts` (service contract/tag + ACP event schemas).
2. `apps/server/src/provider/Layers/CursorAdapter.ts` (single implementation unit; owns ACP process lifecycle, JSON-RPC routing, runtime projection).
3. No manager indirection; keep logic in layer implementation.
### 3.2 Session model
1. One long-lived ACP child process per T3 Cursor provider session.
2. Track:
- `providerSessionId` (T3 synthetic ID)
- `acpSessionId` (from `session/new` or restored via `session/load`)
- `cwd`, `model`, in-flight turn state
- pending permission requests by JSON-RPC request id
3. Resume support:
- persist `acpSessionId` in provider resume metadata and call `session/load` on reattach.
### 3.3 Command strategy
1. `startSession`:
- spawn `agent acp`
- `initialize`
- `authenticate(cursor_login)` (best-effort, typed failure handling)
- `session/new` or `session/load`
2. `sendTurn`:
- send `session/prompt { sessionId, prompt: [...] }`
- consume streaming `session/update` notifications until terminal prompt response
3. `interruptTurn`:
- no native `session/cancel` today; implement fallback:
- terminate ACP process + restart + `session/load` for subsequent turns
- mark in-flight turn as interrupted/failed in canonical events
4. `respondToRequest`:
- map T3 approval decision -> ACP `optionId`
- reply to exact JSON-RPC request id from `session/request_permission`
### 3.4 Effect-first implementation style (required)
1. Keep logic inside `CursorAdapterLive`.
2. Use Effect primitives:
- `Queue` + `Stream.fromQueue` for event fan-out
- `Ref` / `Ref.Synchronized` for session/process/request state
- scoped fibers for stdout/stderr read loops
3. Typed JSON decode at boundary:
- request/response envelopes
- `session/update` union schema
- permission-request schema
4. Keep adapter errors in typed error algebra with explicit mapping at process/protocol boundaries.
---
## 4) Canonical Event Mapping Plan (ACP -> ProviderRuntimeEvent)
1. `session/update: agent_message_chunk`
- emit `message.delta` for assistant stream
2. prompt terminal response (`session/prompt` result `stopReason: end_turn`)
- emit `message.completed` + `turn.completed`
3. `session/update: agent_thought_chunk`
- initial mapping: emit thinking activity (or ignore if we keep current canonical surface minimal)
4. `session/update: tool_call`
- first-seen `toolCallId` emits `tool.started`
- subsequent `tool_call` for same ID treated as metadata update (no duplicate started event)
5. `session/update: tool_call_update`
- `in_progress`: optional progress activity
- `completed`: emit `tool.completed` with summarized `rawOutput` when present
6. `session/request_permission`
- emit `approval.requested` with mapped options
- when client decision sent, emit `approval.resolved`
7. protocol/process error
- emit `runtime.error`
- fail active turn/session as appropriate
Synthetic IDs:
1. `turnId`: T3-generated UUID per `sendTurn`.
2. `itemId`:
- assistant stream: `${turnId}:assistant`
- tools: `${turnId}:${toolCallId}`
---
## 5) Approval, Resume, and Rollback Behavior
### 5.1 Approvals
1. Cursor ACP permission requests are externally controllable; implement full `respondToRequest` path in v1.
2. Decision mapping:
- allow once -> `allow-once`
- allow always -> `allow-always`
- reject -> `reject-once`
### 5.2 Resume
1. `session/load` is available and should be first-class for adapter restart/reconnect.
2. Must send required params: `sessionId`, `cwd`, `mcpServers`.
### 5.3 Rollback / thread read
1. ACP currently has no observed rollback API.
2. Plan for v1:
- `readThread`: adapter-maintained snapshot projection
- `rollbackThread`: explicit unsupported error
3. Product guard:
- disable checkpoint revert for Cursor threads in UI until rollback exists.
---
## 6) Required Contract and Runtime Changes
### 6.1 Contracts
1. Add `cursor` to `ProviderKind`.
2. Add Cursor provider start options (`providerOptions.cursor`), ACP-oriented:
- optional `binaryPath`
- optional auth/mode knobs if needed later
3. Extend model options for Cursor list and traits mapping.
4. Add schemas for ACP-native event union in Cursor adapter service file.
### 6.2 Server orchestration and registry
1. Register `CursorAdapter` in provider registry and server layer wiring.
2. Update provider-kind persistence decoding for `cursor`.
3. Fix `ProviderCommandReactor` precedence to honor explicit provider in turn-start command.
### 6.3 Web
1. Cursor in provider picker and model picker (already partially done).
2. Trait controls map to concrete Cursor model identifiers.
3. Surface unsupported rollback behavior in UX.
---
## 7) Implementation Phases
### Phase A: ACP process and protocol skeleton
1. Implement ACP process lifecycle in `CursorAdapterLive`.
2. Implement JSON-RPC request/response multiplexer.
3. Implement `initialize`/`authenticate`/`session/new|load` flow.
4. Wire `streamEvents` from ACP notifications.
### Phase B: Runtime projection and approvals
1. Map `session/update` variants to canonical runtime events.
2. Implement permission-request bridging to `respondToRequest`.
3. Implement dedupe for repeated `tool_call` on same `toolCallId`.
### Phase C: Turn control and interruption
1. Implement single in-flight prompt protection per session.
2. Implement interruption fallback (process restart + reload) because `session/cancel` unavailable.
3. Ensure clean state recovery on ACP process crash.
### Phase D: Orchestration + UX polish
1. Provider routing precedence fix.
2. Cursor-specific UX notes for unsupported rollback.
3. End-to-end smoke and event log validation.
---
## 8) Test Plan
Follow project rule: backend external-service integrations tested via layered fakes, not by mocking core business logic.
### 8.1 Unit tests (`CursorAdapter`)
1. JSON-RPC envelope parsing:
- response matching by id
- server request handling (`session/request_permission`)
- notification decode (`session/update`)
2. Event projection:
- `agent_message_chunk` / `agent_thought_chunk`
- `tool_call` + `tool_call_update` dedupe/lifecycle
- permission request -> approval events
3. Error mapping:
- unknown session
- method-not-found (`session/cancel`)
- invalid params
### 8.2 Provider service/routing tests
1. Registry resolves `cursor`.
2. Session directory persistence reads/writes `cursor`.
3. ProviderService fan-out ordering with Cursor ACP events.
### 8.3 Orchestration tests
1. `thread.turn.start` with `provider: cursor` routes to Cursor adapter.
2. approval response command maps to ACP permission response.
3. checkpoint revert on Cursor thread returns controlled unsupported failure.
### 8.4 Optional live smoke
1. Env-gated ACP smoke:
- start session
- run prompt
- observe deltas + completion
- exercise permission request path with one tool call
---
## 9) Operational Notes
1. Keep one in-flight turn per ACP session.
2. Keep per-session ACP process logs/NDJSON artifacts for debugging.
3. Treat `session/cancel` as unsupported until Cursor ships it; avoid relying on it.
4. Preserve resume metadata (`acpSessionId`) for crash recovery.
---
## 10) Open Questions
1. Should we call `authenticate` always, or only after auth-required errors?
2. Should model selection be passed at `session/new` only, or can/should we support model switching mid-session if ACP adds API?
3. For interruption UX, do we expose “hard interrupt” semantics (process restart) explicitly?
---
## 11) Delivery Checklist
1. Plan/documentation switched from headless `agent -p` to ACP `agent acp`.
2. Contracts updated (`ProviderKind`, Cursor options, model/trait mapping).
3. Cursor ACP adapter layer implemented and registered.
4. Provider precedence fixed in orchestration router.
5. Approval response path wired through ACP permission requests.
6. Tests added for protocol decode, projection, approval flow, and routing.
7. Lint + tests green.
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 T3 Tools Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+123 -11
View File
@@ -2,23 +2,135 @@
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
## How to use
Run `npx t3` in any project directory to launch the web interface.
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
> [!WARNING]
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
## Architecture
```bash
npx t3@alpha
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
Use can also just install the desktop app (it's cooler).
## Workspace layout
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Some notes
## Codex prerequisites
We are very very early in this project. Expect bugs.
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
We are not accepting contributions yet.
## Quick start
Discord link coming soon.
```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
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
```
## Scripts
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `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:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
### 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`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
### Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
## Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
## Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
## CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0-alpha.22",
"version": "0.0.0-alpha.20",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
-7
View File
@@ -1,7 +0,0 @@
import { defineConfig } from "astro/config";
export default defineConfig({
server: {
port: Number(process.env.PORT ?? 4173),
},
});
-19
View File
@@ -1,19 +0,0 @@
{
"name": "@t3tools/marketing",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"typecheck": "astro check"
},
"dependencies": {
"astro": "^5.7.13"
},
"devDependencies": {
"@astrojs/check": "^0.9.4",
"typescript": "catalog:"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 652 KiB

-326
View File
@@ -1,326 +0,0 @@
---
---
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="T3 Code — The best way to code with AI." />
<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:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" />
<link rel="icon" type="image/png" href="/icon.png" />
<title>T3 Code</title>
</head>
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
</nav>
<main class="main">
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<a
href="https://github.com/pingdotgg/t3code/releases"
target="_blank"
rel="noopener noreferrer"
class="hero-button"
>
Download now
</a>
<div class="screenshot-wrap">
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
</div>
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
</body>
</html>
<style>
:root {
--bg: #09090b;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--border: rgba(255, 255, 255, 0.08);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
color-scheme: dark;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
z-index: 9999;
}
a {
color: inherit;
text-decoration: none;
}
img {
display: block;
max-width: 100%;
}
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
}
.nav-brand {
display: flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
}
/* ── Main content ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding-top: 10vh;
}
/* ── Tagline ── */
.tagline {
font-weight: 500;
font-size: clamp(2rem, 5vw, 3.5rem);
letter-spacing: -0.035em;
line-height: 1.15;
text-align: center;
margin: 0 0 6vh;
opacity: 0;
animation: fade-in 1s ease-out forwards;
}
/* ── Hero button ── */
.hero-button {
display: inline-block;
background: #fafafa;
color: #09090b;
padding: 0.75rem 2rem;
border-radius: 999px;
font-weight: 600;
font-size: 0.9rem;
margin-bottom: 5vh;
opacity: 0;
animation: fade-in 1s ease-out 0.15s forwards;
transition: transform 0.25s ease, box-shadow 0.25s ease;
}
.hero-button:hover {
transform: scale(1.03);
box-shadow: 0 0 24px rgba(255, 255, 255, 0.08);
}
.hero-button:active {
transform: scale(0.98);
}
/* ── Screenshot ── */
.screenshot-wrap {
margin: 0 auto;
width: min(95vw, 1400px);
opacity: 0;
transform: scale(0.98);
animation: screenshot-in 1s ease-out 0.15s forwards;
}
.screenshot {
width: 100%;
display: block;
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.06);
mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
-webkit-mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
}
.screenshot-wrap::after {
content: "";
display: block;
width: 100%;
height: 120px;
background: inherit;
margin-top: -1px;
opacity: 0.04;
transform: scaleY(-1);
mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
-webkit-mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
pointer-events: none;
}
/* ── Footer ── */
.footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
color: var(--fg-dim);
}
.footer-links {
display: flex;
gap: 1.25rem;
}
.footer-links a {
color: var(--fg-dim);
transition: color 0.3s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Animations ── */
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes screenshot-in {
from {
opacity: 0;
transform: scale(0.98);
}
to {
opacity: 1;
transform: scale(1);
}
}
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem 1.25rem;
}
.main {
padding-top: 7vh;
}
.tagline {
margin-bottom: 4vh;
}
.screenshot-wrap {
width: 95vw;
}
.footer {
padding: 1.25rem;
}
}
</style>
-3
View File
@@ -1,3 +0,0 @@
{
"extends": "astro/tsconfigs/strict"
}
@@ -40,7 +40,6 @@ import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
@@ -153,7 +152,7 @@ export interface OrchestrationIntegrationHarness {
readonly rootDir: string;
readonly workspaceDir: string;
readonly dbPath: string;
readonly adapterHarness: TestProviderAdapterHarness | null;
readonly adapterHarness: TestProviderAdapterHarness;
readonly engine: OrchestrationEngineShape;
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
readonly providerService: ProviderService["Service"];
@@ -189,7 +188,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: "codex";
readonly provider?: "codex" | "claudeCode";
readonly realCodex?: boolean;
}
@@ -253,12 +252,10 @@ export const makeOrchestrationIntegrationHarness = (
? makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(realCodexRegistry),
Layer.provide(AnalyticsService.layerTest),
)
: makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(fakeRegistry!),
Layer.provide(AnalyticsService.layerTest),
);
const runtimeServicesLayer = Layer.mergeAll(
@@ -406,14 +403,19 @@ export const makeOrchestrationIntegrationHarness = (
disposed = true;
const shutdown = Effect.gen(function* () {
const stopAllExit = yield* Effect.exit(
Effect.promise(() => runtime.runPromise(providerService.stopAll())),
);
const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void));
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
const failureCause = Exit.isFailure(closeScopeExit)
? closeScopeExit.cause
: Exit.isFailure(disposeRuntimeExit)
? disposeRuntimeExit.cause
: null;
const failureCause = Exit.isFailure(stopAllExit)
? stopAllExit.cause
: Exit.isFailure(closeScopeExit)
? closeScopeExit.cause
: Exit.isFailure(disposeRuntimeExit)
? disposeRuntimeExit.cause
: null;
if (failureCause) {
return yield* Effect.failCause(failureCause);
@@ -433,7 +435,7 @@ export const makeOrchestrationIntegrationHarness = (
rootDir,
workspaceDir,
dbPath,
adapterHarness,
adapterHarness: adapterHarness as TestProviderAdapterHarness,
engine,
snapshotQuery,
providerService,
@@ -35,7 +35,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
readonly provider: "codex" | "claudeCode" | "cursor";
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: "codex";
readonly provider: "codex" | "claudeCode";
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: "codex";
readonly provider?: "codex" | "claudeCode";
}
function nowIso(): string {
@@ -206,7 +206,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: "codex",
provider: "codex" | "claudeCode",
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +216,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: "codex",
provider: "codex" | "claudeCode",
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -32,7 +32,7 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = "codex";
type IntegrationProvider = "codex" | "claudeCode";
function nowIso() {
return new Date().toISOString();
@@ -180,7 +180,7 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
],
};
yield* harness.adapterHarness!.queueTurnResponseForNextSession(turnResponse);
yield* harness.adapterHarness.queueTurnResponseForNextSession(turnResponse);
yield* startTurn({
harness,
commandId: "cmd-turn-start-single",
@@ -314,7 +314,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
@@ -373,7 +373,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
(entry) => entry.checkpoints.length === 1 && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
@@ -473,7 +473,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
@@ -538,7 +538,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
assert.equal(resolvedRow.decision, "accept");
const approvalResponses = yield* waitForSync(
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
() => harness.adapterHarness.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1,
"provider approval response",
);
@@ -554,7 +554,7 @@ it.live("records failed turn runtime state and checkpoint status as error", () =
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
@@ -633,7 +633,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
@@ -691,7 +691,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
(entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1,
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
@@ -796,7 +796,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
assert.deepEqual(harness.adapterHarness.getRollbackCalls(THREAD_ID), [1]);
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID,
@@ -842,3 +842,416 @@ it.live(
}),
),
);
it.live("starts a claudeCode session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-initial",
messageId: "msg-user-claude-initial",
text: "Use Claude",
provider: "claudeCode",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeCode" &&
entry.session.status === "ready" &&
entry.messages.some(
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
),
);
assert.equal(thread.session?.providerName, "claudeCode");
}),
"claudeCode",
),
);
it.live("recovers claudeCode sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-1",
messageId: "msg-user-claude-recover-1",
text: "Before restart",
provider: "claudeCode",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.providerService.stopAll();
yield* waitForSync(
() => harness.adapterHarness.listActiveSessionIds(),
(sessionIds) => sessionIds.length === 0,
"provider stopAll",
);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-2",
messageId: "msg-user-claude-recover-2",
text: "After restart",
});
yield* waitForSync(
() => harness.adapterHarness.getStartCount(),
(count) => count === 2,
"claude provider recovery start",
);
const recoveredThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeCode" &&
entry.messages.some(
(message) => message.role === "user" && message.text === "After restart",
) &&
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
);
assert.equal(recoveredThread.session?.providerName, "claudeCode");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeCode",
),
);
it.live("forwards claudeCode approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
requestKind: "command",
detail: "Approve Claude tool call",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-approval",
messageId: "msg-user-claude-approval",
text: "Need approval",
provider: "claudeCode",
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some((activity) => activity.kind === "approval.requested"),
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
createdAt: nowIso(),
});
yield* harness.waitForPendingApproval(
"req-approval-1",
(row) => row.status === "resolved" && row.decision === "accept",
);
const approvalResponses = yield* waitForSync(
() => harness.adapterHarness.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1,
"claude provider approval response",
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeCode",
),
);
it.live("forwards thread.turn.interrupt to claudeCode provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-interrupt",
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
provider: "claudeCode",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1",
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
threadId: THREAD_ID,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent((event) => event.type === "thread.turn-interrupt-requested");
const interruptCalls = yield* waitForSync(
() => harness.adapterHarness.getInterruptCalls(THREAD_ID),
(calls) => calls.length === 1,
"claude provider interrupt call",
);
assert.equal(interruptCalls.length, 1);
}),
"claudeCode",
),
);
it.live("reverts claudeCode turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
provider: "claudeCode",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeCode",
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeCode",
),
);
@@ -12,7 +12,6 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
@@ -60,7 +59,6 @@ const makeIntegrationFixture = Effect.gen(function* () {
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
AnalyticsService.layerTest,
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.0-alpha.22",
"version": "0.0.0-alpha.20",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
+6 -95
View File
@@ -6,7 +6,6 @@ import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { DEVELOPMENT_ICON_OVERRIDES, PUBLISH_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
@@ -32,84 +31,6 @@ const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Comm
}
});
interface PublishIconBackup {
readonly targetPath: string;
readonly backupPath: string;
}
const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
repoRoot: string,
serverDir: string,
) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const backups: PublishIconBackup[] = [];
for (const override of PUBLISH_ICON_OVERRIDES) {
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
const targetPath = path.join(serverDir, override.targetRelativePath);
const backupPath = `${targetPath}.publish-bak`;
if (!(yield* fs.exists(sourcePath))) {
return yield* new CliError({
message: `Missing publish icon source: ${sourcePath}`,
});
}
if (!(yield* fs.exists(targetPath))) {
return yield* new CliError({
message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
});
}
yield* fs.copyFile(targetPath, backupPath);
yield* fs.copyFile(sourcePath, targetPath);
backups.push({ targetPath, backupPath });
}
yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
return backups as ReadonlyArray<PublishIconBackup>;
});
const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
backups: ReadonlyArray<PublishIconBackup>,
) {
const fs = yield* FileSystem.FileSystem;
for (const backup of backups) {
if (!(yield* fs.exists(backup.backupPath))) {
continue;
}
yield* fs.rename(backup.backupPath, backup.targetPath);
}
});
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
repoRoot: string,
serverDir: string,
) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
for (const override of DEVELOPMENT_ICON_OVERRIDES) {
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
const targetPath = path.join(serverDir, override.targetRelativePath);
if (!(yield* fs.exists(sourcePath))) {
return yield* new CliError({
message: `Missing development icon source: ${sourcePath}`,
});
}
if (!(yield* fs.exists(targetPath))) {
return yield* new CliError({
message: `Missing development icon target: ${targetPath}. Build web first.`,
});
}
yield* fs.copyFile(sourcePath, targetPath);
}
yield* Effect.log("[cli] Applied development icon overrides to dist/client");
});
// ---------------------------------------------------------------------------
// build subcommand
// ---------------------------------------------------------------------------
@@ -140,7 +61,6 @@ const buildCmd = Command.make(
if (yield* fs.exists(webDist)) {
yield* fs.copy(webDist, clientTarget);
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
yield* Effect.log("[cli] Bundled web app into dist/client");
} else {
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
@@ -184,8 +104,10 @@ const publishCmd = Command.make(
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.gen(function* () {
// Resolve catalog dependencies before any file mutations. If this throws,
// acquire fails and no release hook runs, so filesystem must still be untouched.
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
// Build package.json for publish
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = {
name: serverPackageJson.name,
@@ -198,19 +120,15 @@ const publishCmd = Command.make(
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
};
// Resolve catalog: entries in production dependencies
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Resolved package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
}),
// Use: npm publish
() =>
@@ -229,15 +147,8 @@ const publishCmd = Command.make(
);
}),
// Release: restore
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
() =>
Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(
`[cli] Failed to restore publish icon overrides: ${String(error)}`,
),
),
);
yield* fs.rename(backupPath, packageJsonPath);
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
}),
+66
View File
@@ -0,0 +1,66 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import path from "node:path";
import { Effect, FileSystem, Layer, Logger, ServiceMap } from "effect";
import { makeEventNdjsonLogger } from "../src/provider/Layers/EventNdjsonLogger.ts";
class LogDir extends ServiceMap.Service<LogDir, string>()("t3/scripts/logger-scope-repro/LogDir") {}
const main = Effect.gen(function* () {
const logdir = yield* LogDir;
const providerLogPath = path.join(logdir, "provider");
yield* Effect.logInfo(`providerLogPath=${providerLogPath}`);
const providerLogger = yield* makeEventNdjsonLogger(providerLogPath, {
stream: "native",
batchWindowMs: 10,
});
yield* Effect.logInfo("before provider write");
if (providerLogger) {
yield* providerLogger.write(
{
kind: "probe",
message: "provider-only event",
},
"thread-123" as never,
);
}
yield* Effect.logInfo("after provider write");
yield* Effect.sleep("50 millis");
if (providerLogger) {
yield* providerLogger.close();
}
yield* Effect.logInfo("after provider close");
const fs = yield* FileSystem.FileSystem;
const logContents = yield* fs
.readDirectory(logdir, { recursive: true })
.pipe(
Effect.flatMap((entries) =>
Effect.all(entries.map((entry) => fs.readFileString(path.join(logdir, entry)))),
),
);
yield* Effect.logInfo(`logContents=${logContents}`);
});
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const logdir = path.join(process.cwd(), "logtest");
yield* fs.makeDirectory(logdir);
const fileLogger = yield* Logger.formatSimple.pipe(
Logger.toFile(path.join(logdir, "global.log")),
);
const dualLogger = Logger.layer([fileLogger, Logger.consolePretty()]);
const mainLayer = Layer.mergeAll(dualLogger, Layer.succeed(LogDir, logdir));
yield* main.pipe(Effect.provide(mainLayer));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
+7 -218
View File
@@ -7,14 +7,11 @@ import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
import {
buildCodexInitializeParams,
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
CodexAppServerManager,
classifyCodexStderrLine,
isRecoverableThreadResumeError,
normalizeCodexModelSlug,
readCodexAccountSnapshot,
resolveCodexModelForAccount,
} from "./codexAppServerManager";
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
@@ -23,20 +20,14 @@ function createSendTurnHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
runtimeMode: "full-access",
model: "gpt-5.3-codex",
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
};
const requireSession = vi
@@ -66,11 +57,10 @@ function createThreadControlHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
runtimeMode: "full-access",
model: "gpt-5.3-codex",
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
@@ -98,11 +88,10 @@ function createPendingUserInputHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
runtimeMode: "full-access",
model: "gpt-5.3-codex",
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
@@ -205,70 +194,6 @@ describe("isRecoverableThreadResumeError", () => {
});
});
describe("readCodexAccountSnapshot", () => {
it("disables spark for chatgpt plus accounts", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
planType: "plus",
}),
).toEqual({
type: "chatgpt",
planType: "plus",
sparkEnabled: false,
});
});
it("keeps spark enabled for chatgpt pro accounts", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
planType: "pro",
}),
).toEqual({
type: "chatgpt",
planType: "pro",
sparkEnabled: true,
});
});
it("keeps spark enabled for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
}),
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: true,
});
});
});
describe("resolveCodexModelForAccount", () => {
it("falls back from spark to default for unsupported chatgpt plans", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "chatgpt",
planType: "plus",
sparkEnabled: false,
}),
).toBe("gpt-5.3-codex");
});
it("keeps spark for supported plans", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "chatgpt",
planType: "pro",
sparkEnabled: true,
}),
).toBe("gpt-5.3-codex-spark");
});
});
describe("startSession", () => {
it("enables Codex experimental api capabilities during initialize", () => {
expect(buildCodexInitializeParams()).toEqual({
@@ -333,8 +258,8 @@ describe("sendTurn", () => {
},
],
model: "gpt-5.3",
serviceTier: "fast",
effort: "high",
serviceTier: "fast",
});
expect(result).toEqual({
@@ -357,8 +282,8 @@ describe("sendTurn", () => {
},
],
model: "gpt-5.3-codex",
serviceTier: "fast",
effort: "high",
serviceTier: "fast",
});
expect(updateSession).toHaveBeenCalledWith(context, {
status: "running",
@@ -388,7 +313,6 @@ describe("sendTurn", () => {
url: "data:image/png;base64,BBBB",
},
],
model: "gpt-5.3-codex",
});
});
@@ -422,67 +346,6 @@ describe("sendTurn", () => {
});
});
it("passes Codex default mode as a collaboration preset on turn/start", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
threadId: asThreadId("thread_1"),
input: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
interactionMode: "default",
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
text_elements: [],
},
],
model: "gpt-5.3-codex",
collaborationMode: {
mode: "default",
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
it("keeps the session model when interaction mode is set without an explicit model", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
context.session.model = "gpt-5.2-codex";
await manager.sendTurn({
threadId: asThreadId("thread_1"),
input: "Plan this with my current session model",
interactionMode: "plan",
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "Plan this with my current session model",
text_elements: [],
},
],
model: "gpt-5.2-codex",
collaborationMode: {
mode: "plan",
settings: {
model: "gpt-5.2-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
it("rejects empty turn input", async () => {
const { manager } = createSendTurnHarness();
@@ -591,8 +454,8 @@ describe("respondToUserInput", () => {
asThreadId("thread_1"),
ApprovalRequestId.makeUnsafe("req-user-input-1"),
{
scope: "All request methods",
compat: "Keep current envelope",
scope: "All request methods",
compat: "Keep current envelope",
},
);
@@ -619,80 +482,6 @@ describe("respondToUserInput", () => {
}),
);
});
it("preserves explicit empty multi-select answers", async () => {
const { manager, context, requireSession, writeMessage, emitEvent } =
createPendingUserInputHarness();
await manager.respondToUserInput(
asThreadId("thread_1"),
ApprovalRequestId.makeUnsafe("req-user-input-1"),
{
scope: [],
},
);
expect(requireSession).toHaveBeenCalledWith("thread_1");
expect(writeMessage).toHaveBeenCalledWith(context, {
id: 42,
result: {
answers: {
scope: { answers: [] },
},
},
});
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/tool/requestUserInput/answered",
payload: {
requestId: "req-user-input-1",
answers: {
scope: { answers: [] },
},
},
}),
);
});
it("tracks file-read approval requests with the correct method", () => {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: asThreadId("thread_1"),
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
};
type ApprovalRequestContext = {
session: typeof context.session;
pendingApprovals: typeof context.pendingApprovals;
pendingUserInputs: typeof context.pendingUserInputs;
};
(
manager as unknown as {
handleServerRequest: (
context: ApprovalRequestContext,
request: Record<string, unknown>,
) => void;
}
).handleServerRequest(context, {
jsonrpc: "2.0",
id: 42,
method: "item/fileRead/requestApproval",
params: {},
});
const request = Array.from(context.pendingApprovals.values())[0];
expect(request?.requestKind).toBe("file-read");
expect(request?.method).toBe("item/fileRead/requestApproval");
});
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
+21 -140
View File
@@ -34,10 +34,7 @@ interface PendingRequest {
interface PendingApprovalRequest {
requestId: ApprovalRequestId;
jsonRpcId: string | number;
method:
| "item/commandExecution/requestApproval"
| "item/fileChange/requestApproval"
| "item/fileRead/requestApproval";
method: "item/commandExecution/requestApproval" | "item/fileChange/requestApproval";
requestKind: ProviderRequestKind;
threadId: ThreadId;
turnId?: TurnId;
@@ -58,7 +55,6 @@ interface CodexUserInputAnswer {
interface CodexSessionContext {
session: ProviderSession;
account: CodexAccountSnapshot;
child: ChildProcessWithoutNullStreams;
output: readline.Interface;
pending: Map<PendingRequestKey, PendingRequest>;
@@ -90,30 +86,13 @@ interface JsonRpcNotification {
params?: unknown;
}
type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export interface CodexAppServerSendTurnInput {
readonly threadId: ThreadId;
readonly input?: string;
readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>;
readonly model?: string;
readonly serviceTier?: string | null;
readonly effort?: string;
readonly serviceTier?: string;
readonly interactionMode?: ProviderInteractionMode;
}
@@ -153,50 +132,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"unknown thread",
"does not exist",
];
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
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;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: true,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: true,
};
}
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
@@ -319,19 +254,6 @@ Do not ask "should I proceed?" in the final output. The user can easily switch o
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
</collaboration_mode>`;
export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
## request_user_input availability
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
</collaboration_mode>`;
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
readonly approvalPolicy: "on-request" | "never";
readonly sandbox: "workspace-write" | "danger-full-access";
@@ -349,17 +271,6 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
};
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
@@ -412,7 +323,7 @@ function buildCodexCollaborationMode(input: {
readonly effort?: string;
}):
| {
mode: "default" | "plan";
mode: "plan";
settings: {
model: string;
reasoning_effort: string;
@@ -420,19 +331,16 @@ function buildCodexCollaborationMode(input: {
};
}
| undefined {
if (input.interactionMode === undefined) {
if (input.interactionMode !== "plan") {
return undefined;
}
const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex";
return {
mode: input.interactionMode,
mode: "plan",
settings: {
model,
reasoning_effort: input.effort ?? "medium",
developer_instructions:
input.interactionMode === "plan"
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
},
};
}
@@ -444,14 +352,18 @@ function toCodexUserInputAnswer(value: unknown): CodexUserInputAnswer {
if (Array.isArray(value)) {
const answers = value.filter((entry): entry is string => typeof entry === "string");
return { answers };
if (answers.length > 0) {
return { answers };
}
}
if (value && typeof value === "object") {
const maybeAnswers = (value as { answers?: unknown }).answers;
if (Array.isArray(maybeAnswers)) {
const answers = maybeAnswers.filter((entry): entry is string => typeof entry === "string");
return { answers };
if (answers.length > 0) {
return { answers };
}
}
}
@@ -548,11 +460,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context = {
session,
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
child,
output,
pending: new Map(),
@@ -570,33 +477,12 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
await this.sendRequest(context, "initialize", buildCodexInitializeParams());
this.writeMessage(context, { method: "initialized" });
try {
const modelListResponse = await this.sendRequest(context, "model/list", {});
console.log("codex model/list response", modelListResponse);
} catch (error) {
console.log("codex model/list failed", error);
}
try {
const accountReadResponse = await this.sendRequest(context, "account/read", {});
console.log("codex account/read response", accountReadResponse);
context.account = readCodexAccountSnapshot(accountReadResponse);
console.log("codex subscription status", {
type: context.account.type,
planType: context.account.planType,
sparkEnabled: context.account.sparkEnabled,
});
} catch (error) {
console.log("codex account/read failed", error);
}
const normalizedModel = resolveCodexModelForAccount(
normalizeCodexModelSlug(input.model),
context.account,
);
const normalizedModel = normalizeCodexModelSlug(input.model);
const sessionOverrides = {
model: normalizedModel ?? null,
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
cwd: input.cwd ?? null,
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...mapCodexRuntimeMode(input.runtimeMode ?? "full-access"),
};
@@ -756,10 +642,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
serviceTier?: string | null;
effort?: string;
serviceTier?: string;
collaborationMode?: {
mode: "default" | "plan";
mode: "plan";
settings: {
model: string;
reasoning_effort: string;
@@ -770,19 +656,16 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: providerThreadId,
input: turnInput,
};
const normalizedModel = resolveCodexModelForAccount(
normalizeCodexModelSlug(input.model ?? context.session.model),
context.account,
);
const normalizedModel = normalizeCodexModelSlug(input.model ?? context.session.model);
if (normalizedModel) {
turnStartParams.model = normalizedModel;
}
if (input.serviceTier !== undefined) {
turnStartParams.serviceTier = input.serviceTier;
}
if (input.effort) {
turnStartParams.effort = input.effort;
}
if (input.serviceTier) {
turnStartParams.serviceTier = input.serviceTier;
}
const collaborationMode = buildCodexCollaborationMode({
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
...(normalizedModel !== undefined ? { model: normalizedModel } : {}),
@@ -1181,9 +1064,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
method:
requestKind === "command"
? "item/commandExecution/requestApproval"
: requestKind === "file-read"
? "item/fileRead/requestApproval"
: "item/fileChange/requestApproval",
: "item/fileChange/requestApproval",
requestKind,
threadId: context.session.threadId,
...(route.turnId ? { turnId: route.turnId } : {}),
-2
View File
@@ -9,7 +9,6 @@ import { Command } from "effect/unstable/cli";
import { version } from "../package.json" with { type: "json" };
import { ServerLive } from "./wsServer";
import { NetService } from "@t3tools/shared/Net";
import { FetchHttpClient } from "effect/unstable/http";
const RuntimeLayer = Layer.empty.pipe(
Layer.provideMerge(CliConfig.layer),
@@ -17,7 +16,6 @@ const RuntimeLayer = Layer.empty.pipe(
Layer.provideMerge(OpenLive),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(FetchHttpClient.layer),
);
Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain);
+1 -44
View File
@@ -1,20 +1,16 @@
import * as Http from "node:http";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, vi } from "@effect/vitest";
import type { OrchestrationReadModel } from "@t3tools/contracts";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Command from "effect/unstable/cli/Command";
import { FetchHttpClient } from "effect/unstable/http";
import { beforeEach } from "vitest";
import { NetService } from "@t3tools/shared/Net";
import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main";
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
import { ServerConfig, type ServerConfigShape } from "./config";
import { Open, type OpenShape } from "./open";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
import { Server, type ServerShape } from "./wsServer";
const start = vi.fn(() => undefined);
@@ -51,8 +47,6 @@ const testLayer = Layer.mergeAll(
openBrowser: (_target: string) => Effect.void,
openInEditor: () => Effect.void,
} satisfies OpenShape),
AnalyticsService.layerTest,
FetchHttpClient.layer,
NodeServices.layer,
);
@@ -233,43 +227,6 @@ it.layer(testLayer)("server CLI command", (it) => {
}),
);
it.effect("records a startup heartbeat with thread/project counts", () =>
Effect.gen(function* () {
const recordTelemetry = vi.fn(
(_event: string, _properties?: Readonly<Record<string, unknown>>) => Effect.void,
);
const getSnapshot = vi.fn(() =>
Effect.succeed({
snapshotSequence: 2,
projects: [{} as OrchestrationReadModel["projects"][number]],
threads: [
{} as OrchestrationReadModel["threads"][number],
{} as OrchestrationReadModel["threads"][number],
],
updatedAt: new Date(1).toISOString(),
} satisfies OrchestrationReadModel),
);
yield* recordStartupHeartbeat.pipe(
Effect.provideService(ProjectionSnapshotQuery, {
getSnapshot,
}),
Effect.provideService(AnalyticsService, {
record: recordTelemetry,
flush: Effect.void,
}),
);
assert.deepEqual(recordTelemetry.mock.calls[0], [
"server.boot.heartbeat",
{
threadCount: 2,
projectCount: 1,
},
]);
}),
);
it.effect("does not start server for invalid --mode values", () =>
Effect.gen(function* () {
yield* runCli(["--mode", "invalid"]);
+2 -30
View File
@@ -9,6 +9,8 @@
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
// Dummy comment.
import {
DEFAULT_PORT,
resolveStaticDir,
@@ -20,12 +22,9 @@ import { fixPath, resolveStateDir } from "./os-jank";
import { Open } from "./open";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
import { Server } from "./wsServer";
import { ServerLoggerLive } from "./serverLogger";
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
export class StartupError extends Data.TaggedError("StartupError")<{
readonly message: string;
@@ -200,7 +199,6 @@ const LayerLive = (input: CliInput) =>
Layer.provideMerge(ProviderHealthLive),
Layer.provideMerge(SqlitePersistence.layerConfig),
Layer.provideMerge(ServerLoggerLive),
Layer.provideMerge(AnalyticsServiceLayerLive),
Layer.provideMerge(ServerConfigLive(input)),
);
@@ -210,31 +208,6 @@ const isWildcardHost = (host: string | undefined): boolean =>
const formatHostForUrl = (host: string): string =>
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
export const recordStartupHeartbeat = Effect.gen(function* () {
const analytics = yield* AnalyticsService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
Effect.map((snapshot) => ({
threadCount: snapshot.threads.length,
projectCount: snapshot.projects.length,
})),
Effect.catch((cause) =>
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
Effect.as({
threadCount: 0,
projectCount: 0,
}),
),
),
);
yield* analytics.record("server.boot.heartbeat", {
threadCount,
projectCount,
});
});
const makeServerProgram = (input: CliInput) =>
Effect.gen(function* () {
const cliConfig = yield* CliConfig;
@@ -254,7 +227,6 @@ const makeServerProgram = (input: CliInput) =>
}
yield* start;
yield* Effect.forkChild(recordStartupHeartbeat);
const localUrl = `http://localhost:${config.port}`;
const bindUrl =
@@ -43,7 +43,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
readonly provider: "codex" | "claudeCode" | "cursor";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -57,7 +57,7 @@ function createProviderServiceHarness(
cwd: string,
hasSession = true,
sessionCwd = cwd,
providerName: ProviderSession["provider"] = "codex",
providerName: "codex" | "claudeCode" = "codex",
) {
const now = new Date().toISOString();
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
@@ -91,6 +91,7 @@ function createProviderServiceHarness(
listSessions,
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation,
stopAll: () => Effect.void,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
@@ -234,6 +235,7 @@ describe("CheckpointReactor", () => {
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: "codex" | "claudeCode";
}) {
const cwd = createGitRepository();
tempDirs.push(cwd);
@@ -241,7 +243,7 @@ describe("CheckpointReactor", () => {
cwd,
options?.hasSession ?? true,
options?.providerSessionCwd ?? cwd,
"codex",
options?.providerName ?? "codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -474,6 +476,69 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
});
it("captures pre-turn and completion checkpoints for claudeCode runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: "claudeCode",
});
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeCode",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
harness.provider.emit({
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
provider: "claudeCode",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
});
await waitForGitRefExists(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
);
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
harness.provider.emit({
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
provider: "claudeCode",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
payload: { state: "completed" },
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
const thread = await waitForThread(
harness.engine,
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
).toBe(true);
});
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
@@ -780,7 +845,7 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
@@ -789,6 +854,75 @@ describe("CheckpointReactor", () => {
).toBe(false);
});
it("executes provider revert and emits thread.reverted for claudeCode sessions", async () => {
const harness = await createHarness({ providerName: "claudeCode" });
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeCode",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
status: "ready",
files: [],
checkpointTurnCount: 1,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-2"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
status: "ready",
files: [],
checkpointTurnCount: 2,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
);
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
numTurns: 1,
});
});
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
const harness = await createHarness();
const createdAt = new Date().toISOString();
@@ -874,11 +1008,11 @@ describe("CheckpointReactor", () => {
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
});
@@ -111,81 +111,6 @@ describe("OrchestrationEngine", () => {
await system.dispose();
});
it("seeds branched thread history during thread creation", async () => {
const createdAt = now();
const system = await createOrchestrationSystem();
const { engine } = system;
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe("cmd-project-branch-seed"),
projectId: asProjectId("project-branch-seed"),
title: "Project 1",
workspaceRoot: "/tmp/project-branch-seed",
defaultModel: "gpt-5-codex",
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-branch-seed"),
threadId: ThreadId.makeUnsafe("thread-branch-seed"),
projectId: asProjectId("project-branch-seed"),
title: "Branch of Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: "feature/source",
worktreePath: null,
seedMessages: [
{
messageId: asMessageId("msg-seed-user"),
role: "user",
text: "original question",
attachments: [],
createdAt: "2026-02-01T00:00:00.000Z",
updatedAt: "2026-02-01T00:00:00.000Z",
},
{
messageId: asMessageId("msg-seed-assistant"),
role: "assistant",
text: "original answer",
attachments: [],
createdAt: "2026-02-01T00:00:01.000Z",
updatedAt: "2026-02-01T00:00:01.000Z",
},
],
createdAt,
}),
);
const readModel = await system.run(engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === "thread-branch-seed");
expect(thread?.messages.map((message) => message.text)).toEqual([
"original question",
"original answer",
]);
expect(thread?.messages.every((message) => message.turnId === null)).toBe(true);
expect(thread?.session).toBeNull();
const events = await system.run(
Stream.runCollect(engine.readEvents(0)).pipe(
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
),
);
expect(events.map((event) => event.type)).toEqual([
"project.created",
"thread.created",
"thread.message-sent",
"thread.message-sent",
]);
await system.dispose();
});
it("replays append-only events from sequence", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
@@ -93,7 +93,9 @@ describe("ProviderCommandReactor", () => {
typeof input === "object" &&
input !== null &&
"provider" in input &&
input.provider === "codex"
(input.provider === "codex" ||
input.provider === "claudeCode" ||
input.provider === "cursor")
? input.provider
: "codex";
const resumeCursor =
@@ -185,9 +187,10 @@ describe("ProviderCommandReactor", () => {
listSessions: () => Effect.succeed(runtimeSessions),
getCapabilities: (provider) =>
Effect.succeed({
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
sessionModelSwitch: provider === "cursor" ? "unsupported" : "in-session",
}),
rollbackConversation: () => unsupported(),
stopAll: () => Effect.void,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
@@ -382,6 +385,80 @@ describe("ProviderCommandReactor", () => {
});
});
it("starts first turn with requested provider when provider is specified", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-first"),
role: "user",
text: "hello claude",
attachments: [],
},
provider: "claudeCode",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeCode",
cwd: "/tmp/provider-project",
model: "gpt-5-codex",
runtimeMode: "approval-required",
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerName).toBe("claudeCode");
expect(thread?.session?.threadId).toBe("thread-1");
});
it("starts first turn with cursor provider when provider is specified", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-cursor"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-cursor"),
role: "user",
text: "hello cursor",
attachments: [],
},
provider: "cursor",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "cursor",
cwd: "/tmp/provider-project",
model: "gpt-5-codex",
runtimeMode: "approval-required",
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerName).toBe("cursor");
expect(thread?.session?.threadId).toBe("thread-1");
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -428,6 +505,111 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("reuses the same cursor session when requested model is unchanged", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-cursor-model-same-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-cursor-model-same-1"),
role: "user",
text: "first",
attachments: [],
},
provider: "cursor",
model: "composer-1.5",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-cursor-model-same-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-cursor-model-same-2"),
role: "user",
text: "second",
attachments: [],
},
provider: "cursor",
model: "composer-1.5",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls.length).toBe(1);
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("keeps cursor session/model when model change is unsupported", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-cursor-model-change-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-cursor-model-change-1"),
role: "user",
text: "first",
attachments: [],
},
provider: "cursor",
model: "gpt-5.3-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-cursor-model-change-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-cursor-model-change-2"),
role: "user",
text: "second",
attachments: [],
},
provider: "cursor",
model: "composer-1.5",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls.length).toBe(1);
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "gpt-5.3-codex",
});
});
it("restarts the provider session when runtime mode is updated on the thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -513,6 +695,66 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("switches provider by restarting the session when turn request provider changes", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-2"),
role: "user",
text: "second",
attachments: [],
},
provider: "claudeCode",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
provider: "claudeCode",
runtimeMode: "approval-required",
});
expect(harness.startSession.mock.calls[1]?.[1]).not.toHaveProperty("resumeCursor");
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerName).toBe("claudeCode");
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("does not stop the active session when restart fails before rebind", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -708,7 +950,7 @@ describe("ProviderCommandReactor", () => {
harness.respondToRequest.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "codex",
provider: "cursor",
method: "session/request_permission",
detail: "Unknown pending permission request: approval-request-1",
}),
@@ -723,7 +965,7 @@ describe("ProviderCommandReactor", () => {
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerName: "cursor",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
@@ -5,7 +5,6 @@ import {
type OrchestrationEvent,
type ProviderModelOptions,
type ProviderKind,
type ProviderServiceTier,
type OrchestrationSession,
ThreadId,
type ProviderSession,
@@ -202,7 +201,6 @@ const make = Effect.gen(function* () {
readonly provider?: ProviderKind;
readonly model?: string;
readonly modelOptions?: ProviderModelOptions;
readonly serviceTier?: ProviderServiceTier | null;
},
) {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -213,7 +211,11 @@ const make = Effect.gen(function* () {
const desiredRuntimeMode = thread.runtimeMode;
const currentProvider: ProviderKind | undefined =
thread.session?.providerName === "codex" ? thread.session.providerName : undefined;
thread.session?.providerName === "codex" ||
thread.session?.providerName === "claudeCode" ||
thread.session?.providerName === "cursor"
? thread.session.providerName
: undefined;
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
const desiredModel = options?.model ?? thread.model;
const effectiveCwd = resolveThreadWorkspaceCwd({
@@ -237,7 +239,6 @@ const make = Effect.gen(function* () {
: {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(desiredModel ? { model: desiredModel } : {}),
...(options?.serviceTier !== undefined ? { serviceTier: options.serviceTier } : {}),
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
@@ -323,7 +324,6 @@ const make = Effect.gen(function* () {
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly provider?: ProviderKind;
readonly model?: string;
readonly serviceTier?: ProviderServiceTier | null;
readonly modelOptions?: ProviderModelOptions;
readonly interactionMode?: "default" | "plan";
readonly createdAt: string;
@@ -335,7 +335,6 @@ const make = Effect.gen(function* () {
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
});
const normalizedInput = toNonEmptyProviderInput(input.messageText);
@@ -355,7 +354,6 @@ const make = Effect.gen(function* () {
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
@@ -470,7 +468,6 @@ const make = Effect.gen(function* () {
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.serviceTier !== undefined ? { serviceTier: event.payload.serviceTier } : {}),
...(event.payload.modelOptions !== undefined ? { modelOptions: event.payload.modelOptions } : {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
@@ -41,7 +41,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
readonly provider: "codex" | "claudeCode" | "cursor";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -65,6 +65,7 @@ function createProviderServiceHarness() {
listSessions: () => Effect.succeed([]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
stopAll: () => Effect.void,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
@@ -436,6 +437,60 @@ describe("ProviderRuntimeIngestion", () => {
);
});
it("accepts claude turn lifecycle when seeded thread id is a synthetic placeholder", async () => {
const harness = await createHarness();
const seededAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-seed-claude-placeholder"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeCode",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: seededAt,
lastError: null,
},
createdAt: seededAt,
}),
);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-claude-placeholder"),
provider: "claudeCode",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-claude-placeholder",
);
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-claude-placeholder"),
provider: "claudeCode",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
status: "completed",
});
await waitForThread(
harness.engine,
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
);
});
it("ignores non-active turn completion when runtime omits thread id", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
+1 -28
View File
@@ -144,7 +144,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
threadId: command.threadId,
});
const threadCreatedEvent: Omit<OrchestrationEvent, "sequence"> = {
return {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
@@ -165,32 +165,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
updatedAt: command.createdAt,
},
};
const seedMessageEvents: ReadonlyArray<Omit<OrchestrationEvent, "sequence">> =
command.seedMessages?.map((message) => ({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
type: "thread.message-sent" as const,
payload: {
threadId: command.threadId,
messageId: message.messageId,
role: message.role,
text: message.text,
attachments: message.attachments,
turnId: null,
streaming: false,
createdAt: message.createdAt,
updatedAt: message.updatedAt,
},
})) ?? [];
return seedMessageEvents.length > 0
? [threadCreatedEvent, ...seedMessageEvents]
: threadCreatedEvent;
}
case "thread.delete": {
@@ -327,7 +301,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
messageId: command.message.messageId,
...(command.provider !== undefined ? { provider: command.provider } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.serviceTier !== undefined ? { serviceTier: command.serviceTier } : {}),
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
runtimeMode:
@@ -444,78 +444,6 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
it.effect("preserves file-read request type when mapping serverRequest/resolved", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
id: asEventId("evt-file-read-request-resolved"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
requestId: ApprovalRequestId.makeUnsafe("req-file-read-1"),
payload: {
request: {
method: "item/fileRead/requestApproval",
},
decision: "accept",
},
};
lifecycleManager.emit("event", event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "request.resolved");
if (firstEvent.value.type !== "request.resolved") {
return;
}
assert.equal(firstEvent.value.payload.requestType, "file_read_approval");
}),
);
it.effect("preserves explicit empty multi-select user-input answers", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
id: asEventId("evt-user-input-empty"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
payload: {
answers: {
scope: [],
},
},
};
lifecycleManager.emit("event", event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "user-input.resolved");
if (firstEvent.value.type !== "user-input.resolved") {
return;
}
assert.deepEqual(firstEvent.value.payload.answers, {
scope: [],
});
}),
);
it.effect("maps windowsSandbox/setupCompleted to session state and warning on failure", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
@@ -274,6 +274,9 @@ function toCanonicalUserInputAnswers(
if (Array.isArray(value)) {
const normalized = value.filter((entry): entry is string => typeof entry === "string");
if (normalized.length === 0) {
return [];
}
return [[questionId, normalized.length === 1 ? normalized[0] : normalized] as const];
}
@@ -281,7 +284,7 @@ function toCanonicalUserInputAnswers(
const answerList = asArray(answerObject?.answers)?.filter(
(entry): entry is string => typeof entry === "string",
);
if (!answerList) {
if (!answerList || answerList.length === 0) {
return [];
}
return [[questionId, answerList.length === 1 ? answerList[0] : answerList] as const];
@@ -1354,7 +1357,6 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
threadId: input.threadId,
...(input.input !== undefined ? { input: input.input } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions?.codex?.reasoningEffort !== undefined
? { effort: input.modelOptions.codex.reasoningEffort }
: {}),
@@ -0,0 +1,655 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import readline from "node:readline";
import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import { Effect, Fiber, Stream } from "effect";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { makeCursorAdapterLive } from "./CursorAdapter.ts";
const THREAD_ID = ThreadId.makeUnsafe("thread-cursor-1");
const RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-cursor-resume");
const LEGACY_RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-cursor-legacy");
class FakeCursorAcpProcess extends EventEmitter {
readonly stdin = new PassThrough();
readonly stdout = new PassThrough();
readonly stderr = new PassThrough();
readonly requests: Array<{ method: string; params: unknown }> = [];
killed = false;
private readonly input = readline.createInterface({ input: this.stdin });
private permissionRequestId = 700;
lastPermissionSelection: string | undefined;
constructor() {
super();
this.input.on("line", (line) => {
const message = JSON.parse(line) as Record<string, unknown>;
if (typeof message.method === "string") {
this.handleRequest(message);
return;
}
if (message.id === this.permissionRequestId) {
const optionId =
(message.result as { outcome?: { optionId?: unknown } } | undefined)?.outcome?.optionId;
if (typeof optionId === "string") {
this.lastPermissionSelection = optionId;
}
}
});
}
kill(): boolean {
if (this.killed) {
return true;
}
this.killed = true;
this.emit("exit", 0, null);
return true;
}
emitPermissionRequest(): void {
this.emitServerMessage({
jsonrpc: "2.0",
id: this.permissionRequestId,
method: "session/request_permission",
params: {
sessionId: "acp-session-1",
toolCall: {
toolCallId: "tool-perm-1",
kind: "execute",
title: "`pwd`",
},
options: [
{ optionId: "allow-once", kind: "allow_once" },
{ optionId: "allow-always", kind: "allow_always" },
{ optionId: "reject-once", kind: "reject_once" },
],
},
});
}
private handleRequest(message: Record<string, unknown>): void {
const method = message.method;
const id = message.id;
if (typeof method !== "string" || (typeof id !== "string" && typeof id !== "number")) {
return;
}
this.requests.push({ method, params: message.params });
switch (method) {
case "initialize": {
const protocolVersion = (message.params as { protocolVersion?: unknown } | undefined)
?.protocolVersion;
if (typeof protocolVersion !== "number") {
this.emitServerMessage({
jsonrpc: "2.0",
id,
error: {
code: -32602,
message: "Invalid params",
data: {
_errors: [],
protocolVersion: {
_errors: ["Invalid input: expected number, received undefined"],
},
},
},
});
return;
}
this.emitServerMessage({
jsonrpc: "2.0",
id,
result: {
protocolVersion: 1,
agentCapabilities: {
loadSession: true,
},
authMethods: [{ id: "cursor_login" }],
},
});
return;
}
case "authenticate":
this.emitServerMessage({
jsonrpc: "2.0",
id,
result: {},
});
return;
case "session/new":
this.emitServerMessage({
jsonrpc: "2.0",
id,
result: {
sessionId: "acp-session-1",
modes: {
currentModeId: "agent",
availableModes: [{ id: "agent" }],
},
},
});
return;
case "session/load":
this.emitServerMessage({
jsonrpc: "2.0",
id,
result: {},
});
return;
case "session/set_model":
this.emitServerMessage({
jsonrpc: "2.0",
id,
result: {},
});
return;
case "session/prompt": {
this.emitServerMessage({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "acp-session-1",
update: {
sessionUpdate: "agent_thought_chunk",
content: {
type: "text",
text: "thinking",
},
},
},
});
this.emitServerMessage({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "acp-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: "hello",
},
},
},
});
this.emitServerMessage({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "acp-session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-1",
kind: "execute",
title: "`pwd`",
rawInput: { command: "pwd" },
},
},
});
this.emitServerMessage({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "acp-session-1",
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-1",
status: "completed",
rawOutput: {
exitCode: 0,
stdout: "/tmp/project",
stderr: "",
},
},
},
});
this.emitServerMessage({
jsonrpc: "2.0",
id,
result: {
stopReason: "end_turn",
},
});
return;
}
case "session/cancel":
this.emitServerMessage({
jsonrpc: "2.0",
id,
error: {
code: -32601,
message: "Method not found",
},
});
return;
default:
this.emitServerMessage({
jsonrpc: "2.0",
id,
error: {
code: -32601,
message: `Unhandled method: ${method}`,
},
});
}
}
private emitServerMessage(message: unknown): void {
this.stdout.write(`${JSON.stringify(message)}\n`);
}
}
describe("CursorAdapterLive", () => {
it.effect("returns validation error for non-cursor provider on startSession", () => {
const fake = new FakeCursorAcpProcess();
const layer = makeCursorAdapterLive({
createProcess: () => fake as never,
});
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const result = yield* adapter
.startSession({
provider: "codex",
threadId: THREAD_ID,
runtimeMode: "full-access",
})
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
if (result._tag !== "Failure") {
return;
}
assert.deepEqual(
result.failure,
new ProviderAdapterValidationError({
provider: "cursor",
operation: "startSession",
issue: "Expected provider 'cursor' but received 'codex'.",
}),
);
}).pipe(Effect.provide(layer));
});
it.effect("maps ACP prompt/update events into canonical runtime events", () => {
const fake = new FakeCursorAcpProcess();
const layer = makeCursorAdapterLive({
createProcess: () => fake as never,
});
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const eventsFiber = yield* Stream.take(adapter.streamEvents, 13).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
provider: "cursor",
threadId: THREAD_ID,
cwd: "/tmp/project",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
const events = Array.from(yield* Fiber.join(eventsFiber));
assert.deepEqual(
events.map((event) => event.type),
[
"session.configured",
"auth.status",
"auth.status",
"session.started",
"thread.started",
"session.state.changed",
"turn.started",
"content.delta",
"content.delta",
"item.started",
"item.completed",
"item.completed",
"turn.completed",
],
);
const turnStarted = events[6];
assert.equal(turnStarted?.type, "turn.started");
if (turnStarted?.type === "turn.started") {
assert.equal(String(turnStarted.turnId), String(turn.turnId));
}
const completion = events[12];
assert.equal(completion?.type, "turn.completed");
if (completion?.type === "turn.completed") {
assert.equal(completion.payload.state, "completed");
}
}).pipe(Effect.provide(layer));
});
it.effect("passes requested model to ACP process startup", () => {
const fake = new FakeCursorAcpProcess();
let createProcessInput:
| {
readonly binaryPath: string;
readonly cwd: string;
readonly env: NodeJS.ProcessEnv;
readonly model?: string;
}
| undefined;
const layer = makeCursorAdapterLive({
createProcess: (input) => {
createProcessInput = input;
return fake as never;
},
});
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
yield* adapter.startSession({
provider: "cursor",
threadId: THREAD_ID,
model: "composer-1.5",
runtimeMode: "full-access",
});
assert.deepEqual(createProcessInput?.model, "composer-1.5");
}).pipe(Effect.provide(layer));
});
it.effect("writes provider-native observability records when enabled", () => {
const nativeEvents: Array<{
event?: {
provider?: string;
method?: string;
threadId?: string;
};
}> = [];
const fake = new FakeCursorAcpProcess();
const layer = makeCursorAdapterLive({
createProcess: () => fake as never,
nativeEventLogger: {
filePath: "memory://cursor-native-events",
write: (event) => {
nativeEvents.push(event as (typeof nativeEvents)[number]);
return Effect.void;
},
close: () => Effect.void,
},
});
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const session = yield* adapter.startSession({
provider: "cursor",
threadId: THREAD_ID,
cwd: "/tmp/project",
runtimeMode: "full-access",
});
assert.equal(nativeEvents.length > 0, true);
assert.equal(nativeEvents.some((record) => record.event?.provider === "cursor"), true);
assert.equal(nativeEvents.some((record) => record.event?.threadId === session.threadId), true);
assert.equal(nativeEvents.some((record) => record.event?.method === "cursor/acp/response"), true);
}).pipe(Effect.provide(layer));
});
it.effect("resumes ACP session using resumeCursor.acpSessionId", () => {
const fake = new FakeCursorAcpProcess();
const layer = makeCursorAdapterLive({
createProcess: () => fake as never,
});
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const session = yield* adapter.startSession({
provider: "cursor",
threadId: RESUME_THREAD_ID,
cwd: "/tmp/project",
resumeCursor: {
acpSessionId: "acp-session-resume",
},
runtimeMode: "full-access",
});
const methods = new Set(fake.requests.map((request) => request.method));
assert.equal(methods.has("session/load"), true);
assert.equal(methods.has("session/new"), false);
const loadRequest = fake.requests.find((request) => request.method === "session/load");
assert.deepEqual(loadRequest?.params, {
sessionId: "acp-session-resume",
cwd: "/tmp/project",
mcpServers: [],
});
assert.equal(session.threadId, RESUME_THREAD_ID);
assert.deepEqual(session.resumeCursor, {
acpSessionId: "acp-session-resume",
});
}).pipe(Effect.provide(layer));
});
it.effect("accepts legacy resumeCursor.sessionId for ACP session resume", () => {
const fake = new FakeCursorAcpProcess();
const layer = makeCursorAdapterLive({
createProcess: () => fake as never,
});
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const session = yield* adapter.startSession({
provider: "cursor",
threadId: LEGACY_RESUME_THREAD_ID,
cwd: "/tmp/project",
resumeCursor: {
sessionId: "acp-session-legacy",
},
runtimeMode: "full-access",
});
const loadRequest = fake.requests.find((request) => request.method === "session/load");
assert.deepEqual(loadRequest?.params, {
sessionId: "acp-session-legacy",
cwd: "/tmp/project",
mcpServers: [],
});
assert.equal(session.threadId, LEGACY_RESUME_THREAD_ID);
assert.deepEqual(session.resumeCursor, {
acpSessionId: "acp-session-legacy",
});
}).pipe(Effect.provide(layer));
});
it.effect("bridges permission requests to request.opened/request.resolved", () => {
const fake = new FakeCursorAcpProcess();
const layer = makeCursorAdapterLive({
createProcess: () => fake as never,
});
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const session = yield* adapter.startSession({
provider: "cursor",
threadId: THREAD_ID,
runtimeMode: "approval-required",
});
// consume startup events
yield* Stream.take(adapter.streamEvents, 6).pipe(Stream.runDrain);
fake.emitPermissionRequest();
const opened = yield* Stream.runHead(adapter.streamEvents);
assert.equal(opened._tag, "Some");
if (opened._tag !== "Some") {
return;
}
assert.equal(opened.value.type, "request.opened");
if (opened.value.type !== "request.opened") {
return;
}
const runtimeRequestId = opened.value.requestId;
assert.equal(typeof runtimeRequestId, "string");
if (runtimeRequestId === undefined) {
return;
}
yield* adapter.respondToRequest(
session.threadId,
ApprovalRequestId.makeUnsafe(runtimeRequestId),
"acceptForSession",
);
const resolved = yield* Stream.runHead(adapter.streamEvents);
assert.equal(resolved._tag, "Some");
if (resolved._tag !== "Some") {
return;
}
assert.equal(resolved.value.type, "request.resolved");
if (resolved.value.type !== "request.resolved") {
return;
}
assert.equal(resolved.value.payload.decision, "acceptForSession");
assert.equal(fake.lastPermissionSelection, "allow-always");
}).pipe(Effect.provide(layer));
});
it.effect("auto-approves cursor permission requests when approval policy is never", () => {
const fake = new FakeCursorAcpProcess();
const layer = makeCursorAdapterLive({
createProcess: () => fake as never,
});
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
yield* adapter.startSession({
provider: "cursor",
threadId: THREAD_ID,
runtimeMode: "full-access",
});
// consume startup events
yield* Stream.take(adapter.streamEvents, 6).pipe(Stream.runDrain);
fake.emitPermissionRequest();
const resolved = yield* Stream.runHead(adapter.streamEvents);
assert.equal(resolved._tag, "Some");
if (resolved._tag !== "Some") {
return;
}
assert.equal(resolved.value.type, "request.resolved");
if (resolved.value.type !== "request.resolved") {
return;
}
assert.equal(resolved.value.payload.decision, "acceptForSession");
assert.equal(fake.lastPermissionSelection, "allow-always");
}).pipe(Effect.provide(layer));
});
it.effect("rejects empty prompt input before starting a turn", () => {
const fake = new FakeCursorAcpProcess();
const layer = makeCursorAdapterLive({
createProcess: () => fake as never,
});
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const session = yield* adapter.startSession({
provider: "cursor",
threadId: THREAD_ID,
runtimeMode: "full-access",
});
yield* Stream.take(adapter.streamEvents, 6).pipe(Stream.runDrain);
const result = yield* adapter
.sendTurn({
threadId: session.threadId,
input: " ",
attachments: [],
})
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
if (result._tag !== "Failure") {
return;
}
assert.deepEqual(
result.failure,
new ProviderAdapterValidationError({
provider: "cursor",
operation: "sendTurn",
issue: "Turn input must be non-empty.",
}),
);
assert.equal(fake.requests.some((request) => request.method === "session/prompt"), false);
}).pipe(Effect.provide(layer));
});
it.effect("keeps tool_call item types consistent through tool_call_update", () => {
const fake = new FakeCursorAcpProcess();
const layer = makeCursorAdapterLive({
createProcess: () => fake as never,
});
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const eventsFiber = yield* Stream.take(adapter.streamEvents, 13).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
provider: "cursor",
threadId: THREAD_ID,
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
const events = Array.from(yield* Fiber.join(eventsFiber));
const started = events.find(
(event) => event.type === "item.started" && String(event.itemId) === "tool-1",
);
const completed = events.find(
(event) => event.type === "item.completed" && String(event.itemId) === "tool-1",
);
assert.equal(started?.type, "item.started");
assert.equal(completed?.type, "item.completed");
if (started?.type !== "item.started" || completed?.type !== "item.completed") {
return;
}
assert.equal(started.payload.itemType, "command_execution");
assert.equal(completed.payload.itemType, "command_execution");
}).pipe(Effect.provide(layer));
});
});
File diff suppressed because it is too large. Load diff
@@ -5,6 +5,7 @@ import { assertFailure } from "@effect/vitest/utils";
import { Effect, Layer, Stream } from "effect";
import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CursorAdapter, CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
import { ProviderUnsupportedError } from "../Errors.ts";
@@ -27,11 +28,30 @@ const fakeCodexAdapter: CodexAdapterShape = {
streamEvents: Stream.empty,
};
const fakeCursorAdapter: CursorAdapterShape = {
provider: "cursor",
capabilities: { sessionModelSwitch: "unsupported" },
startSession: vi.fn(),
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
readThread: vi.fn(),
rollbackThread: vi.fn(),
stopAll: vi.fn(),
streamEvents: Stream.empty,
};
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLive,
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(CursorAdapter, fakeCursorAdapter),
),
),
NodeServices.layer,
),
@@ -42,10 +62,12 @@ layer("ProviderAdapterRegistryLive", (it) => {
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const codex = yield* registry.getByProvider("codex");
const cursor = yield* registry.getByProvider("cursor");
assert.equal(codex, fakeCodexAdapter);
assert.equal(cursor, fakeCursorAdapter);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex"]);
assert.deepEqual(providers, ["codex", "cursor"]);
}),
);
@@ -16,6 +16,7 @@ import {
type ProviderAdapterRegistryShape,
} from "../Services/ProviderAdapterRegistry.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
export interface ProviderAdapterRegistryLiveOptions {
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
@@ -26,7 +27,7 @@ const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOption
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter];
: [yield* CodexAdapter, yield* CursorAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
@@ -42,7 +42,6 @@ import {
makeSqlitePersistenceLive,
SqlitePersistenceMemory,
} from "../../persistence/Layers/Sqlite.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
@@ -52,7 +51,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
readonly provider: "codex" | "claudeCode" | "cursor";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -217,12 +216,15 @@ const sleep = (ms: number) =>
function makeProviderServiceLayer() {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeCode");
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(codex.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
: provider === "claudeCode"
? Effect.succeed(claude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex", "claudeCode"]),
};
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
@@ -236,10 +238,8 @@ function makeProviderServiceLayer() {
makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provideMerge(AnalyticsService.layerTest),
),
directoryLayer,
runtimeRepositoryLayer,
NodeServices.layer,
),
@@ -247,6 +247,7 @@ function makeProviderServiceLayer() {
return {
codex,
claude,
layer,
};
}
@@ -283,7 +284,6 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
Layer.provide(directoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
yield* Effect.gen(function* () {
@@ -342,7 +342,6 @@ it.effect(
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
Layer.provide(firstDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
const startedSession = yield* Effect.gen(function* () {
@@ -356,6 +355,11 @@ it.effect(
});
}).pipe(Effect.provide(firstProviderLayer));
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.stopAll();
}).pipe(Effect.provide(firstProviderLayer));
const persistedAfterStopAll = yield* Effect.gen(function* () {
const repository = yield* ProviderSessionRuntimeRepository;
return yield* repository.getByThreadId({ threadId: startedSession.threadId });
@@ -380,7 +384,6 @@ it.effect(
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
Layer.provide(secondDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
secondCodex.startSession.mockClear();
@@ -493,6 +496,29 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("routes explicit claudeCode provider session starts to the claude adapter", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-claude"), {
provider: "claudeCode",
threadId: asThreadId("thread-claude"),
cwd: "/tmp/project-claude",
runtimeMode: "full-access",
});
assert.equal(session.provider, "claudeCode");
assert.equal(routing.claude.startSession.mock.calls.length, 1);
const startInput = routing.claude.startSession.mock.calls[0]?.[0];
assert.equal(typeof startInput === "object" && startInput !== null, true);
if (startInput && typeof startInput === "object") {
const startPayload = startInput as { provider?: string; cwd?: string };
assert.equal(startPayload.provider, "claudeCode");
assert.equal(startPayload.cwd, "/tmp/project-claude");
}
}),
);
it.effect("recovers stale persisted sessions for rollback by resuming thread identity", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -544,7 +570,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
runtimeMode: "full-access",
});
yield* routing.codex.stopAll();
yield* provider.stopAll();
routing.codex.startSession.mockClear();
routing.codex.sendTurn.mockClear();
@@ -573,7 +599,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("lists no sessions after adapter runtime clears", () =>
it.effect("stops all sessions and clears adapter runtime", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -588,7 +614,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
runtimeMode: "full-access",
});
yield* routing.codex.stopAll();
yield* provider.stopAll();
const remaining = yield* provider.listSessions();
assert.equal(remaining.length, 0);
@@ -636,6 +662,14 @@ routing.layer("ProviderServiceLive routing", (it) => {
}
}
yield* provider.stopAll();
const stoppedRuntime = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(stoppedRuntime), true);
if (Option.isSome(stoppedRuntime)) {
assert.equal(stoppedRuntime.value.status, "stopped");
}
}),
);
});
@@ -31,7 +31,6 @@ import {
type ProviderRuntimeBinding,
} from "../Services/ProviderSessionDirectory.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
export interface ProviderServiceLiveOptions {
readonly canonicalEventLogPath?: string;
@@ -109,7 +108,6 @@ function readPersistedCwd(
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
Effect.gen(function* () {
const analytics = yield* Effect.service(AnalyticsService);
const canonicalEventLogger =
options?.canonicalEventLogger ??
(options?.canonicalEventLogPath !== undefined
@@ -180,11 +178,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const existing = activeSessions.find((session) => session.threadId === input.binding.threadId);
if (existing) {
yield* upsertSessionBinding(existing, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: existing.provider,
strategy: "adopt-existing",
hasResumeCursor: existing.resumeCursor !== undefined,
});
return { adapter, session: existing } as const;
}
}
@@ -213,11 +206,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
yield* upsertSessionBinding(resumed, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: resumed.provider,
strategy: "resume-thread",
hasResumeCursor: resumed.resumeCursor !== undefined,
});
return { adapter, session: resumed } as const;
});
@@ -274,13 +262,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
yield* upsertSessionBinding(session, threadId);
yield* analytics.record("provider.session.started", {
provider: session.provider,
runtimeMode: input.runtimeMode,
hasResumeCursor: session.resumeCursor !== undefined,
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
hasModel: typeof input.model === "string" && input.model.trim().length > 0,
});
return session;
});
@@ -320,13 +301,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
lastRuntimeEventAt: new Date().toISOString(),
},
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
return turn;
});
@@ -343,9 +317,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
allowRecovery: true,
});
yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
yield* analytics.record("provider.turn.interrupted", {
provider: routed.adapter.provider,
});
});
const respondToRequest: ProviderServiceShape["respondToRequest"] = (rawInput) =>
@@ -361,10 +332,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
allowRecovery: true,
});
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
yield* analytics.record("provider.request.responded", {
provider: routed.adapter.provider,
decision: input.decision,
});
});
const respondToUserInput: ProviderServiceShape["respondToUserInput"] = (rawInput) =>
@@ -398,9 +365,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
yield* routed.adapter.stopSession(routed.threadId);
}
yield* directory.remove(input.threadId);
yield* analytics.record("provider.session.stopped", {
provider: routed.adapter.provider,
});
});
const listSessions: ProviderServiceShape["listSessions"] = () =>
@@ -465,13 +429,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
allowRecovery: true,
});
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
yield* analytics.record("provider.conversation.rolled_back", {
provider: routed.adapter.provider,
turns: input.numTurns,
});
});
const runStopAll = () =>
const stopAll: ProviderServiceShape["stopAll"] = () =>
Effect.gen(function* () {
const threadIds = yield* directory.listThreadIds();
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
@@ -491,18 +451,8 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
),
),
).pipe(Effect.asVoid);
yield* analytics.record("provider.sessions.stopped_all", {
sessionCount: threadIds.length,
});
yield* analytics.flush;
});
yield* Effect.addFinalizer(() =>
Effect.catch(runStopAll(), (cause) =>
Effect.logWarning("failed to stop provider service", { cause }),
),
);
return {
startSession,
sendTurn,
@@ -513,6 +463,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
listSessions,
getCapabilities,
rollbackConversation,
stopAll,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
} satisfies ProviderServiceShape;
});
@@ -133,36 +133,6 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
}
}));
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
const threadId = ThreadId.makeUnsafe("thread-provider-change");
yield* runtimeRepository.upsert({
threadId,
providerName: "cursor",
adapterKey: "cursor",
runtimeMode: "full-access",
status: "running",
lastSeenAt: new Date().toISOString(),
resumeCursor: null,
runtimePayload: null,
});
yield* directory.upsert({
provider: "codex",
threadId,
});
const runtime = yield* runtimeRepository.getByThreadId({ threadId });
assert.equal(Option.isSome(runtime), true);
if (Option.isSome(runtime)) {
assert.equal(runtime.value.providerName, "codex");
assert.equal(runtime.value.adapterKey, "codex");
}
}));
it("rehydrates persisted mappings across layer restart", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-directory-"));
@@ -204,4 +174,26 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
fs.rmSync(tempDir, { recursive: true, force: true });
}));
it("accepts cursor provider bindings", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const threadId = ThreadId.makeUnsafe("thread-cursor");
yield* directory.upsert({
provider: "cursor",
threadId,
});
const provider = yield* directory.getProvider(threadId);
assert.equal(provider, "cursor");
const resolvedBinding = yield* directory.getBinding(threadId);
assertSome(resolvedBinding, {
threadId,
provider: "cursor",
});
if (Option.isSome(resolvedBinding)) {
assert.equal(resolvedBinding.value.threadId, threadId);
}
}));
});
@@ -25,7 +25,7 @@ function decodeProviderKind(
providerName: string,
operation: string,
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
if (providerName === "codex") {
if (providerName === "codex" || providerName === "claudeCode" || providerName === "cursor") {
return Effect.succeed(providerName);
}
return Effect.fail(
@@ -95,15 +95,11 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
}
const now = new Date().toISOString();
const providerChanged =
existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
yield* repository
.upsert({
threadId: resolvedThreadId,
providerName: binding.provider,
adapterKey:
binding.adapterKey ??
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
adapterKey: binding.adapterKey ?? existingRuntime?.adapterKey ?? binding.provider,
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
status: binding.status ?? existingRuntime?.status ?? "running",
lastSeenAt: now,
@@ -0,0 +1,131 @@
import { Schema } from "effect";
import { describe, expect, it } from "vitest";
import {
CursorAcpPermissionRequest,
CursorAcpSessionPromptResult,
CursorAcpSessionUpdateNotification,
} from "./CursorAdapter.ts";
describe("Cursor ACP schemas", () => {
it("decodes session/update thought and message chunks", () => {
const thought = Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "sess-1",
update: {
sessionUpdate: "agent_thought_chunk",
content: {
type: "text",
text: "thinking",
},
},
},
});
expect(thought.params.update.sessionUpdate).toBe("agent_thought_chunk");
const message = Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "sess-1",
update: {
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: "hello",
},
},
},
});
expect(message.params.update.sessionUpdate).toBe("agent_message_chunk");
});
it("decodes tool call lifecycle updates", () => {
const started = Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "sess-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-1",
title: "Terminal",
kind: "execute",
status: "pending",
rawInput: { command: "pwd" },
},
},
});
expect(started.params.update.sessionUpdate).toBe("tool_call");
const completed = Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "sess-1",
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-1",
status: "completed",
rawOutput: {
exitCode: 0,
stdout: "ok",
stderr: "",
},
},
},
});
expect(completed.params.update.sessionUpdate).toBe("tool_call_update");
});
it("decodes permission requests", () => {
const decoded = Schema.decodeUnknownSync(CursorAcpPermissionRequest)({
jsonrpc: "2.0",
id: 9,
method: "session/request_permission",
params: {
sessionId: "sess-1",
toolCall: {
toolCallId: "tool-1",
kind: "execute",
},
options: [
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
],
},
});
expect(decoded.method).toBe("session/request_permission");
expect(decoded.params.options).toHaveLength(2);
});
it("decodes prompt completion result payload", () => {
const decoded = Schema.decodeUnknownSync(CursorAcpSessionPromptResult)({
stopReason: "end_turn",
});
expect(decoded.stopReason).toBe("end_turn");
});
it("rejects unsupported update types", () => {
expect(() =>
Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "sess-1",
update: {
sessionUpdate: "unknown_update",
},
},
}),
).toThrow();
});
});
@@ -0,0 +1,110 @@
/**
* CursorAdapter - Cursor ACP implementation of the generic provider adapter contract.
*
* Defines ACP JSON-RPC schemas used by the Cursor adapter layer.
*
* @module CursorAdapter
*/
import { Schema, ServiceMap } from "effect";
import type { ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
export const CursorAcpJsonRpcId = Schema.Union([Schema.String, Schema.Int]);
export type CursorAcpJsonRpcId = typeof CursorAcpJsonRpcId.Type;
export const CursorAcpTextContent = Schema.Struct({
type: Schema.Literal("text"),
text: Schema.String,
});
export type CursorAcpTextContent = typeof CursorAcpTextContent.Type;
export const CursorAcpSessionUpdate = Schema.Union([
Schema.Struct({
sessionUpdate: Schema.Literal("available_commands_update"),
availableCommands: Schema.Array(
Schema.Struct({
name: Schema.String,
description: Schema.optional(Schema.String),
}),
),
}),
Schema.Struct({
sessionUpdate: Schema.Literal("agent_thought_chunk"),
content: CursorAcpTextContent,
}),
Schema.Struct({
sessionUpdate: Schema.Literal("agent_message_chunk"),
content: CursorAcpTextContent,
}),
Schema.Struct({
sessionUpdate: Schema.Literal("tool_call"),
toolCallId: Schema.String,
title: Schema.optional(Schema.String),
kind: Schema.optional(Schema.String),
status: Schema.optional(Schema.String),
rawInput: Schema.optional(Schema.Unknown),
}),
Schema.Struct({
sessionUpdate: Schema.Literal("tool_call_update"),
toolCallId: Schema.String,
status: Schema.String,
rawOutput: Schema.optional(Schema.Unknown),
}),
]);
export type CursorAcpSessionUpdate = typeof CursorAcpSessionUpdate.Type;
export const CursorAcpSessionUpdateNotification = Schema.Struct({
jsonrpc: Schema.optional(Schema.Literal("2.0")),
method: Schema.Literal("session/update"),
params: Schema.Struct({
sessionId: Schema.String,
update: CursorAcpSessionUpdate,
}),
});
export type CursorAcpSessionUpdateNotification = typeof CursorAcpSessionUpdateNotification.Type;
export const CursorAcpPermissionOption = Schema.Struct({
optionId: Schema.String,
name: Schema.optional(Schema.String),
kind: Schema.optional(Schema.String),
});
export type CursorAcpPermissionOption = typeof CursorAcpPermissionOption.Type;
export const CursorAcpPermissionRequest = Schema.Struct({
jsonrpc: Schema.optional(Schema.Literal("2.0")),
id: CursorAcpJsonRpcId,
method: Schema.Literal("session/request_permission"),
params: Schema.Struct({
sessionId: Schema.String,
toolCall: Schema.optional(Schema.Unknown),
options: Schema.Array(CursorAcpPermissionOption),
}),
});
export type CursorAcpPermissionRequest = typeof CursorAcpPermissionRequest.Type;
export const CursorAcpInitializeResult = Schema.Struct({
protocolVersion: Schema.optional(Schema.Int),
agentCapabilities: Schema.optional(Schema.Unknown),
authMethods: Schema.optional(Schema.Array(Schema.Unknown)),
});
export type CursorAcpInitializeResult = typeof CursorAcpInitializeResult.Type;
export const CursorAcpSessionNewResult = Schema.Struct({
sessionId: Schema.String,
modes: Schema.optional(Schema.Unknown),
});
export type CursorAcpSessionNewResult = typeof CursorAcpSessionNewResult.Type;
export const CursorAcpSessionPromptResult = Schema.Struct({
stopReason: Schema.optional(Schema.String),
});
export type CursorAcpSessionPromptResult = typeof CursorAcpSessionPromptResult.Type;
export interface CursorAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
readonly provider: "cursor";
}
export class CursorAdapter extends ServiceMap.Service<CursorAdapter, CursorAdapterShape>()(
"t3/provider/Services/CursorAdapter",
) {}
@@ -99,6 +99,16 @@ export interface ProviderServiceShape {
readonly numTurns: number;
}) => Effect.Effect<void, ProviderServiceError>;
/**
* Stop all active provider sessions.
*
* Persisted session bindings remain so stale sessions can be resumed after
* process restart.
*
* Runtime alias mappings are cleared as part of shutdown.
*/
readonly stopAll: () => Effect.Effect<void, ProviderServiceError>;
/**
* Canonical provider runtime event stream.
*
+6 -2
View File
@@ -19,6 +19,7 @@ import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
import { ProviderUnsupportedError } from "./provider/Errors";
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
import { makeCursorAdapterLive } from "./provider/Layers/CursorAdapter";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
@@ -34,12 +35,11 @@ import { CodexTextGenerationLive } from "./git/Layers/CodexTextGeneration";
import { GitServiceLive } from "./git/Layers/GitService";
import { BunPtyAdapterLive } from "./terminal/Layers/BunPTY";
import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
export function makeServerProviderLayer(): Layer.Layer<
ProviderService,
ProviderUnsupportedError,
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | AnalyticsService
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem
> {
return Effect.gen(function* () {
const { stateDir } = yield* ServerConfig;
@@ -57,8 +57,12 @@ export function makeServerProviderLayer(): Layer.Layer<
const codexAdapterLayer = makeCodexAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const cursorAdapterLayer = makeCursorAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
Layer.provide(codexAdapterLayer),
Layer.provide(cursorAdapterLayer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
return makeProviderServiceLive(
+6 -3
View File
@@ -1,15 +1,18 @@
import fs from "node:fs";
import path from "node:path";
import { Effect, Logger } from "effect";
import { Effect, Logger, Option } from "effect";
import * as Layer from "effect/Layer";
import { ServerConfig } from "./config";
export const ServerLoggerLive = Effect.gen(function* () {
const config = yield* ServerConfig;
const config = yield* Effect.serviceOption(ServerConfig);
if (Option.isNone(config)) {
return Logger.layer([Logger.defaultLogger]);
}
const logDir = path.join(config.stateDir, "logs");
const logDir = path.join(config.value.stateDir, "logs");
const logPath = path.join(logDir, "server.log");
yield* Effect.sync(() => {
-79
View File
@@ -1,79 +0,0 @@
import { Effect, FileSystem, Path, Random, Schema } from "effect";
import * as Crypto from "node:crypto";
import { homedir } from "node:os";
import { ServerConfig } from "../config";
const CodexAuthJsonSchema = Schema.Struct({
tokens: Schema.Struct({
account_id: Schema.String,
}),
});
class IdentifyUserError extends Schema.TaggedErrorClass<IdentifyUserError>()("IdentifyUserError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {}
const hash = (value: string) =>
Effect.try({
try: () => Crypto.createHash("sha256").update(value).digest("hex"),
catch: (error) =>
new IdentifyUserError({
message: "Failed to hash identifier",
cause: error,
}),
});
const getCodexAccountId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const authJsonPath = path.join(homedir(), ".codex", "auth.json");
const authJson = yield* Effect.flatMap(
fileSystem.readFileString(authJsonPath),
Schema.decodeEffect(Schema.fromJsonString(CodexAuthJsonSchema)),
);
return authJson.tokens.account_id;
});
const upsertAnonymousId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const anonymousIdPath = path.join(serverConfig.stateDir, "anonymous-id");
const anonymousId = yield* fileSystem.readFileString(anonymousIdPath).pipe(
Effect.catch(() =>
Effect.gen(function* () {
const randomId = yield* Random.nextUUIDv4;
yield* fileSystem.writeFileString(anonymousIdPath, randomId);
return randomId;
}),
),
);
return anonymousId;
});
/**
* getTelemetryIdentifier - Users are "identified" by finding the first match of the following, then hashing the value.
* 1. ~/.codex/auth.json tokens.account_id
* 2. ~/.t3/telemetry/anonymous-id
*/
export const getTelemetryIdentifier = Effect.gen(function* () {
const codexAccountId = yield* Effect.result(getCodexAccountId);
if (codexAccountId._tag === "Success") {
return yield* hash(codexAccountId.success);
}
const anonymousId = yield* Effect.result(upsertAnonymousId);
if (anonymousId._tag === "Success") {
return yield* hash(anonymousId.success);
}
return null;
}).pipe(
Effect.tapError((error) => Effect.logWarning("Failed to get identifier", { cause: error })),
Effect.orElseSucceed(() => null),
);
@@ -1,122 +0,0 @@
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { ConfigProvider, Effect, FileSystem, Layer } from "effect";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { ServerConfig } from "../../config.ts";
import { getTelemetryIdentifier } from "../Identify.ts";
import { AnalyticsService } from "../Services/AnalyticsService.ts";
import { AnalyticsServiceLayerLive } from "./AnalyticsService.ts";
interface RecordedBatchRequest {
readonly path: string;
readonly body: {
readonly batch?: ReadonlyArray<{
readonly event?: string;
readonly properties?: {
readonly index?: number;
readonly clientType?: string;
};
}>;
} | null;
}
interface RecordedBatchBody {
readonly batch: ReadonlyArray<{
readonly event?: string;
readonly properties?: {
readonly index?: number;
readonly clientType?: string;
};
}>;
}
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
it.effect("flush drains all buffered events across multiple batches", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const stateDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-telemetry-flush-",
});
const capturedRequests: Array<RecordedBatchRequest> = [];
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), stateDir);
const telemetryLayer = AnalyticsServiceLayerLive.pipe(Layer.provideMerge(serverConfigLayer));
const configLayer = ConfigProvider.layer(
ConfigProvider.fromUnknown({
T3CODE_TELEMETRY_ENABLED: true,
T3CODE_POSTHOG_KEY: "phc_test_key",
T3CODE_POSTHOG_HOST: "",
T3CODE_TELEMETRY_FLUSH_BATCH_SIZE: 20,
}),
);
const batchServerLayer = HttpServer.serve(
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
if (request.method !== "POST") {
return HttpServerResponse.empty({ status: 404 });
}
const payload = yield* request.json.pipe(
Effect.map((body) => body as RecordedBatchRequest["body"]),
Effect.catch(() => Effect.succeed(null)),
);
capturedRequests.push({ path: request.url, body: payload });
return HttpServerResponse.jsonUnsafe({});
}),
);
const runtimeLayer = telemetryLayer.pipe(
Layer.provide(configLayer),
Layer.provideMerge(NodeHttpServer.layerTest),
);
yield* Effect.gen(function* () {
yield* Layer.launch(batchServerLayer).pipe(Effect.forkScoped);
const telemetryIdentifier = yield* getTelemetryIdentifier;
assert.equal(telemetryIdentifier !== null, true);
const analytics = yield* AnalyticsService;
for (let index = 0; index < 45; index += 1) {
yield* analytics.record("test.flush.drain", { index });
}
yield* analytics.flush;
}).pipe(Effect.provide(runtimeLayer));
const batchRequests = capturedRequests.filter(
(request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
Array.isArray(request.body?.batch),
);
assert.equal(batchRequests.length, 3);
assert.equal(
batchRequests.every((request) => request.path === "/batch/" || request.path === "/batch"),
true,
);
const deliveredIndexes = batchRequests.flatMap((request) =>
request.body.batch
.filter((event) => event.event === "test.flush.drain")
.map((event) => event.properties?.index)
.filter((index): index is number => typeof index === "number"),
);
const sorted = deliveredIndexes.toSorted((a, b) => a - b);
assert.equal(sorted.length, 45);
assert.deepEqual(
sorted,
Array.from({ length: 45 }, (_, index) => index),
);
assert.equal(
batchRequests.every((request) =>
request.body.batch.every((event) => event.properties?.clientType === "cli-web-client"),
),
true,
);
}),
);
});
@@ -1,151 +0,0 @@
/**
* AnalyticsServiceLive - Anonymous PostHog telemetry layer.
*
* Persists a random installation-scoped anonymous id to state dir, buffers
* events in memory, and flushes batches to PostHog over Effect HttpClient.
*
* @module AnalyticsServiceLive
*/
import { Config, DateTime, Effect, Layer, Ref } from "effect";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { ServerConfig } from "../../config.ts";
import { AnalyticsService, type AnalyticsServiceShape } from "../Services/AnalyticsService.ts";
import { getTelemetryIdentifier } from "../Identify.ts";
import { version } from "../../../package.json" with { type: "json" };
interface BufferedAnalyticsEvent {
readonly event: string;
readonly properties?: Readonly<Record<string, unknown>>;
readonly capturedAt: string;
}
const TelemetryEnvConfig = Config.all({
posthogKey: Config.string("T3CODE_POSTHOG_KEY").pipe(
Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
),
posthogHost: Config.string("T3CODE_POSTHOG_HOST").pipe(
Config.withDefault("https://us.i.posthog.com"),
),
enabled: Config.boolean("T3CODE_TELEMETRY_ENABLED").pipe(Config.withDefault(true)),
flushBatchSize: Config.number("T3CODE_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)),
maxBufferedEvents: Config.number("T3CODE_TELEMETRY_MAX_BUFFERED_EVENTS").pipe(
Config.withDefault(1_000),
),
});
const makeAnalyticsService = Effect.gen(function* () {
const telemetryConfig = yield* TelemetryEnvConfig.asEffect();
const httpClient = yield* HttpClient.HttpClient;
const serverConfig = yield* ServerConfig;
const identifier = yield* getTelemetryIdentifier;
const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>
Effect.flatMap(DateTime.now, (now) =>
Ref.modify(bufferRef, (current) => {
const appended = [
...current,
{
event,
...(properties ? { properties } : {}),
capturedAt: DateTime.formatIso(now),
} satisfies BufferedAnalyticsEvent,
];
const next =
appended.length > telemetryConfig.maxBufferedEvents
? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
: appended;
return [
{
size: next.length,
dropped: next.length !== appended.length,
} as const,
next,
] as const;
}),
);
const sendBatch = (events: ReadonlyArray<BufferedAnalyticsEvent>) =>
Effect.gen(function* () {
if (!telemetryConfig.enabled || !identifier) return;
const payload = {
api_key: telemetryConfig.posthogKey,
batch: events.map((event) => ({
event: event.event,
distinct_id: identifier,
properties: {
...event.properties,
$process_person_profile: false,
platform: process.platform,
wsl: process.env.WSL_DISTRO_NAME,
arch: process.arch,
t3CodeVersion: version,
clientType,
},
timestamp: event.capturedAt,
})),
};
yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
HttpClientRequest.bodyJson(payload),
Effect.flatMap(httpClient.execute),
Effect.flatMap(HttpClientResponse.filterStatusOk),
);
});
const flush: AnalyticsServiceShape["flush"] = Effect.gen(function* () {
while (true) {
const batch = yield* Ref.modify(bufferRef, (current) => {
if (current.length === 0) {
return [[] as ReadonlyArray<BufferedAnalyticsEvent>, current] as const;
}
const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
const remaining = current.slice(nextBatch.length);
return [nextBatch, remaining] as const;
});
if (batch.length === 0) {
return;
}
yield* sendBatch(batch).pipe(
Effect.catch((error) =>
Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
Effect.flatMap(() => Effect.fail(error)),
),
),
);
}
}).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
const record: AnalyticsServiceShape["record"] = Effect.fnUntraced(function* (event, properties) {
if (!telemetryConfig.enabled || !identifier) return;
const enqueueResult = yield* enqueueBufferedEvent(event, properties);
if (enqueueResult.dropped) {
yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
size: enqueueResult.size,
event,
});
}
});
yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
disableYield: true,
}).pipe(Effect.forkScoped);
yield* Effect.addFinalizer(() => flush);
return {
record,
flush,
} satisfies AnalyticsServiceShape;
});
export const AnalyticsServiceLayerLive = Layer.effect(AnalyticsService, makeAnalyticsService);
@@ -1,33 +0,0 @@
/**
* AnalyticsService - Anonymous telemetry capture contract.
*
* Provides a best-effort event API for runtime telemetry and a strict
* `captureImmediate` method for call sites that need explicit error handling.
*
* @module AnalyticsService
*/
import { Effect, Layer, ServiceMap } from "effect";
export interface AnalyticsServiceShape {
/**
* Capture an event immediately; returns typed failure when capture fails.
*/
readonly record: (
event: string,
properties?: Readonly<Record<string, unknown>>,
) => Effect.Effect<void, never>;
/**
* Flush queued telemetry.
*/
readonly flush: Effect.Effect<void, never>;
}
export class AnalyticsService extends ServiceMap.Service<AnalyticsService, AnalyticsServiceShape>()(
"t3/telemetry/Services/AnalyticsService",
) {
static readonly layerTest = Layer.succeed(AnalyticsService, {
record: () => Effect.void,
flush: Effect.void,
});
}
+6 -70
View File
@@ -50,7 +50,6 @@ import type { GitCoreShape } from "./git/Services/GitCore.ts";
import { GitCore } from "./git/Services/GitCore.ts";
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
interface PendingMessages {
queue: unknown[];
@@ -394,7 +393,10 @@ describe("WebSocket Server", () => {
providerHealth?: ProviderHealthShape;
open?: OpenShape;
gitManager?: GitManagerShape;
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
gitCore?: Pick<
GitCoreShape,
"listBranches" | "initRepo" | "pullCurrentBranch"
>;
terminalManager?: TerminalManagerShape;
} = {},
): Promise<Http.Server> {
@@ -435,7 +437,6 @@ describe("WebSocket Server", () => {
? Layer.succeed(TerminalManager, options.terminalManager)
: Layer.empty,
);
const runtimeLayer = Layer.merge(
Layer.merge(
makeServerRuntimeServicesLayer().pipe(Layer.provide(infrastructureLayer)),
@@ -448,7 +449,6 @@ describe("WebSocket Server", () => {
Layer.provideMerge(providerHealthLayer),
Layer.provideMerge(openLayer),
Layer.provideMerge(serverConfigLayer),
Layer.provideMerge(AnalyticsService.layerTest),
Layer.provideMerge(NodeServices.layer),
);
const runtimeServices = await Effect.runPromise(
@@ -1143,72 +1143,6 @@ describe("WebSocket Server", () => {
expect(response.error?.message).toContain("exceeds current turn count");
});
it("returns seeded thread messages in snapshots after thread creation", async () => {
server = await createTestServer({ cwd: "/test" });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const createdAt = new Date().toISOString();
const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
type: "project.create",
commandId: "cmd-seed-project-create",
projectId: "project-seed",
title: "Seed Project",
workspaceRoot: "/tmp/ws-seed-project",
defaultModel: "gpt-5-codex",
createdAt,
});
expect(createProjectResponse.error).toBeUndefined();
const createThreadResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
type: "thread.create",
commandId: "cmd-seed-thread-create",
threadId: "thread-seed",
projectId: "project-seed",
title: "Seed Thread",
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
seedMessages: [
{
messageId: "msg-seed-1",
role: "user",
text: "seeded question",
attachments: [],
createdAt: "2026-02-01T00:00:00.000Z",
updatedAt: "2026-02-01T00:00:00.000Z",
},
{
messageId: "msg-seed-2",
role: "assistant",
text: "seeded answer",
attachments: [],
createdAt: "2026-02-01T00:00:01.000Z",
updatedAt: "2026-02-01T00:00:01.000Z",
},
],
createdAt,
});
expect(createThreadResponse.error).toBeUndefined();
const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot);
expect(snapshotResponse.error).toBeUndefined();
const snapshot = snapshotResponse.result as {
threads: Array<{ id: string; messages: Array<{ text: string }> }>;
};
const thread = snapshot.threads.find((entry) => entry.id === "thread-seed");
expect(thread?.messages.map((message) => message.text)).toEqual([
"seeded question",
"seeded answer",
]);
});
it("keeps orchestration domain push behavior for provider runtime events", async () => {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const emitRuntimeEvent = (event: ProviderRuntimeEvent) => {
@@ -1237,6 +1171,7 @@ describe("WebSocket Server", () => {
listSessions: () => Effect.succeed([]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
stopAll: () => Effect.void,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
const providerLayer = Layer.succeed(ProviderService, providerService);
@@ -1685,6 +1620,7 @@ describe("WebSocket Server", () => {
expect(pullResponse.result).toBeUndefined();
expect(pullResponse.error?.message).toContain("No upstream configured");
expect(pullCurrentBranch).toHaveBeenCalledWith("/repo/path");
});
it("supports git.status over websocket", async () => {
+7 -3
View File
@@ -71,7 +71,6 @@ import {
resolveAttachmentPathById,
} from "./attachmentStore.ts";
import { parseBase64DataUrl } from "./imageMime.ts";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
/**
* ServerShape - Service API for server lifecycle control.
@@ -208,8 +207,7 @@ export type ServerRuntimeServices =
| GitCore
| TerminalManager
| Keybindings
| Open
| AnalyticsService;
| Open;
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
"ServerLifecycleError",
@@ -568,6 +566,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
const checkpointDiffQuery = yield* CheckpointDiffQuery;
const liveProviderService = yield* ProviderService;
const orchestrationReactor = yield* OrchestrationReactor;
const { openInEditor } = yield* Open;
@@ -659,6 +658,11 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
}
const runPromise = yield* Effect.map(Effect.services<never>(), Effect.runPromiseWith);
yield* Effect.addFinalizer(() =>
Effect.catch(liveProviderService.stopAll(), (cause) =>
Effect.logWarning("failed to stop provider service", { cause }),
),
);
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
(event) => void Effect.runPromise(onTerminalEvent(event)),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.0-alpha.22",
"version": "0.0.0-alpha.20",
"private": true,
"type": "module",
"scripts": {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1003 B

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 204 KiB

After

Width:  |  Height:  |  Size: 279 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

+22 -33
View File
@@ -1,13 +1,6 @@
import { describe, expect, it } from "vitest";
import {
getAppModelOptions,
getSlashModelOptions,
normalizeCustomModelSlugs,
resolveAppServiceTier,
shouldShowFastTierIcon,
resolveAppModelSelection,
} from "./appSettings";
import { getAppModelOptions, getSlashModelOptions, normalizeCustomModelSlugs } from "./appSettings";
describe("normalizeCustomModelSlugs", () => {
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
@@ -22,6 +15,17 @@ describe("normalizeCustomModelSlugs", () => {
]),
).toEqual(["custom/internal-model"]);
});
it("normalizes provider-specific aliases for claude and cursor", () => {
expect(normalizeCustomModelSlugs(["sonnet"], "claudeCode")).toEqual([]);
expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeCode")).toEqual([
"claude/custom-sonnet",
]);
expect(normalizeCustomModelSlugs(["composer"], "cursor")).toEqual([]);
expect(normalizeCustomModelSlugs(["cursor/custom-model"], "cursor")).toEqual([
"cursor/custom-model",
]);
});
});
describe("getAppModelOptions", () => {
@@ -47,18 +51,14 @@ describe("getAppModelOptions", () => {
isCustom: true,
});
});
});
describe("resolveAppModelSelection", () => {
it("preserves saved custom model slugs instead of falling back to the default", () => {
expect(resolveAppModelSelection("codex", ["galapagos-alpha"], "galapagos-alpha")).toBe(
"galapagos-alpha",
it("keeps a saved custom provider model available as an exact slug option", () => {
const options = getAppModelOptions("claudeCode", ["claude/custom-opus"], "claude/custom-opus");
expect(options.some((option) => option.slug === "claude/custom-opus" && option.isCustom)).toBe(
true,
);
});
it("falls back to the provider default when no model is selected", () => {
expect(resolveAppModelSelection("codex", [], "")).toBe("gpt-5.4");
});
});
describe("getSlashModelOptions", () => {
@@ -83,23 +83,12 @@ describe("getSlashModelOptions", () => {
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
});
});
describe("resolveAppServiceTier", () => {
it("maps automatic to no override", () => {
expect(resolveAppServiceTier("auto")).toBeNull();
});
it("includes provider-specific custom slugs in non-codex model lists", () => {
const claudeOptions = getAppModelOptions("claudeCode", ["claude/custom-opus"]);
const cursorOptions = getAppModelOptions("cursor", ["cursor/custom-model"]);
it("preserves explicit service tier overrides", () => {
expect(resolveAppServiceTier("fast")).toBe("fast");
expect(resolveAppServiceTier("flex")).toBe("flex");
});
});
describe("shouldShowFastTierIcon", () => {
it("shows the fast-tier icon only for gpt-5.4 on fast tier", () => {
expect(shouldShowFastTierIcon("gpt-5.4", "fast")).toBe(true);
expect(shouldShowFastTierIcon("gpt-5.4", "auto")).toBe(false);
expect(shouldShowFastTierIcon("gpt-5.3-codex", "fast")).toBe(false);
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
expect(cursorOptions.some((option) => option.slug === "cursor/custom-model")).toBe(true);
});
});
+12 -71
View File
@@ -1,33 +1,15 @@
import { useCallback, useSyncExternalStore } from "react";
import { Option, Schema } from "effect";
import { type ProviderKind, type ProviderServiceTier } from "@t3tools/contracts";
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
import { type ProviderKind } from "@t3tools/contracts";
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
export const APP_SERVICE_TIER_OPTIONS = [
{
value: "auto",
label: "Automatic",
description: "Use Codex defaults without forcing a service tier.",
},
{
value: "fast",
label: "Fast",
description: "Request the fast service tier when the model supports it.",
},
{
value: "flex",
label: "Flex",
description: "Request the flex service tier when the model supports it.",
},
] as const;
export type AppServiceTier = (typeof APP_SERVICE_TIER_OPTIONS)[number]["value"];
const AppServiceTierSchema = Schema.Literals(["auto", "fast", "flex"]);
const MODELS_WITH_FAST_SUPPORT = new Set(["gpt-5.4"]);
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
claudeCode: new Set(getModelOptions("claudeCode").map((option) => option.slug)),
cursor: new Set(getModelOptions("cursor").map((option) => option.slug)),
};
const AppSettingsSchema = Schema.Struct({
@@ -41,10 +23,15 @@ const AppSettingsSchema = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(
Schema.withConstructorDefault(() => Option.some(false)),
),
codexServiceTier: AppServiceTierSchema.pipe(Schema.withConstructorDefault(() => Option.some("auto"))),
customCodexModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
customClaudeModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
customCursorModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
});
export type AppSettings = typeof AppSettingsSchema.Type;
export interface AppModelOption {
@@ -53,22 +40,6 @@ export interface AppModelOption {
isCustom: boolean;
}
export function resolveAppServiceTier(serviceTier: AppServiceTier): ProviderServiceTier | null {
return serviceTier === "auto" ? null : serviceTier;
}
export function shouldShowFastTierIcon(
model: string | null | undefined,
serviceTier: AppServiceTier,
): boolean {
const normalizedModel = normalizeModelSlug(model);
return (
resolveAppServiceTier(serviceTier) === "fast" &&
normalizedModel !== null &&
MODELS_WITH_FAST_SUPPORT.has(normalizedModel)
);
}
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
let listeners: Array<() => void> = [];
@@ -108,6 +79,8 @@ function normalizeAppSettings(settings: AppSettings): AppSettings {
return {
...settings,
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeCode"),
customCursorModels: normalizeCustomModelSlugs(settings.customCursorModels, "cursor"),
};
}
@@ -148,38 +121,6 @@ export function getAppModelOptions(
return options;
}
export function resolveAppModelSelection(
provider: ProviderKind,
customModels: readonly string[],
selectedModel: string | null | undefined,
): string {
const options = getAppModelOptions(provider, customModels, selectedModel);
const trimmedSelectedModel = selectedModel?.trim();
if (trimmedSelectedModel) {
const direct = options.find((option) => option.slug === trimmedSelectedModel);
if (direct) {
return direct.slug;
}
const byName = options.find(
(option) => option.name.toLowerCase() === trimmedSelectedModel.toLowerCase(),
);
if (byName) {
return byName.slug;
}
}
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
if (!normalizedSelectedModel) {
return getDefaultModel(provider);
}
return (
options.find((option) => option.slug === normalizedSelectedModel)?.slug ??
getDefaultModel(provider)
);
}
export function getSlashModelOptions(
provider: ProviderKind,
customModels: readonly string[],
@@ -19,7 +19,6 @@ import { page } from "vitest/browser";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
import { getRouter } from "../router";
import { useStore } from "../store";
import { estimateTimelineMessageHeight } from "./timelineHeight";
@@ -45,7 +44,6 @@ interface TestFixture {
}
let fixture: TestFixture;
const wsRequests: WsRequestEnvelope["body"][] = [];
const wsLink = ws.link(/ws(s)?:\/\/.*/);
interface ViewportSpec {
@@ -245,17 +243,6 @@ function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
};
}
function createDraftOnlySnapshot(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-draft-target" as MessageId,
targetText: "draft thread",
});
return {
...snapshot,
threads: [],
};
}
function resolveWsRpc(tag: string): unknown {
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
return fixture.snapshot;
@@ -320,7 +307,6 @@ const worker = setupWorker(
}
const method = request.body?._tag;
if (typeof method !== "string") return;
wsRequests.push(request.body);
client.send(
JSON.stringify({
id: request.id,
@@ -392,23 +378,6 @@ async function waitForElement<T extends Element>(
return element;
}
async function waitForComposerEditor(): Promise<HTMLElement> {
return waitForElement(
() => document.querySelector<HTMLElement>('[contenteditable="true"]'),
"Unable to find composer editor.",
);
}
async function waitForInteractionModeButton(expectedLabel: "Chat" | "Plan"): Promise<HTMLButtonElement> {
return waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === expectedLabel,
) as HTMLButtonElement | null,
`Unable to find ${expectedLabel} interaction mode button.`,
);
}
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
const images = Array.from(scope.querySelectorAll("img"));
if (images.length === 0) {
@@ -497,10 +466,8 @@ async function measureUserRow(options: {
async function mountChatView(options: {
viewport: ViewportSpec;
snapshot: OrchestrationReadModel;
configureFixture?: (fixture: TestFixture) => void;
}): Promise<MountedChatView> {
fixture = buildFixture(options.snapshot);
options.configureFixture?.(fixture);
await setViewport(options.viewport);
await waitForProductionStyles();
@@ -580,12 +547,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
await setViewport(DEFAULT_VIEWPORT);
localStorage.clear();
document.body.innerHTML = "";
wsRequests.length = 0;
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
useStore.setState({
projects: [],
threads: [],
@@ -747,124 +708,4 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
},
);
it("opens the project cwd for draft threads without a worktree path", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
envMode: "local",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createDraftOnlySnapshot(),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
availableEditors: ["vscode"],
};
},
});
try {
const openButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "Open",
) as HTMLButtonElement | null,
"Unable to find Open button.",
);
openButton.click();
await vi.waitFor(
() => {
const openRequest = wsRequests.find((request) => request._tag === WS_METHODS.shellOpenInEditor);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.shellOpenInEditor,
cwd: "/repo/project",
editor: "vscode",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-target-hotkey" as MessageId,
targetText: "hotkey target",
}),
});
try {
const initialModeButton = await waitForInteractionModeButton("Chat");
expect(initialModeButton.title).toContain("enter plan mode");
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Tab",
shiftKey: true,
bubbles: true,
cancelable: true,
}),
);
await waitForLayout();
expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
composerEditor.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Tab",
shiftKey: true,
bubbles: true,
cancelable: true,
}),
);
await vi.waitFor(
async () => {
expect((await waitForInteractionModeButton("Plan")).title).toContain(
"return to normal chat mode",
);
},
{ timeout: 8_000, interval: 16 },
);
composerEditor.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Tab",
shiftKey: true,
bubbles: true,
cancelable: true,
}),
);
await vi.waitFor(
async () => {
expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
});
File diff suppressed because it is too large. Load diff
@@ -1,83 +0,0 @@
import { describe, expect, it } from "vitest";
import { planBranchedThread } from "./Sidebar.logic";
describe("planBranchedThread", () => {
it("reuses the source branch without cloning a worktree for local threads", () => {
expect(
planBranchedThread({
thread: {
title: "Original thread",
branch: "feature/original",
worktreePath: null,
},
projectCwd: "/repo",
}),
).toEqual({
title: "Branch of Original thread",
branch: "feature/original",
worktreePath: null,
createWorktree: null,
});
});
it("requests a fresh worktree when branching a worktree-backed thread", () => {
expect(
planBranchedThread({
thread: {
title: "Original thread",
branch: "feature/original",
worktreePath: "/tmp/original",
},
projectCwd: "/repo",
}),
).toEqual({
title: "Branch of Original thread",
branch: "feature/original",
worktreePath: null,
createWorktree: {
cwd: "/repo",
branch: "feature/original",
},
});
});
it("uses a generic fallback title when the source title is blank", () => {
expect(
planBranchedThread({
thread: {
title: " ",
branch: null,
worktreePath: null,
},
projectCwd: "/repo",
}).title,
).toBe("Branched thread");
});
it("rejects worktree threads that are missing a branch", () => {
expect(() =>
planBranchedThread({
thread: {
title: "Original thread",
branch: null,
worktreePath: "/tmp/original",
},
projectCwd: "/repo",
}),
).toThrow("Cannot branch a worktree thread without a branch.");
});
it("rejects worktree threads when the project cwd is unavailable", () => {
expect(() =>
planBranchedThread({
thread: {
title: "Original thread",
branch: "feature/original",
worktreePath: "/tmp/original",
},
projectCwd: null,
}),
).toThrow("Project working directory is unavailable.");
});
});
-42
View File
@@ -1,42 +0,0 @@
import type { Thread } from "../types";
import { truncateTitle } from "../truncateTitle";
export interface BranchedThreadPlan {
title: string;
branch: string | null;
worktreePath: string | null;
createWorktree: {
cwd: string;
branch: string;
} | null;
}
export function planBranchedThread(input: {
thread: Pick<Thread, "title" | "branch" | "worktreePath">;
projectCwd: string | null;
}): BranchedThreadPlan {
const { thread, projectCwd } = input;
if (thread.worktreePath) {
if (!thread.branch) {
throw new Error("Cannot branch a worktree thread without a branch.");
}
if (!projectCwd) {
throw new Error("Project working directory is unavailable.");
}
}
return {
title: truncateTitle(
thread.title.trim().length > 0 ? `Branch of ${thread.title}` : "Branched thread",
),
branch: thread.branch,
worktreePath: null,
createWorktree: thread.worktreePath
? {
cwd: projectCwd!,
branch: thread.branch!,
}
: null,
};
}
+4 -54
View File
@@ -9,7 +9,7 @@ import {
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
DEFAULT_RUNTIME_MODE,
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_MODEL,
type DesktopUpdateState,
ProjectId,
ThreadId,
@@ -26,11 +26,7 @@ import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
import { type Thread } from "../types";
import { derivePendingApprovals } from "../session-logic";
import {
gitCreateWorktreeMutationOptions,
gitRemoveWorktreeMutationOptions,
gitStatusQueryOptions,
} from "../lib/gitReactQuery";
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
@@ -64,7 +60,6 @@ import {
} from "./ui/sidebar";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { isNonEmpty as isNonEmptyString } from "effect/String";
import { branchConversationThread, createBranchedThreadWorktree } from "./threadBranching";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
@@ -265,7 +260,6 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
export default function Sidebar() {
const projects = useStore((store) => store.projects);
const threads = useStore((store) => store.threads);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const markThreadUnread = useStore((store) => store.markThreadUnread);
const toggleProject = useStore((store) => store.toggleProject);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
@@ -273,7 +267,6 @@ export default function Sidebar() {
(store) => store.getDraftThreadByProjectId,
);
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const setBootstrapMessages = useComposerDraftStore((store) => store.setBootstrapMessages);
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
@@ -295,7 +288,6 @@ export default function Sidebar() {
select: (config) => config.keybindings,
});
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
@@ -514,7 +506,7 @@ export default function Sidebar() {
projectId,
title,
workspaceRoot: cwd,
defaultModel: DEFAULT_MODEL_BY_PROVIDER.codex,
defaultModel: DEFAULT_MODEL,
createdAt,
})
.then(() => true)
@@ -596,40 +588,12 @@ export default function Sidebar() {
[],
);
const branchConversation = useCallback(
async (thread: Thread) => {
const api = readNativeApi();
if (!api) return;
await branchConversationThread({
api,
thread,
seedMessages: thread.messages,
projectCwd: projectCwdById.get(thread.projectId) ?? null,
createWorktree: ({ cwd, branch }) =>
createBranchedThreadWorktree({
createWorktree: (args) => createWorktreeMutation.mutateAsync(args),
cwd,
branch,
}),
syncServerReadModel,
setBootstrapMessages,
navigateToThread: (threadId) =>
navigate({
to: "/$threadId",
params: { threadId },
}),
});
},
[createWorktreeMutation, navigate, projectCwdById, setBootstrapMessages, syncServerReadModel],
);
const handleThreadContextMenu = useCallback(
async (threadId: ThreadId, position: { x: number; y: number }) => {
const api = readNativeApi();
if (!api) return;
const clicked = await api.contextMenu.show(
[
{ id: "branch", label: "Branch conversation" },
{ id: "rename", label: "Rename thread" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-thread-id", label: "Copy Thread ID" },
@@ -640,19 +604,6 @@ export default function Sidebar() {
const thread = threads.find((t) => t.id === threadId);
if (!thread) return;
if (clicked === "branch") {
try {
await branchConversation(thread);
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to branch conversation",
description: error instanceof Error ? error.message : "An error occurred.",
});
}
return;
}
if (clicked === "rename") {
setRenamingThreadId(threadId);
setRenamingTitle(thread.title);
@@ -782,7 +733,6 @@ export default function Sidebar() {
clearComposerDraftForThread,
clearProjectDraftThreadById,
clearTerminalState,
branchConversation,
markThreadUnread,
navigate,
projects,
@@ -935,7 +885,7 @@ export default function Sidebar() {
? "text-sky-400"
: shouldHighlightDesktopUpdateError(desktopUpdateState)
? "text-rose-500 animate-pulse"
: "text-amber-500 animate-pulse";
: "text-amber-500 animate-pulse";
const newThreadShortcutLabel = useMemo(
() =>
shortcutLabelForCommand(keybindings, "chat.newLocal") ??
@@ -1,69 +0,0 @@
import { MessageId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import type { ChatMessage } from "../types";
import { selectBranchedMessages } from "./threadBranching";
function messageId(value: string): MessageId {
return MessageId.makeUnsafe(value);
}
function makeMessage(input: {
id: string;
role: ChatMessage["role"];
text: string;
createdAt?: string;
}): ChatMessage {
return {
id: messageId(input.id),
role: input.role,
text: input.text,
createdAt: input.createdAt ?? "2026-03-05T00:00:00.000Z",
streaming: false,
};
}
describe("selectBranchedMessages", () => {
it("returns the full transcript when no target message is provided", () => {
const messages = [
makeMessage({ id: "msg-1", role: "user", text: "first" }),
makeMessage({ id: "msg-2", role: "assistant", text: "second" }),
];
expect(selectBranchedMessages({ messages })).toEqual(messages);
});
it("returns messages up to and including the targeted assistant message", () => {
const messages = [
makeMessage({ id: "msg-1", role: "user", text: "first" }),
makeMessage({ id: "msg-2", role: "assistant", text: "second" }),
makeMessage({ id: "msg-3", role: "user", text: "third" }),
makeMessage({ id: "msg-4", role: "assistant", text: "fourth" }),
];
expect(
selectBranchedMessages({
messages,
targetMessageId: messageId("msg-2"),
}).map((message) => message.id),
).toEqual([messageId("msg-1"), messageId("msg-2")]);
});
it("rejects non-assistant branch targets", () => {
expect(() =>
selectBranchedMessages({
messages: [makeMessage({ id: "msg-1", role: "user", text: "first" })],
targetMessageId: messageId("msg-1"),
}),
).toThrow("Can only branch from an assistant message.");
});
it("rejects missing branch targets", () => {
expect(() =>
selectBranchedMessages({
messages: [makeMessage({ id: "msg-1", role: "assistant", text: "first" })],
targetMessageId: messageId("missing"),
}),
).toThrow("Branch target message was not found.");
});
});
-106
View File
@@ -1,106 +0,0 @@
import type { MessageId, NativeApi, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
import { newCommandId, newThreadId } from "../lib/utils";
import type { ChatMessage, Thread } from "../types";
import { buildTemporaryWorktreeBranchName } from "../worktreeBranches";
import { planBranchedThread } from "./Sidebar.logic";
export function selectBranchedMessages(input: {
messages: ReadonlyArray<ChatMessage>;
targetMessageId?: MessageId | null;
}): ChatMessage[] {
if (!input.targetMessageId) {
return [...input.messages];
}
const targetIndex = input.messages.findIndex((message) => message.id === input.targetMessageId);
if (targetIndex < 0) {
throw new Error("Branch target message was not found.");
}
const targetMessage = input.messages[targetIndex];
if (!targetMessage || targetMessage.role !== "assistant") {
throw new Error("Can only branch from an assistant message.");
}
return input.messages.slice(0, targetIndex + 1);
}
export async function branchConversationThread(input: {
api: NativeApi;
thread: Thread;
seedMessages: ChatMessage[];
projectCwd: string | null;
createWorktree: (args: { cwd: string; branch: string }) => Promise<{
branch: string;
path: string;
}>;
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
setBootstrapMessages: (threadId: ThreadId, messages: ChatMessage[]) => void;
navigateToThread: (threadId: ThreadId) => Promise<void>;
}): Promise<ThreadId> {
const branchedThreadId = newThreadId();
const createdAt = new Date().toISOString();
const plan = planBranchedThread({ thread: input.thread, projectCwd: input.projectCwd });
let branchedThreadBranch = plan.branch;
let branchedThreadWorktreePath = plan.worktreePath;
if (plan.createWorktree) {
const result = await input.createWorktree({
cwd: plan.createWorktree.cwd,
branch: plan.createWorktree.branch,
});
branchedThreadBranch = result.branch;
branchedThreadWorktreePath = result.path;
}
await input.api.orchestration.dispatchCommand({
type: "thread.create",
commandId: newCommandId(),
threadId: branchedThreadId,
projectId: input.thread.projectId,
title: plan.title,
model: input.thread.model,
runtimeMode: input.thread.runtimeMode,
interactionMode: input.thread.interactionMode,
branch: branchedThreadBranch,
worktreePath: branchedThreadWorktreePath,
seedMessages: input.seedMessages.map((message) => ({
messageId: message.id,
role: message.role,
text: message.text,
attachments: message.attachments ?? [],
createdAt: message.createdAt,
updatedAt: message.completedAt ?? message.createdAt,
})),
createdAt,
});
const snapshot = await input.api.orchestration.getSnapshot();
input.syncServerReadModel(snapshot);
if (input.seedMessages.length > 0) {
input.setBootstrapMessages(branchedThreadId, input.seedMessages);
}
await input.navigateToThread(branchedThreadId);
return branchedThreadId;
}
export async function createBranchedThreadWorktree(input: {
createWorktree: (args: { cwd: string; branch: string; newBranch: string }) => Promise<{
worktree: { branch: string; path: string };
}>;
cwd: string;
branch: string;
}): Promise<{ branch: string; path: string }> {
const result = await input.createWorktree({
cwd: input.cwd,
branch: input.branch,
newBranch: buildTemporaryWorktreeBranchName(),
});
return {
branch: result.worktree.branch,
path: result.worktree.path,
};
}
+4 -33
View File
@@ -1,4 +1,4 @@
import { MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { type ComposerImageAttachment, useComposerDraftStore } from "./composerDraftStore";
@@ -152,35 +152,6 @@ describe("composerDraftStore clearComposerContent", () => {
expect(draft).toBeUndefined();
expect(revokeSpy).not.toHaveBeenCalledWith("blob:optimistic");
});
it("preserves hidden bootstrap transcript state", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(threadId, "draft prompt");
store.setBootstrapMessages(threadId, [
{
id: MessageId.makeUnsafe("msg-bootstrap"),
role: "user",
text: "Earlier context",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
]);
store.clearComposerContent(threadId);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
prompt: "",
bootstrapMessages: [
{
id: "msg-bootstrap",
role: "user",
text: "Earlier context",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
],
});
});
});
describe("composerDraftStore project draft thread mapping", () => {
@@ -423,15 +394,15 @@ describe("composerDraftStore setProvider", () => {
it("persists provider-only selection even when prompt/model are empty", () => {
const store = useComposerDraftStore.getState();
store.setProvider(threadId, "codex");
store.setProvider(threadId, "cursor");
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.provider).toBe("codex");
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.provider).toBe("cursor");
});
it("removes empty provider-only draft when provider is reset", () => {
const store = useComposerDraftStore.getState();
store.setProvider(threadId, "codex");
store.setProvider(threadId, "cursor");
store.setProvider(threadId, null);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
+1 -154
View File
@@ -1,6 +1,5 @@
import {
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
MessageId,
ProjectId,
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
ThreadId,
@@ -14,7 +13,6 @@ import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type ChatImageAttachment,
type ChatMessage,
} from "./types";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
@@ -38,7 +36,6 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
interface PersistedComposerThreadDraftState {
prompt: string;
attachments: PersistedComposerImageAttachment[];
bootstrapMessages?: ChatMessage[];
provider?: ProviderKind | null;
model?: string | null;
runtimeMode?: RuntimeMode | null;
@@ -69,7 +66,6 @@ interface ComposerThreadDraftState {
images: ComposerImageAttachment[];
nonPersistedImageIds: string[];
persistedAttachments: PersistedComposerImageAttachment[];
bootstrapMessages: ChatMessage[];
provider: ProviderKind | null;
model: string | null;
runtimeMode: RuntimeMode | null;
@@ -126,8 +122,6 @@ interface ComposerDraftStoreState {
clearProjectDraftThreadById: (projectId: ProjectId, threadId: ThreadId) => void;
clearDraftThread: (threadId: ThreadId) => void;
setPrompt: (threadId: ThreadId, prompt: string) => void;
setBootstrapMessages: (threadId: ThreadId, messages: ChatMessage[]) => void;
clearBootstrapMessages: (threadId: ThreadId) => void;
setProvider: (threadId: ThreadId, provider: ProviderKind | null | undefined) => void;
setModel: (threadId: ThreadId, model: string | null | undefined) => void;
setRuntimeMode: (threadId: ThreadId, runtimeMode: RuntimeMode | null | undefined) => void;
@@ -158,17 +152,14 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE: PersistedComposerDraftStoreState = {
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
const EMPTY_IDS: string[] = [];
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
const EMPTY_BOOTSTRAP_MESSAGES: ChatMessage[] = [];
Object.freeze(EMPTY_IMAGES);
Object.freeze(EMPTY_IDS);
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
Object.freeze(EMPTY_BOOTSTRAP_MESSAGES);
const EMPTY_THREAD_DRAFT = Object.freeze({
prompt: "",
images: EMPTY_IMAGES,
nonPersistedImageIds: EMPTY_IDS,
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
bootstrapMessages: EMPTY_BOOTSTRAP_MESSAGES,
provider: null,
model: null,
runtimeMode: null,
@@ -187,7 +178,6 @@ function createEmptyThreadDraft(): ComposerThreadDraftState {
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
bootstrapMessages: [],
provider: null,
model: null,
runtimeMode: null,
@@ -208,7 +198,6 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
draft.prompt.length === 0 &&
draft.images.length === 0 &&
draft.persistedAttachments.length === 0 &&
draft.bootstrapMessages.length === 0 &&
draft.provider === null &&
draft.model === null &&
draft.runtimeMode === null &&
@@ -219,7 +208,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
}
function normalizeProviderKind(value: unknown): ProviderKind | null {
return value === "codex" ? value : null;
return value === "codex" || value === "claudeCode" || value === "cursor" ? value : null;
}
function revokeObjectPreviewUrl(previewUrl: string): void {
@@ -263,81 +252,6 @@ function normalizePersistedAttachment(value: unknown): PersistedComposerImageAtt
};
}
function normalizeBootstrapAttachment(
value: unknown,
): Omit<ChatImageAttachment, "previewUrl"> | null {
if (!value || typeof value !== "object") {
return null;
}
const candidate = value as Record<string, unknown>;
const id = candidate.id;
const name = candidate.name;
const mimeType = candidate.mimeType;
const sizeBytes = candidate.sizeBytes;
if (
typeof id !== "string" ||
id.length === 0 ||
typeof name !== "string" ||
name.length === 0 ||
typeof mimeType !== "string" ||
mimeType.length === 0 ||
typeof sizeBytes !== "number" ||
!Number.isFinite(sizeBytes)
) {
return null;
}
return {
type: "image",
id,
name,
mimeType,
sizeBytes,
};
}
function normalizeBootstrapMessage(value: unknown): ChatMessage | null {
if (!value || typeof value !== "object") {
return null;
}
const candidate = value as Record<string, unknown>;
const id = candidate.id;
const role = candidate.role;
const text = candidate.text;
const createdAt = candidate.createdAt;
const streaming = candidate.streaming;
const completedAt = candidate.completedAt;
if (
typeof id !== "string" ||
id.length === 0 ||
(role !== "user" && role !== "assistant" && role !== "system") ||
typeof text !== "string" ||
typeof createdAt !== "string" ||
createdAt.length === 0 ||
typeof streaming !== "boolean"
) {
return null;
}
const attachments = Array.isArray(candidate.attachments)
? candidate.attachments.flatMap((entry) => {
const normalized = normalizeBootstrapAttachment(entry);
if (!normalized) {
return [];
}
return [normalized];
})
: undefined;
return {
id: MessageId.makeUnsafe(id),
role,
text,
createdAt,
streaming,
...(attachments && attachments.length > 0 ? { attachments } : {}),
...(typeof completedAt === "string" && completedAt.length > 0 ? { completedAt } : {}),
};
}
function normalizeDraftThreadEnvMode(
value: unknown,
fallbackWorktreePath: string | null,
@@ -452,12 +366,6 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
return normalized ? [normalized] : [];
})
: [];
const bootstrapMessages = Array.isArray(draftCandidate.bootstrapMessages)
? draftCandidate.bootstrapMessages.flatMap((entry) => {
const normalized = normalizeBootstrapMessage(entry);
return normalized ? [normalized] : [];
})
: [];
const provider = normalizeProviderKind(draftCandidate.provider);
const model =
typeof draftCandidate.model === "string"
@@ -484,7 +392,6 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
if (
prompt.length === 0 &&
attachments.length === 0 &&
bootstrapMessages.length === 0 &&
!provider &&
!model &&
!runtimeMode &&
@@ -497,7 +404,6 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
nextDraftsByThreadId[threadId as ThreadId] = {
prompt,
attachments,
...(bootstrapMessages.length > 0 ? { bootstrapMessages } : {}),
...(provider ? { provider } : {}),
...(model ? { model } : {}),
...(runtimeMode ? { runtimeMode } : {}),
@@ -605,7 +511,6 @@ function toHydratedThreadDraft(
images: hydrateImagesFromPersisted(persistedDraft.attachments),
nonPersistedImageIds: [],
persistedAttachments: persistedDraft.attachments,
bootstrapMessages: persistedDraft.bootstrapMessages ?? [],
provider: persistedDraft.provider ?? null,
model: persistedDraft.model ?? null,
runtimeMode: persistedDraft.runtimeMode ?? null,
@@ -873,47 +778,6 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
return { draftsByThreadId: nextDraftsByThreadId };
});
},
setBootstrapMessages: (threadId, messages) => {
if (threadId.length === 0) {
return;
}
set((state) => {
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
const nextDraft: ComposerThreadDraftState = {
...existing,
bootstrapMessages: [...messages],
};
const nextDraftsByThreadId = { ...state.draftsByThreadId };
if (shouldRemoveDraft(nextDraft)) {
delete nextDraftsByThreadId[threadId];
} else {
nextDraftsByThreadId[threadId] = nextDraft;
}
return { draftsByThreadId: nextDraftsByThreadId };
});
},
clearBootstrapMessages: (threadId) => {
if (threadId.length === 0) {
return;
}
set((state) => {
const current = state.draftsByThreadId[threadId];
if (!current) {
return state;
}
const nextDraft: ComposerThreadDraftState = {
...current,
bootstrapMessages: [],
};
const nextDraftsByThreadId = { ...state.draftsByThreadId };
if (shouldRemoveDraft(nextDraft)) {
delete nextDraftsByThreadId[threadId];
} else {
nextDraftsByThreadId[threadId] = nextDraft;
}
return { draftsByThreadId: nextDraftsByThreadId };
});
},
setProvider: (threadId, provider) => {
if (threadId.length === 0) {
return;
@@ -1315,7 +1179,6 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
if (
draft.prompt.length === 0 &&
draft.persistedAttachments.length === 0 &&
draft.bootstrapMessages.length === 0 &&
draft.provider === null &&
draft.model === null &&
draft.runtimeMode === null &&
@@ -1329,22 +1192,6 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
prompt: draft.prompt,
attachments: draft.persistedAttachments,
};
if (draft.bootstrapMessages.length > 0) {
persistedDraft.bootstrapMessages = draft.bootstrapMessages.map((message) => ({
...message,
...(message.attachments
? {
attachments: message.attachments.map((attachment) => ({
type: attachment.type,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
})),
}
: {}),
}));
}
if (draft.model) {
persistedDraft.model = draft.model;
}
+1 -127
View File
@@ -1,11 +1,7 @@
import { MessageId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
buildBootstrapInput,
resolveTurnBootstrapMessages,
selectBootstrapMessages,
} from "./historyBootstrap";
import { buildBootstrapInput } from "./historyBootstrap";
const messageId = (value: string) => MessageId.makeUnsafe(value);
@@ -126,126 +122,4 @@ describe("buildBootstrapInput", () => {
expect(result.text).toContain("Attached image");
expect(result.text).toContain("screenshot.png");
});
it("labels system messages distinctly in transcript blocks", () => {
const result = buildBootstrapInput(
[
{
id: messageId("sys-1"),
role: "system",
text: "Follow repository rules.",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
],
"continue",
1_500,
);
expect(result.text).toContain("SYSTEM:\nFollow repository rules.");
});
});
describe("selectBootstrapMessages", () => {
it("returns the newest fitting suffix in chronological order", () => {
const result = selectBootstrapMessages(
[
{
id: messageId("u-1"),
role: "user",
text: "first question with details",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
{
id: messageId("a-1"),
role: "assistant",
text: "first answer with details",
createdAt: "2026-02-09T00:00:01.000Z",
streaming: false,
},
{
id: messageId("u-2"),
role: "user",
text: "second question with details",
createdAt: "2026-02-09T00:00:02.000Z",
streaming: false,
},
],
"final request",
320,
);
expect(result.omittedCount).toBeGreaterThan(0);
expect(result.messages.map((message) => message.id)).toEqual([messageId("u-2")]);
});
});
describe("resolveTurnBootstrapMessages", () => {
it("prefers explicit draft bootstrap messages", () => {
const draftBootstrapMessages = [
{
id: messageId("draft-1"),
role: "user" as const,
text: "draft bootstrap",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
];
const threadMessages = [
{
id: messageId("thread-1"),
role: "assistant" as const,
text: "visible history",
createdAt: "2026-02-09T00:00:01.000Z",
streaming: false,
},
];
expect(
resolveTurnBootstrapMessages({
draftBootstrapMessages,
threadMessages,
providerThreadId: null,
}),
).toEqual(draftBootstrapMessages);
});
it("reuses visible thread history when no provider thread exists yet", () => {
const threadMessages = [
{
id: messageId("thread-1"),
role: "assistant" as const,
text: "visible history",
createdAt: "2026-02-09T00:00:01.000Z",
streaming: false,
},
];
expect(
resolveTurnBootstrapMessages({
draftBootstrapMessages: [],
threadMessages,
providerThreadId: null,
}),
).toEqual(threadMessages);
});
it("skips bootstrap when the provider thread already exists", () => {
expect(
resolveTurnBootstrapMessages({
draftBootstrapMessages: [],
threadMessages: [
{
id: messageId("thread-1"),
role: "assistant" as const,
text: "visible history",
createdAt: "2026-02-09T00:00:01.000Z",
streaming: false,
},
],
providerThreadId: "provider-thread-1",
}),
).toEqual([]);
});
});
+55 -126
View File
@@ -7,28 +7,6 @@ export interface BootstrapInputResult {
truncated: boolean;
}
export interface BootstrapMessageSelectionResult {
messages: ChatMessage[];
omittedCount: number;
promptTruncated: boolean;
}
export function resolveTurnBootstrapMessages(input: {
draftBootstrapMessages: ChatMessage[];
threadMessages: ChatMessage[];
providerThreadId: string | null;
}): ChatMessage[] {
if (input.draftBootstrapMessages.length > 0) {
return input.draftBootstrapMessages;
}
if (input.providerThreadId === null && input.threadMessages.length > 0) {
return input.threadMessages;
}
return [];
}
const BOOTSTRAP_PREAMBLE =
"Continue this conversation using the transcript context below. The final section is the latest user request to answer now.";
const TRANSCRIPT_HEADER = "Transcript context:";
@@ -36,14 +14,8 @@ const LATEST_PROMPT_HEADER = "Latest user request (answer this now):";
const OMITTED_SUMMARY = (count: number) =>
`[${count} earlier message(s) omitted to stay within input limits.]`;
function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" | "SYSTEM" {
if (message.role === "assistant") {
return "ASSISTANT";
}
if (message.role === "system") {
return "SYSTEM";
}
return "USER";
function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
return message.role === "assistant" ? "ASSISTANT" : "USER";
}
function attachmentSummary(message: ChatMessage): string | null {
@@ -85,85 +57,6 @@ function finalizeWithPrompt(
return text.length <= maxChars ? text : null;
}
function buildTranscriptBody(messages: ReadonlyArray<ChatMessage>, omittedCount: number): string {
const transcript = messages.map(buildMessageBlock).join("\n\n");
if (omittedCount === 0) {
return transcript;
}
if (transcript.length === 0) {
return OMITTED_SUMMARY(omittedCount);
}
return `${OMITTED_SUMMARY(omittedCount)}\n\n${transcript}`;
}
export function selectBootstrapMessages(
previousMessages: ChatMessage[],
latestPrompt: string,
maxChars: number,
): BootstrapMessageSelectionResult {
const budget = Number.isFinite(maxChars) ? Math.max(1, Math.floor(maxChars)) : 1;
const promptOnly = latestPrompt.length <= budget ? latestPrompt : latestPrompt.slice(0, budget);
const promptTruncated = latestPrompt.length !== promptOnly.length;
if (previousMessages.length === 0) {
return {
messages: [],
omittedCount: 0,
promptTruncated,
};
}
const newestFirstMessages: ChatMessage[] = [];
for (let index = previousMessages.length - 1; index >= 0; index -= 1) {
const message = previousMessages[index];
if (!message) continue;
newestFirstMessages.push(message);
}
if (newestFirstMessages.length === 0) {
return {
messages: [],
omittedCount: previousMessages.length,
promptTruncated: true,
};
}
let includedNewestFirst: ChatMessage[] = [];
for (const message of newestFirstMessages) {
const nextNewestFirst = [...includedNewestFirst, message];
const nextChronological = nextNewestFirst.toReversed();
const omittedCount = newestFirstMessages.length - nextChronological.length;
const transcriptBody = buildTranscriptBody(nextChronological, omittedCount);
if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
break;
}
includedNewestFirst = nextNewestFirst;
}
let includedChronological = includedNewestFirst.toReversed();
while (true) {
const omittedCount = newestFirstMessages.length - includedChronological.length;
const transcriptBody = buildTranscriptBody(includedChronological, omittedCount);
if (finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
return {
messages: includedChronological,
omittedCount,
promptTruncated,
};
}
if (includedChronological.length === 0) {
return {
messages: [],
omittedCount: previousMessages.length,
promptTruncated: true,
};
}
includedChronological = includedChronological.slice(1);
}
}
export function buildBootstrapInput(
previousMessages: ChatMessage[],
latestPrompt: string,
@@ -180,8 +73,15 @@ export function buildBootstrapInput(
truncated: promptOnly.length !== latestPrompt.length,
};
}
const selection = selectBootstrapMessages(previousMessages, latestPrompt, budget);
if (selection.messages.length === 0) {
const newestFirstBlocks: string[] = [];
for (let index = previousMessages.length - 1; index >= 0; index -= 1) {
const message = previousMessages[index];
if (!message) continue;
newestFirstBlocks.push(buildMessageBlock(message));
}
if (newestFirstBlocks.length === 0) {
return {
text: promptOnly,
includedCount: 0,
@@ -190,21 +90,50 @@ export function buildBootstrapInput(
};
}
const transcriptBody = buildTranscriptBody(selection.messages, selection.omittedCount);
const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);
if (!finalized) {
return {
text: promptOnly,
includedCount: 0,
omittedCount: previousMessages.length,
truncated: true,
};
// Include a contiguous suffix from newest to oldest, then reverse to chronological.
let includedNewestFirst: string[] = [];
for (const block of newestFirstBlocks) {
const nextNewestFirst = [...includedNewestFirst, block];
const nextChronological = nextNewestFirst.toReversed();
const omittedCount = newestFirstBlocks.length - nextChronological.length;
const transcriptBody =
omittedCount > 0
? `${OMITTED_SUMMARY(omittedCount)}\n\n${nextChronological.join("\n\n")}`
: nextChronological.join("\n\n");
if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
break;
}
includedNewestFirst = nextNewestFirst;
}
return {
text: finalized,
includedCount: selection.messages.length,
omittedCount: selection.omittedCount,
truncated: selection.omittedCount > 0 || selection.promptTruncated,
};
let includedChronological = includedNewestFirst.toReversed();
while (true) {
const omittedCount = newestFirstBlocks.length - includedChronological.length;
const transcriptBody =
omittedCount > 0
? includedChronological.length > 0
? `${OMITTED_SUMMARY(omittedCount)}\n\n${includedChronological.join("\n\n")}`
: OMITTED_SUMMARY(omittedCount)
: includedChronological.join("\n\n");
const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);
if (finalized) {
return {
text: finalized,
includedCount: includedChronological.length,
omittedCount,
truncated: omittedCount > 0 || latestPrompt.length !== promptOnly.length,
};
}
if (includedChronological.length === 0) {
return {
text: promptOnly,
includedCount: 0,
omittedCount: previousMessages.length,
truncated: true,
};
}
includedChronological = includedChronological.slice(1);
}
}
@@ -1,32 +0,0 @@
import { ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { collectActiveTerminalThreadIds } from "./terminalStateCleanup";
const threadId = (id: string): ThreadId => ThreadId.makeUnsafe(id);
describe("collectActiveTerminalThreadIds", () => {
it("retains non-deleted server threads", () => {
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: [
{ id: threadId("server-1"), deletedAt: null },
{ id: threadId("server-2"), deletedAt: null },
],
draftThreadIds: [],
});
expect(activeThreadIds).toEqual(new Set([threadId("server-1"), threadId("server-2")]));
});
it("ignores deleted server threads and keeps local draft threads", () => {
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: [
{ id: threadId("server-active"), deletedAt: null },
{ id: threadId("server-deleted"), deletedAt: "2026-03-05T08:00:00.000Z" },
],
draftThreadIds: [threadId("local-draft")],
});
expect(activeThreadIds).toEqual(new Set([threadId("server-active"), threadId("local-draft")]));
});
});
-25
View File
@@ -1,25 +0,0 @@
import type { ThreadId } from "@t3tools/contracts";
interface TerminalRetentionThread {
id: ThreadId;
deletedAt: string | null;
}
interface CollectActiveTerminalThreadIdsInput {
snapshotThreads: readonly TerminalRetentionThread[];
draftThreadIds: Iterable<ThreadId>;
}
export function collectActiveTerminalThreadIds(
input: CollectActiveTerminalThreadIdsInput,
): Set<ThreadId> {
const activeThreadIds = new Set<ThreadId>();
for (const thread of input.snapshotThreads) {
if (thread.deletedAt !== null) continue;
activeThreadIds.add(thread.id);
}
for (const draftThreadId of input.draftThreadIds) {
activeThreadIds.add(draftThreadId);
}
return activeThreadIds;
}
-27
View File
@@ -5,7 +5,6 @@ import {
buildPlanImplementationPrompt,
buildProposedPlanMarkdownFilename,
proposedPlanTitle,
resolvePlanFollowUpSubmission,
} from "./proposedPlan";
describe("proposedPlanTitle", () => {
@@ -26,32 +25,6 @@ describe("buildPlanImplementationPrompt", () => {
});
});
describe("resolvePlanFollowUpSubmission", () => {
it("switches to default mode when implementing the ready plan without extra text", () => {
expect(
resolvePlanFollowUpSubmission({
draftText: " ",
planMarkdown: "## Ship it\n\n- step 1\n",
}),
).toEqual({
text: "PLEASE IMPLEMENT THIS PLAN:\n## Ship it\n\n- step 1",
interactionMode: "default",
});
});
it("stays in plan mode when the user adds a follow-up prompt", () => {
expect(
resolvePlanFollowUpSubmission({
draftText: "Refine step 2 first",
planMarkdown: "## Ship it\n\n- step 1\n",
}),
).toEqual({
text: "Refine step 2 first",
interactionMode: "plan",
});
});
});
describe("buildPlanImplementationThreadTitle", () => {
it("uses the plan heading when building the implementation thread title", () => {
expect(buildPlanImplementationThreadTitle("# Integrate RPC\n\nBody")).toBe(
-21
View File
@@ -16,27 +16,6 @@ export function buildPlanImplementationPrompt(planMarkdown: string): string {
return `PLEASE IMPLEMENT THIS PLAN:\n${planMarkdown.trim()}`;
}
export function resolvePlanFollowUpSubmission(input: {
draftText: string;
planMarkdown: string;
}): {
text: string;
interactionMode: "default" | "plan";
} {
const trimmedDraftText = input.draftText.trim();
if (trimmedDraftText.length > 0) {
return {
text: trimmedDraftText,
interactionMode: "plan",
};
}
return {
text: buildPlanImplementationPrompt(input.planMarkdown),
interactionMode: "default",
};
}
export function buildPlanImplementationThreadTitle(planMarkdown: string): string {
const title = proposedPlanTitle(planMarkdown);
if (!title) {
+3 -9
View File
@@ -14,14 +14,12 @@ import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { preferredTerminalEditor } from "../terminal-links";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
import { providerQueryKeys } from "../lib/providerReactQuery";
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
@@ -156,13 +154,9 @@ function EventRouter() {
if (disposed) return;
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
syncServerReadModel(snapshot);
const draftThreadIds = Object.keys(
useComposerDraftStore.getState().draftThreadsByThreadId,
) as ThreadId[];
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: snapshot.threads,
draftThreadIds,
});
const activeThreadIds = new Set(
snapshot.threads.filter((t) => t.deletedAt === null).map((t) => t.id),
);
removeOrphanedTerminalStates(activeThreadIds);
if (pending) {
pending = false;
+25 -54
View File
@@ -3,14 +3,8 @@ import { useQuery } from "@tanstack/react-query";
import { useCallback, useState } from "react";
import { type ProviderKind } from "@t3tools/contracts";
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
import { ZapIcon } from "lucide-react";
import {
APP_SERVICE_TIER_OPTIONS,
MAX_CUSTOM_MODEL_LENGTH,
shouldShowFastTierIcon,
useAppSettings,
} from "../appSettings";
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
@@ -18,7 +12,6 @@ import { ensureNativeApi } from "../nativeApi";
import { preferredTerminalEditor } from "../terminal-links";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../components/ui/select";
import { Switch } from "../components/ui/switch";
import { SidebarInset } from "~/components/ui/sidebar";
@@ -54,6 +47,13 @@ const MODEL_PROVIDER_SETTINGS: Array<{
placeholder: "your-codex-model-slug",
example: "gpt-6.7-codex-ultra-preview",
},
{
provider: "cursor",
title: "Cursor",
description: "Save additional Cursor model slugs for the picker and `/model` command.",
placeholder: "your-cursor-model-slug",
example: "openai/gpt-oss-120b",
},
] as const;
function getCustomModelsForProvider(
@@ -61,6 +61,10 @@ function getCustomModelsForProvider(
provider: ProviderKind,
) {
switch (provider) {
case "claudeCode":
return settings.customClaudeModels;
case "cursor":
return settings.customCursorModels;
case "codex":
default:
return settings.customCodexModels;
@@ -72,6 +76,10 @@ function getDefaultCustomModelsForProvider(
provider: ProviderKind,
) {
switch (provider) {
case "claudeCode":
return defaults.customClaudeModels;
case "cursor":
return defaults.customCursorModels;
case "codex":
default:
return defaults.customCodexModels;
@@ -80,6 +88,10 @@ function getDefaultCustomModelsForProvider(
function patchCustomModels(provider: ProviderKind, models: string[]) {
switch (provider) {
case "claudeCode":
return { customClaudeModels: models };
case "cursor":
return { customCursorModels: models };
case "codex":
default:
return { customCodexModels: models };
@@ -96,6 +108,8 @@ function SettingsRouteView() {
Record<ProviderKind, string>
>({
codex: "",
claudeCode: "",
cursor: "",
});
const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState<
Partial<Record<ProviderKind, string | null>>
@@ -103,7 +117,6 @@ function SettingsRouteView() {
const codexBinaryPath = settings.codexBinaryPath;
const codexHomePath = settings.codexHomePath;
const codexServiceTier = settings.codexServiceTier;
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
const openKeybindingsFile = useCallback(() => {
@@ -310,43 +323,6 @@ function SettingsRouteView() {
</div>
<div className="space-y-5">
<label className="block space-y-1">
<span className="text-xs font-medium text-foreground">Default service tier</span>
<Select
items={APP_SERVICE_TIER_OPTIONS.map((option) => ({
label: option.label,
value: option.value,
}))}
value={codexServiceTier}
onValueChange={(value) => {
if (!value) return;
updateSettings({ codexServiceTier: value });
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectPopup alignItemWithTrigger={false}>
{APP_SERVICE_TIER_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
<div className="flex min-w-0 items-center gap-2">
{option.value === "fast" ? (
<ZapIcon className="size-3.5 text-amber-500" />
) : (
<span className="size-3.5 shrink-0" aria-hidden="true" />
)}
<span className="truncate">{option.label}</span>
</div>
</SelectItem>
))}
</SelectPopup>
</Select>
<span className="text-xs text-muted-foreground">
{APP_SERVICE_TIER_OPTIONS.find((option) => option.value === codexServiceTier)
?.description ?? "Use Codex defaults without forcing a service tier."}
</span>
</label>
{MODEL_PROVIDER_SETTINGS.map((providerSettings) => {
const provider = providerSettings.provider;
const customModels = getCustomModelsForProvider(settings, provider);
@@ -445,14 +421,9 @@ function SettingsRouteView() {
key={`${provider}:${slug}`}
className="flex items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2"
>
<div className="flex min-w-0 flex-1 items-center gap-2">
{provider === "codex" && shouldShowFastTierIcon(slug, codexServiceTier) ? (
<ZapIcon className="size-3.5 shrink-0 text-amber-500" />
) : null}
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
{slug}
</code>
</div>
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
{slug}
</code>
<Button
size="xs"
variant="ghost"
+3 -37
View File
@@ -343,35 +343,6 @@ describe("deriveWorkLogEntries", () => {
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
});
it("omits task start and completion lifecycle entries", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "task-start",
createdAt: "2026-02-23T00:00:01.000Z",
kind: "task.started",
summary: "default task started",
tone: "info",
}),
makeActivity({
id: "task-progress",
createdAt: "2026-02-23T00:00:02.000Z",
kind: "task.progress",
summary: "Updating files",
tone: "info",
}),
makeActivity({
id: "task-complete",
createdAt: "2026-02-23T00:00:03.000Z",
kind: "task.completed",
summary: "Task completed",
tone: "info",
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
expect(entries.map((entry) => entry.id)).toEqual(["task-progress"]);
});
it("filters by turn id when provided", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({ id: "turn-1", turnId: "turn-1", summary: "Tool call", kind: "tool.started" }),
@@ -543,14 +514,9 @@ describe("isLatestTurnSettled", () => {
});
describe("PROVIDER_OPTIONS", () => {
it("keeps Claude Code and Cursor visible as unavailable placeholders in the stack base", () => {
it("advertises codex and cursor on the cursor branch while keeping Claude Code as coming soon", () => {
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeCode");
const cursor = PROVIDER_OPTIONS.find((option) => option.value === "cursor");
expect(PROVIDER_OPTIONS).toEqual([
{ value: "codex", label: "Codex", available: true },
{ value: "claudeCode", label: "Claude Code", available: false },
{ value: "cursor", label: "Cursor", available: false },
]);
expect(claude).toEqual({
value: "claudeCode",
label: "Claude Code",
@@ -558,8 +524,8 @@ describe("PROVIDER_OPTIONS", () => {
});
expect(cursor).toEqual({
value: "cursor",
label: "Cursor",
available: false,
label: "Cursor Agent",
available: true,
});
});
});
+1 -2
View File
@@ -19,7 +19,7 @@ export const PROVIDER_OPTIONS: Array<{
}> = [
{ value: "codex", label: "Codex", available: true },
{ value: "claudeCode", label: "Claude Code", available: false },
{ value: "cursor", label: "Cursor", available: false },
{ value: "cursor", label: "Cursor Agent", available: true },
];
export interface WorkLogEntry {
@@ -394,7 +394,6 @@ export function deriveWorkLogEntries(
return ordered
.filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
.filter((activity) => activity.kind !== "tool.started")
.filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
.filter((activity) => activity.summary !== "Checkpoint captured")
.map((activity) => {
const payload =
+48 -9
View File
@@ -1,10 +1,4 @@
import {
DEFAULT_MODEL_BY_PROVIDER,
ProjectId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { ProjectId, ThreadId, TurnId, type OrchestrationReadModel } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { markThreadUnread, syncServerReadModel, type AppState } from "./store";
@@ -135,7 +129,7 @@ describe("store pure functions", () => {
});
describe("store read model sync", () => {
it("falls back to the codex default for unsupported provider models without an active session", () => {
it("preserves claude model slugs without an active session", () => {
const initialState = makeState(makeThread());
const readModel = makeReadModel(
makeReadModelThread({
@@ -145,6 +139,51 @@ describe("store read model sync", () => {
const next = syncServerReadModel(initialState, readModel);
expect(next.threads[0]?.model).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
expect(next.threads[0]?.model).toBe("claude-opus-4-6");
});
it("resolves claude aliases when session provider is claudeCode", () => {
const initialState = makeState(makeThread());
const readModel = makeReadModel(
makeReadModelThread({
model: "sonnet",
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeCode",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: "2026-02-27T00:00:00.000Z",
},
}),
);
const next = syncServerReadModel(initialState, readModel);
expect(next.threads[0]?.model).toBe("claude-sonnet-4-6");
});
it("resolves cursor aliases when session provider is cursor", () => {
const initialState = makeState(makeThread());
const readModel = makeReadModel(
makeReadModelThread({
model: "composer",
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "cursor",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: "2026-02-27T00:00:00.000Z",
},
}),
);
const next = syncServerReadModel(initialState, readModel);
expect(next.threads[0]?.model).toBe("composer-1.5");
expect(next.threads[0]?.session?.provider).toBe("cursor");
});
});
+64 -17
View File
@@ -1,6 +1,6 @@
import { Fragment, type ReactNode, createElement, useEffect } from "react";
import {
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_MODEL,
type ProviderKind,
ThreadId,
type OrchestrationReadModel,
@@ -13,7 +13,11 @@ import {
resolveModelSlugForProvider,
} from "@t3tools/shared/model";
import { create } from "zustand";
import { type ChatMessage, type Project, type Thread } from "./types";
import {
type ChatMessage,
type Project,
type Thread,
} from "./types";
// ── State ────────────────────────────────────────────────────────────
@@ -110,9 +114,7 @@ function mapProjectsFromReadModel(
id: project.id,
name: project.title,
cwd: project.workspaceRoot,
model:
existing?.model ??
resolveModelSlug(project.defaultModel ?? DEFAULT_MODEL_BY_PROVIDER.codex),
model: existing?.model ?? resolveModelSlug(project.defaultModel ?? DEFAULT_MODEL),
expanded:
existing?.expanded ??
(persistedExpandedProjectCwds.size > 0
@@ -143,26 +145,52 @@ function toLegacySessionStatus(
}
function toLegacyProvider(providerName: string | null): ProviderKind {
if (providerName === "codex") {
if (providerName === "codex" || providerName === "claudeCode" || providerName === "cursor") {
return providerName;
}
return "codex";
}
const CODEX_MODEL_SLUGS = new Set<string>(getModelOptions("codex").map((option) => option.slug));
const CLAUDE_MODEL_SLUGS = new Set<string>(getModelOptions("claudeCode").map((option) => option.slug));
const CURSOR_MODEL_SLUGS = new Set<string>(getModelOptions("cursor").map((option) => option.slug));
const CURSOR_DISTINCT_MODEL_SLUGS = new Set(
[...CURSOR_MODEL_SLUGS].filter(
(slug) => !CODEX_MODEL_SLUGS.has(slug) && !CLAUDE_MODEL_SLUGS.has(slug),
),
);
function inferProviderForThreadModel(input: {
readonly model: string;
readonly sessionProviderName: string | null;
}): ProviderKind {
if (input.sessionProviderName === "codex") {
if (
input.sessionProviderName === "codex" ||
input.sessionProviderName === "claudeCode" ||
input.sessionProviderName === "cursor"
) {
return input.sessionProviderName;
}
const normalizedCursor = normalizeModelSlug(input.model, "cursor");
if (normalizedCursor && CURSOR_DISTINCT_MODEL_SLUGS.has(normalizedCursor)) {
return "cursor";
}
const normalizedClaude = normalizeModelSlug(input.model, "claudeCode");
if (normalizedClaude && CLAUDE_MODEL_SLUGS.has(normalizedClaude)) {
return "claudeCode";
}
const normalizedCodex = normalizeModelSlug(input.model, "codex");
if (normalizedCodex && CODEX_MODEL_SLUGS.has(normalizedCodex)) {
return "codex";
}
return "codex";
if (
input.model.trim().startsWith("composer-") ||
input.model.trim().startsWith("gemini-") ||
input.model.trim().endsWith("-thinking")
) {
return "cursor";
}
return input.model.trim().startsWith("claude-") ? "claudeCode" : "codex";
}
function resolveWsHttpOrigin(): string {
@@ -179,7 +207,11 @@ function resolveWsHttpOrigin(): string {
try {
const wsUrl = new URL(wsCandidate);
const protocol =
wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
wsUrl.protocol === "wss:"
? "https:"
: wsUrl.protocol === "ws:"
? "http:"
: wsUrl.protocol;
return `${protocol}//${wsUrl.host}`;
} catch {
return window.location.origin;
@@ -199,12 +231,17 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
// ── Pure state transition functions ────────────────────────────────────
export function syncServerReadModel(state: AppState, readModel: OrchestrationReadModel): AppState {
export function syncServerReadModel(
state: AppState,
readModel: OrchestrationReadModel,
): AppState {
const projects = mapProjectsFromReadModel(
readModel.projects.filter((project) => project.deletedAt === null),
state.projects,
);
const existingThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const));
const existingThreadById = new Map(
state.threads.map((thread) => [thread.id, thread] as const),
);
const threads = readModel.threads
.filter((thread) => thread.deletedAt === null)
.map((thread) => {
@@ -323,7 +360,9 @@ export function markThreadUnread(state: AppState, threadId: ThreadId): AppState
export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
return {
...state,
projects: state.projects.map((p) => (p.id === projectId ? { ...p, expanded: !p.expanded } : p)),
projects: state.projects.map((p) =>
p.id === projectId ? { ...p, expanded: !p.expanded } : p,
),
};
}
@@ -377,19 +416,27 @@ interface AppStore extends AppState {
toggleProject: (projectId: Project["id"]) => void;
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
setError: (threadId: ThreadId, error: string | null) => void;
setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void;
setThreadBranch: (
threadId: ThreadId,
branch: string | null,
worktreePath: string | null,
) => void;
}
export const useStore = create<AppStore>((set) => ({
...readPersistedState(),
syncServerReadModel: (readModel) => set((state) => syncServerReadModel(state, readModel)),
syncServerReadModel: (readModel) =>
set((state) => syncServerReadModel(state, readModel)),
markThreadVisited: (threadId, visitedAt) =>
set((state) => markThreadVisited(state, threadId, visitedAt)),
markThreadUnread: (threadId) => set((state) => markThreadUnread(state, threadId)),
toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
markThreadUnread: (threadId) =>
set((state) => markThreadUnread(state, threadId)),
toggleProject: (projectId) =>
set((state) => toggleProject(state, projectId)),
setProjectExpanded: (projectId, expanded) =>
set((state) => setProjectExpanded(state, projectId, expanded)),
setError: (threadId, error) => set((state) => setError(state, threadId, error)),
setError: (threadId, error) =>
set((state) => setError(state, threadId, error)),
setThreadBranch: (threadId, branch, worktreePath) =>
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
}));
-2
View File
@@ -30,14 +30,12 @@ describe("getVscodeIconUrlForEntry", () => {
const tsxUrl = getVscodeIconUrlForEntry("checkbox.tsx", "file", "light");
const dockerfileUrl = getVscodeIconUrlForEntry("Dockerfile", "file", "dark");
const shellUrl = getVscodeIconUrlForEntry("entrypoint.sh", "file", "dark");
const htmlUrl = getVscodeIconUrlForEntry("index.html", "file", "dark");
const cursorRulesUrl = getVscodeIconUrlForEntry("general.mdc", "file", "dark");
const githubWorkflowUrl = getVscodeIconUrlForEntry(".github/workflows/ci.yml", "file", "light");
assert.isTrue(tsxUrl.endsWith("/file_type_reactts.svg"));
assert.isTrue(dockerfileUrl.endsWith("/file_type_docker.svg"));
assert.isTrue(shellUrl.endsWith("/file_type_shell.svg"));
assert.isTrue(htmlUrl.endsWith("/file_type_html.svg"));
assert.isTrue(cursorRulesUrl.endsWith("/file_type_markdown.svg"));
assert.isTrue(githubWorkflowUrl.endsWith("/file_type_light_yaml.svg"));
});
-3
View File
@@ -45,9 +45,6 @@ const languageIdByFileName = toLowercaseLookup(languageAssociations.fileNameToLa
const localLanguageIdByExtensionOverrides = {
// Cursor rules files (*.mdc) are commonly treated as markdown in VSCode/Cursor.
mdc: "markdown",
// Upstream languages.ts currently maps .html to django-html before html.
// Prefer the base HTML icon for standalone HTML files.
html: "html",
// Upstream languages.ts maps yml/yaml to specialized language ids that can produce
// non-generic YAML icons (for example cloudfoundry/esphome). Prefer the base YAML icon
// unless a more specific basename/extension match (e.g. azure-pipelines.yml) is found.
-7
View File
@@ -1,7 +0,0 @@
const WORKTREE_BRANCH_PREFIX = "t3code";
export function buildTemporaryWorktreeBranchName(): string {
// Keep the 8-hex suffix shape for backend temporary-branch detection.
const token = crypto.randomUUID().slice(0, 8).toLowerCase();
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 4.5 MiB

After

Width:  |  Height:  |  Size: 4.5 MiB

+4
View File
@@ -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

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more