Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e29fcbd259 | ||
|
|
6271b989bc | ||
|
|
57aa6bf16c | ||
|
|
40a7f4b4b1 | ||
|
|
cba0f23a9e | ||
|
|
a7ec0179fb | ||
|
|
c97c6b7836 | ||
|
|
59b0527c38 | ||
|
|
b74c7a79ab | ||
|
|
f772720d8c | ||
|
|
0763a35fbc | ||
|
|
e1c33dcd33 | ||
|
|
0a902790ca | ||
|
|
0837c8b639 | ||
|
|
5a90b6be9c | ||
|
|
42675571c9 | ||
|
|
e9f00f65ca | ||
|
|
04b95e37c5 | ||
|
|
5820e1b6ff | ||
|
|
8c904ffe34 | ||
|
|
9fa9cb4b31 | ||
|
|
24599aaeed | ||
|
|
f403b23e9a | ||
|
|
39c71a0394 | ||
|
|
d249e628ee | ||
|
|
40fcb6bdf8 | ||
|
|
d58ff5de26 | ||
|
|
e28ad18106 | ||
|
|
525411101d | ||
|
|
0f208447ed | ||
|
|
71e0573459 | ||
|
|
c63ea8d25b | ||
|
|
b9e529e0b5 | ||
|
|
0f702fcd62 | ||
|
|
13f2f9bc58 | ||
|
|
91cf202177 | ||
|
|
d21a8d597b | ||
|
|
14022f1d00 | ||
|
|
28c62f3efd | ||
|
|
268bb4bfa3 | ||
|
|
477b4f9d0e | ||
|
|
d5d88270f0 | ||
|
|
373725f96e | ||
|
|
fcb1a50ee4 | ||
|
|
ec3778bbf4 | ||
|
|
8c5b8d3b72 | ||
|
|
010ba70561 | ||
|
|
6ee057e25b | ||
|
|
551aebc604 | ||
|
|
9de85ea16e | ||
|
|
10dde452f9 | ||
|
|
116c8c5e8e | ||
|
|
f8886e874d | ||
|
|
2435a9cd58 | ||
|
|
78d53062d1 | ||
|
|
697d71d57d | ||
|
|
d74b086aaf | ||
|
|
6496aedc92 | ||
|
|
e972fad300 | ||
|
|
1bd4d6d953 | ||
|
|
e9655d43d5 | ||
|
|
f0a7ddaf80 | ||
|
|
ed6c12c709 | ||
|
|
a1b75fe17f | ||
|
|
2e5e75699e | ||
|
|
be308beacc | ||
|
|
2589176c82 | ||
|
|
adfd99bdec | ||
|
|
1683ee7b11 | ||
|
|
e6575c4149 | ||
|
|
ae7283e021 | ||
|
|
640a2cca9f | ||
|
|
12edc3455c | ||
|
|
26f631b638 | ||
|
|
981cf40561 | ||
|
|
689dda59e9 | ||
|
|
0a67f9dd39 | ||
|
|
df6bb188d4 | ||
|
|
03053d9ee0 | ||
|
|
9c4d7a83e2 | ||
|
|
7425a3c4b3 | ||
|
|
344e04b623 | ||
|
|
7b71e234e0 | ||
|
|
77f67d1766 | ||
|
|
1c2ed75937 | ||
|
|
17e6cad479 | ||
|
|
feff86638e | ||
|
|
ad28eaa86f | ||
|
|
d36bbc177d | ||
|
|
aeddb57594 | ||
|
|
f2253269dd | ||
|
|
d08cecf126 | ||
|
|
afad39d125 | ||
|
|
f97916f371 | ||
|
|
86e204439e | ||
|
|
04a931fc79 | ||
|
|
75354bbd96 | ||
|
|
6a10e97a97 | ||
|
|
1542b00db2 | ||
|
|
f79f8bac80 | ||
|
|
92f1a4aa3c | ||
|
|
11f929c397 | ||
|
|
0616338911 | ||
|
|
58427d565d | ||
|
|
9b3dbada17 | ||
|
|
4797f99cf8 | ||
|
|
50f35351a2 | ||
|
|
c7460bde16 | ||
|
|
2c110e8ce2 | ||
|
|
5707a6ee1d | ||
|
|
291411a45e | ||
|
|
87abc22f39 | ||
|
|
441582dbb8 | ||
|
|
1b1ede92ba | ||
|
|
4ec7ae33c5 | ||
|
|
317fcc659b | ||
|
|
ff7e084a33 | ||
|
|
c590beb4e3 | ||
|
|
e9ced44ac6 | ||
|
|
802cd127d1 | ||
|
|
931c56b2d0 | ||
|
|
484662b2d4 | ||
|
|
2cd04f08c1 | ||
|
|
4916dad78e |
No files matched your search
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: btca-cli
|
||||
description: btca is a cli for getting information from other git repositories by querying them with natural language. Spawns an external subagent to explore external codebases (i.e. a github repo) and answer questions about them. Great when integrating complex libraries, frameworks, or tools.
|
||||
---
|
||||
|
||||
btca is a cli for asking questions about various folders, primarily git repositories. It's built to give you the exact information you need without bloating your context window. btca uses agents under the hood to answer your question, so prompt it the way you would prompt a tool similar to yourself.
|
||||
|
||||
For example, assuming you have a resource named `codex`, you can ask questions like:
|
||||
|
||||
```bash
|
||||
btca ask -r codex -q "What is the return format for Codex App Server responses? Are there any edge cases worth knowing?"
|
||||
```
|
||||
|
||||
Your prompt may include specific names for resources to use, if they do then you should try those first. If you need to check available resources, you can use the `btca resources` command.
|
||||
|
||||
New resources can be created if the ones you need do not yet exist.
|
||||
|
||||
```bash
|
||||
btca add -n svelte-dev https://github.com/sveltejs/svelte.dev
|
||||
```
|
||||
@@ -1,3 +0,0 @@
|
||||
interface:
|
||||
display_name: "BTCA CLI"
|
||||
short_description: "Help with BTCA CLI setup and usage workflows"
|
||||
@@ -0,0 +1,21 @@
|
||||
# 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 │
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
@@ -0,0 +1,6 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,5 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,14 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,22 @@
|
||||
# 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
|
||||
```
|
||||
@@ -0,0 +1,6 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,42 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,6 @@
|
||||
# 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.
|
||||
@@ -22,6 +22,8 @@ jobs:
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
|
||||
make_latest: ${{ steps.release_meta.outputs.make_latest }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -45,6 +47,13 @@ jobs:
|
||||
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -239,7 +248,7 @@ jobs:
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
@@ -260,7 +269,8 @@ jobs:
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
make_latest: true
|
||||
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
|
||||
make_latest: ${{ needs.preflight.outputs.make_latest }}
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
|
||||
@@ -5,6 +5,7 @@ node_modules
|
||||
*.log
|
||||
*.tsbuildinfo
|
||||
apps/*/dist
|
||||
.astro
|
||||
packages/*/dist
|
||||
.env
|
||||
.env.local
|
||||
|
||||
@@ -1,327 +0,0 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,21 @@
|
||||
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.
|
||||
@@ -2,135 +2,23 @@
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
|
||||
|
||||
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.
|
||||
## How to use
|
||||
|
||||
## 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 │
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
## 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.
|
||||
|
||||
## Quick start
|
||||
> [!WARNING]
|
||||
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||
|
||||
```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
|
||||
You can also just install the desktop app. It's cooler.
|
||||
|
||||
- `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`.
|
||||
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
## Some 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`.
|
||||
We are very very early in this project. Expect bugs.
|
||||
|
||||
### Running multiple dev instances
|
||||
We are not accepting contributions yet.
|
||||
|
||||
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.
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -2,24 +2,12 @@
|
||||
|
||||
## Small things
|
||||
|
||||
- [ ] Plan mode
|
||||
- [ ] Submitting new messages should scroll to bottom
|
||||
- [ ] 1 click copy in codeblocks
|
||||
- [x] Pasting/adding images to submit with prompts
|
||||
- [ ] Only show last 10 threads for a given project
|
||||
- [ ] Thread archiving
|
||||
- [x] Selecting folder should instantly create project
|
||||
- [ ] New projects should go on top
|
||||
- [ ] Projects should be sorted by latest thread update
|
||||
- [x] "Response" bar should ONLY appear on work completed
|
||||
- [x] "Response" bar should ONLY appear above the FINAL message in a series
|
||||
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
|
||||
- [x] Insta focus input on new thread creation
|
||||
- [x] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||
- [x] Making new thread should auto-focus input box
|
||||
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
|
||||
|
||||
## Bigger things
|
||||
|
||||
- [ ] Queueing messages
|
||||
- [x] External runners (i.e. running the cli on a mac mini)
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import * as ChildProcess from "node:child_process";
|
||||
import { readPathFromLoginShell } from "@t3tools/shared/shell";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
const result = readPathFromLoginShell(shell);
|
||||
if (result) {
|
||||
process.env.PATH = result;
|
||||
}
|
||||
|
||||
@@ -58,6 +58,8 @@ const LOG_FILE_MAX_FILES = 10;
|
||||
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
||||
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
|
||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
|
||||
@@ -725,7 +727,10 @@ function configureAutoUpdater(): void {
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
autoUpdater.allowPrerelease = app.getVersion().includes("-");
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
|
||||
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
|
||||
autoUpdater.allowDowngrade = false;
|
||||
let lastLoggedDownloadMilestone = -1;
|
||||
|
||||
autoUpdater.on("checking-for-update", () => {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from "astro/config";
|
||||
|
||||
export default defineConfig({
|
||||
server: {
|
||||
port: Number(process.env.PORT ?? 4173),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"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:"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 414 B |
|
After Width: | Height: | Size: 662 B |
|
After Width: | Height: | Size: 9.9 KiB |
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 652 KiB |
@@ -0,0 +1,328 @@
|
||||
---
|
||||
---
|
||||
|
||||
<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" sizes="48x48" />
|
||||
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-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">↗</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">© {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>
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "astro/tsconfigs/strict"
|
||||
}
|
||||
@@ -40,6 +40,7 @@ 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";
|
||||
@@ -152,7 +153,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly rootDir: string;
|
||||
readonly workspaceDir: string;
|
||||
readonly dbPath: string;
|
||||
readonly adapterHarness: TestProviderAdapterHarness;
|
||||
readonly adapterHarness: TestProviderAdapterHarness | null;
|
||||
readonly engine: OrchestrationEngineShape;
|
||||
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
|
||||
readonly providerService: ProviderService["Service"];
|
||||
@@ -188,7 +189,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
readonly provider?: "codex";
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
@@ -252,10 +253,12 @@ 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(
|
||||
@@ -403,19 +406,14 @@ 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(stopAllExit)
|
||||
? stopAllExit.cause
|
||||
: Exit.isFailure(closeScopeExit)
|
||||
? closeScopeExit.cause
|
||||
: Exit.isFailure(disposeRuntimeExit)
|
||||
? disposeRuntimeExit.cause
|
||||
: null;
|
||||
const failureCause = Exit.isFailure(closeScopeExit)
|
||||
? closeScopeExit.cause
|
||||
: Exit.isFailure(disposeRuntimeExit)
|
||||
? disposeRuntimeExit.cause
|
||||
: null;
|
||||
|
||||
if (failureCause) {
|
||||
return yield* Effect.failCause(failureCause);
|
||||
@@ -435,7 +433,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness: adapterHarness as TestProviderAdapterHarness,
|
||||
adapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
|
||||
@@ -35,7 +35,7 @@ export interface TestTurnResponse {
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly provider: "codex";
|
||||
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" | "claudeCode";
|
||||
readonly provider: "codex";
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
readonly provider?: "codex";
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
@@ -206,7 +206,7 @@ function nowIso(): string {
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: "codex" | "claudeCode",
|
||||
provider: "codex",
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
@@ -216,7 +216,7 @@ function sessionNotFound(
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: "codex" | "claudeCode",
|
||||
provider: "codex",
|
||||
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" | "claudeCode";
|
||||
type IntegrationProvider = "codex";
|
||||
|
||||
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,416 +842,3 @@ 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,6 +12,7 @@ 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";
|
||||
|
||||
@@ -59,6 +60,7 @@ 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,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
|
||||
@@ -6,6 +6,7 @@ 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" };
|
||||
@@ -31,6 +32,84 @@ 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
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -53,6 +132,7 @@ const buildCmd = Command.make(
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
shell: process.platform === "win32",
|
||||
})`bun tsdown`,
|
||||
);
|
||||
|
||||
@@ -61,6 +141,7 @@ 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.");
|
||||
@@ -104,10 +185,8 @@ const publishCmd = Command.make(
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
|
||||
// Build package.json for publish
|
||||
// Resolve catalog dependencies before any file mutations. If this throws,
|
||||
// acquire fails and no release hook runs, so filesystem must still be untouched.
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg = {
|
||||
name: serverPackageJson.name,
|
||||
@@ -120,15 +199,19 @@ 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
|
||||
() =>
|
||||
@@ -143,12 +226,20 @@ const publishCmd = Command.make(
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// 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");
|
||||
}),
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
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,11 +7,14 @@ 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);
|
||||
@@ -20,14 +23,20 @@ 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
|
||||
@@ -57,10 +66,11 @@ 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",
|
||||
@@ -88,10 +98,11 @@ 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",
|
||||
@@ -194,6 +205,70 @@ 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({
|
||||
@@ -241,6 +316,59 @@ describe("startSession", () => {
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("fails fast with an upgrade message when codex is below the minimum supported version", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
method: event.method,
|
||||
kind: event.kind,
|
||||
...(event.message ? { message: event.message } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const versionCheck = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
assertSupportedCodexCliVersion: (input: {
|
||||
binaryPath: string;
|
||||
cwd: string;
|
||||
homePath?: string;
|
||||
}) => void;
|
||||
},
|
||||
"assertSupportedCodexCliVersion",
|
||||
)
|
||||
.mockImplementation(() => {
|
||||
throw new Error(
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
expect(versionCheck).toHaveBeenCalledTimes(1);
|
||||
expect(events).toEqual([
|
||||
{
|
||||
method: "session/startFailed",
|
||||
kind: "error",
|
||||
message:
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
versionCheck.mockRestore();
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendTurn", () => {
|
||||
@@ -258,8 +386,8 @@ describe("sendTurn", () => {
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
effort: "high",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
@@ -282,8 +410,8 @@ describe("sendTurn", () => {
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
effort: "high",
|
||||
});
|
||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
||||
status: "running",
|
||||
@@ -313,6 +441,7 @@ describe("sendTurn", () => {
|
||||
url: "data:image/png;base64,BBBB",
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -346,6 +475,67 @@ 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();
|
||||
|
||||
@@ -454,8 +644,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",
|
||||
},
|
||||
);
|
||||
|
||||
@@ -482,6 +672,80 @@ 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", () => {
|
||||
|
||||
@@ -22,6 +22,12 @@ import {
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { Effect, ServiceMap } from "effect";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "./provider/codexCliVersion";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
interface PendingRequest {
|
||||
@@ -34,7 +40,10 @@ interface PendingRequest {
|
||||
interface PendingApprovalRequest {
|
||||
requestId: ApprovalRequestId;
|
||||
jsonRpcId: string | number;
|
||||
method: "item/commandExecution/requestApproval" | "item/fileChange/requestApproval";
|
||||
method:
|
||||
| "item/commandExecution/requestApproval"
|
||||
| "item/fileChange/requestApproval"
|
||||
| "item/fileRead/requestApproval";
|
||||
requestKind: ProviderRequestKind;
|
||||
threadId: ThreadId;
|
||||
turnId?: TurnId;
|
||||
@@ -55,6 +64,7 @@ interface CodexUserInputAnswer {
|
||||
|
||||
interface CodexSessionContext {
|
||||
session: ProviderSession;
|
||||
account: CodexAccountSnapshot;
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
output: readline.Interface;
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
@@ -86,13 +96,30 @@ 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;
|
||||
}
|
||||
|
||||
@@ -117,6 +144,8 @@ export interface CodexThreadSnapshot {
|
||||
turns: CodexThreadTurnSnapshot[];
|
||||
}
|
||||
|
||||
const CODEX_VERSION_CHECK_TIMEOUT_MS = 4_000;
|
||||
|
||||
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
|
||||
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
|
||||
const CODEX_STDERR_LOG_REGEX =
|
||||
@@ -132,6 +161,50 @@ 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.
|
||||
@@ -254,6 +327,19 @@ 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";
|
||||
@@ -271,6 +357,17 @@ 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
|
||||
@@ -323,7 +420,7 @@ function buildCodexCollaborationMode(input: {
|
||||
readonly effort?: string;
|
||||
}):
|
||||
| {
|
||||
mode: "plan";
|
||||
mode: "default" | "plan";
|
||||
settings: {
|
||||
model: string;
|
||||
reasoning_effort: string;
|
||||
@@ -331,16 +428,19 @@ function buildCodexCollaborationMode(input: {
|
||||
};
|
||||
}
|
||||
| undefined {
|
||||
if (input.interactionMode !== "plan") {
|
||||
if (input.interactionMode === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex";
|
||||
return {
|
||||
mode: "plan",
|
||||
mode: input.interactionMode,
|
||||
settings: {
|
||||
model,
|
||||
reasoning_effort: input.effort ?? "medium",
|
||||
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
developer_instructions:
|
||||
input.interactionMode === "plan"
|
||||
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
|
||||
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -352,18 +452,14 @@ function toCodexUserInputAnswer(value: unknown): CodexUserInputAnswer {
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const answers = value.filter((entry): entry is string => typeof entry === "string");
|
||||
if (answers.length > 0) {
|
||||
return { answers };
|
||||
}
|
||||
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");
|
||||
if (answers.length > 0) {
|
||||
return { answers };
|
||||
}
|
||||
return { answers };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -447,6 +543,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const codexOptions = readCodexProviderOptions(input);
|
||||
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
|
||||
const codexHomePath = codexOptions.homePath;
|
||||
this.assertSupportedCodexCliVersion({
|
||||
binaryPath: codexBinaryPath,
|
||||
cwd: resolvedCwd,
|
||||
...(codexHomePath ? { homePath: codexHomePath } : {}),
|
||||
});
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
@@ -460,6 +561,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
context = {
|
||||
session,
|
||||
account: {
|
||||
type: "unknown",
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
},
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
@@ -477,12 +583,33 @@ 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 = normalizeCodexModelSlug(input.model);
|
||||
const normalizedModel = resolveCodexModelForAccount(
|
||||
normalizeCodexModelSlug(input.model),
|
||||
context.account,
|
||||
);
|
||||
const sessionOverrides = {
|
||||
model: normalizedModel ?? null,
|
||||
cwd: input.cwd ?? null,
|
||||
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
|
||||
cwd: input.cwd ?? null,
|
||||
...mapCodexRuntimeMode(input.runtimeMode ?? "full-access"),
|
||||
};
|
||||
|
||||
@@ -642,10 +769,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: "plan";
|
||||
mode: "default" | "plan";
|
||||
settings: {
|
||||
model: string;
|
||||
reasoning_effort: string;
|
||||
@@ -656,16 +783,19 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
threadId: providerThreadId,
|
||||
input: turnInput,
|
||||
};
|
||||
const normalizedModel = normalizeCodexModelSlug(input.model ?? context.session.model);
|
||||
const normalizedModel = resolveCodexModelForAccount(
|
||||
normalizeCodexModelSlug(input.model ?? context.session.model),
|
||||
context.account,
|
||||
);
|
||||
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 } : {}),
|
||||
@@ -1064,7 +1194,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
method:
|
||||
requestKind === "command"
|
||||
? "item/commandExecution/requestApproval"
|
||||
: "item/fileChange/requestApproval",
|
||||
: requestKind === "file-read"
|
||||
? "item/fileRead/requestApproval"
|
||||
: "item/fileChange/requestApproval",
|
||||
requestKind,
|
||||
threadId: context.session.threadId,
|
||||
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||
@@ -1201,6 +1333,14 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.emit("event", event);
|
||||
}
|
||||
|
||||
private assertSupportedCodexCliVersion(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly homePath?: string;
|
||||
}): void {
|
||||
assertSupportedCodexCliVersion(input);
|
||||
}
|
||||
|
||||
private updateSession(context: CodexSessionContext, updates: Partial<ProviderSession>): void {
|
||||
context.session = {
|
||||
...context.session,
|
||||
@@ -1381,6 +1521,51 @@ function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
|
||||
};
|
||||
}
|
||||
|
||||
function assertSupportedCodexCliVersion(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly homePath?: string;
|
||||
}): void {
|
||||
const result = spawnSync(input.binaryPath, ["--version"], {
|
||||
cwd: input.cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
|
||||
},
|
||||
encoding: "utf8",
|
||||
shell: process.platform === "win32",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
timeout: CODEX_VERSION_CHECK_TIMEOUT_MS,
|
||||
maxBuffer: 1024 * 1024,
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
const lower = result.error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("enoent") ||
|
||||
lower.includes("command not found") ||
|
||||
lower.includes("not found")
|
||||
) {
|
||||
throw new Error(`Codex CLI (${input.binaryPath}) is not installed or not executable.`);
|
||||
}
|
||||
throw new Error(
|
||||
`Failed to execute Codex CLI version check: ${result.error.message || String(result.error)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const stdout = result.stdout ?? "";
|
||||
const stderr = result.stderr ?? "";
|
||||
if (result.status !== 0) {
|
||||
const detail = stderr.trim() || stdout.trim() || `Command exited with code ${result.status}.`;
|
||||
throw new Error(`Codex CLI version check failed. ${detail}`);
|
||||
}
|
||||
|
||||
const parsedVersion = parseCodexCliVersion(`${stdout}\n${stderr}`);
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
throw new Error(formatCodexCliUpgradeMessage(parsedVersion));
|
||||
}
|
||||
}
|
||||
|
||||
function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
|
||||
if (!resumeCursor || typeof resumeCursor !== "object" || Array.isArray(resumeCursor)) {
|
||||
return undefined;
|
||||
|
||||
@@ -654,7 +654,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
const realGitService = yield* GitService;
|
||||
let fetchStarted = false;
|
||||
let releaseFetch: () => void = () => undefined;
|
||||
let releaseFetch!: () => void;
|
||||
const waitForReleasePromise = new Promise<void>((resolve) => {
|
||||
releaseFetch = resolve;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function isGitRepository(cwd: string): boolean {
|
||||
return existsSync(join(cwd, ".git"));
|
||||
}
|
||||
@@ -9,6 +9,7 @@ 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),
|
||||
@@ -16,6 +17,7 @@ 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,16 +1,20 @@
|
||||
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, t3Cli, type CliConfigShape } from "./main";
|
||||
import { CliConfig, recordStartupHeartbeat, 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);
|
||||
@@ -47,6 +51,8 @@ const testLayer = Layer.mergeAll(
|
||||
openBrowser: (_target: string) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
} satisfies OpenShape),
|
||||
AnalyticsService.layerTest,
|
||||
FetchHttpClient.layer,
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
@@ -227,6 +233,43 @@ 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"]);
|
||||
|
||||
@@ -9,8 +9,6 @@
|
||||
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,
|
||||
@@ -22,9 +20,12 @@ 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;
|
||||
@@ -199,6 +200,7 @@ const LayerLive = (input: CliInput) =>
|
||||
Layer.provideMerge(ProviderHealthLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
@@ -208,6 +210,31 @@ 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;
|
||||
@@ -227,6 +254,7 @@ 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" | "claudeCode" | "cursor";
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -57,7 +57,7 @@ function createProviderServiceHarness(
|
||||
cwd: string,
|
||||
hasSession = true,
|
||||
sessionCwd = cwd,
|
||||
providerName: "codex" | "claudeCode" = "codex",
|
||||
providerName: ProviderSession["provider"] = "codex",
|
||||
) {
|
||||
const now = new Date().toISOString();
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
@@ -91,7 +91,6 @@ function createProviderServiceHarness(
|
||||
listSessions,
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation,
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
@@ -235,7 +234,6 @@ describe("CheckpointReactor", () => {
|
||||
readonly projectWorkspaceRoot?: string;
|
||||
readonly threadWorktreePath?: string | null;
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: "codex" | "claudeCode";
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
@@ -243,7 +241,7 @@ describe("CheckpointReactor", () => {
|
||||
cwd,
|
||||
options?.hasSession ?? true,
|
||||
options?.providerSessionCwd ?? cwd,
|
||||
options?.providerName ?? "codex",
|
||||
"codex",
|
||||
);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -476,69 +474,6 @@ 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();
|
||||
@@ -845,7 +780,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");
|
||||
@@ -854,75 +789,6 @@ 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();
|
||||
@@ -1008,11 +874,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,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,6 +20,7 @@ import { CheckpointReactor, type CheckpointReactorShape } from "../Services/Chec
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/isRepo.ts";
|
||||
|
||||
type ReactorInput =
|
||||
| {
|
||||
@@ -144,6 +145,8 @@ const make = Effect.gen(function* () {
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
|
||||
|
||||
const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
|
||||
) {
|
||||
@@ -184,6 +187,14 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(checkpointCwd)) {
|
||||
yield* Effect.logDebug("checkpoint capture skipped for non-git workspace", {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
cwd: checkpointCwd,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
@@ -319,6 +330,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(checkpointCwd)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
@@ -378,6 +392,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(checkpointCwd)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
@@ -425,6 +442,15 @@ const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(sessionRuntime.value.cwd)) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: "Checkpoints are unavailable because this project is not a git repository.",
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
|
||||
@@ -93,9 +93,7 @@ describe("ProviderCommandReactor", () => {
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"provider" in input &&
|
||||
(input.provider === "codex" ||
|
||||
input.provider === "claudeCode" ||
|
||||
input.provider === "cursor")
|
||||
input.provider === "codex"
|
||||
? input.provider
|
||||
: "codex";
|
||||
const resumeCursor =
|
||||
@@ -187,10 +185,9 @@ describe("ProviderCommandReactor", () => {
|
||||
listSessions: () => Effect.succeed(runtimeSessions),
|
||||
getCapabilities: (provider) =>
|
||||
Effect.succeed({
|
||||
sessionModelSwitch: provider === "cursor" ? "unsupported" : "in-session",
|
||||
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
|
||||
}),
|
||||
rollbackConversation: () => unsupported(),
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
@@ -385,80 +382,6 @@ 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();
|
||||
@@ -505,111 +428,6 @@ 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();
|
||||
@@ -695,66 +513,6 @@ 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();
|
||||
@@ -950,7 +708,7 @@ describe("ProviderCommandReactor", () => {
|
||||
harness.respondToRequest.mockImplementation(() =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "cursor",
|
||||
provider: "codex",
|
||||
method: "session/request_permission",
|
||||
detail: "Unknown pending permission request: approval-request-1",
|
||||
}),
|
||||
@@ -965,7 +723,7 @@ describe("ProviderCommandReactor", () => {
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "cursor",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
type ProviderKind,
|
||||
type ProviderServiceTier,
|
||||
type ProviderStartOptions,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
type ProviderSession,
|
||||
@@ -143,6 +145,8 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly kind:
|
||||
@@ -201,6 +205,8 @@ const make = Effect.gen(function* () {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly serviceTier?: ProviderServiceTier | null;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
},
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -211,11 +217,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const desiredRuntimeMode = thread.runtimeMode;
|
||||
const currentProvider: ProviderKind | undefined =
|
||||
thread.session?.providerName === "codex" ||
|
||||
thread.session?.providerName === "claudeCode" ||
|
||||
thread.session?.providerName === "cursor"
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
thread.session?.providerName === "codex" ? thread.session.providerName : undefined;
|
||||
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
|
||||
const desiredModel = options?.model ?? thread.model;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
@@ -239,7 +241,9 @@ const make = Effect.gen(function* () {
|
||||
: {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
...(desiredModel ? { model: desiredModel } : {}),
|
||||
...(options?.serviceTier !== undefined ? { serviceTier: options.serviceTier } : {}),
|
||||
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
|
||||
...(options?.providerOptions !== undefined ? { providerOptions: options.providerOptions } : {}),
|
||||
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
});
|
||||
@@ -324,7 +328,9 @@ const make = Effect.gen(function* () {
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly serviceTier?: ProviderServiceTier | null;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
@@ -332,10 +338,15 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
if (input.providerOptions !== undefined) {
|
||||
threadProviderOptions.set(input.threadId, input.providerOptions);
|
||||
}
|
||||
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 } : {}),
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
});
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
@@ -354,6 +365,7 @@ 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 } : {}),
|
||||
});
|
||||
@@ -468,7 +480,9 @@ 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 } : {}),
|
||||
...(event.payload.providerOptions !== undefined ? { providerOptions: event.payload.providerOptions } : {}),
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
@@ -624,7 +638,14 @@ const make = Effect.gen(function* () {
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt);
|
||||
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(
|
||||
event.payload.threadId,
|
||||
event.occurredAt,
|
||||
cachedProviderOptions !== undefined
|
||||
? { providerOptions: cachedProviderOptions }
|
||||
: {},
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "thread.turn-start-requested":
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { OrchestrationReadModel, ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -41,7 +45,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -65,7 +69,6 @@ function createProviderServiceHarness() {
|
||||
listSessions: () => Effect.succeed([]),
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation: () => unsupported(),
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
@@ -113,6 +116,13 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
@@ -123,9 +133,14 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
async function createHarness() {
|
||||
const workspaceRoot = makeTempDir("t3-provider-project-");
|
||||
fs.mkdirSync(path.join(workspaceRoot, ".git"));
|
||||
const provider = createProviderServiceHarness();
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -153,7 +168,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
commandId: CommandId.makeUnsafe("cmd-provider-project-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
@@ -437,60 +452,6 @@ 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();
|
||||
@@ -873,6 +834,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
detail: "hello live",
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Ref, Stream } from "effect";
|
||||
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { isGitRepository } from "../../git/isRepo.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ProviderRuntimeIngestionService,
|
||||
@@ -507,6 +509,22 @@ const make = Effect.gen(function* () {
|
||||
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
|
||||
});
|
||||
|
||||
const isGitRepoForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return false;
|
||||
}
|
||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
if (!workspaceCwd) {
|
||||
return false;
|
||||
}
|
||||
return isGitRepository(workspaceCwd);
|
||||
});
|
||||
|
||||
const rememberAssistantMessageId = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
@@ -933,6 +951,10 @@ const make = Effect.gen(function* () {
|
||||
if (assistantCompletion) {
|
||||
const assistantMessageId = assistantCompletion.messageId;
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const existingAssistantMessage = thread.messages.find((entry) => entry.id === assistantMessageId);
|
||||
const shouldApplyFallbackCompletionText =
|
||||
!existingAssistantMessage ||
|
||||
existingAssistantMessage.text.length === 0;
|
||||
if (turnId) {
|
||||
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
|
||||
}
|
||||
@@ -945,7 +967,7 @@ const make = Effect.gen(function* () {
|
||||
createdAt: now,
|
||||
commandTag: "assistant-complete",
|
||||
finalDeltaCommandTag: "assistant-delta-finalize",
|
||||
...(assistantCompletion.fallbackText !== undefined
|
||||
...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText
|
||||
? { fallbackText: assistantCompletion.fallbackText }
|
||||
: {}),
|
||||
});
|
||||
@@ -1041,7 +1063,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (event.type === "turn.diff.updated") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
if (turnId && (yield* isGitRepoForThread(thread.id))) {
|
||||
const assistantMessageId = MessageId.makeUnsafe(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
||||
);
|
||||
|
||||
@@ -301,7 +301,9 @@ 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 } : {}),
|
||||
...(command.providerOptions !== undefined ? { providerOptions: command.providerOptions } : {}),
|
||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
runtimeMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readPathFromLoginShell } from "@t3tools/shared/shell";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
const result = readPathFromLoginShell(shell);
|
||||
if (result) {
|
||||
process.env.PATH = result;
|
||||
}
|
||||
@@ -20,12 +17,12 @@ export function fixPath(): void {
|
||||
}
|
||||
|
||||
export const expandHomePath = Effect.fn(function* (input: string) {
|
||||
const { join, sep } = yield* Path.Path;
|
||||
const { join } = yield* Path.Path;
|
||||
if (input === "~") {
|
||||
return OS.homedir();
|
||||
}
|
||||
if (input.startsWith(`~${sep}`)) {
|
||||
return join(OS.homedir(), input.slice(sep.length));
|
||||
if (input.startsWith("~/") || input.startsWith("~\\")) {
|
||||
return join(OS.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
});
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
type CodexAppServerSendTurnInput,
|
||||
} from "../../codexAppServerManager.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||
@@ -444,6 +443,78 @@ 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,9 +274,6 @@ 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];
|
||||
}
|
||||
|
||||
@@ -284,7 +281,7 @@ function toCanonicalUserInputAnswers(
|
||||
const answerList = asArray(answerObject?.answers)?.filter(
|
||||
(entry): entry is string => typeof entry === "string",
|
||||
);
|
||||
if (!answerList || answerList.length === 0) {
|
||||
if (!answerList) {
|
||||
return [];
|
||||
}
|
||||
return [[questionId, answerList.length === 1 ? answerList[0] : answerList] as const];
|
||||
@@ -1357,6 +1354,7 @@ 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 }
|
||||
: {}),
|
||||
|
||||
@@ -1,655 +0,0 @@
|
||||
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));
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,6 @@ 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";
|
||||
@@ -28,30 +27,11 @@ 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.mergeAll(
|
||||
Layer.succeed(CodexAdapter, fakeCodexAdapter),
|
||||
Layer.succeed(CursorAdapter, fakeCursorAdapter),
|
||||
),
|
||||
Layer.succeed(CodexAdapter, fakeCodexAdapter),
|
||||
),
|
||||
NodeServices.layer,
|
||||
),
|
||||
@@ -62,12 +42,10 @@ 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", "cursor"]);
|
||||
assert.deepEqual(providers, ["codex"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ 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>>;
|
||||
@@ -27,7 +26,7 @@ const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOption
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [yield* CodexAdapter, yield* CursorAdapter];
|
||||
: [yield* CodexAdapter];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
|
||||
|
||||
@@ -85,6 +85,28 @@ it.effect("returns unavailable when codex is missing", () =>
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is below the minimum supported version", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
|
||||
@@ -16,6 +16,11 @@ import type {
|
||||
import { Effect, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "../codexCliVersion";
|
||||
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
@@ -247,6 +252,18 @@ export const checkCodexProviderStatus: Effect.Effect<
|
||||
};
|
||||
}
|
||||
|
||||
const parsedVersion = parseCodexCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: formatCodexCliUpgradeMessage(parsedVersion),
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
|
||||
@@ -42,6 +42,7 @@ 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);
|
||||
@@ -51,7 +52,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -216,15 +217,12 @@ 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)
|
||||
: provider === "claudeCode"
|
||||
? Effect.succeed(claude.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex", "claudeCode"]),
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
@@ -238,8 +236,10 @@ function makeProviderServiceLayer() {
|
||||
makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
),
|
||||
directoryLayer,
|
||||
|
||||
runtimeRepositoryLayer,
|
||||
NodeServices.layer,
|
||||
),
|
||||
@@ -247,7 +247,6 @@ function makeProviderServiceLayer() {
|
||||
|
||||
return {
|
||||
codex,
|
||||
claude,
|
||||
layer,
|
||||
};
|
||||
}
|
||||
@@ -284,6 +283,7 @@ 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,6 +342,7 @@ 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* () {
|
||||
@@ -355,11 +356,6 @@ 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 });
|
||||
@@ -384,6 +380,7 @@ it.effect(
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
|
||||
Layer.provide(secondDirectoryLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
secondCodex.startSession.mockClear();
|
||||
@@ -496,29 +493,6 @@ 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;
|
||||
@@ -570,7 +544,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* provider.stopAll();
|
||||
yield* routing.codex.stopAll();
|
||||
routing.codex.startSession.mockClear();
|
||||
routing.codex.sendTurn.mockClear();
|
||||
|
||||
@@ -599,7 +573,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stops all sessions and clears adapter runtime", () =>
|
||||
it.effect("lists no sessions after adapter runtime clears", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
@@ -614,7 +588,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* provider.stopAll();
|
||||
yield* routing.codex.stopAll();
|
||||
|
||||
const remaining = yield* provider.listSessions();
|
||||
assert.equal(remaining.length, 0);
|
||||
@@ -662,14 +636,6 @@ 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,6 +31,7 @@ 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;
|
||||
@@ -85,15 +86,30 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
|
||||
}
|
||||
}
|
||||
|
||||
function toRuntimePayloadFromSession(session: ProviderSession): Record<string, unknown> {
|
||||
function toRuntimePayloadFromSession(
|
||||
session: ProviderSession,
|
||||
extra?: { readonly providerOptions?: unknown },
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
cwd: session.cwd ?? null,
|
||||
model: session.model ?? null,
|
||||
activeTurnId: session.activeTurnId ?? null,
|
||||
lastError: session.lastError ?? null,
|
||||
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function readPersistedProviderOptions(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): Record<string, unknown> | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
}
|
||||
const raw = "providerOptions" in runtimePayload ? runtimePayload.providerOptions : undefined;
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
|
||||
return raw as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function readPersistedCwd(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): string | undefined {
|
||||
@@ -108,6 +124,7 @@ function readPersistedCwd(
|
||||
|
||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const analytics = yield* Effect.service(AnalyticsService);
|
||||
const canonicalEventLogger =
|
||||
options?.canonicalEventLogger ??
|
||||
(options?.canonicalEventLogPath !== undefined
|
||||
@@ -135,6 +152,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const upsertSessionBinding = (
|
||||
session: ProviderSession,
|
||||
threadId: ThreadId,
|
||||
extra?: { readonly providerOptions?: unknown },
|
||||
) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
@@ -142,7 +160,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
runtimeMode: session.runtimeMode,
|
||||
status: toRuntimeStatus(session),
|
||||
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
|
||||
runtimePayload: toRuntimePayloadFromSession(session),
|
||||
runtimePayload: toRuntimePayloadFromSession(session, extra),
|
||||
});
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
@@ -178,6 +196,11 @@ 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;
|
||||
}
|
||||
}
|
||||
@@ -190,11 +213,13 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
|
||||
|
||||
const resumed = yield* adapter.startSession({
|
||||
threadId: input.binding.threadId,
|
||||
provider: input.binding.provider,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
});
|
||||
@@ -206,6 +231,11 @@ 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;
|
||||
});
|
||||
|
||||
@@ -261,7 +291,20 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId);
|
||||
yield* upsertSessionBinding(
|
||||
session,
|
||||
threadId,
|
||||
input.providerOptions !== undefined
|
||||
? { providerOptions: input.providerOptions }
|
||||
: {},
|
||||
);
|
||||
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;
|
||||
});
|
||||
@@ -301,6 +344,13 @@ 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;
|
||||
});
|
||||
|
||||
@@ -317,6 +367,9 @@ 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) =>
|
||||
@@ -332,6 +385,10 @@ 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) =>
|
||||
@@ -365,6 +422,9 @@ 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"] = () =>
|
||||
@@ -400,13 +460,17 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
return session;
|
||||
}
|
||||
|
||||
return {
|
||||
...session,
|
||||
...(session.resumeCursor === undefined && binding.resumeCursor !== undefined
|
||||
? { resumeCursor: binding.resumeCursor }
|
||||
: {}),
|
||||
...(binding.runtimeMode !== undefined ? { runtimeMode: binding.runtimeMode } : {}),
|
||||
};
|
||||
const overrides: {
|
||||
resumeCursor?: ProviderSession["resumeCursor"];
|
||||
runtimeMode?: ProviderSession["runtimeMode"];
|
||||
} = {};
|
||||
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
|
||||
overrides.resumeCursor = binding.resumeCursor;
|
||||
}
|
||||
if (binding.runtimeMode !== undefined) {
|
||||
overrides.runtimeMode = binding.runtimeMode;
|
||||
}
|
||||
return Object.assign({}, session, overrides);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -429,9 +493,13 @@ 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 stopAll: ProviderServiceShape["stopAll"] = () =>
|
||||
const runStopAll = () =>
|
||||
Effect.gen(function* () {
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
|
||||
@@ -451,8 +519,18 @@ 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,
|
||||
@@ -463,7 +541,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
listSessions,
|
||||
getCapabilities,
|
||||
rollbackConversation,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
} satisfies ProviderServiceShape;
|
||||
});
|
||||
|
||||
@@ -133,6 +133,36 @@ 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-"));
|
||||
@@ -174,26 +204,4 @@ 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" || providerName === "claudeCode" || providerName === "cursor") {
|
||||
if (providerName === "codex") {
|
||||
return Effect.succeed(providerName);
|
||||
}
|
||||
return Effect.fail(
|
||||
@@ -95,11 +95,15 @@ 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 ?? existingRuntime?.adapterKey ?? binding.provider,
|
||||
adapterKey:
|
||||
binding.adapterKey ??
|
||||
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
|
||||
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
|
||||
status: binding.status ?? existingRuntime?.status ?? "running",
|
||||
lastSeenAt: now,
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,110 +0,0 @@
|
||||
/**
|
||||
* 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,16 +99,6 @@ 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.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/;
|
||||
|
||||
export const MINIMUM_CODEX_CLI_VERSION = "0.37.0";
|
||||
|
||||
interface ParsedSemver {
|
||||
readonly major: number;
|
||||
readonly minor: number;
|
||||
readonly patch: number;
|
||||
readonly prerelease: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
function normalizeCodexVersion(version: string): string {
|
||||
const [main, prerelease] = version.trim().split("-", 2);
|
||||
const segments = (main ?? "")
|
||||
.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0);
|
||||
|
||||
if (segments.length === 2) {
|
||||
segments.push("0");
|
||||
}
|
||||
|
||||
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
|
||||
}
|
||||
|
||||
function parseSemver(version: string): ParsedSemver | null {
|
||||
const normalized = normalizeCodexVersion(version);
|
||||
const [main = "", prerelease] = normalized.split("-", 2);
|
||||
const segments = main.split(".");
|
||||
if (segments.length !== 3) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [majorSegment, minorSegment, patchSegment] = segments;
|
||||
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const major = Number.parseInt(majorSegment, 10);
|
||||
const minor = Number.parseInt(minorSegment, 10);
|
||||
const patch = Number.parseInt(patchSegment, 10);
|
||||
if (![major, minor, patch].every(Number.isInteger)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
prerelease:
|
||||
prerelease
|
||||
?.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0) ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function comparePrereleaseIdentifier(left: string, right: string): number {
|
||||
const leftNumeric = /^\d+$/.test(left);
|
||||
const rightNumeric = /^\d+$/.test(right);
|
||||
|
||||
if (leftNumeric && rightNumeric) {
|
||||
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
|
||||
}
|
||||
if (leftNumeric) {
|
||||
return -1;
|
||||
}
|
||||
if (rightNumeric) {
|
||||
return 1;
|
||||
}
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
export function compareCodexCliVersions(left: string, right: string): number {
|
||||
const parsedLeft = parseSemver(left);
|
||||
const parsedRight = parseSemver(right);
|
||||
if (!parsedLeft || !parsedRight) {
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
if (parsedLeft.major !== parsedRight.major) {
|
||||
return parsedLeft.major - parsedRight.major;
|
||||
}
|
||||
if (parsedLeft.minor !== parsedRight.minor) {
|
||||
return parsedLeft.minor - parsedRight.minor;
|
||||
}
|
||||
if (parsedLeft.patch !== parsedRight.patch) {
|
||||
return parsedLeft.patch - parsedRight.patch;
|
||||
}
|
||||
|
||||
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
if (parsedLeft.prerelease.length === 0) {
|
||||
return 1;
|
||||
}
|
||||
if (parsedRight.prerelease.length === 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const leftIdentifier = parsedLeft.prerelease[index];
|
||||
const rightIdentifier = parsedRight.prerelease[index];
|
||||
if (leftIdentifier === undefined) {
|
||||
return -1;
|
||||
}
|
||||
if (rightIdentifier === undefined) {
|
||||
return 1;
|
||||
}
|
||||
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
|
||||
if (comparison !== 0) {
|
||||
return comparison;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function parseCodexCliVersion(output: string): string | null {
|
||||
const match = CODEX_VERSION_PATTERN.exec(output);
|
||||
if (!match?.[1]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = parseSemver(match[1]);
|
||||
if (!parsed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeCodexVersion(match[1]);
|
||||
}
|
||||
|
||||
export function isCodexCliVersionSupported(version: string): boolean {
|
||||
return compareCodexCliVersions(version, MINIMUM_CODEX_CLI_VERSION) >= 0;
|
||||
}
|
||||
|
||||
export function formatCodexCliUpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Codex CLI ${versionLabel} is too old for T3 Code. Upgrade to v${MINIMUM_CODEX_CLI_VERSION} or newer and restart T3 Code.`;
|
||||
}
|
||||
@@ -19,7 +19,6 @@ 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";
|
||||
@@ -35,11 +34,12 @@ 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
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | AnalyticsService
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
@@ -57,12 +57,8 @@ 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(
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { Effect, Logger, Option } from "effect";
|
||||
import { Effect, Logger } from "effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { ServerConfig } from "./config";
|
||||
|
||||
export const ServerLoggerLive = Effect.gen(function* () {
|
||||
const config = yield* Effect.serviceOption(ServerConfig);
|
||||
if (Option.isNone(config)) {
|
||||
return Logger.layer([Logger.defaultLogger]);
|
||||
}
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
const logDir = path.join(config.value.stateDir, "logs");
|
||||
const logDir = path.join(config.stateDir, "logs");
|
||||
const logPath = path.join(logDir, "server.log");
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
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),
|
||||
);
|
||||
@@ -0,0 +1,122 @@
|
||||
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,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* 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);
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* 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,
|
||||
});
|
||||
}
|
||||
@@ -1150,7 +1150,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
|
||||
private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
|
||||
const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
|
||||
let release: () => void = () => {};
|
||||
let release!: () => void;
|
||||
const current = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
@@ -50,6 +50,7 @@ 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[];
|
||||
@@ -393,10 +394,7 @@ 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> {
|
||||
@@ -437,6 +435,7 @@ describe("WebSocket Server", () => {
|
||||
? Layer.succeed(TerminalManager, options.terminalManager)
|
||||
: Layer.empty,
|
||||
);
|
||||
|
||||
const runtimeLayer = Layer.merge(
|
||||
Layer.merge(
|
||||
makeServerRuntimeServicesLayer().pipe(Layer.provide(infrastructureLayer)),
|
||||
@@ -449,6 +448,7 @@ 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(
|
||||
@@ -1108,13 +1108,14 @@ describe("WebSocket Server", () => {
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const workspaceRoot = makeTempDir("t3code-ws-diff-project-");
|
||||
const createdAt = new Date().toISOString();
|
||||
const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "project.create",
|
||||
commandId: "cmd-diff-project-create",
|
||||
projectId: "project-diff",
|
||||
title: "Diff Project",
|
||||
workspaceRoot: "/tmp/ws-diff-project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
@@ -1171,7 +1172,6 @@ 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);
|
||||
@@ -1187,13 +1187,14 @@ describe("WebSocket Server", () => {
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const workspaceRoot = makeTempDir("t3code-ws-project-");
|
||||
const createdAt = new Date().toISOString();
|
||||
const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "project.create",
|
||||
commandId: "cmd-ws-project-create",
|
||||
projectId: "project-1",
|
||||
title: "WS Project",
|
||||
workspaceRoot: "/tmp/ws-project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
@@ -1620,7 +1621,6 @@ 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 () => {
|
||||
|
||||
@@ -71,6 +71,8 @@ import {
|
||||
resolveAttachmentPathById,
|
||||
} from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { expandHomePath } from "./os-jank.ts";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -193,6 +195,13 @@ function stripRequestTag<T extends { _tag: string }>(body: T) {
|
||||
return Struct.omit(body, ["_tag"]);
|
||||
}
|
||||
|
||||
function messageFromCause(cause: Cause.Cause<unknown>): string {
|
||||
const squashed = Cause.squash(cause);
|
||||
const message =
|
||||
squashed instanceof Error ? squashed.message.trim() : String(squashed).trim();
|
||||
return message.length > 0 ? message : Cause.pretty(cause);
|
||||
}
|
||||
|
||||
export type ServerCoreRuntimeServices =
|
||||
| OrchestrationEngineService
|
||||
| ProjectionSnapshotQuery
|
||||
@@ -207,7 +216,8 @@ export type ServerRuntimeServices =
|
||||
| GitCore
|
||||
| TerminalManager
|
||||
| Keybindings
|
||||
| Open;
|
||||
| Open
|
||||
| AnalyticsService;
|
||||
|
||||
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
|
||||
"ServerLifecycleError",
|
||||
@@ -296,6 +306,41 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
||||
readonly command: ClientOrchestrationCommand;
|
||||
}) {
|
||||
const normalizeProjectWorkspaceRoot = Effect.fnUntraced(function* (workspaceRoot: string) {
|
||||
const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath(workspaceRoot.trim()));
|
||||
const workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!workspaceStat) {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Project directory does not exist: ${normalizedWorkspaceRoot}`,
|
||||
});
|
||||
}
|
||||
if (workspaceStat.type !== "Directory") {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Project path is not a directory: ${normalizedWorkspaceRoot}`,
|
||||
});
|
||||
}
|
||||
return normalizedWorkspaceRoot;
|
||||
});
|
||||
|
||||
if (input.command.type === "project.create") {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (
|
||||
input.command.type === "project.meta.update" &&
|
||||
input.command.workspaceRoot !== undefined
|
||||
) {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (input.command.type !== "thread.turn.start") {
|
||||
return input.command as OrchestrationCommand;
|
||||
}
|
||||
@@ -566,7 +611,6 @@ 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;
|
||||
|
||||
@@ -657,12 +701,10 @@ 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 runtimeServices = yield* Effect.services<
|
||||
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>();
|
||||
const runPromise = Effect.runPromiseWith(runtimeServices);
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
|
||||
(event) => void Effect.runPromise(onTerminalEvent(event)),
|
||||
@@ -877,7 +919,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
if (request._tag === "Failure") {
|
||||
const errorResponse = yield* encodeResponse({
|
||||
id: "unknown",
|
||||
error: { message: `Invalid request format: ${Cause.pretty(request.cause)}` },
|
||||
error: { message: `Invalid request format: ${messageFromCause(request.cause)}` },
|
||||
});
|
||||
ws.send(errorResponse);
|
||||
return;
|
||||
@@ -887,7 +929,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
if (result._tag === "Failure") {
|
||||
const errorResponse = yield* encodeResponse({
|
||||
id: request.value.id,
|
||||
error: { message: Cause.pretty(result.cause) },
|
||||
error: { message: messageFromCause(result.cause) },
|
||||
});
|
||||
ws.send(errorResponse);
|
||||
return;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"version": "0.0.4-alpha.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
|
Before Width: | Height: | Size: 47 KiB After Width: | Height: | Size: 74 KiB |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1003 B |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 279 KiB After Width: | Height: | Size: 204 KiB |
@@ -1,4 +0,0 @@
|
||||
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M0 10C0 4.47715 4.47715 0 10 0H118C123.523 0 128 4.47715 128 10V118C128 123.523 123.523 128 118 128H10C4.47715 128 0 123.523 0 118V10Z" fill="black"/>
|
||||
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="white"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
@@ -1,6 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAppModelOptions, getSlashModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
import {
|
||||
getAppModelOptions,
|
||||
getSlashModelOptions,
|
||||
normalizeCustomModelSlugs,
|
||||
resolveAppServiceTier,
|
||||
shouldShowFastTierIcon,
|
||||
resolveAppModelSelection,
|
||||
} from "./appSettings";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
@@ -15,17 +22,6 @@ 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", () => {
|
||||
@@ -51,14 +47,18 @@ describe("getAppModelOptions", () => {
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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,
|
||||
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("falls back to the provider default when no model is selected", () => {
|
||||
expect(resolveAppModelSelection("codex", [], "")).toBe("gpt-5.4");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSlashModelOptions", () => {
|
||||
@@ -83,12 +83,23 @@ describe("getSlashModelOptions", () => {
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
|
||||
});
|
||||
});
|
||||
|
||||
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"]);
|
||||
describe("resolveAppServiceTier", () => {
|
||||
it("maps automatic to no override", () => {
|
||||
expect(resolveAppServiceTier("auto")).toBeNull();
|
||||
});
|
||||
|
||||
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
|
||||
expect(cursorOptions.some((option) => option.slug === "cursor/custom-model")).toBe(true);
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,33 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { type ProviderKind, type ProviderServiceTier } from "@t3tools/contracts";
|
||||
import { getDefaultModel, 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({
|
||||
@@ -23,15 +41,10 @@ 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 {
|
||||
@@ -40,6 +53,22 @@ 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> = [];
|
||||
@@ -79,8 +108,6 @@ function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
|
||||
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeCode"),
|
||||
customCursorModels: normalizeCustomModelSlugs(settings.customCursorModels, "cursor"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -121,6 +148,38 @@ 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[],
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
type SupportedLanguages,
|
||||
} from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
import React, {
|
||||
Children,
|
||||
Suspense,
|
||||
isValidElement,
|
||||
@@ -28,6 +28,27 @@ import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
|
||||
class CodeHighlightErrorBoundary extends React.Component<
|
||||
{ fallback: ReactNode; children: ReactNode },
|
||||
{ hasError: boolean }
|
||||
> {
|
||||
constructor(props: { fallback: ReactNode; children: ReactNode }) {
|
||||
super(props);
|
||||
this.state = { hasError: false };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
override render() {
|
||||
if (this.state.hasError) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
interface ChatMarkdownProps {
|
||||
text: string;
|
||||
cwd: string | undefined;
|
||||
@@ -99,6 +120,14 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||
langs: [language as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
}).catch((err) => {
|
||||
highlighterPromiseCache.delete(language);
|
||||
if (language === "text") {
|
||||
// "text" itself failed — Shiki cannot initialize at all, surface the error
|
||||
throw err;
|
||||
}
|
||||
// Language not supported by Shiki — fall back to "text"
|
||||
return getHighlighterPromise("text");
|
||||
});
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
return promise;
|
||||
@@ -179,10 +208,14 @@ function SuspenseShikiCodeBlock({
|
||||
}
|
||||
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(
|
||||
() => highlighter.codeToHtml(code, { lang: language, theme: themeName }),
|
||||
[code, highlighter, language, themeName],
|
||||
);
|
||||
const highlightedHtml = useMemo(() => {
|
||||
try {
|
||||
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
|
||||
} catch {
|
||||
// If highlighting fails for this language, render as plain text
|
||||
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
||||
}
|
||||
}, [code, highlighter, language, themeName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming) {
|
||||
@@ -235,14 +268,16 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
<CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</CodeHighlightErrorBoundary>
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
|
||||
@@ -19,6 +19,7 @@ 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";
|
||||
@@ -44,6 +45,7 @@ interface TestFixture {
|
||||
}
|
||||
|
||||
let fixture: TestFixture;
|
||||
const wsRequests: WsRequestEnvelope["body"][] = [];
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
@@ -243,6 +245,17 @@ 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;
|
||||
@@ -307,6 +320,7 @@ const worker = setupWorker(
|
||||
}
|
||||
const method = request.body?._tag;
|
||||
if (typeof method !== "string") return;
|
||||
wsRequests.push(request.body);
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
@@ -378,6 +392,23 @@ 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) {
|
||||
@@ -466,8 +497,10 @@ 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();
|
||||
|
||||
@@ -547,6 +580,12 @@ 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: [],
|
||||
@@ -708,4 +747,124 @@ 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
@@ -175,6 +176,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
|
||||
);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
|
||||
const isGitRepo = gitBranchesQuery.data?.isRepo ?? true;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
@@ -250,6 +253,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
|
||||
enabled: isGitRepo,
|
||||
}),
|
||||
);
|
||||
const selectedTurnCheckpointDiff = selectedTurn
|
||||
@@ -530,6 +534,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Select a thread to inspect turn diffs.
|
||||
</div>
|
||||
) : !isGitRepo ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Turn diffs are unavailable because this project is not a git repository.
|
||||
</div>
|
||||
) : orderedTurnDiffSummaries.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
No completed turns yet.
|
||||
|
||||
@@ -42,7 +42,7 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, { kind: "open_pr", label: "Open PR", disabled: false });
|
||||
assert.deepInclude(quick, { kind: "open_pr", label: "View PR", disabled: false });
|
||||
});
|
||||
|
||||
it("buildMenuItems disables commit/push and enables open PR", () => {
|
||||
@@ -78,7 +78,7 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Open PR",
|
||||
label: "View PR",
|
||||
disabled: false,
|
||||
icon: "pr",
|
||||
kind: "open_pr",
|
||||
@@ -199,7 +199,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Open PR",
|
||||
label: "View PR",
|
||||
disabled: false,
|
||||
icon: "pr",
|
||||
kind: "open_pr",
|
||||
@@ -547,7 +547,7 @@ describe("when: branch has no upstream configured", () => {
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "open_pr",
|
||||
label: "Open PR",
|
||||
label: "View PR",
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -151,7 +151,7 @@ export function buildMenuItems(
|
||||
hasOpenPr
|
||||
? {
|
||||
id: "pr",
|
||||
label: "Open PR",
|
||||
label: "View PR",
|
||||
disabled: !canOpenPr,
|
||||
icon: "pr",
|
||||
kind: "open_pr",
|
||||
@@ -216,7 +216,7 @@ export function resolveQuickAction(
|
||||
if (!gitStatus.hasUpstream) {
|
||||
if (!isAhead) {
|
||||
if (hasOpenPr) {
|
||||
return { label: "Open PR", disabled: false, kind: "open_pr" };
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
return {
|
||||
label: "Push",
|
||||
@@ -266,7 +266,7 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (hasOpenPr && gitStatus.hasUpstream) {
|
||||
return { label: "Open PR", disabled: false, kind: "open_pr" };
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -98,7 +98,7 @@ function getMenuActionDisabledReason(
|
||||
}
|
||||
|
||||
if (hasOpenPr) {
|
||||
return "Open PR is currently unavailable.";
|
||||
return "View PR is currently unavailable.";
|
||||
}
|
||||
if (!hasBranch) {
|
||||
return "Detached HEAD: checkout a branch before creating a PR.";
|
||||
@@ -374,12 +374,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
},
|
||||
}
|
||||
: shouldOfferOpenPrCta
|
||||
? {
|
||||
actionProps: {
|
||||
children: "Open PR",
|
||||
onClick: () => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
? {
|
||||
actionProps: {
|
||||
children: "View PR",
|
||||
onClick: () => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
closeResultToast();
|
||||
void api.shell.openExternal(prUrl);
|
||||
},
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type DesktopUpdateState,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -225,7 +225,7 @@ function getServerHttpOrigin(): string {
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `ws://${window.location.hostname}:${window.location.port}`;
|
||||
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`;
|
||||
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
|
||||
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
|
||||
try {
|
||||
@@ -499,20 +499,26 @@ export default function Sidebar() {
|
||||
const projectId = newProjectId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||
const projectCreated = await api.orchestration
|
||||
.dispatchCommand({
|
||||
try {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "project.create",
|
||||
commandId: newCommandId(),
|
||||
projectId,
|
||||
title,
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: DEFAULT_MODEL,
|
||||
defaultModel: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
createdAt,
|
||||
})
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
if (projectCreated) {
|
||||
});
|
||||
await handleNewThread(projectId).catch(() => undefined);
|
||||
} catch (error) {
|
||||
setIsAddingProject(false);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to add project",
|
||||
description:
|
||||
error instanceof Error ? error.message : "An error occurred while adding the project.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
finishAddingProject();
|
||||
},
|
||||
@@ -885,7 +891,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") ??
|
||||
|
||||
@@ -394,15 +394,15 @@ describe("composerDraftStore setProvider", () => {
|
||||
it("persists provider-only selection even when prompt/model are empty", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setProvider(threadId, "cursor");
|
||||
store.setProvider(threadId, "codex");
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.provider).toBe("cursor");
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.provider).toBe("codex");
|
||||
});
|
||||
|
||||
it("removes empty provider-only draft when provider is reset", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setProvider(threadId, "cursor");
|
||||
store.setProvider(threadId, "codex");
|
||||
store.setProvider(threadId, null);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
|
||||
@@ -208,7 +208,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
}
|
||||
|
||||
function normalizeProviderKind(value: unknown): ProviderKind | null {
|
||||
return value === "codex" || value === "claudeCode" || value === "cursor" ? value : null;
|
||||
return value === "codex" ? value : null;
|
||||
}
|
||||
|
||||
function revokeObjectPreviewUrl(previewUrl: string): void {
|
||||
|
||||
@@ -263,9 +263,30 @@ label:has(> select#reasoning-effort) select {
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown ul,
|
||||
.chat-markdown ul {
|
||||
padding-left: 1.25rem;
|
||||
list-style-type: disc;
|
||||
}
|
||||
|
||||
.chat-markdown ol {
|
||||
padding-left: 1.25rem;
|
||||
list-style-type: decimal;
|
||||
}
|
||||
|
||||
.chat-markdown ul ul {
|
||||
list-style-type: circle;
|
||||
}
|
||||
|
||||
.chat-markdown ul ul ul {
|
||||
list-style-type: square;
|
||||
}
|
||||
|
||||
.chat-markdown ol ol {
|
||||
list-style-type: lower-alpha;
|
||||
}
|
||||
|
||||
.chat-markdown ol ol ol {
|
||||
list-style-type: lower-roman;
|
||||
}
|
||||
|
||||
.chat-markdown li + li {
|
||||
|
||||
@@ -12,6 +12,7 @@ interface CheckpointDiffQueryInput {
|
||||
fromTurnCount: number | null;
|
||||
toTurnCount: number | null;
|
||||
cacheScope?: string | null;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export const providerQueryKeys = {
|
||||
@@ -52,6 +53,33 @@ function asCheckpointErrorMessage(error: unknown): string {
|
||||
return "";
|
||||
}
|
||||
|
||||
function normalizeCheckpointErrorMessage(error: unknown): string {
|
||||
const message = asCheckpointErrorMessage(error).trim();
|
||||
if (message.length === 0) {
|
||||
return "Failed to load checkpoint diff.";
|
||||
}
|
||||
|
||||
const lower = message.toLowerCase();
|
||||
if (lower.includes("not a git repository")) {
|
||||
return "Turn diffs are unavailable because this project is not a git repository.";
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("checkpoint unavailable for thread") ||
|
||||
lower.includes("checkpoint invariant violation")
|
||||
) {
|
||||
const separatorIndex = message.indexOf(":");
|
||||
if (separatorIndex >= 0) {
|
||||
const detail = message.slice(separatorIndex + 1).trim();
|
||||
if (detail.length > 0) {
|
||||
return detail;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
|
||||
const message = asCheckpointErrorMessage(error).toLowerCase();
|
||||
return (
|
||||
@@ -71,12 +99,16 @@ export function checkpointDiffQueryOptions(input: CheckpointDiffQueryInput) {
|
||||
if (!input.threadId || decodedRequest._tag === "None") {
|
||||
throw new Error("Checkpoint diff is unavailable.");
|
||||
}
|
||||
if (decodedRequest.value.kind === "fullThreadDiff") {
|
||||
return api.orchestration.getFullThreadDiff(decodedRequest.value.input);
|
||||
try {
|
||||
if (decodedRequest.value.kind === "fullThreadDiff") {
|
||||
return await api.orchestration.getFullThreadDiff(decodedRequest.value.input);
|
||||
}
|
||||
return await api.orchestration.getTurnDiff(decodedRequest.value.input);
|
||||
} catch (error) {
|
||||
throw new Error(normalizeCheckpointErrorMessage(error), { cause: error });
|
||||
}
|
||||
return api.orchestration.getTurnDiff(decodedRequest.value.input);
|
||||
},
|
||||
enabled: !!input.threadId && decodedRequest._tag === "Some",
|
||||
enabled: (input.enabled ?? true) && !!input.threadId && decodedRequest._tag === "Some",
|
||||
staleTime: Infinity,
|
||||
retry: (failureCount, error) => {
|
||||
if (isCheckpointTemporarilyUnavailable(error)) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
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")]));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
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;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
buildPlanImplementationPrompt,
|
||||
buildProposedPlanMarkdownFilename,
|
||||
proposedPlanTitle,
|
||||
resolvePlanFollowUpSubmission,
|
||||
} from "./proposedPlan";
|
||||
|
||||
describe("proposedPlanTitle", () => {
|
||||
@@ -25,6 +26,32 @@ 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(
|
||||
|
||||
@@ -16,6 +16,27 @@ 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) {
|
||||
|
||||