diff --git a/.agents/skills/btca-cli/SKILL.md b/.agents/skills/btca-cli/SKILL.md deleted file mode 100644 index e6b71ee4e8..0000000000 --- a/.agents/skills/btca-cli/SKILL.md +++ /dev/null @@ -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 -``` diff --git a/.agents/skills/btca-cli/agents/openai.yaml b/.agents/skills/btca-cli/agents/openai.yaml deleted file mode 100644 index 37e4009913..0000000000 --- a/.agents/skills/btca-cli/agents/openai.yaml +++ /dev/null @@ -1,3 +0,0 @@ -interface: - display_name: "BTCA CLI" - short_description: "Help with BTCA CLI setup and usage workflows" diff --git a/.docs/architecture.md b/.docs/architecture.md new file mode 100644 index 0000000000..ce5a0afe92 --- /dev/null +++ b/.docs/architecture.md @@ -0,0 +1,143 @@ +# 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) │ +│ wsTransport (state machine) │ +│ Typed push decode at boundary │ +└──────────┬──────────────────────┘ + │ ws://localhost:3773 +┌──────────▼──────────────────────┐ +│ apps/server (Node.js) │ +│ WebSocket + HTTP static server │ +│ ServerPushBus (ordered pushes) │ +│ ServerReadiness (startup gate) │ +│ OrchestrationEngine │ +│ ProviderService │ +│ CheckpointReactor │ +│ RuntimeReceiptBus │ +└──────────┬──────────────────────┘ + │ JSON-RPC over stdio +┌──────────▼──────────────────────┐ +│ codex app-server │ +└─────────────────────────────────┘ +``` + +## Components + +- **Browser app**: The React app renders session state, owns the client-side WebSocket transport, and treats typed push events as the boundary between server runtime details and UI state. + +- **Server**: `apps/server` is the main coordinator. It serves the web app, accepts WebSocket requests, waits for startup readiness before welcoming clients, and sends all outbound pushes through a single ordered push path. + +- **Provider runtime**: `codex app-server` does the actual provider/session work. The server talks to it over JSON-RPC on stdio and translates those runtime events into the app's orchestration model. + +- **Background workers**: Long-running async flows such as runtime ingestion, command reaction, and checkpoint processing run as queue-backed workers. This keeps work ordered, reduces timing races, and gives tests a deterministic way to wait for the system to go idle. + +- **Runtime signals**: The server emits lightweight typed receipts when important async milestones finish, such as checkpoint capture, diff finalization, or a turn becoming fully quiescent. Tests and orchestration code wait on these signals instead of polling internal state. + +## Event Lifecycle + +### Startup and client connect + +```mermaid +sequenceDiagram + participant Browser + participant Transport as WsTransport + participant Server as wsServer + participant Layers as serverLayers + participant Ready as ServerReadiness + participant Push as ServerPushBus + + Browser->>Transport: Load app and open WebSocket + Transport->>Server: Connect + Server->>Layers: Start runtime services + Server->>Ready: Wait for startup barriers + Ready-->>Server: Ready + Server->>Push: Publish server.welcome + Push-->>Transport: Ordered welcome push + Transport-->>Browser: Hydrate initial state +``` + +1. The browser boots [`WsTransport`][1] and registers typed listeners in [`wsNativeApi`][2]. +2. The server accepts the connection in [`wsServer`][3] and brings up the runtime graph defined in [`serverLayers`][7]. +3. [`ServerReadiness`][4] waits until the key startup barriers are complete. +4. Once the server is ready, [`wsServer`][3] sends `server.welcome` from the contracts in [`ws.ts`][6] through [`ServerPushBus`][5]. +5. The browser receives that ordered push through [`WsTransport`][1], and [`wsNativeApi`][2] uses it to seed local client state. + +### User turn flow + +```mermaid +sequenceDiagram + participant Browser + participant Transport as WsTransport + participant Server as wsServer + participant Provider as ProviderService + participant Codex as codex app-server + participant Ingest as ProviderRuntimeIngestion + participant Engine as OrchestrationEngine + participant Push as ServerPushBus + + Browser->>Transport: Send user action + Transport->>Server: Typed WebSocket request + Server->>Provider: Route request + Provider->>Codex: JSON-RPC over stdio + Codex-->>Ingest: Provider runtime events + Ingest->>Engine: Normalize into orchestration events + Engine-->>Server: Domain events + Server->>Push: Publish orchestration.domainEvent + Push-->>Browser: Typed push +``` + +1. A user action in the browser becomes a typed request through [`WsTransport`][1] and the browser API layer in [`nativeApi`][12]. +2. [`wsServer`][3] decodes that request using the shared WebSocket contracts in [`ws.ts`][6] and routes it to the right service. +3. [`ProviderService`][8] starts or resumes a session and talks to `codex app-server` over JSON-RPC on stdio. +4. Provider-native events are pulled back into the server by [`ProviderRuntimeIngestion`][9], which converts them into orchestration events. +5. [`OrchestrationEngine`][10] persists those events, updates the read model, and exposes them as domain events. +6. [`wsServer`][3] pushes those updates to the browser through [`ServerPushBus`][5] on channels defined in [`orchestration.ts`][11]. + +### Async completion flow + +```mermaid +sequenceDiagram + participant Server as wsServer + participant Worker as Queue-backed workers + participant Cmd as ProviderCommandReactor + participant Checkpoint as CheckpointReactor + participant Receipt as RuntimeReceiptBus + participant Push as ServerPushBus + participant Browser + + Server->>Worker: Enqueue follow-up work + Worker->>Cmd: Process provider commands + Worker->>Checkpoint: Process checkpoint tasks + Checkpoint->>Receipt: Publish completion receipt + Cmd-->>Server: Produce orchestration changes + Checkpoint-->>Server: Produce orchestration changes + Server->>Push: Publish resulting state updates + Push-->>Browser: User-visible push +``` + +1. Some work continues after the initial request returns, especially in [`ProviderRuntimeIngestion`][9], [`ProviderCommandReactor`][13], and [`CheckpointReactor`][14]. +2. These flows run as queue-backed workers using [`DrainableWorker`][16], which helps keep side effects ordered and test synchronization deterministic. +3. When a milestone completes, the server emits a typed receipt on [`RuntimeReceiptBus`][15], such as checkpoint completion or turn quiescence. +4. Tests and orchestration code wait on those receipts instead of polling git state, projections, or timers. +5. Any user-visible state changes produced by that async work still go back through [`wsServer`][3] and [`ServerPushBus`][5]. + +[1]: ../apps/web/src/wsTransport.ts +[2]: ../apps/web/src/wsNativeApi.ts +[3]: ../apps/server/src/wsServer.ts +[4]: ../apps/server/src/wsServer/readiness.ts +[5]: ../apps/server/src/wsServer/pushBus.ts +[6]: ../packages/contracts/src/ws.ts +[7]: ../apps/server/src/serverLayers.ts +[8]: ../apps/server/src/provider/Layers/ProviderService.ts +[9]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +[10]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts +[11]: ../packages/contracts/src/orchestration.ts +[12]: ../apps/web/src/nativeApi.ts +[13]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +[14]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts +[15]: ../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts +[16]: ../packages/shared/src/DrainableWorker.ts diff --git a/.docs/ci.md b/.docs/ci.md new file mode 100644 index 0000000000..71f1db4e91 --- /dev/null +++ b/.docs/ci.md @@ -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. diff --git a/.docs/codex-prerequisites.md b/.docs/codex-prerequisites.md new file mode 100644 index 0000000000..608374d5db --- /dev/null +++ b/.docs/codex-prerequisites.md @@ -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. diff --git a/.docs/encyclopedia.md b/.docs/encyclopedia.md new file mode 100644 index 0000000000..76df004e04 --- /dev/null +++ b/.docs/encyclopedia.md @@ -0,0 +1,180 @@ +# Encyclopedia + +This is a living glossary for T3 Code. It explains what common terms mean in this codebase. + +## Table of contents + +- [Project and workspace](#project-and-workspace) +- [Thread timeline](#thread-timeline) +- [Orchestration](#orchestration) +- [Provider runtime](#provider-runtime) +- [Checkpointing](#checkpointing) + +## Concepts + +### Project and workspace + +#### Project + +The top-level workspace record in the app. In [the orchestration contracts][1], a project has a `workspaceRoot`, a title, and one or more threads. See [workspace-layout.md][2]. + +#### Workspace root + +The root filesystem path for a project. In [the orchestration model][1], it is the base directory for branches and optional worktrees. See [workspace-layout.md][2]. + +#### Worktree + +A Git worktree used as an isolated workspace for a thread. If a thread has a `worktreePath` in [the contracts][1], it runs there instead of in the main working tree. Git operations live in [GitCore.ts][3]. + +### Thread timeline + +#### Thread + +The main durable unit of conversation and workspace history. In [the orchestration contracts][1], a thread holds messages, activities, checkpoints, and session-related state. See [projector.ts][4]. + +#### Turn + +A single user-to-assistant work cycle inside a thread. It starts with user input and ends when follow-up work like checkpointing settles. See [the contracts][1], [ProviderRuntimeIngestion.ts][5], and [CheckpointReactor.ts][6]. + +#### Activity + +A user-visible log item attached to a thread. In [the contracts][1], activities cover important non-message events like approvals, tool actions, and failures. They are projected into thread state in [projector.ts][4]. + +### Orchestration + +Orchestration is the server-side domain layer that turns runtime activity into stable app state. The main entry point is [OrchestrationEngine.ts][7], with core logic in [decider.ts][8] and [projector.ts][4]. + +#### Aggregate + +The domain object a command or event belongs to. In [the contracts][1], that is usually `project` or `thread`. See [decider.ts][8]. + +#### Command + +A typed request to change domain state. In [the contracts][1], commands are validated in [commandInvariants.ts][9] and turned into events by [decider.ts][8]. +Examples include `thread.create`, `thread.turn.start`, and `thread.checkpoint.revert`. + +#### Domain Event + +A persisted fact that something already happened. In [the contracts][1], events are the source of truth, and [projector.ts][4] shows how they are applied. +Examples include `thread.created`, `thread.message-sent`, and `thread.turn-diff-completed`. + +#### Decider + +The pure orchestration logic that turns commands plus current state into events. The core implementation is in [decider.ts][8], with preconditions in [commandInvariants.ts][9]. + +#### Projection + +A read-optimized view derived from events. See [projector.ts][4], [ProjectionPipeline.ts][11], and [ProjectionSnapshotQuery.ts][10]. + +#### Projector + +The logic that applies domain events to the read model or projection tables. See [projector.ts][4] and [ProjectionPipeline.ts][11]. + +#### Read model + +The current materialized view of orchestration state. In [the contracts][1], it holds projects, threads, messages, activities, checkpoints, and session state. See [ProjectionSnapshotQuery.ts][10] and [OrchestrationEngine.ts][7]. + +#### Reactor + +A side-effecting service that handles follow-up work after events or runtime signals. Examples include [CheckpointReactor.ts][6], [ProviderCommandReactor.ts][12], and [ProviderRuntimeIngestion.ts][5]. + +#### Receipt + +A lightweight typed runtime signal emitted when an async milestone completes. See [RuntimeReceiptBus.ts][13]. +Examples include `checkpoint.baseline.captured`, `checkpoint.diff.finalized`, and `turn.processing.quiesced`, which are emitted by flows such as [CheckpointReactor.ts][6]. + +#### Quiesced + +"Quiesced" means a turn has gone quiet and stable. In [the receipt schema][13], it means the follow-up work has settled, including work in [CheckpointReactor.ts][6]. + +### Provider runtime + +The live backend agent implementation and its event stream. The main service is [ProviderService.ts][14], the adapter contract is [ProviderAdapter.ts][15], and the overview is in [provider-architecture.md][16]. + +#### Provider + +The backend agent runtime that actually performs work. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17]. + +#### Session + +The live provider-backed runtime attached to a thread. Session shape is in [the orchestration contracts][1], and lifecycle is managed in [ProviderService.ts][14]. + +#### Runtime mode + +The safety/access mode for a thread or session. In [the contracts][1], the main values are `approval-required` and `full-access`. See [runtime-modes.md][18]. + +#### Interaction mode + +The agent interaction style for a thread. In [the contracts][1], the main values are `default` and `plan`. See [runtime-modes.md][18]. + +#### Assistant delivery mode + +Controls how assistant text reaches the thread timeline. In [the contracts][1], `streaming` updates incrementally and `buffered` delivers a completed result. See [ProviderService.ts][14]. + +#### Snapshot + +A point-in-time view of state. The word is used in multiple layers, including orchestration, provider, and checkpointing. See [ProjectionSnapshotQuery.ts][10], [ProviderAdapter.ts][15], and [CheckpointStore.ts][19]. + +### Checkpointing + +Checkpointing captures workspace state over time so the app can diff turns and restore earlier points. The main pieces are [CheckpointStore.ts][19], [CheckpointDiffQuery.ts][20], and [CheckpointReactor.ts][6]. + +#### Checkpoint + +A saved snapshot of a thread workspace at a particular turn. In practice it is a hidden Git ref in [CheckpointStore.ts][19] plus a projected summary from [ProjectionCheckpoints.ts][21]. Capture and lifecycle work happen in [CheckpointReactor.ts][6]. + +#### Checkpoint ref + +The durable identifier for a filesystem checkpoint, stored as a Git ref. It is typed in [the contracts][1], constructed in [Utils.ts][22], and used by [CheckpointStore.ts][19]. + +#### Checkpoint baseline + +The starting checkpoint for diffing a thread timeline. This flow is surfaced through [RuntimeReceiptBus.ts][13], coordinated in [CheckpointReactor.ts][6], and supported by [Utils.ts][22]. + +#### Checkpoint diff + +The patch difference between two checkpoints. Query logic lives in [CheckpointDiffQuery.ts][20], diff parsing lives in [Diffs.ts][23], and finalization is coordinated by [CheckpointReactor.ts][6]. + +#### Turn diff + +The file patch and changed-file summary for one turn. It is usually computed in [CheckpointDiffQuery.ts][20], represented in [the contracts][1], and recorded into thread state by [projector.ts][4]. + +## Practical Shortcuts + +- If you see `requested`, think "intent recorded". +- If you see `completed`, think "result applied". +- If you see `receipt`, think "async milestone signal". +- If you see `checkpoint`, think "workspace snapshot for diff/restore". +- If you see `quiesced`, think "all relevant follow-up work has gone idle". + +## Related Docs + +- [architecture.md][24] +- [provider-architecture.md][16] +- [runtime-modes.md][18] +- [workspace-layout.md][2] + +[1]: ../packages/contracts/src/orchestration.ts +[2]: ./workspace-layout.md +[3]: ../apps/server/src/git/Layers/GitCore.ts +[4]: ../apps/server/src/orchestration/projector.ts +[5]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +[6]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts +[7]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts +[8]: ../apps/server/src/orchestration/decider.ts +[9]: ../apps/server/src/orchestration/commandInvariants.ts +[10]: ../apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +[11]: ../apps/server/src/orchestration/Layers/ProjectionPipeline.ts +[12]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +[13]: ../apps/server/src/orchestration/Services/RuntimeReceiptBus.ts +[14]: ../apps/server/src/provider/Layers/ProviderService.ts +[15]: ../apps/server/src/provider/Services/ProviderAdapter.ts +[16]: ./provider-architecture.md +[17]: ../apps/server/src/provider/Layers/CodexAdapter.ts +[18]: ./runtime-modes.md +[19]: ../apps/server/src/checkpointing/Services/CheckpointStore.ts +[20]: ../apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts +[21]: ../apps/server/src/persistence/Services/ProjectionCheckpoints.ts +[22]: ../apps/server/src/checkpointing/Utils.ts +[23]: ../apps/server/src/checkpointing/Diffs.ts +[24]: ./architecture.md diff --git a/.docs/provider-architecture.md b/.docs/provider-architecture.md new file mode 100644 index 0000000000..794b6aa5d5 --- /dev/null +++ b/.docs/provider-architecture.md @@ -0,0 +1,30 @@ +# 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**: typed envelopes with `channel`, `sequence` (monotonic per connection), and channel-specific `data` + +Push channels: `server.welcome`, `server.configUpdated`, `terminal.event`, `orchestration.domainEvent`. Payloads are schema-validated at the transport boundary (`wsTransport.ts`). Decode failures produce structured `WsDecodeDiagnostic` with `code`, `reason`, and path info. + +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. + +## Client transport + +`wsTransport.ts` manages connection state: `connecting` → `open` → `reconnecting` → `closed` → `disposed`. Outbound requests are queued while disconnected and flushed on reconnect. Inbound pushes are decoded and validated at the boundary, then cached per channel. Subscribers can opt into `replayLatest` to receive the last push on subscribe. + +## Server-side orchestration layers + +Provider runtime events flow through queue-based workers: + +1. **ProviderRuntimeIngestion** — consumes provider runtime streams, emits orchestration commands +2. **ProviderCommandReactor** — reacts to orchestration intent events, dispatches provider calls +3. **CheckpointReactor** — captures git checkpoints on turn start/complete, publishes runtime receipts + +All three use `DrainableWorker` internally and expose `drain()` for deterministic test synchronization. diff --git a/.docs/quick-start.md b/.docs/quick-start.md new file mode 100644 index 0000000000..2206d53ee5 --- /dev/null +++ b/.docs/quick-start.md @@ -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 +``` diff --git a/.docs/runtime-modes.md b/.docs/runtime-modes.md new file mode 100644 index 0000000000..956b242e1c --- /dev/null +++ b/.docs/runtime-modes.md @@ -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. diff --git a/.docs/scripts.md b/.docs/scripts.md new file mode 100644 index 0000000000..b3fcd4b30e --- /dev/null +++ b/.docs/scripts.md @@ -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 -- --base-dir ~/.t3-2` +- `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 --target --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. diff --git a/.docs/workspace-layout.md b/.docs/workspace-layout.md new file mode 100644 index 0000000000..be88f2b603 --- /dev/null +++ b/.docs/workspace-layout.md @@ -0,0 +1,7 @@ +# 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 effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. +- `/packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`, `@t3tools/shared/DrainableWorker`) — no barrel index. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..705bd8f43e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt +* text=auto eol=lf diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000..07438b251c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,117 @@ +name: Bug report +description: Report broken behavior, regressions, crashes, or reliability issues. +title: "[Bug]: " +labels: + - bug + - needs-triage +body: + - type: markdown + attributes: + value: | + Use this form for broken behavior, regressions, crashes, or reliability problems. + Search existing issues first and keep the report focused on one problem. + + - type: checkboxes + id: checks + attributes: + label: Before submitting + options: + - label: I searched existing issues and did not find a duplicate. + required: true + - label: I included enough detail to reproduce or investigate the problem. + required: true + + - type: dropdown + id: area + attributes: + label: Area + description: Which part of the project is affected? + options: + - apps/web + - apps/server + - apps/desktop + - packages/contracts or packages/shared + - Build, CI, or release tooling + - Docs + - Not sure + validations: + required: true + + - type: textarea + id: steps + attributes: + label: Steps to reproduce + description: Provide a minimal, deterministic repro. + placeholder: | + 1. Start the app with ... + 2. Open ... + 3. Disconnect the network + 4. Reconnect and send another prompt + validations: + required: true + + - type: textarea + id: expected + attributes: + label: Expected behavior + placeholder: The thread should resume normally and accept the new message. + validations: + required: true + + - type: textarea + id: actual + attributes: + label: Actual behavior + placeholder: The composer clears, no new turn starts, and the session stays in a pending state. + validations: + required: true + + - type: dropdown + id: impact + attributes: + label: Impact + description: How bad is this in practice? + options: + - Blocks work completely + - Major degradation or frequent failure + - Minor bug or occasional failure + - Cosmetic issue + validations: + required: true + + - type: input + id: version + attributes: + label: Version or commit + description: Release version, commit SHA, or branch name if known. + placeholder: main @ abc1234 + + - type: input + id: environment + attributes: + label: Environment + description: OS, browser or desktop app version, Node/Bun version, provider/model if relevant. + placeholder: macOS 15.3, Chrome 135, Bun 1.3.9, Codex app-server ... + + - type: textarea + id: logs + attributes: + label: Logs or stack traces + description: Paste the most relevant output only. Redact secrets. + render: shell + + - type: upload + id: attachments + attributes: + label: Screenshots, recordings, or supporting files + description: Upload screenshots, short recordings, repro archives, or log files. Redact secrets before uploading. + validations: + required: false + accept: ".png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.mov,.webm,.log,.txt,.json,.zip" + + - type: textarea + id: workaround + attributes: + label: Workaround + description: If you found a temporary workaround, include it. + placeholder: Restarting the provider session clears the stuck state. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000000..53aab5166a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,101 @@ +name: Feature request +description: Propose a scoped improvement or new capability. +title: "[Feature]: " +labels: + - enhancement + - needs-triage +body: + - type: markdown + attributes: + value: | + Use this form for new capabilities or meaningful improvements to existing behavior. + This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate. + + - type: checkboxes + id: checks + attributes: + label: Before submitting + options: + - label: I searched existing issues and did not find a duplicate. + required: true + - label: I am describing a concrete problem or use case, not just a vague idea. + required: true + + - type: dropdown + id: area + attributes: + label: Area + description: Which part of the project would this change affect? + options: + - apps/web + - apps/server + - apps/desktop + - packages/contracts or packages/shared + - Build, CI, or release tooling + - Docs + - Not sure + validations: + required: true + + - type: textarea + id: problem + attributes: + label: Problem or use case + description: What are you trying to do? What is hard, slow, or impossible today? + placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state. + validations: + required: true + + - type: textarea + id: proposal + attributes: + label: Proposed solution + description: Describe the behavior, API, or UX you want. + placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load. + validations: + required: true + + - type: textarea + id: value + attributes: + label: Why this matters + description: Who benefits, and what outcome does this unlock? + placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions. + validations: + required: true + + - type: textarea + id: scope + attributes: + label: Smallest useful scope + description: What is the narrowest version of this request that would still solve your problem? + placeholder: A first pass only needs to support restoring the active session for the current thread. + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: Alternatives considered + description: Workarounds, prior art, or other approaches you considered. + placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context. + + - type: textarea + id: tradeoffs + attributes: + label: Risks or tradeoffs + description: What costs, complexity, or edge cases should be considered? + placeholder: This may require careful handling when the underlying provider session has already exited. + + - type: textarea + id: references + attributes: + label: Examples or references + description: Links, screenshots, mockups, or comparable tools. + + - type: checkboxes + id: contribution + attributes: + label: Contribution + options: + - label: I would be open to helping implement this. diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td new file mode 100644 index 0000000000..5535d54a5b --- /dev/null +++ b/.github/VOUCHED.td @@ -0,0 +1,32 @@ +# Trust list for this repository. +# +# External contributors listed here are treated as trusted by the vouch +# workflow. Collaborators with write access are automatically trusted and +# do not need to be duplicated in this file. +# +# Syntax: +# github:username +# -github:username reason for denouncement +# +# Keep entries sorted alphabetically. +github:adityavardhansharma +github:binbandit +github:chuks-qua +github:cursoragent +github:gbarros-dev +github:github-actions[bot] +github:hwanseoc +github:jamesx0416 +github:jasonLaster +github:JoeEverest +github:maria-rcks +github:nmggithub +github:Noojuno +github:notkainoa +github:PatrickBauer +github:realAhmedRoach +github:shiroyasha9 +github:Yash-Singh1 +github:eggfriedrice24 +github:Ymit24 +github:shivamhwp diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..76aac7e4d8 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,33 @@ + + +## What Changed + + + +## Why + + + +## UI Changes + + + +## Checklist + +- [ ] This PR is small and focused +- [ ] I explained what changed and why +- [ ] I included before/after screenshots for any UI changes +- [ ] I included a video for animation/interaction changes diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5e2cc265cc..67b5e32860 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,19 +8,24 @@ on: jobs: quality: - name: Lint, Typecheck, Test, Build - runs-on: ubuntu-latest + name: Format, Lint, Typecheck, Test, Browser Test, Build + runs-on: blacksmith-4vcpu-ubuntu-2404 steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Bun uses: oven-sh/setup-bun@v2 with: - bun-version: 1.3.9 + bun-version-file: package.json + + - name: Setup Node + uses: actions/setup-node@v6 + with: + node-version-file: package.json - name: Cache Bun and Turbo - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: | ~/.bun/install/cache @@ -29,9 +34,20 @@ jobs: restore-keys: | ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}- + - name: Cache Playwright browsers + uses: actions/cache@v5 + with: + path: ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }} + restore-keys: | + ${{ runner.os }}-playwright- + - name: Install dependencies run: bun install --frozen-lockfile + - name: Format + run: bun run fmt:check + - name: Lint run: bun run lint @@ -41,6 +57,14 @@ jobs: - name: Test run: bun run test + - name: Install browser test runtime + run: | + cd apps/web + bunx playwright install --with-deps chromium + + - name: Browser test + run: bun run --cwd apps/web test:browser + - name: Build desktop pipeline run: bun run build:desktop @@ -48,3 +72,23 @@ jobs: run: | test -f apps/desktop/dist-electron/preload.js grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js + + release_smoke: + name: Release Smoke + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version-file: package.json + + - name: Setup Node + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Exercise release-only workflow steps + run: node scripts/release-smoke.ts diff --git a/.github/workflows/issue-labels.yml b/.github/workflows/issue-labels.yml new file mode 100644 index 0000000000..d6571d65d4 --- /dev/null +++ b/.github/workflows/issue-labels.yml @@ -0,0 +1,75 @@ +name: Issue Labels + +on: + push: + branches: + - main + paths: + - .github/ISSUE_TEMPLATE/** + - .github/workflows/issue-labels.yml + workflow_dispatch: + +permissions: + issues: write + +jobs: + sync: + name: Sync issue labels + runs-on: ubuntu-24.04 + steps: + - name: Ensure managed issue labels exist + uses: actions/github-script@v7 + with: + script: | + const managedLabels = [ + { + name: "bug", + color: "d73a4a", + description: "Something is broken or behaving incorrectly.", + }, + { + name: "enhancement", + color: "a2eeef", + description: "Requested improvement or new capability.", + }, + { + name: "needs-triage", + color: "fbca04", + description: "Issue needs maintainer review and initial categorization.", + }, + ]; + + for (const label of managedLabels) { + try { + const { data: existing } = await github.rest.issues.getLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + name: label.name, + }); + + if ( + existing.color !== label.color || + (existing.description ?? "") !== label.description + ) { + await github.rest.issues.updateLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + name: label.name, + color: label.color, + description: label.description, + }); + } + } catch (error) { + if (error.status !== 404) { + throw error; + } + + await github.rest.issues.createLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + name: label.name, + color: label.color, + description: label.description, + }); + } + } diff --git a/.github/workflows/pr-size.yml b/.github/workflows/pr-size.yml new file mode 100644 index 0000000000..15c04d663d --- /dev/null +++ b/.github/workflows/pr-size.yml @@ -0,0 +1,292 @@ +name: PR Size + +on: + pull_request_target: + types: [opened, reopened, synchronize, ready_for_review, converted_to_draft] + +permissions: + contents: read + +jobs: + prepare-config: + name: Prepare PR size config + runs-on: ubuntu-24.04 + outputs: + labels_json: ${{ steps.config.outputs.labels_json }} + steps: + - id: config + name: Build PR size label config + uses: actions/github-script@v8 + with: + result-encoding: string + script: | + const managedLabels = [ + { + name: "size:XS", + color: "0e8a16", + description: "0-9 effective changed lines (test files excluded in mixed PRs).", + }, + { + name: "size:S", + color: "5ebd3e", + description: "10-29 effective changed lines (test files excluded in mixed PRs).", + }, + { + name: "size:M", + color: "fbca04", + description: "30-99 effective changed lines (test files excluded in mixed PRs).", + }, + { + name: "size:L", + color: "fe7d37", + description: "100-499 effective changed lines (test files excluded in mixed PRs).", + }, + { + name: "size:XL", + color: "d93f0b", + description: "500-999 effective changed lines (test files excluded in mixed PRs).", + }, + { + name: "size:XXL", + color: "b60205", + description: "1,000+ effective changed lines (test files excluded in mixed PRs).", + }, + ]; + + core.setOutput("labels_json", JSON.stringify(managedLabels)); + sync-label-definitions: + name: Sync PR size label definitions + needs: prepare-config + if: github.event_name != 'pull_request_target' + runs-on: ubuntu-24.04 + permissions: + contents: read + issues: write + steps: + - name: Ensure PR size labels exist + uses: actions/github-script@v8 + env: + PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }} + with: + script: | + const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]"); + + for (const label of managedLabels) { + try { + const { data: existing } = await github.rest.issues.getLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + name: label.name, + }); + + if ( + existing.color !== label.color || + (existing.description ?? "") !== label.description + ) { + await github.rest.issues.updateLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + name: label.name, + color: label.color, + description: label.description, + }); + } + } catch (error) { + if (error.status !== 404) { + throw error; + } + + try { + await github.rest.issues.createLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + name: label.name, + color: label.color, + description: label.description, + }); + } catch (createError) { + if (createError.status !== 422) { + throw createError; + } + } + } + } + label: + name: Label PR size + needs: prepare-config + if: github.event_name == 'pull_request_target' + runs-on: ubuntu-24.04 + permissions: + contents: read + issues: read + pull-requests: write + concurrency: + group: pr-size-${{ github.event.pull_request.number }} + cancel-in-progress: true + steps: + - name: Checkout base repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Sync PR size label + uses: actions/github-script@v8 + env: + PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }} + with: + script: | + const { execFileSync } = require("node:child_process"); + + const issueNumber = context.payload.pull_request.number; + const baseSha = context.payload.pull_request.base.sha; + const headSha = context.payload.pull_request.head.sha; + const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`; + const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]"); + const managedLabelNames = new Set(managedLabels.map((label) => label.name)); + // Keep this aligned with the repo's test entrypoints and test-only support files. + const testExcludePathspecs = [ + ":(glob,exclude)**/__tests__/**", + ":(glob,exclude)**/test/**", + ":(glob,exclude)**/tests/**", + ":(glob,exclude)apps/server/integration/**", + ":(glob,exclude)**/*.test.*", + ":(glob,exclude)**/*.spec.*", + ":(glob,exclude)**/*.browser.*", + ":(glob,exclude)**/*.integration.*", + ]; + + const sumNumstat = (text) => + text + .split("\n") + .filter(Boolean) + .reduce((total, line) => { + const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t"); + const additions = + insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0; + const deletions = + deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0; + + return total + additions + deletions; + }, 0); + + const resolveSizeLabel = (totalChangedLines) => { + if (totalChangedLines < 10) { + return "size:XS"; + } + + if (totalChangedLines < 30) { + return "size:S"; + } + + if (totalChangedLines < 100) { + return "size:M"; + } + + if (totalChangedLines < 500) { + return "size:L"; + } + + if (totalChangedLines < 1000) { + return "size:XL"; + } + + return "size:XXL"; + }; + + execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], { + stdio: "inherit", + }); + + execFileSync( + "git", + ["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`], + { + stdio: "inherit", + }, + ); + + const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], { + encoding: "utf8", + }).trim(); + + if (resolvedHeadSha !== headSha) { + core.warning( + `Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`, + ); + } + + execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], { + stdio: "inherit", + }); + + const diffArgs = [ + "diff", + "--numstat", + "--ignore-all-space", + "--ignore-blank-lines", + `${baseSha}...${resolvedHeadSha}`, + ]; + + const totalChangedLines = sumNumstat( + execFileSync( + "git", + diffArgs, + { encoding: "utf8" }, + ), + ); + const nonTestChangedLines = sumNumstat( + execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], { + encoding: "utf8", + }), + ); + const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines); + + const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines; + const nextLabelName = resolveSizeLabel(changedLines); + + const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + per_page: 100, + }); + + for (const label of currentLabels) { + if (!managedLabelNames.has(label.name) || label.name === nextLabelName) { + continue; + } + + try { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + name: label.name, + }); + } catch (removeError) { + if (removeError.status !== 404) { + throw removeError; + } + } + } + + if (!currentLabels.some((label) => label.name === nextLabelName)) { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + labels: [nextLabelName], + }); + } + + const classification = + nonTestChangedLines === 0 + ? testChangedLines > 0 + ? "test-only PR" + : "no line changes" + : testChangedLines > 0 + ? "test lines excluded" + : "all non-test changes"; + + core.info( + `PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`, + ); diff --git a/.github/workflows/pr-vouch.yml b/.github/workflows/pr-vouch.yml new file mode 100644 index 0000000000..c4abb08b72 --- /dev/null +++ b/.github/workflows/pr-vouch.yml @@ -0,0 +1,199 @@ +name: PR Vouch + +on: + pull_request_target: + types: [opened, reopened, synchronize, ready_for_review, converted_to_draft] + issue_comment: + types: [created] + push: + branches: + - main + paths: + - .github/VOUCHED.td + - .github/workflows/pr-vouch.yml + +permissions: + contents: read + issues: write + pull-requests: write + +jobs: + collect-targets: + name: Collect PR targets + runs-on: ubuntu-24.04 + outputs: + targets: ${{ steps.collect.outputs.targets }} + steps: + - id: collect + uses: actions/github-script@v8 + with: + script: | + if (context.eventName === "pull_request_target") { + const pr = context.payload.pull_request; + core.setOutput("targets", JSON.stringify([{ number: pr.number, user: pr.user.login }])); + return; + } + + if (context.eventName === "issue_comment") { + const issue = context.payload.issue; + const body = context.payload.comment?.body ?? ""; + if (!issue?.pull_request || !body.includes("/recheck-vouch")) { + core.setOutput("targets", "[]"); + return; + } + + core.setOutput( + "targets", + JSON.stringify([{ number: issue.number, user: issue.user.login }]), + ); + return; + } + + const pulls = await github.paginate(github.rest.pulls.list, { + owner: context.repo.owner, + repo: context.repo.repo, + state: "open", + per_page: 100, + }); + + const targets = pulls.map((pull) => ({ + number: pull.number, + user: pull.user.login, + })); + core.setOutput("targets", JSON.stringify(targets)); + + label: + name: Label PR ${{ matrix.target.number }} + needs: collect-targets + if: ${{ needs.collect-targets.outputs.targets != '[]' }} + runs-on: ubuntu-24.04 + concurrency: + group: pr-vouch-${{ matrix.target.number }} + cancel-in-progress: true + strategy: + fail-fast: false + matrix: + target: ${{ fromJson(needs.collect-targets.outputs.targets) }} + steps: + - id: vouch + name: Check PR author trust + uses: mitchellh/vouch/action/check-user@v1 + with: + user: ${{ matrix.target.user }} + allow-fail: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Sync PR labels + uses: actions/github-script@v8 + env: + PR_NUMBER: ${{ matrix.target.number }} + VOUCH_STATUS: ${{ steps.vouch.outputs.status }} + with: + script: | + const issueNumber = Number(process.env.PR_NUMBER); + const status = process.env.VOUCH_STATUS; + const managedLabels = [ + { + name: "vouch:trusted", + color: "1f883d", + description: "PR author is trusted by repo permissions or the VOUCHED list.", + }, + { + name: "vouch:unvouched", + color: "fbca04", + description: "PR author is not yet trusted in the VOUCHED list.", + }, + { + name: "vouch:denounced", + color: "d1242f", + description: "PR author is explicitly blocked by the VOUCHED list.", + }, + ]; + + const managedLabelNames = new Set(managedLabels.map((label) => label.name)); + + for (const label of managedLabels) { + try { + const { data: existing } = await github.rest.issues.getLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + name: label.name, + }); + + if ( + existing.color !== label.color || + (existing.description ?? "") !== label.description + ) { + await github.rest.issues.updateLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + name: label.name, + color: label.color, + description: label.description, + }); + } + } catch (error) { + if (error.status !== 404) { + throw error; + } + + try { + await github.rest.issues.createLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + name: label.name, + color: label.color, + description: label.description, + }); + } catch (createError) { + if (createError.status !== 422) { + throw createError; + } + } + } + } + + const nextLabelName = + status === "denounced" + ? "vouch:denounced" + : ["bot", "collaborator", "vouched"].includes(status) + ? "vouch:trusted" + : "vouch:unvouched"; + + const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + per_page: 100, + }); + + for (const label of currentLabels) { + if (!managedLabelNames.has(label.name) || label.name === nextLabelName) { + continue; + } + + try { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + name: label.name, + }); + } catch (removeError) { + if (removeError.status !== 404) { + throw removeError; + } + } + } + + if (!currentLabels.some((label) => label.name === nextLabelName)) { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + labels: [nextLabelName], + }); + } + + core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`); diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000000..504952e3aa --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,377 @@ +name: Release Desktop + +on: + push: + tags: + - "v*.*.*" + workflow_dispatch: + inputs: + version: + description: "Release version (for example 1.2.3 or v1.2.3)" + required: true + type: string + +permissions: + contents: write + id-token: write + +jobs: + preflight: + name: Preflight + runs-on: ubuntu-24.04 + 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 + uses: actions/checkout@v6 + + - id: release_meta + name: Resolve release version + shell: bash + run: | + if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then + raw="${{ github.event.inputs.version }}" + else + raw="${GITHUB_REF_NAME}" + fi + + version="${raw#v}" + if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then + echo "Invalid release version: $raw" >&2 + exit 1 + fi + + 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 + with: + bun-version-file: package.json + + - name: Setup Node + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Install dependencies + run: bun install --frozen-lockfile + + - name: Lint + run: bun run lint + + - name: Typecheck + run: bun run typecheck + + - name: Test + run: bun run test + + build: + name: Build ${{ matrix.label }} + needs: preflight + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - label: macOS arm64 + runner: macos-14 + platform: mac + target: dmg + arch: arm64 + - label: macOS x64 + runner: macos-15-intel + platform: mac + target: dmg + arch: x64 + - label: Linux x64 + runner: ubuntu-24.04 + platform: linux + target: AppImage + arch: x64 + - label: Windows x64 + runner: windows-2022 + platform: win + target: nsis + arch: x64 + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + ref: ${{ needs.preflight.outputs.ref }} + fetch-depth: 0 + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version-file: package.json + + - name: Setup Node + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Install dependencies + run: bun install --frozen-lockfile + + - name: Align package versions to release version + run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}" + + - name: Build desktop artifact + shell: bash + env: + CSC_LINK: ${{ secrets.CSC_LINK }} + CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} + APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }} + AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }} + AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }} + AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }} + run: | + args=( + --platform "${{ matrix.platform }}" + --target "${{ matrix.target }}" + --arch "${{ matrix.arch }}" + --build-version "${{ needs.preflight.outputs.version }}" + --verbose + ) + + has_all() { + for value in "$@"; do + if [[ -z "$value" ]]; then + return 1 + fi + done + return 0 + } + + if [[ "${{ matrix.platform }}" == "mac" ]]; then + if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then + key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8" + printf '%s' "$APPLE_API_KEY" > "$key_path" + export APPLE_API_KEY="$key_path" + echo "macOS signing enabled." + args+=(--signed) + else + echo "macOS signing disabled (missing one or more Apple signing secrets)." + fi + elif [[ "${{ matrix.platform }}" == "win" ]]; then + if has_all \ + "$AZURE_TENANT_ID" \ + "$AZURE_CLIENT_ID" \ + "$AZURE_CLIENT_SECRET" \ + "$AZURE_TRUSTED_SIGNING_ENDPOINT" \ + "$AZURE_TRUSTED_SIGNING_ACCOUNT_NAME" \ + "$AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME" \ + "$AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"; then + echo "Windows signing enabled (Azure Trusted Signing)." + args+=(--signed) + else + echo "Windows signing disabled (missing one or more Azure Trusted Signing secrets)." + fi + else + echo "Signing disabled for ${{ matrix.platform }}." + fi + + bun run dist:desktop:artifact -- "${args[@]}" + + - name: Collect release assets + shell: bash + run: | + set -euo pipefail + mkdir -p release-publish + + shopt -s nullglob + for pattern in \ + "release/*.dmg" \ + "release/*.zip" \ + "release/*.AppImage" \ + "release/*.exe" \ + "release/*.blockmap" \ + "release/latest*.yml"; do + for file in $pattern; do + cp "$file" release-publish/ + done + done + + if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then + if [[ -f release-publish/latest-mac.yml ]]; then + mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml" + fi + fi + + - name: Upload build artifacts + uses: actions/upload-artifact@v7 + with: + name: desktop-${{ matrix.platform }}-${{ matrix.arch }} + path: release-publish/* + if-no-files-found: error + + publish_cli: + name: Publish CLI to npm + needs: [preflight, build] + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + ref: ${{ needs.preflight.outputs.ref }} + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version-file: package.json + + - name: Setup Node + uses: actions/setup-node@v6 + with: + node-version-file: package.json + registry-url: https://registry.npmjs.org + + - name: Install dependencies + run: bun install --frozen-lockfile + + - name: Align package versions to release version + run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}" + + - name: Build CLI package + run: bun run build --filter=@t3tools/web --filter=t3 + + - name: Publish CLI package + run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose + + release: + name: Publish GitHub Release + needs: [preflight, build, publish_cli] + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + ref: ${{ needs.preflight.outputs.ref }} + + - name: Setup Node + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Download all desktop artifacts + uses: actions/download-artifact@v8 + with: + pattern: desktop-* + merge-multiple: true + path: release-assets + + - name: Merge macOS updater manifests + run: | + node scripts/merge-mac-update-manifests.ts \ + release-assets/latest-mac.yml \ + release-assets/latest-mac-x64.yml + rm -f release-assets/latest-mac-x64.yml + + - name: Publish release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ needs.preflight.outputs.tag }} + target_commitish: ${{ needs.preflight.outputs.ref }} + name: T3 Code v${{ needs.preflight.outputs.version }} + generate_release_notes: true + prerelease: ${{ needs.preflight.outputs.is_prerelease }} + make_latest: ${{ needs.preflight.outputs.make_latest }} + files: | + release-assets/*.dmg + release-assets/*.zip + release-assets/*.AppImage + release-assets/*.exe + release-assets/*.blockmap + release-assets/latest*.yml + fail_on_unmatched_files: true + + finalize: + name: Finalize release + needs: [preflight, release] + runs-on: ubuntu-24.04 + steps: + - id: app_token + name: Mint release app token + uses: actions/create-github-app-token@v2 + with: + app-id: ${{ secrets.RELEASE_APP_ID }} + private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + + - name: Checkout + uses: actions/checkout@v6 + with: + ref: main + fetch-depth: 0 + token: ${{ steps.app_token.outputs.token }} + persist-credentials: true + + - id: app_bot + name: Resolve GitHub App bot identity + env: + GH_TOKEN: ${{ steps.app_token.outputs.token }} + APP_SLUG: ${{ steps.app_token.outputs.app-slug }} + run: | + user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)" + echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT" + echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT" + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version-file: package.json + + - name: Setup Node + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - id: update_versions + name: Update version strings + env: + RELEASE_VERSION: ${{ needs.preflight.outputs.version }} + run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output + + - name: Format package.json files + if: steps.update_versions.outputs.changed == 'true' + run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json + + - name: Refresh lockfile + if: steps.update_versions.outputs.changed == 'true' + run: bun install --lockfile-only --ignore-scripts + + - name: Commit and push version bump + if: steps.update_versions.outputs.changed == 'true' + shell: bash + env: + RELEASE_TAG: ${{ needs.preflight.outputs.tag }} + run: | + if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then + echo "No version changes to commit." + exit 0 + fi + + git config user.name "${{ steps.app_bot.outputs.name }}" + git config user.email "${{ steps.app_bot.outputs.email }}" + + git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock + git commit -m "chore(release): prepare $RELEASE_TAG" + git push origin HEAD:main diff --git a/.gitignore b/.gitignore index 3ac5a88fdf..6e5f8cc59c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,8 +5,19 @@ node_modules *.log *.tsbuildinfo apps/*/dist +.astro packages/*/dist .env .env.local build/ .logs/ +release/ +release-mock/ +.t3 +.idea/ +apps/web/.playwright +apps/web/playwright-report +apps/web/src/components/__screenshots__ +.vitest-* +__screenshots__/ +.tanstack diff --git a/.mise.toml b/.mise.toml new file mode 100644 index 0000000000..364d9793d2 --- /dev/null +++ b/.mise.toml @@ -0,0 +1,3 @@ +[tools] +node = "24.13.1" +bun = "1.3.9" diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 8bb9df7241..a3e32c9797 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -1,12 +1,15 @@ { "$schema": "./node_modules/oxfmt/configuration_schema.json", "ignorePatterns": [ + ".reference", ".plans", "dist", "dist-electron", "node_modules", "bun.lock", - "*.tsbuildinfo" + "*.tsbuildinfo", + "**/routeTree.gen.ts", + "apps/web/public/mockServiceWorker.js" ], - "experimentalSortPackageJson": {} + "sortPackageJson": {} } diff --git a/.oxlintrc.json b/.oxlintrc.json index d45179a4c4..8ea8fbf2b8 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -1,6 +1,13 @@ { "$schema": "./node_modules/oxlint/configuration_schema.json", - "ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"], + "ignorePatterns": [ + "dist", + "dist-electron", + "node_modules", + "bun.lock", + "*.tsbuildinfo", + "**/routeTree.gen.ts" + ], "plugins": ["eslint", "oxc", "react", "unicorn", "typescript"], "categories": { "correctness": "warn", @@ -8,6 +15,8 @@ "perf": "warn" }, "rules": { - "react-in-jsx-scope": "off" + "react-in-jsx-scope": "off", + "eslint/no-shadow": "off", + "eslint/no-await-in-loop": "off" } } diff --git a/.plans/01-shared-model-normalization.md b/.plans/01-shared-model-normalization.md index e1e5f77db4..d38c41643f 100644 --- a/.plans/01-shared-model-normalization.md +++ b/.plans/01-shared-model-normalization.md @@ -1,20 +1,24 @@ # Plan: Centralize Model Normalization in Contracts ## Summary + Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth. ## Motivation + - Removes duplicated logic between: - `apps/desktop/src/codexAppServerManager.ts` - `apps/renderer/src/model-logic.ts` - Prevents behavior drift when model aliases/defaults are updated. ## Scope + - Add shared model utilities to contracts. - Update desktop and renderer to consume shared utilities. - Keep renderer-specific display options in renderer. ## Proposed Changes + 1. Add `packages/contracts/src/model.ts` with: - Canonical model list - Alias map @@ -29,14 +33,17 @@ Move model alias/default normalization into `packages/contracts` so desktop and - Keep renderer tests focused on renderer-only behavior. ## Risks + - Desktop/renderer may currently rely on slightly different fallback behavior. - Import graph must avoid bundling issues for Electron main/preload. ## Validation + - `bun run test` - `bun run typecheck` - Manual check that model selection and session start still send expected model slug. ## Done Criteria + - No duplicated alias/default map in desktop and renderer. - Shared model utilities are contract-tested. diff --git a/.plans/02-typed-ipc-boundaries.md b/.plans/02-typed-ipc-boundaries.md index 4e91004356..fac5b1fc2e 100644 --- a/.plans/02-typed-ipc-boundaries.md +++ b/.plans/02-typed-ipc-boundaries.md @@ -1,17 +1,21 @@ # Plan: Strengthen Typed IPC Boundaries in Main Process ## Summary + Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers. ## Motivation + - `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`. - Casts can hide contract breakages until runtime. ## Scope + - Desktop main process IPC registration. - Optional shared helper for handler registration. ## Proposed Changes + 1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to: - Parse payload(s) with Zod schemas - Standardize typed handler signatures @@ -24,14 +28,17 @@ Replace loose payload casting in IPC handlers with strict schema parsing and typ 4. Add tests for handler parsing failure paths (invalid payloads). ## Risks + - Refactor can subtly change IPC error shape/messages. - Helper abstraction should stay simple and not obscure control flow. ## Validation + - `bun run test` - `bun run typecheck` - Manual invalid payload check from renderer/devtools to confirm fast failure. ## Done Criteria + - No provider handler uses `payload as Parameters<...>`. - All IPC entrypoints parse unknown payloads at boundary. diff --git a/.plans/03-split-codex-app-server-manager.md b/.plans/03-split-codex-app-server-manager.md index e425a6ae7d..4f7fadb431 100644 --- a/.plans/03-split-codex-app-server-manager.md +++ b/.plans/03-split-codex-app-server-manager.md @@ -1,9 +1,11 @@ # Plan: Decompose CodexAppServerManager ## Summary + Split `CodexAppServerManager` into smaller modules with clear responsibilities. ## Motivation + - `apps/desktop/src/codexAppServerManager.ts` is large and mixes: - Process lifecycle - JSON-RPC parsing/routing @@ -12,10 +14,12 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities. - This increases regression risk and slows changes. ## Scope + - Desktop provider internals only. - Keep external behavior/API stable. ## Proposed Changes + 1. Extract modules: - `codex/processLifecycle.ts` - `codex/jsonrpcRouter.ts` @@ -29,13 +33,16 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities. - Session state transitions ## Risks + - Reordering event handling can change behavior. - Must preserve pending request timeout/cancellation semantics. ## Validation + - Existing tests pass. - Add module-level tests for parsing and transition logic. ## Done Criteria + - Main manager file materially smaller and orchestration-focused. - Core protocol/state logic covered by focused tests. diff --git a/.plans/04-split-chatview-component.md b/.plans/04-split-chatview-component.md index 3d6f949e9c..abf30c04f8 100644 --- a/.plans/04-split-chatview-component.md +++ b/.plans/04-split-chatview-component.md @@ -1,9 +1,11 @@ # Plan: Split ChatView into Smaller UI/Logic Units ## Summary + Refactor `ChatView.tsx` into composable pieces with isolated responsibilities. ## Motivation + - `apps/renderer/src/components/ChatView.tsx` is large and handles: - Session orchestration - Send/interrupt actions @@ -13,10 +15,12 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities. - Hard to test and maintain as one component. ## Scope + - Renderer component boundaries and hooks. - Keep visual behavior unchanged. ## Proposed Changes + 1. Create hook: `apps/renderer/src/hooks/useChatSession.ts` - `ensureSession` - `sendTurn` @@ -29,12 +33,15 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities. 4. Add focused tests for hook behavior (error handling, session reuse). ## Risks + - Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send). ## Validation + - `bun run test` - Manual smoke: send, stream, interrupt, model switch. ## Done Criteria + - `ChatView.tsx` significantly reduced and easier to scan. - Session logic isolated from rendering. diff --git a/.plans/05-zod-persisted-state-validation.md b/.plans/05-zod-persisted-state-validation.md index 51fcf805d8..869da86796 100644 --- a/.plans/05-zod-persisted-state-validation.md +++ b/.plans/05-zod-persisted-state-validation.md @@ -1,17 +1,21 @@ # Plan: Move Renderer Persisted-State Validation to Zod ## Summary + Use explicit Zod schemas for localStorage state parsing and migration. ## Motivation + - `apps/renderer/src/store.ts` has large manual sanitize functions. - Manual type guards are verbose and easier to get wrong during schema evolution. ## Scope + - Renderer state hydration/persistence path. - No backend/protocol changes. ## Proposed Changes + 1. Add schema module: `apps/renderer/src/persistenceSchema.ts` - Persisted payload versions (`v1`, `v2`) - Thread/message/project schemas @@ -23,12 +27,15 @@ Use explicit Zod schemas for localStorage state parsing and migration. - Unknown thread/project references filtered ## Risks + - Overly strict schemas could drop valid historical data unexpectedly. ## Validation + - Unit tests for migration/hydration. - Manual reload test with existing localStorage data. ## Done Criteria + - Store hydration logic is schema-driven. - Migration behavior is tested and documented. diff --git a/.plans/06-provider-logstream-lifecycle.md b/.plans/06-provider-logstream-lifecycle.md index 71d1cbd95b..0a92de36f7 100644 --- a/.plans/06-provider-logstream-lifecycle.md +++ b/.plans/06-provider-logstream-lifecycle.md @@ -1,17 +1,21 @@ # Plan: Add Provider Log Stream Lifecycle Management ## Summary + Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely. ## Motivation + - `apps/desktop/src/providerManager.ts` opens a write stream in constructor. - Stream lifecycle is not explicit on shutdown. ## Scope + - Desktop provider logging behavior. - App shutdown integration. ## Proposed Changes + 1. Add explicit `dispose()` on `ProviderManager`: - Remove event listeners - End/close log stream @@ -20,12 +24,15 @@ Ensure `ProviderManager` logging stream is initialized, rotated/structured, and 4. Optional: per-session log files under `.logs/providers/`. ## Risks + - Improper close sequencing may lose final log lines. ## Validation + - Manual run/quit cycle to ensure no open handle warnings. - Confirm logs flush on quit and file descriptors are not leaked. ## Done Criteria + - ProviderManager owns complete log stream lifecycle. - Shutdown path explicitly disposes provider resources. diff --git a/.plans/07-ci-quality-gates.md b/.plans/07-ci-quality-gates.md index 5ebcb04487..ff27a9dbd9 100644 --- a/.plans/07-ci-quality-gates.md +++ b/.plans/07-ci-quality-gates.md @@ -1,17 +1,21 @@ # Plan: Add CI Workflow for Core Quality Gates ## Summary + Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs. ## Motivation + - Repository currently has no CI workflow files. - Quality checks are only local/manual. ## Scope + - `.github/workflows/ci.yml` - Bun + Turbo setup in CI. ## Proposed Changes + 1. Add `ci.yml` with jobs: - Setup Bun and Node environment - Install deps @@ -22,13 +26,16 @@ Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-tes 3. Configure caching for Bun/Turbo as appropriate. ## Risks + - Smoke test may be flaky in headless CI environments. - CI runtime can grow if caching is misconfigured. ## Validation + - Verify workflow runs on a branch PR. - Ensure failures surface clearly by job name. ## Done Criteria + - CI blocks regressions in lint/typecheck/test. - Workflow docs added to README. diff --git a/.plans/08-precommit-format-and-lint.md b/.plans/08-precommit-format-and-lint.md index e892892781..a919ac07e4 100644 --- a/.plans/08-precommit-format-and-lint.md +++ b/.plans/08-precommit-format-and-lint.md @@ -1,17 +1,21 @@ # Plan: Add Pre-Commit Formatting/Lint Hooks ## Summary + Introduce pre-commit automation so formatting and basic lint checks happen before commits. ## Motivation + - Current lint failures include formatting-only issues. - Shift-left feedback reduces noisy CI failures and cleanup churn. ## Scope + - Root tooling config and package scripts. - No runtime code changes. ## Proposed Changes + 1. Add hook tooling (e.g. Husky + lint-staged or Lefthook). 2. Configure staged-file tasks: - `biome format --write` @@ -20,13 +24,16 @@ Introduce pre-commit automation so formatting and basic lint checks happen befor 4. Keep checks fast to avoid developer friction. ## Risks + - Slow hooks can frustrate contributors and be bypassed. - Need to ensure compatibility with Bun workspace setup. ## Validation + - Create sample staged changes and verify hook behavior. - Confirm formatting fixes are applied automatically. ## Done Criteria + - Pre-commit hook installed and documented. - Formatting-only lint failures drop significantly. diff --git a/.plans/09-event-state-test-expansion.md b/.plans/09-event-state-test-expansion.md index 226ebf4cda..35db64bc0e 100644 --- a/.plans/09-event-state-test-expansion.md +++ b/.plans/09-event-state-test-expansion.md @@ -1,17 +1,21 @@ # Plan: Expand Event/State Transition Test Coverage ## Summary + Add focused tests for renderer event handling and session evolution logic. ## Motivation + - Core behavior is event-driven and stateful. - Existing renderer tests cover only a subset of timeline/model behavior. ## Scope + - `apps/renderer/src/session-logic.test.ts` - Optional reducer tests for `apps/renderer/src/store.ts`. ## Proposed Changes + 1. Add tests for `evolveSession`: - `thread/started` - `turn/started` @@ -24,12 +28,15 @@ Add focused tests for renderer event handling and session evolution logic. 3. Add reducer integration tests for `APPLY_EVENT`. ## Risks + - Tests may be brittle if event payload fixtures are too coupled to implementation details. ## Validation + - `bun run test` - Ensure new tests remain deterministic and fast. ## Done Criteria + - High-risk event transitions are covered by unit tests. - Regressions in stream assembly/session status are caught quickly. diff --git a/.plans/10-unify-process-session-abstraction.md b/.plans/10-unify-process-session-abstraction.md index c3feec020f..72f5d618b9 100644 --- a/.plans/10-unify-process-session-abstraction.md +++ b/.plans/10-unify-process-session-abstraction.md @@ -1,17 +1,21 @@ # Plan: Unify Process and PTY Session Abstractions in ProcessManager ## Summary + Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes. ## Motivation + - `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic. - New execution backends/providers will multiply complexity. ## Scope + - Desktop process execution internals. - Preserve public `ProcessManager` API. ## Proposed Changes + 1. Introduce internal interface (e.g. `RuntimeSession`): - `write(data)` - `kill()` @@ -24,12 +28,15 @@ Refactor `ProcessManager` to use a single runtime-session interface for child-pr 5. Add tests for both implementations. ## Risks + - PTY behavior differs by platform; abstraction must not hide required differences. ## Validation + - Existing `processManager.test.ts` passes. - Add PTY-path tests where feasible. ## Done Criteria + - Manager no longer branches per backend in `write/kill/killAll`. - Session backends are independently testable. diff --git a/.plans/11-effect.md b/.plans/11-effect.md new file mode 100644 index 0000000000..66521c20aa --- /dev/null +++ b/.plans/11-effect.md @@ -0,0 +1,40 @@ +PR 1: Service contracts + error taxonomy +Add ProviderService, CodexService, CheckpointStore as Context.Tag service defs. +Add typed Schema.TaggedError hierarchies for all 3 services (cause: Schema.optional(Schema.Defect) on each). +No behavior change yet, just interfaces and compile-time wiring points. +PR 2: CheckpointStore Effect adapter +Wrap current filesystemCheckpointStore behind CheckpointStoreLive (adapter). +Map all thrown/Promise errors to tagged errors. +Add service tests proving parity for isGitRepository, capture, restore, diff, prune. +PR 3: CodexService Effect adapter +Wrap current CodexAppServerManager behind CodexServiceLive (adapter). +Convert public API to Effect return types with typed errors. +Preserve existing EventEmitter internally for now, but expose Effect-friendly subscribe API. +PR 4: ProviderService Effect adapter +Wrap current ProviderManager behind ProviderServiceLive (adapter). +Provider methods become Effect methods with typed errors. +Route emitted provider events through an Effect PubSub surface. +PR 5: wsServer migration to Effect services +Stop instantiating provider/codex classes directly in wsServer. +Resolve ProviderService (and related services) from one runtime/layer graph. +Keep WS contract behavior identical. +PR 6: Native CheckpointStore implementation +Refactor checkpoint internals from Promise/throws to native Effect. +Replace ad-hoc locking with Effect concurrency primitive (keyed lock/semaphore/queue). +Keep adapter tests plus new failure-path tests. +PR 7: Codex transport/RPC core as native Effect +Split codex into scoped process layer + RPC request/response layer + session registry. +Replace timeout/pending maps with Deferred + Effect timeout/finalizer semantics. +Keep protocol behavior and ordering guarantees. +PR 8: Codex protocol decoding hardening +Replace ad-hoc unknown parsing with runtime schema decoding for inbound/outbound protocol shapes. +Map decode failures to typed tagged errors (with root cause). +Add regression tests for malformed/partial protocol messages. +PR 9: Native ProviderService orchestration +Rebuild provider logic in Effect using CodexService + CheckpointStore dependencies. +Move event fanout, checkpoint capture/revert orchestration, thread-log routing to Effect state/services. +Remove throw-based flow entirely from provider path. +PR 10: Cleanup + deprecation removal +Remove legacy class implementations/adapters once parity is proven. +Finalize layer composition and startup graph docs. +Add architecture notes for service boundaries and error model. diff --git a/.plans/12-effect-new.md b/.plans/12-effect-new.md new file mode 100644 index 0000000000..3d87049f8b --- /dev/null +++ b/.plans/12-effect-new.md @@ -0,0 +1,67 @@ +# Effect Migration Plan (From Current State) + +Current status summary: + +- Service contracts, typed errors, and most checkpoint/persistence services exist. +- `ProviderServiceLive` is already native orchestration (not a thin adapter). +- Production server path still uses legacy `ProviderManager`/`FilesystemCheckpointStore`. +- Checkpoint flow now avoids snapshot re-sync and is write-time driven. + +## PR 1: Wire Provider/Checkpoint Effect Stack Into `wsServer` + +- Build one runtime layer graph for provider + checkpoint + persistence + orchestration. +- Resolve `ProviderService` from runtime in `wsServer`. +- Replace `ProviderManager` method calls in WS handlers with `ProviderService` calls. +- Forward provider events by subscribing to `ProviderService.subscribeToEvents`. +- Keep WS method/push payloads identical. + +## PR 2: Runtime Composition + Startup Ownership + +- Create/centralize `AppLive` composition for server startup. +- Ensure outer runtime provides Node/platform services once. +- Ensure migrations run at startup via scoped/layer startup path. +- Remove ad-hoc service initialization in request-time paths. + +## PR 3: Session Lifecycle Hygiene + Checkpoint Invariants + +- Add explicit checkpoint session cleanup on `stopSession` / `stopAll`. +- Remove per-session lock/cwd map leaks. +- Keep strict invariant model: + - root checkpoint created at session initialization before agent modifications + - each completed turn captures filesystem checkpoint and persists metadata + - no after-the-fact metadata rebuild/sync +- Add tests for lifecycle cleanup and invariant-failure surfaces. + +## PR 4: Provider Event Stream Hardening (Without Extra Service Fragmentation) + +- Keep `ProviderService` as the public event surface. +- Internally move callback fanout to Effect concurrency primitives (`Queue`/`PubSub`) for ordering/backpressure control. +- Keep API as `subscribeToEvents` unless we explicitly choose stream API later. +- Add tests for ordering and subscriber isolation under load. + +## PR 5: Codex Runtime Split (Scoped Effect Core) + +- Extract `CodexAppServerManager` responsibilities into Effect-native layers: + - scoped process lifecycle + - RPC request/response + pending map via `Deferred` + - session registry/state +- Keep `CodexAdapter` contract stable while swapping internals. +- Preserve protocol behavior and timeout semantics. + +## PR 6: Codex Protocol Decode Hardening + +- Replace ad-hoc unknown parsing with runtime schema decode. +- Map decode failures to typed tagged errors with `cause` retained. +- Add regression tests for malformed/partial protocol frames. + +## PR 7: Remove Legacy Provider Stack + +- Remove `ProviderManager` + legacy checkpoint integration from runtime path. +- Remove `FilesystemCheckpointStore` from active server flow (keep only if explicitly needed for compatibility tooling). +- Update tests to assert only Effect service path is used. + +## PR 8: Final Cleanup + Docs + +- Update architecture docs with final layer graph and service boundaries. +- Document error model and recovery semantics. +- Trim dead compatibility code and stale plan references. diff --git a/.plans/13-provider-service-integration-tests.md b/.plans/13-provider-service-integration-tests.md new file mode 100644 index 0000000000..f3fe4edf02 --- /dev/null +++ b/.plans/13-provider-service-integration-tests.md @@ -0,0 +1,123 @@ +# ProviderService Integration Test Plan + +Goal: + +- Validate end-to-end `ProviderService` behavior with real layers: + - `ProviderServiceLive` + - `CheckpointServiceLive` + - `CheckpointStoreLive` + - `CheckpointRepositoryLive` (sqlite in-memory) + - `ProviderSessionDirectoryLive` +- Only fake the adapter event source (deterministic Codex-like stream). +- Avoid mocking checkpointing/persistence orchestration logic. + +## Test Harness + +Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`: + +- Service contract: `ProviderAdapterShape`. +- Internal state: + - session registry (session + cwd + threadId) + - thread snapshot store (`threadId`, `turns`) + - event subscribers +- Behavior: + - `startSession`: creates session with threadId. + - `sendTurn`: appends a deterministic turn snapshot and emits ordered events: + - `turn/started` + - `item/started` / `item/completed` (tool + approval variants depending on scenario) + - `item/agentMessage/delta` chunks + - `turn/completed` + - optional "mutator" callback per turn to change workspace files before completion. + - `readThread`, `rollbackThread`, `stopSession`, `stopAll`. + +Use real git-backed temporary workspaces in integration tests: + +- initialize repo with baseline commit +- run provider turn in workspace +- assert checkpoint diffs against real git refs + +## Core Integration Specs + +1. `startSession` initializes checkpoint root exactly once + +- Arrange: + - start provider session in git repo. +- Assert: + - `provider_checkpoints` contains root row (turn 0). + - checkpoint ref exists in git. + - second `startSession` for new session creates a new independent root. + +2. Turn without filesystem change + +- Arrange: + - emit normal turn events, no file mutation. +- Assert: + - provider subscribers receive: + - `turn/started` + - `turn/completed` + - synthetic `checkpoint/captured` + - `listCheckpoints` returns root + turn 1. + - `getCheckpointDiff(0 -> 1)` returns empty/no-op diff. + +3. Turn with filesystem change + +- Arrange: + - mutate `README.md` during turn. +- Assert: + - `listCheckpoints` returns root + turn 1. + - `getCheckpointDiff(0 -> 1)` contains file path and hunk. + - persisted checkpoint metadata includes non-empty `checkpointRef`. + +4. Multi-turn sequencing and checkpoint monotonicity + +- Arrange: + - turn 1: no file change + - turn 2: file change + - turn 3: file change +- Assert: + - turn counts are monotonic and contiguous in DB (0,1,2,3). + - latest checkpoint is marked current. + - diffs for adjacent turns map to expected filesystem deltas. + +5. Revert to checkpoint + +- Arrange: + - execute 3 turns with at least one file-changing turn. + - call `revertToCheckpoint(turnCount=1)`. +- Assert: + - workspace content matches turn 1 state. + - adapter `rollbackThread` called with `numTurns=2`. + - DB rows for turns >1 are removed. + - later refs are deleted from git. + +6. Capture failure surface + +- Arrange: + - adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails. +- Assert: + - `ProviderService` emits `checkpoint/captureError`. + - no partial metadata/ref divergence is left behind. + +## WebSocket Coverage (Thin Integration) + +Add one ws server integration spec: + +- Subscribe to `providers.event`. +- Run a deterministic provider turn through ws methods. +- Assert push stream includes: + - `turn/started`, tool events, `turn/completed`, `checkpoint/captured`. +- Assert orchestration projection still updates assistant message and turn diff summary. + +## Proposed PR Split + +PR A: + +- Test adapter harness + shared integration fixtures (repo setup, runtime/layer setup). + +PR B: + +- Core ProviderService integration specs (cases 1-4). + +PR C: + +- Revert + failure-path specs (cases 5-6) + ws thin integration spec. diff --git a/.plans/14-server-authoritative-event-sourcing-cleanup.md b/.plans/14-server-authoritative-event-sourcing-cleanup.md new file mode 100644 index 0000000000..e5c5023205 --- /dev/null +++ b/.plans/14-server-authoritative-event-sourcing-cleanup.md @@ -0,0 +1,227 @@ +# Server-Authoritative Event-Sourcing Cleanup Plan + +Goal: + +- Move to a cleaner service architecture with: + - durable, server-authoritative event sourcing + - strict command routing/validation + - pluggable provider adapters + - explicit separation between transport, domain orchestration, provider runtime, and persistence + +## Target Service Graph (ASCII) + +```text + +---------------------------+ + | wsServer | + | transport | + +---------------------------+ + | orchestration.dispatchCommand + v + +-------------------------------------------+ + | OrchestrationCommandRouter | + +-------------------------------------------+ + | + v + +-------------------------------------------+ + | OrchestrationCommandHandlers | + +-------------------------------------------+ + | + v + +-------------------------------------------+ + | OrchestrationEventStore | + +-------------------------------------------+ + | + v + +-------------------------------------------+ + | OrchestrationProjectionService | + +-------------------------------------------+ + | snapshot/replay + +---------------------------> wsServer + + +wsServer -- providers.* RPC --> +---------------------------+ + | ProviderService | + +---------------------------+ + | | + v v + +-------------------+ +-------------------------+ + | ProviderSession | | ProviderAdapterRegistry | + | Registry (durable)| +-------------------------+ + +-------------------+ | + ^ v + | +-------------------------+ + | | ProviderAdapter(s) | + | +-------------------------+ + | | + | runtime events v + | +---------------------------+ + +----------| ProviderRuntimeIngestion | + +---------------------------+ + | | | + v v v + Router Session Checkpoint + Registry Service + + +-------------------------------------------+ + | CheckpointService | + +-------------------------------------------+ + | | | + v v v + +--------------------+ +-------------+ +-------------------+ + | CheckpointCatalog | | Checkpoint | | ProviderAdapter(s)| + | (durable) | | Store (git) | | (read/rollback) | + +--------------------+ +-------------+ +-------------------+ + | + v + +------+ + |SQLite| + +------+ + +OrchestrationEventStore ------> SQLite +OrchestrationProjectionService -> SQLite +ProviderSessionRegistry ------> SQLite +CheckpointCatalog ------> SQLite +``` + +## Commit Series + +### Commit 1: Split public vs system orchestration command contracts + +- Create separate schemas/types: + - `ClientOrchestrationCommandSchema` + - `SystemOrchestrationCommandSchema` + - `OrchestrationCommandSchema = union(client, system)` +- Ensure client transport can only submit client commands. +- Keep system commands for server-internal workflows only. +- Expected files: + - `packages/contracts/src/orchestration.ts` + - `apps/server/src/wsServer.ts` + - orchestration/service tests +- Tests: + - reject system-only command via WS dispatch path + - preserve internal dispatch functionality for system commands + +### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary + +- Add dedicated router service to validate, authorize, and route commands. +- Move command-to-event mapping out of `orchestration/Layer.ts` into handlers. +- Add aggregate-level invariant checks before append (thread exists, project exists, etc.). +- Expected files: + - `apps/server/src/orchestration/Services/CommandRouter.ts` (new) + - `apps/server/src/orchestration/Layers/CommandRouter.ts` (new) + - `apps/server/src/orchestration/Layer.ts` + - `apps/server/src/orchestration/reducer.ts` (only if needed for event payload changes) +- Tests: + - router validation and invariant failures + - handler happy-path tests per command type + +### Commit 3: Harden event store for idempotency + optimistic append metadata + +- Add DB-level idempotency guard for `command_id` (`UNIQUE` where non-null). +- Extend append API to support idempotent replays and deterministic return of prior event on duplicate `commandId`. +- Add optional aggregate version metadata for future optimistic concurrency. +- Expected files: + - `apps/server/src/persistence/Migrations/00x_*.ts` (new migration) + - `apps/server/src/persistence/Services/OrchestrationEvents.ts` + - `apps/server/src/persistence/Layers/OrchestrationEvents.ts` +- Tests: + - duplicate command ID append returns same event/sequence (or explicit idempotent behavior) + - concurrent append behavior stays ordered and deterministic + +### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer` + +- Create `ProviderRuntimeIngestionService` that: + - subscribes to `ProviderService.streamEvents` + - translates runtime events into orchestration commands + - dispatches through router/engine +- Remove provider-to-orchestration state mutation logic from `wsServer`. +- Expected files: + - `apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts` (new) + - `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (new) + - `apps/server/src/wsServer.ts` +- Tests: + - ingestion service mapping tests (turn started/completed, message delta/completed, runtime error) + - ws integration confirms same external push behavior + +### Commit 5: Make session directory durable (`ProviderSessionRegistry`) + +- Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry. +- Keep in-memory cache optional, but source of truth must be persistent. +- Add startup reconciliation to prune dead sessions / keep known thread mapping. +- Expected files: + - `apps/server/src/provider/Services/ProviderSessionDirectory.ts` (or new SessionRegistry service) + - `apps/server/src/provider/Layers/ProviderSessionDirectory.ts` + - `apps/server/src/persistence/Migrations/00x_*.ts` (new table/indexes) + - provider persistence tests +- Tests: + - survives server restart with correct mapping + - stale session cleanup semantics + +### Commit 6: Re-key checkpoint metadata from session to thread identity + +- Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`. +- Keep `session_id` as nullable metadata only. +- Update checkpoint flows (`initialize`, `capture`, `list`, `diff`, `revert`) to use thread identity. +- Expected files: + - `apps/server/src/persistence/Migrations/00x_*.ts` (checkpoint schema migration) + - `apps/server/src/persistence/Services/Checkpoints.ts` + - `apps/server/src/persistence/Layers/Checkpoints.ts` + - `apps/server/src/checkpointing/Layers/CheckpointService.ts` +- Tests: + - resume/new session over same thread sees same checkpoint history + - revert/diff still work after session churn + +### Commit 7: Add durable projection persistence for orchestration read models + +- Introduce projection tables/snapshots persisted in DB to avoid full replay dependency. +- Keep event stream as source of truth; projection rebuild stays deterministic. +- `getSnapshot` reads from projection store (memory cache optional). +- Expected files: + - `apps/server/src/persistence/Migrations/00x_*.ts` (projection tables) + - `apps/server/src/orchestration/*` projection service/layer + - `apps/server/src/wsServer.ts` (snapshot/replay path wiring) +- Tests: + - cold boot snapshot load without replaying full history in process + - projection rebuild from events yields same result as previous reducer semantics + +### Commit 8: Narrow `ProviderService` responsibilities + +- Keep `ProviderService` focused on provider RPC/session lifecycle + unified runtime stream. +- Move checkpoint-capture side effects out of provider event worker into dedicated ingestion/checkpoint pipeline service. +- Preserve adapter pluggability and provider-neutral contracts. +- Expected files: + - `apps/server/src/provider/Layers/ProviderService.ts` + - new orchestration/checkpoint runtime coordinator service(s) +- Tests: + - provider service routing stays intact + - checkpoint capture still triggered by turn completion through new coordinator + +### Commit 9: Look over schemas (contracts and events) + +- Scan for unused schemas. +- Use effect/Schema everywhere +- Analyze which we need + - RPC Input/Output (both for routeRequest and command handler) + - Event payloads + - Persistence entities + +### Commit 10: Remove dead legacy path and finalize docs + +- Remove unused legacy manager/store path from active architecture: + - `providerManager.ts` + - `filesystemCheckpointStore.ts` (if no longer needed by tests/tools) +- Look over effect services for unused methods, errors, etc +- Update architecture docs with final service boundaries and boot/runtime graph. +- Expected files: + - legacy files + references + - `AGENTS.md`/docs as needed + - `.plans` docs linkage +- Tests: + - full server integration suite passes on Effect-only path + - no regressions in WS protocol behavior + +## Risk Controls + +- Keep WS method names and payload contracts stable throughout. +- Gate each commit with targeted integration tests before moving forward. +- Avoid broad event-type churn in one step; migrate schemas incrementally with clear compatibility windows. diff --git a/.plans/15-effect-server.md b/.plans/15-effect-server.md new file mode 100644 index 0000000000..5e245bb8e9 --- /dev/null +++ b/.plans/15-effect-server.md @@ -0,0 +1,11 @@ +Rewrite `createServer` and `index.ts` to be Effect native. + +Maybe use `effect/unstable/Socket` for the web socket server + +- https://github.com/Effect-TS/effect-smol/blob/main/packages/effect/src/unstable/socket/SocketServer.ts +- https://github.com/Effect-TS/effect-smol/blob/main/packages/platform-node/test/NodeSocket.test.ts + +- Migrate remaining runtime code to Effect + - `gitManager` -> `src/git` + - `terminalManager` -> `src/terminal` (Manager + PTY) + - ... diff --git a/.plans/16-pr89-review-remediation-phases.md b/.plans/16-pr89-review-remediation-phases.md new file mode 100644 index 0000000000..81ed6bd9f2 --- /dev/null +++ b/.plans/16-pr89-review-remediation-phases.md @@ -0,0 +1,165 @@ +# PR #89 Review Remediation Plan (Phased) + +## How To Use These Files + +- Working checklist with updateable status per item (single source of truth): `.plans/16c-pr89-remediation-checklist.md` +- This file (`16-pr89-review-remediation-phases.md`): phase strategy and grouping. + +## Scope + +- Source: GitHub review comments on PR #89 (`Add server-side orchestration engine with event sourcing`). +- Triage baseline used here: + - Total threads: 185 + - Outdated: 94 (excluded) + - Active unresolved: 85 + - Invalid/false-positive: 3 (excluded) + - Duplicate reposts: collapsed + - Unique actionable findings after filtering: 58 + - Post-rewrite validity audit: 5 additional stale items marked invalid, leaving 53 actionable (`34 valid` + `19 partially-valid`) + +## Phase 0: Canonical Triage Lock + +- Create a single tracking checklist for the 53 currently actionable findings. +- Map every duplicate thread to its canonical item. +- Mark invalid/false-positive items with explicit rationale. + +Exit criteria: + +- Every open thread is mapped to one canonical fix item or marked invalid. + +## Phase 1: Runtime Survival and Critical Event Wiring + +Related bug groups solved together: + +- Worker loop/fiber fatal error handling in orchestration reactors. +- WebSocket message error boundaries and unhandled rejection guards. +- Close invalid `providers.event` review findings as documented architecture mismatch (no code change expected). + +Primary files: + +- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` +- `apps/server/src/orchestration/Layers/CheckpointReactor.ts` +- `apps/server/src/wsServer.ts` + +Exit criteria: + +- A single event-processing failure cannot permanently stop ingestion/reactor loops. +- WS message handling cannot produce unhandled promise rejections. +- Invalid provider-event-channel review findings are closed with architecture rationale. + +## Phase 2: State Consistency and Ordering + +Related bug groups solved together: + +- Fire-and-forget revert completion causing consistency windows. +- Non-atomic append/projection paths and retry behavior. +- Race-sensitive thread/event association issues. + +Primary files: + +- `apps/server/src/orchestration/Layers/CheckpointReactor.ts` +- `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` +- `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` +- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` + +Exit criteria: + +- Revert flow is deterministically reflected in read model updates. +- Append/project failure mode is explicit and safe under retry. +- No cross-thread misassociation under concurrent runtime events. + +## Phase 3: Checkpointing Correctness Bundle + +Related bug groups solved together: + +- Checkpoint input normalization consistency. +- Snapshot/projector coverage mismatches. +- Checkpoint ref/workspace CWD utility duplication. +- Checkpoint diff/error handling behavior gaps. + +Primary files: + +- `apps/server/src/checkpointing/Layers/CheckpointStore.ts` +- `apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts` +- `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts` +- `apps/server/src/orchestration/Layers/CheckpointReactor.ts` +- `apps/server/src/wsServer.ts` + +Exit criteria: + +- Checkpoint capture/restore/revert paths use one normalization policy. +- Required projectors are actually represented in snapshot reads. +- Shared checkpoint/ref/CWD helpers are centralized. + +## Phase 4: Memory and Lifecycle Hygiene + +Related bug groups solved together: + +- Unbounded in-memory dedup sets/maps. +- Missing cleanup/lifecycle protections in long-lived effects/resources. + +Primary files: + +- `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts` +- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` +- `apps/server/src/config.ts` + +Exit criteria: + +- Long-running server memory does not grow unbounded from dedup bookkeeping. +- Resource cleanup paths are registered for interruption/shutdown. + +## Phase 5: Transport, Parsing, and Platform Edge Cases + +Related bug groups solved together: + +- UTF-8 chunk boundary decode correctness. +- Markdown/file-link parsing edge cases. +- Shell/OS-specific PATH parsing behavior. +- Git rename parsing and small keybinding edge cases. + +Primary files: + +- `apps/server/src/wsServer.ts` +- `apps/server/src/git/Layers/CodexTextGeneration.ts` +- `apps/web/src/markdown-links.ts` +- `apps/server/src/os-jank.ts` +- `apps/server/src/git/Layers/GitCore.ts` +- `apps/server/src/keybindings.ts` + +Exit criteria: + +- Edge-case parsers are robust across valid but non-trivial inputs. +- Platform-dependent command behavior has safe fallbacks. + +## Phase 6: Build and Maintainability Cleanup + +Related bug groups solved together: + +- Build script/runtime assumption cleanup. +- Redundant error-union declarations and utility/type duplication. +- Non-functional cleanup comments/docs markers. + +Primary files: + +- `apps/server/package.json` +- `apps/server/src/checkpointing/Errors.ts` +- Shared utility locations introduced during earlier phases +- `AGENTS.md` (if cleanup is still pending) + +Exit criteria: + +- Build path is explicit and environment-safe. +- Redundant types/utilities are removed in favor of single sources of truth. + +## Phase 7: Verification and Closeout + +- Add backend tests for all behavioral fixes (integration-focused; external services may be layered/mocked, core business logic not mocked out). +- Run lint and backend tests for all touched packages. +- Resolve threads with fix references per canonical checklist item. + +Exit criteria: + +- Lint passes. +- Backend tests pass. +- All actionable review threads are resolved or explicitly justified. diff --git a/.plans/16c-pr89-remediation-checklist.md b/.plans/16c-pr89-remediation-checklist.md new file mode 100644 index 0000000000..6512e92467 --- /dev/null +++ b/.plans/16c-pr89-remediation-checklist.md @@ -0,0 +1,478 @@ +# PR #89 Remediation Checklist (Consolidated) + +_Last updated: 2026-02-26_ + +This is the working checklist for remediation execution. + +Status values: + +- `TODO`: Not started +- `IN_PROGRESS`: Currently being worked +- `BLOCKED`: Waiting on decision/dependency +- `DONE`: Implemented and verified +- `CLOSED_INVALID`: Stale/invalid review finding + +Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6` + +## Active Checklist + +### Phase 1 + +- [x] `C002` A dispatch error in `processEvent` will terminate the `Effect.forever` loop, permanently halting event ingestion. Consider adding error recovery (e.g., `Effect.catchAll` with logging) around `processEvent` so failures don't kill the fiber. + - Status: `DONE` + - Verdict: `valid` + - Severity: `High` + - Area: `Runtime resilience and failure handling` + - File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:333` + - Threads: PRRT_kwDORLtfbc5wj4cH, PRRT_kwDORLtfbc5wnWwF, PRRT_kwDORLtfbc5wyTaP, PRRT_kwDORLtfbc5wzliw, PRRT_kwDORLtfbc5w0_g3, PRRT_kwDORLtfbc5w1HGT (+5 duplicate thread(s)) + - Audit note: Ingestion worker loop can terminate on unhandled processEvent failure. + +- [x] `C003` Consider attaching a no-op error listener before `socket.write` (e.g., `socket.on('error', () => {})`) to prevent an unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake. + - Status: `DONE` + - Verdict: `valid` + - Severity: `High` + - Area: `WebSocket robustness` + - File: `apps/server/src/wsServer.ts:75` + - Threads: PRRT_kwDORLtfbc5v-cf4 + - Audit note: Upgrade reject writes then destroys socket without defensive error listener. + +- [x] `C012` Forked revert dispatch risks read model inconsistency + - Status: `DONE` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Runtime resilience and failure handling` + - File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:542` + - Threads: PRRT_kwDORLtfbc5whszW, PRRT_kwDORLtfbc5wyTaS, PRRT_kwDORLtfbc5wzli0, PRRT_kwDORLtfbc5w0_g4, PRRT_kwDORLtfbc5w1HGX (+4 duplicate thread(s)) + - Audit note: Revert completion dispatch remains forked; state consistency window remains. + +- [ ] `C019` ProviderRuntimeIngestion processes events for wrong thread on race + - Status: `TODO` + - Verdict: `partially-valid` + - Severity: `Medium` + - Area: `Runtime resilience and failure handling` + - File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:178` + - Threads: PRRT_kwDORLtfbc5wkPaL + - Audit note: SessionId-only routing can misassociate events under races/rebinds. + +- [x] `C020` On `message.completed`, the message ID is added to the set and `thread.message.assistant.complete` is dispatched. On `turn.completed`, the same set is iterated and `thread.message.assistant.complete` is dispatched again for each ID—including already-completed ones. Consider removing message IDs from the set after dispatching on `message.completed`, or filtering out already-completed IDs before the `turn.completed` loop. + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Medium` + - Area: `Runtime resilience and failure handling` + - File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:266` + - Threads: PRRT_kwDORLtfbc5w1GPr + - Audit note: Duplicate complete dispatch exists; downstream impact often idempotent. + +- [x] `C026` Consider adding `.catch(() => {})` after `Effect.runPromise(handleMessage(ws, raw))` to prevent unhandled rejections from crashing the server if `encodeResponse` or setup logic fails. + - Status: `DONE` + - Verdict: `valid` + - Severity: `Medium` + - Area: `WebSocket robustness` + - File: `apps/server/src/wsServer.ts:545` + - Threads: PRRT_kwDORLtfbc5wj4cE + - Audit note: runPromise result still not caught; rejection can surface unhandled. + +- [x] `C027` WS message handler can cause unhandled promise rejection + - Status: `DONE` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Runtime resilience and failure handling` + - File: `apps/server/src/wsServer.ts:545` + - Threads: PRRT_kwDORLtfbc5wyTaW, PRRT_kwDORLtfbc5wzli3 (+1 duplicate thread(s)) + - Audit note: Same unhandled rejection path remains in WS message handler. + +- [x] `C042` Duplicated `resolveThreadWorkspaceCwd` across three files + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Low` + - Area: `Runtime resilience and failure handling` + - File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:62` + - Threads: PRRT_kwDORLtfbc5wzli2 + - Audit note: Duplication exists but one instance is variant logic, so impact is moderate. + +- [x] `C043` Duplicated workspace CWD resolution logic across reactor modules + - Status: `DONE` + - Verdict: `valid` + - Severity: `Low` + - Area: `Runtime resilience and failure handling` + - File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:62` + - Threads: PRRT_kwDORLtfbc5wnWwM, PRRT_kwDORLtfbc5w1C3-, PRRT_kwDORLtfbc5w1HGZ (+2 duplicate thread(s)) + - Audit note: Workspace CWD resolution duplication still present across modules. + +- [x] `C044` Checkpoint reactor swallows diff errors silently for `turn.completed` + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Low` + - Area: `Runtime resilience and failure handling` + - File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:274` + - Threads: PRRT_kwDORLtfbc5wkPaO + - Audit note: Errors are swallowed to empty diff with warning; not fully silent but still lossy. + +- [x] `C045` `truncateDetail` slices to `limit - 1` then appends `"..."` (3 chars), producing strings of length `limit + 2`. Consider slicing to `limit - 3` instead.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `valid` + - Severity: `Low` + - Area: `Runtime resilience and failure handling` + - File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:29` + - Threads: PRRT_kwDORLtfbc5wzp4R + - Audit note: truncateDetail still overshoots limit. + +- [x] `C046` `latestMessageIdByTurnKey` is written to but never read, and `clearAssistantMessageIdsForTurn` doesn't clear its entries—only `clearTurnStateForSession` does. Consider removing this map entirely if unused, or clearing it alongside `turnMessageIdsByTurnKey` in `clearAssistantMessageIdsForTurn`.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `valid` + - Severity: `Low` + - Area: `Runtime resilience and failure handling` + - File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:133` + - Threads: PRRT_kwDORLtfbc5wxvIQ + - Audit note: latestMessageIdByTurnKey still unused/unpruned in per-turn clear path. + +- [x] `C053` Consider using `socket.end(response)` instead of `socket.write(response)` + `socket.destroy()` to ensure the HTTP error response is fully flushed before closing the connection. + - Status: `DONE` + - Verdict: `valid` + - Severity: `Low` + - Area: `WebSocket robustness` + - File: `apps/server/src/wsServer.ts:83` + - Threads: PRRT_kwDORLtfbc5v-WPD + - Audit note: Still uses write+destroy rather than end() for rejection response. + +- [ ] `C054` When array chunks contain a multi-byte UTF-8 character split across boundaries, decoding each chunk separately produces replacement characters. Consider using `Buffer.concat()` on all chunks before calling `.toString("utf8")`.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `TODO` + - Verdict: `valid` + - Severity: `Low` + - Area: `WebSocket robustness` + - File: `apps/server/src/wsServer.ts:104` + - Threads: PRRT_kwDORLtfbc5whtrR + - Audit note: Array chunk UTF-8 decode remains vulnerable to split multibyte corruption. + +- [x] `C059` Suggestion: don’t spread `params` into `body`; it can override `_tag` and mishandle non-object values. Keep `_tag` separate and nest `params` under a single key (e.g., `data`), or validate `params` is a plain object. + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Low` + - Area: `WebSocket robustness` + - File: `apps/web/src/wsTransport.ts:59` + - Threads: PRRT_kwDORLtfbc5whtrN + - Audit note: Transport \_tag override risk exists but current callsites are constrained. + +### Phase 2 + +- [x] `C001` Non-atomic event appending can corrupt state on retry. If an error occurs mid-loop (lines 96-102) after some events are persisted but before the receipt is written, the command appears to fail. A retry generates new UUIDs via `crypto.randomUUID()` in the decider, appending duplicate events. Consider wrapping the loop in a transaction or using deterministic event IDs derived from `commandId`.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `valid` + - Severity: `High` + - Area: `Event ordering and state consistency` + - File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:96` + - Threads: PRRT_kwDORLtfbc5wzp4T + - Audit note: Append/project/receipt are non-atomic; retry can duplicate events. + +- [x] `C013` If `projectionPipeline.projectEvent` fails after `eventStore.append` succeeds, the event is persisted but `readModel` isn't updated, causing desync. Consider updating the in-memory `readModel` immediately after append (before the external projection), so local state stays consistent regardless of downstream failures. + - Status: `DONE` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Event ordering and state consistency` + - File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:99` + - Threads: PRRT_kwDORLtfbc5whtrM + - Audit note: Persisted event can outpace in-memory projection on mid-flight failure. + +- [x] `C015` The gap-filling fallback logic can retain messages from turns that are about to be deleted, causing foreign key violations. Consider removing the fallback logic entirely, or filtering `fallbackUserMessages` and `fallbackAssistantMessages` to only include messages whose `turnId` is in `retainedTurnIds`.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Medium` + - Area: `Event ordering and state consistency` + - File: `apps/server/src/orchestration/Layers/ProjectionPipeline.ts:99` + - Threads: PRRT_kwDORLtfbc5whxJO + - Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated. + +- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes _after_ the committed sequence. Consider persisting this pending state or processing these two events atomically.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Event ordering and state consistency` + - File: `apps/server/src/orchestration/Layers/ProjectionPipeline.ts:490` + - Threads: PRRT_kwDORLtfbc5wxvH8 + - Audit note: Pending turn-start map is in-memory only and not rebuilt on bootstrap. + +### Phase 3 + +- [x] `C008` Inconsistent input normalization across CheckpointStore methods + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Medium` + - Area: `Checkpointing correctness` + - File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:94` + - Threads: PRRT*kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv*, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s)) + - Audit note: Edge schema strategy is in place across contracts/consumers (trim/normalize via schemas and decode at boundaries); CheckpointStore remains an internal repository boundary. + +- [x] `C017` `REQUIRED_SNAPSHOT_PROJECTORS` includes `pending-approvals` and `thread-turns`, but `getSnapshot` doesn't query their data. If these projectors lag behind, the returned `snapshotSequence` will be lower than what the included data actually reflects, causing clients to replay already-applied events. Consider filtering `REQUIRED_SNAPSHOT_PROJECTORS` to only include projectors whose data is actually fetched in the snapshot.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Medium` + - Area: `Checkpointing correctness` + - File: `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts:71` + - Threads: PRRT_kwDORLtfbc5wiLhQ + - Audit note: Snapshot sequence can under-report due to extra projectors, but replay impact is lower now. + +- [x] `C033` Three error classes defined but never instantiated anywhere + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Low` + - Area: `Checkpointing correctness` + - File: `apps/server/src/checkpointing/Errors.ts:51` + - Threads: PRRT_kwDORLtfbc5wlYgo + - Audit note: Original claim overstated; some errors used, others appear unused. + +- [x] `C034` Redundant `CheckpointInvariantError` in `CheckpointServiceError` union type + - Status: `DONE` + - Verdict: `valid` + - Severity: `Low` + - Area: `Checkpointing correctness` + - File: `apps/server/src/checkpointing/Errors.ts:79` + - Threads: PRRT_kwDORLtfbc5wj5fn + - Audit note: CheckpointInvariantError remains redundantly included in service union. + +- [x] `C035` Redundant error type in CheckpointServiceError union definition + - Status: `DONE` + - Verdict: `valid` + - Severity: `Low` + - Area: `Checkpointing correctness` + - File: `apps/server/src/checkpointing/Errors.ts:79` + - Threads: PRRT_kwDORLtfbc5wlYgs, PRRT_kwDORLtfbc5wxsO6, PRRT_kwDORLtfbc5w1C4B (+2 duplicate thread(s)) + - Audit note: Same as C034. + +### Phase 4 + +- [ ] `C018` Unbounded memory growth in turn start deduplication set + - Status: `TODO` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Memory/resource growth` + - File: `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts:84` + - Threads: PRRT_kwDORLtfbc5whszQ, PRRT_kwDORLtfbc5wl2A8, PRRT_kwDORLtfbc5wyTaT, PRRT_kwDORLtfbc5wzliz, PRRT_kwDORLtfbc5w0_g-, PRRT_kwDORLtfbc5w1HGW (+5 duplicate thread(s)) + - Audit note: handledTurnStartKeys still grows without pruning. + +### Phase 5 + +- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after `=>` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `TODO` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Edge-case parsing/platform behavior` + - File: `apps/server/src/git/Layers/GitCore.ts:41` + - Threads: PRRT_kwDORLtfbc5w1CxT + - Audit note: Braced rename parsing still breaks paths like src/{old => new}/file.ts. + +- [ ] `C010` `loadCustomKeybindingsConfig` fails when the config file doesn't exist, which is expected for new users. Consider catching `ENOENT` and returning an empty array instead.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `TODO` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Edge-case parsing/platform behavior` + - File: `apps/server/src/keybindings.ts:418` + - Threads: PRRT_kwDORLtfbc5wxvIJ + - Audit note: ENOENT for missing keybindings config still not handled as empty/default. + +- [ ] `C022` Fish shell outputs `$PATH` as space-separated, not colon-separated. Consider checking if the shell is fish and using `string join : $PATH` instead, or validating the result contains colons before assigning. + - Status: `TODO` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Edge-case parsing/platform behavior` + - File: `apps/server/src/os-jank.ts:10` + - Threads: PRRT_kwDORLtfbc5wkRZM + - Audit note: fish PATH formatting risk still exists in os-jank path recovery. + +- [ ] `C023` Using `-il` flags causes the shell to source profile scripts that may print banners or other text, polluting the captured `PATH`. Consider using `-lc` (login only, non-interactive) to reduce unwanted output. + - Status: `TODO` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Edge-case parsing/platform behavior` + - File: `apps/server/src/os-jank.ts:10` + - Threads: PRRT_kwDORLtfbc5wj4cM + - Audit note: -ilc shell invocation can pollute captured PATH output. + +- [x] `C029` `parseFileUrlHref` already decodes the path (line 46), but `safeDecode` is called again here, corrupting filenames containing `%` sequences. Consider skipping the decode when `fileUrlTarget` is non-null. + - Status: `DONE` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Edge-case parsing/platform behavior` + - File: `apps/web/src/markdown-links.ts:105` + - Threads: PRRT_kwDORLtfbc5wnVsU + - Audit note: file URL decoding still double-decodes in one path. + +- [x] `C030` `EXTERNAL_SCHEME_PATTERN` matches `script.ts:10` as a scheme because `.ts:` looks like `scheme:`. Consider requiring `://` after the colon, or checking that what follows the colon is not just digits.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `valid` + - Severity: `Medium` + - Area: `Edge-case parsing/platform behavior` + - File: `apps/web/src/markdown-links.ts:111` + - Threads: PRRT_kwDORLtfbc5wnVsK + - Audit note: Scheme regex still misclassifies script.ts:10 as external scheme. + +- [ ] `C038` Multi-byte UTF-8 characters split across chunks will be corrupted when decoding each chunk separately. Consider accumulating all chunks first, then decoding once, or use `TextDecoder` with `stream: true`.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `TODO` + - Verdict: `valid` + - Severity: `Low` + - Area: `Edge-case parsing/platform behavior` + - File: `apps/server/src/git/Layers/CodexTextGeneration.ts:136` + - Threads: PRRT_kwDORLtfbc5w1GPo + - Audit note: Chunk-by-chunk UTF-8 decode can still corrupt split multibyte characters. + +- [x] `C039` The `+` key can be parsed (via trailing `+` handling) but cannot be encoded because `shortcut.key.includes("+")` returns true for the literal `+` key. Consider checking `shortcut.key === "+"` separately and encoding it as `"space"` style (e.g., a special token), or adjusting the condition to allow the single `+` character.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Low` + - Area: `Edge-case parsing/platform behavior` + - File: `apps/server/src/keybindings.ts:352` + - Threads: PRRT_kwDORLtfbc5wxvIB + - Audit note: Parser/encoder mismatch remains, but encoder path currently low-use. + +- [x] `C040` `upsertKeybindingRule` has a race condition: concurrent calls read the same file state, then the last write overwrites earlier changes. Consider wrapping the read-modify-write sequence with `Effect.Semaphore` to serialize access.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `valid` + - Severity: `Low` + - Area: `Edge-case parsing/platform behavior` + - File: `apps/server/src/keybindings.ts:488` + - Threads: PRRT_kwDORLtfbc5wxvIA + - Audit note: upsertKeybindingRule read-modify-write remains race-prone. + +### Phase 6 + +- [ ] `C028` Branch sync dispatches both server and stale local update + - Status: `TODO` + - Verdict: `partially-valid` + - Severity: `Medium` + - Area: `Other` + - File: `apps/web/src/components/BranchToolbar.tsx:102` + - Threads: PRRT_kwDORLtfbc5v-XCu + - Audit note: Optimistic local+server dual update is intentional but can temporarily diverge. + +- [x] `C037` `Effect.callback` should return a cleanup function to close the server(s) on fiber interruption. Without it, the `Net.Server` handles keep the process alive and leak the port if the effect is cancelled.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Low` + - Area: `Other` + - File: `apps/server/src/config.ts:41` + - Threads: PRRT_kwDORLtfbc5wj4cO + - Audit note: Callback cleanup missing, but practical exposure is low in one-shot startup path. + +- [ ] `C047` `SqlSchema.findOneOption` can produce both SQL errors and decode errors, but `mapError` wraps all as `PersistenceSqlError`. Consider distinguishing `ParseError` from SQL errors and mapping decode failures to `PersistenceDecodeError` instead.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `TODO` + - Verdict: `valid` + - Severity: `Low` + - Area: `Other` + - File: `apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts:75` + - Threads: PRRT_kwDORLtfbc5wiaR- + - Audit note: Decode and SQL errors still collapsed into one persistence error kind. + +- [x] `C049` `JSON.stringify(cause)` returns `undefined` for `undefined`, functions, or symbols, violating the `string` return type. Consider coercing the result to a string (e.g., `String(JSON.stringify(cause))`) or adding a fallback. + - Status: `DONE` + - Verdict: `valid` + - Severity: `Low` + - Area: `Other` + - File: `apps/server/src/provider/Layers/ProviderService.ts:59` + - Threads: PRRT_kwDORLtfbc5wnVsI + - Audit note: JSON.stringify(cause) may return undefined despite string expectations. + +- [ ] `C050` The read-modify-write pattern (`getBySessionId` → merge → `upsert`) is susceptible to lost updates under concurrent writes. Consider wrapping in a transaction or adding optimistic concurrency control (e.g., version field) if concurrent session updates are expected.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `TODO` + - Verdict: `valid` + - Severity: `Low` + - Area: `Other` + - File: `apps/server/src/provider/Layers/ProviderSessionDirectory.ts:94` + - Threads: PRRT_kwDORLtfbc5wiLhY + - Audit note: ProviderSessionDirectory upsert remains read-merge-write without concurrency control. + +- [x] `C051` Using `??` for `providerThreadId` and `adapterKey` makes it impossible to clear these fields by passing `null`, since `null ?? existing` evaluates to `existing`. Consider using explicit `undefined` checks (like `resumeCursor` does) if clearing should be supported.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `DONE` + - Verdict: `partially-valid` + - Severity: `Low` + - Area: `Other` + - File: `apps/server/src/provider/Layers/ProviderSessionDirectory.ts:119` + - Threads: PRRT_kwDORLtfbc5wxvH9 + - Audit note: Null-clearing issue is real for providerThreadId; adapterKey part overstated. + +- [ ] `C052` Race condition: `processHandle` may be `null` when `data` callback fires, since it's assigned after `Bun.spawn` returns. Consider initializing `BunPtyProcess` first, then passing it to the callback to avoid losing initial output.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `TODO` + - Verdict: `valid` + - Severity: `Low` + - Area: `Other` + - File: `apps/server/src/terminal/Layers/BunPTY.ts:97` + - Threads: PRRT_kwDORLtfbc5w1CxE + - Audit note: Data callback may race before processHandle assignment. + +- [ ] `C056` When `onOpenChange` is provided without `open`, the internal `_open` state never updates because `setOpenProp` takes precedence. Consider calling `_setOpen` when `openProp === undefined`, regardless of whether `setOpenProp` exists. + - Status: `TODO` + - Verdict: `partially-valid` + - Severity: `Low` + - Area: `Other` + - File: `apps/web/src/components/ui/sidebar.tsx:114` + - Threads: PRRT_kwDORLtfbc5wxvIq + - Audit note: Bug pattern exists, but current callsites mostly avoid triggering it. + +- [ ] `C057` The `resizable` object is recreated on every render, causing `SidebarRail`'s `useEffect` to repeatedly read localStorage and update the DOM. Consider memoizing the object with `useMemo`.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `TODO` + - Verdict: `valid` + - Severity: `Low` + - Area: `Other` + - File: `apps/web/src/routes/_chat.$threadId.tsx:105` + - Threads: PRRT_kwDORLtfbc5wyWz4 + - Audit note: Resizable object recreation still retriggers effect/storage reads. + +- [ ] `C058` When `localStorage.getItem()` returns `null`, `Number(null)` evaluates to `0`, which passes `Number.isFinite(0)`. This causes the sidebar to clamp to `minWidth` on first load, overriding the `DIFF_INLINE_DEFAULT_WIDTH` CSS clamp. Consider checking for `null` or empty string before parsing, e.g. guard with `storedWidth === null || storedWidth === ''`.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `TODO` + - Verdict: `valid` + - Severity: `Low` + - Area: `Other` + - File: `apps/web/src/routes/_chat.$threadId.tsx:122` + - Threads: PRRT_kwDORLtfbc5wnVsX + - Audit note: Number(null) -> 0 path still forces min width on initial load. + +- [ ] `C060` `defaultModel` should be `Schema.optional(Schema.NullOr(Schema.String))` to allow clearing the value. Currently there's no way to reset it to `null` since omitting means "no change" in patch semantics.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent: + - Status: `TODO` + - Verdict: `valid` + - Severity: `Low` + - Area: `Other` + - File: `packages/contracts/src/orchestration.ts:253` + - Threads: PRRT_kwDORLtfbc5whxJC + - Audit note: Schema still cannot express null clear for defaultModel patch. + +## Closed Invalid Items + +- [x] `C014` Engine error handler catches all errors including non-invariant ones + - Status: `CLOSED_INVALID` + - Severity: `Medium` + - File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:144` + - Threads: PRRT_kwDORLtfbc5wkPaJ + - Rationale: Broad catch is intentional for worker liveness; transactional dispatch path prevents the claimed non-invariant idempotency break in current design. + +- [x] `C021` Shared mutable default metadata object causes stale eventId + - Status: `CLOSED_INVALID` + - Severity: `Medium` + - File: `apps/server/src/orchestration/decider.ts:27` + - Threads: PRRT_kwDORLtfbc5wkPaA + - Rationale: Stale-eventId claim no longer applies; eventId is regenerated per event. + +- [x] `C025` Duplicated checkpoint ref computation across two files + - Status: `CLOSED_INVALID` + - Severity: `Medium` + - File: `apps/server/src/wsServer.ts:128` + - Threads: PRRT_kwDORLtfbc5wvwag + - Rationale: No longer duplicated; checkpoint ref helper now centralized. + +- [x] `C031` Revert uses wrong turn count from positional inference + - Status: `CLOSED_INVALID` + - Severity: `Medium` + - File: `apps/web/src/session-logic.ts:127` + - Threads: PRRT_kwDORLtfbc5v9SCp + - Rationale: Revert now uses explicit checkpointTurnCount first; positional fallback is non-primary. + +- [x] `C036` Duplicate `checkpointRefForThreadTurn` function in two production files + - Status: `CLOSED_INVALID` + - Severity: `Low` + - File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:284` + - Threads: PRRT_kwDORLtfbc5wiqFX + - Rationale: No longer duplicated; single production source via Refs.ts. + +- [x] `C055` Duplicate `checkpointRefForThreadTurn` function across files + - Status: `CLOSED_INVALID` + - Severity: `Low` + - File: `apps/server/src/wsServer.ts:128` + - Threads: PRRT_kwDORLtfbc5wkPaG + - Rationale: No longer duplicated; helper is centralized. diff --git a/.plans/17-claude-agent.md b/.plans/17-claude-agent.md new file mode 100644 index 0000000000..a2d906e0e0 --- /dev/null +++ b/.plans/17-claude-agent.md @@ -0,0 +1,441 @@ +# Plan: Claude Code Integration (Orchestration Architecture) + +## Why this plan was rewritten + +The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through: + +1. `orchestration.dispatchCommand` (client intent) +2. `OrchestrationEngine` (decide + persist + publish domain events) +3. `ProviderCommandReactor` (domain intent -> `ProviderService`) +4. `ProviderService` (adapter routing + canonical runtime stream) +5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands) +6. `orchestration.domainEvent` (single push channel consumed by web) + +Claude integration must plug into this path instead of reintroducing legacy provider-specific flows. + +--- + +## Current constraints to design around (post-Stage 1) + +1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads. +2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed. +3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`. +4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`. +5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior. +6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only. + +--- + +## Architecture target + +Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths. + +Key decisions: + +1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries. +2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract. +3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`. +4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally. + +--- + +## Phase 1: Contracts and command shape updates + +### 1.1 Provider-aware model contract + +Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only. + +Expected outcomes: + +1. Introduce provider-scoped model lists (Codex + Claude). +2. Add helpers that resolve model by provider. +3. Preserve backwards compatibility for existing Codex defaults. + +### 1.2 Turn-start provider intent + +Update `packages/contracts/src/orchestration.ts`: + +1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`. +2. Carry provider through `ThreadTurnStartRequestedPayload`. +3. Keep existing command valid when provider is omitted. + +This removes the implicit “Codex unless session already exists” behavior as the only path. + +### 1.3 Provider session start input for Claude runtime knobs (completed) + +Update `packages/contracts/src/provider.ts`: + +1. Move provider-specific start fields into typed `providerOptions`: + - `providerOptions.codex` + - `providerOptions.claudeCode` +2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`. +3. Deprecate/remove `resumeThreadId` from the generic start contract. +4. Treat `resumeCursor` as adapter-owned opaque state. + +### 1.4 Contract tests (completed) + +Update/add tests in `packages/contracts/src/*.test.ts` for: + +1. New command payload shape. +2. Provider-aware model resolution behavior. +3. Breaking-change expectations for removed top-level provider fields. + +--- + +## Phase 2: Claude adapter implementation + +### 2.1 Add adapter service + layer + +Create: + +1. `apps/server/src/provider/Services/ClaudeAdapter.ts` +2. `apps/server/src/provider/Layers/ClaudeAdapter.ts` + +Adapter must implement `ProviderAdapterShape`. + +### 2.1.a SDK dependency and baseline config + +Add server dependency: + +1. `@anthropic-ai/claude-agent-sdk` + +Baseline adapter options to support from day one: + +1. `cwd` +2. `model` +3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`) +4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`) +5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`) +6. `resume` +7. `resumeSessionAt` +8. `includePartialMessages` +9. `canUseTool` +10. `hooks` +11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity) + +### 2.2 Claude runtime bridge + +Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle. + +Required capabilities: + +1. Long-lived session context per adapter session. +2. Multi-turn input queue. +3. Interrupt support. +4. Approval request/response bridge. +5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only). + +#### 2.2.a Agent SDK details to preserve + +The adapter should explicitly rely on these SDK capabilities: + +1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers). +2. Multi-turn input is supported via async-iterable prompt input. +3. Tool approval decisions are provided via `canUseTool`. +4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`. +5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events. + +#### 2.2.b Effect-native session lifecycle skeleton + +```ts +import { query } from "@anthropic-ai/claude-agent-sdk"; +import { Effect } from "effect"; + +const acquireSession = (input: ProviderSessionStartInput) => + Effect.acquireRelease( + Effect.tryPromise({ + try: async () => { + const claudeOptions = input.providerOptions?.claudeCode; + const resumeState = readClaudeResumeState(input.resumeCursor); + const abortController = new AbortController(); + const result = query({ + prompt: makePromptAsyncIterable(), + options: { + cwd: input.cwd, + model: input.model, + permissionMode: claudeOptions?.permissionMode, + maxThinkingTokens: claudeOptions?.maxThinkingTokens, + pathToClaudeCodeExecutable: claudeOptions?.binaryPath, + resume: resumeState?.threadId, + resumeSessionAt: resumeState?.sessionAt, + signal: abortController.signal, + includePartialMessages: true, + canUseTool: makeCanUseTool(), + hooks: makeClaudeHooks(), + }, + }); + return { abortController, result }; + }, + catch: (cause) => + new ProviderAdapterProcessError({ + provider: "claudeCode", + sessionId: "pending", + detail: "Failed to start Claude runtime session.", + cause, + }), + }), + ({ abortController }) => Effect.sync(() => abortController.abort()), + ); +``` + +#### 2.2.c AsyncIterable -> Effect Stream integration + +Preferred when available in the pinned Effect version: + +```ts +const sdkMessageStream = Stream.fromAsyncIterable( + session.result, + (cause) => + new ProviderAdapterProcessError({ + provider: "claudeCode", + sessionId, + detail: "Claude runtime stream failed.", + cause, + }), +); +``` + +Portable fallback (already aligned with current server patterns): + +```ts +const sdkMessageStream = Stream.async((emit) => { + let cancelled = false; + void (async () => { + try { + for await (const message of session.result) { + if (cancelled) break; + emit.single(message); + } + emit.end(); + } catch (cause) { + emit.fail( + new ProviderAdapterProcessError({ + provider: "claudeCode", + sessionId, + detail: "Claude runtime stream failed.", + cause, + }), + ); + } + })(); + return Effect.sync(() => { + cancelled = true; + }); +}); +``` + +### 2.3 Canonical event mapping + +Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`. + +Initial mapping target: + +1. assistant text deltas -> `content.delta` +2. final assistant text -> `item.completed` and/or `turn.completed` +3. approval requests -> `request.opened` +4. approval results -> `request.resolved` +5. system lifecycle -> `session.*`, `thread.*`, `turn.*` +6. errors -> `runtime.error` +7. plan/proposed-plan content when derivable + +Implementation note: + +1. Keep raw Claude message on `raw` for debugging. +2. Prefer canonical item/request kinds over provider-native enums. +3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently. + +### 2.4 Resume cursor strategy + +Define Claude-owned opaque resume state, e.g.: + +```ts +interface ClaudeResumeCursor { + readonly version: 1; + readonly threadId?: string; + readonly sessionAt?: string; +} +``` + +Rules: + +1. Serialize only adapter-owned state into `resumeCursor`. +2. Parse/validate only inside Claude adapter. +3. Store updated cursor when Claude runtime yields enough data to resume safely. +4. Never overload orchestration thread id as Claude thread id. + +### 2.5 Interrupt and stop semantics + +Map orchestration stop/interrupt expectations onto SDK controls: + +1. `interruptTurn()` -> active query interrupt. +2. `stopSession()` -> close session resources and prevent future sends. +3. `rollbackThread()` -> see Phase 4. + +--- + +## Phase 3: Provider service and composition + +### 3.1 Register Claude adapter + +Update provider registry layer to include Claude: + +1. add `claudeCode` -> `ClaudeAdapter` +2. ensure `ProviderService.listProviderStatuses()` reports Claude availability + +### 3.2 Persist provider binding + +Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`. + +Required validation: + +1. Claude bindings survive restart. +2. resume cursor remains opaque and round-trips untouched. +3. stopAll + restart can recover Claude sessions when possible. + +### 3.3 Provider start routing + +Update `ProviderCommandReactor` / orchestration flow: + +1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists. +2. If a thread already has Claude session binding, reuse it. +3. If provider switches between Codex and Claude, explicitly stop/rebind before next send. + +--- + +## Phase 4: Checkpoint and revert strategy + +Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`. + +Pick one explicit strategy: + +### Option A: provider-native rewind + +If SDK/runtime supports safe rewind: + +1. implement in Claude adapter +2. keep `CheckpointReactor` unchanged + +### Option B: session restart + state truncation shim + +If no native rewind exists: + +1. Claude adapter returns successful rollback by: + - stopping current Claude session + - clearing/rewriting stored Claude resume cursor to last safe resumable point + - forcing next turn to recreate session from persisted orchestration state +2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion. + +Whichever option is chosen: + +1. behavior must be deterministic +2. checkpoint revert tests must pass under orchestration expectations +3. user-visible activity log should explain failures clearly when provider rollback is impossible + +--- + +## Phase 5: Web integration + +### 5.1 Provider picker and model picker + +Update web state/UI: + +1. allow choosing Claude as thread provider before first turn +2. show Claude model list from provider-aware model helpers +3. preserve existing Codex default behavior when provider omitted + +Likely touch points: + +1. `apps/web/src/store.ts` +2. `apps/web/src/components/ChatView.tsx` +3. `apps/web/src/types.ts` +4. `packages/shared/src/model.ts` + +### 5.2 Settings for Claude executable/options + +Add app settings if needed for: + +1. Claude binary path +2. default permission mode +3. default max thinking tokens + +Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`. + +### 5.3 Session rendering + +No new WS channel should be needed. Claude should appear through existing: + +1. thread messages +2. activities/worklog +3. approvals +4. session state +5. checkpoints/diffs + +--- + +## Phase 6: Testing strategy + +### 6.1 Contract tests + +Cover: + +1. provider-aware model schemas +2. provider field on turn-start command +3. provider-specific start options schema + +### 6.2 Adapter layer tests + +Add `ClaudeAdapter.test.ts` covering: + +1. session start +2. event mapping +3. approval bridge +4. resume cursor parse/serialize +5. interrupt behavior +6. rollback behavior or explicit unsupported error path + +Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests. + +### 6.3 Provider service integration tests + +Extend provider integration coverage so Claude is exercised through `ProviderService`: + +1. start Claude session +2. send turn +3. receive canonical runtime events +4. restart/recover using persisted binding + +### 6.4 Orchestration integration tests + +Add/extend integration tests around: + +1. first-turn provider selection +2. Claude approval requests routed through orchestration +3. Claude runtime ingestion -> messages/activities/session updates +4. checkpoint revert behavior under Claude +5. stopAll/restart recovery + +These should validate real orchestration flows, not just adapter behavior. + +--- + +## Phase 7: Rollout order + +Recommended implementation order: + +1. contracts/provider-aware models +2. provider field on turn-start +3. Claude adapter skeleton + start/send/stream +4. canonical event mapping +5. provider registry/service wiring +6. orchestration recovery + checkpoint strategy +7. web provider/model picker +8. full integration tests + +--- + +## Non-goals + +1. Reintroducing provider-specific WS methods/channels. +2. Storing provider-native thread ids as orchestration ids. +3. Bypassing orchestration engine for Claude-specific UI flows. +4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`. diff --git a/.plans/17-provider-neutral-runtime-determinism.md b/.plans/17-provider-neutral-runtime-determinism.md new file mode 100644 index 0000000000..d70ec10548 --- /dev/null +++ b/.plans/17-provider-neutral-runtime-determinism.md @@ -0,0 +1,109 @@ +# Plan: Provider-Neutral Runtime Determinism and Flake Elimination + +## Summary +Replace timing-sensitive websocket and orchestration behavior with explicit typed runtime boundaries, ordered push delivery, and server-owned completion receipts. The cutover is broad and single-shot: no compatibility shim, no mixed old/new transport. The design must reduce flakes without baking Codex-specific lifecycle semantics into generic runtime code. + +## Implementation Status + +All 7 sections are implemented. CI passes (format, lint, typecheck, test, browser test, build). One deferred item remains: the shared `WsTestClient` helper from section 7 — tests use direct transport subscription and receipt-based waits instead. + +### New files + +| File | Purpose | +|------|---------| +| `packages/shared/src/DrainableWorker.ts` | Queue-based Effect worker with deterministic `drain` signal | +| `packages/shared/src/schemaJson.ts` | Two-phase JSON→Schema decode helpers (`decodeJsonResult`, `formatSchemaError`) | +| `apps/server/src/wsServer/pushBus.ts` | `ServerPushBus` — ordered typed push pipeline with auto-incrementing sequence | +| `apps/server/src/wsServer/readiness.ts` | `ServerReadiness` — Deferred-based barriers for startup sequencing | +| `apps/server/src/orchestration/Services/RuntimeReceiptBus.ts` | Receipt schema union: checkpoint captured, diff finalized, turn quiesced | +| `apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts` | PubSub-backed receipt bus implementation | +| `apps/server/src/watchFileWithStatPolling.ts` | Stat-polling file watcher for containers where `fs.watch` is unreliable | +| `apps/server/vitest.config.ts` | Server-specific test config (timeout bumps) | +| `apps/server/src/wsServer/pushBus.test.ts` | Push bus serialization and welcome-gating tests | +| `packages/shared/src/DrainableWorker.test.ts` | Drainable worker enqueue/drain lifecycle tests | + +### Key modifications + +| File | Change | +|------|--------| +| `packages/contracts/src/ws.ts` | Channel-indexed `WsPushPayloadByChannel` map, `WsPush` union schema, `WsPushSequence` | +| `apps/server/src/wsServer.ts` | Integrated `ServerPushBus` and `ServerReadiness`; welcome gated on readiness | +| `apps/server/src/keybindings.ts` | Explicit runtime with `start`/`ready`/`snapshot`; dual `fs.watch` + stat-polling watcher | +| `apps/web/src/wsTransport.ts` | Connection state machine (`connecting`→`open`→`reconnecting`→`closed`→`disposed`); two-phase decode at boundary; cached latest push by channel | +| `apps/web/src/wsNativeApi.ts` | Removed decode logic; delegates to pre-validated transport messages | +| `apps/server/src/orchestration/Layers/CheckpointReactor.ts` | Uses `DrainableWorker`; publishes completion receipts | +| `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts` | Uses `DrainableWorker` for command processing | +| `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` | Uses `DrainableWorker` for event ingestion | +| `apps/server/integration/OrchestrationEngineHarness.integration.ts` | Receipt-based waits replace polling loops | + +## Key Changes +### 1. Strengthen the generic boundaries, not the Codex boundary — DONE +- `ProviderRuntimeEvent` remains the canonical provider event contract; `ProviderService` remains the only cross-provider facade. +- Raw Codex payloads and event ordering stay isolated in `CodexAdapter.ts` and `codexAppServerManager.ts`. +- `ProviderKind` was not expanded. The runtime stays provider-neutral by contract. + +### 2. Replace loose websocket envelopes with channel-indexed typed pushes — DONE +- `packages/contracts/src/ws.ts` now derives push messages from a `WsPushPayloadByChannel` channel-to-schema map. `WsPush` is a union schema replacing `channel: string` + `data: unknown`. +- Every server push carries `sequence: number`, auto-incremented in `ServerPushBus`. +- `packages/shared/src/schemaJson.ts` provides structured decode diagnostics via `formatSchemaError`. +- `packages/contracts/src/ws.test.ts` covers typed push envelope validation and channel/payload mismatch rejection. + +### 3. Introduce explicit server readiness and a single push pipeline — DONE +- `apps/server/src/wsServer/pushBus.ts`: `ServerPushBus` with `publishAll` (broadcast) and `publishClient` (targeted) methods, backed by one ordered path. All pushes flow through it. +- `apps/server/src/wsServer/readiness.ts`: `ServerReadiness` with Deferred-based barriers for HTTP listening, push bus, keybindings, terminal subscriptions, and orchestration subscriptions. +- `server.welcome` is emitted only after connection-scoped and server-scoped readiness is complete. +- `wsServer.ts` no longer publishes directly from ad hoc background streams. + +### 4. Turn background watchers into explicit runtimes — DONE +- `apps/server/src/keybindings.ts` refactored as explicit `KeybindingsShape` service with `start`, `ready`, `snapshot` semantics. +- Initial config load, cache warmup, and dual watcher attachment (`fs.watch` + `watchFileWithStatPolling`) complete before `ready` resolves. +- `watchFileWithStatPolling.ts` is the thin adapter for environments where `fs.watch` is unreliable. + +### 5. Replace polling-based orchestration waiting with receipts — DONE +- `RuntimeReceiptBus` service defines three receipt types: `CheckpointBaselineCapturedReceipt`, `CheckpointDiffFinalizedReceipt` (with `status: "ready"|"missing"|"error"`), and `TurnProcessingQuiescedReceipt`. +- `CheckpointReactor`, `ProviderCommandReactor`, and `ProviderRuntimeIngestion` use `DrainableWorker` and publish receipts on completion. +- Integration harness and checkpoint tests await receipts instead of polling snapshots and git refs. + +### 6. Centralize client transport state and decoding — DONE +- `apps/web/src/wsTransport.ts` implements an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`. +- Two-phase decode (JSON parse → Schema validate) happens at the transport boundary. `wsNativeApi.ts` receives pre-validated messages. +- Cached latest welcome/config modeled as explicit `latestPushByChannel` state. + +### 7. Replace ad hoc test helpers with semantic test clients — MOSTLY DONE +- `DrainableWorker` replaces timing-sensitive `Effect.sleep` with deterministic `drain()` across reactor tests. +- Orchestration harness waits on receipts/barriers instead of `waitForThread`, `waitForGitRef`, and retry loops. +- Behavioral assertions moved to deterministic unit-style harnesses; narrow integration tests kept for real filesystem/socket behavior. +- **Deferred:** Shared `WsTestClient` helper (connect, awaitSemanticWelcome, awaitTypedPush, trackSequence, matchRpcResponseById). Tests use direct transport subscription instead. + +## Provider-Coupling Guardrails +- No generic runtime API may depend on Codex-native event names, thread IDs, or request payload shapes. +- No readiness barrier may be defined as "Codex has emitted X." Readiness is owned by the server runtime, not by provider event order. +- No websocket channel payload may contain raw provider-native payloads unless the channel is explicitly debug/internal. +- Any provider-specific divergence must be exposed through provider capabilities from `ProviderService.getCapabilities()`, not `if provider === "codex"` branches in shared runtime code. +- Generic tests must use canonical `ProviderRuntimeEvent` fixtures. Codex-specific ordering and translation tests stay in adapter/app-server suites only. +- Keep UI/provider-specific knobs such as Codex-only options scoped to provider UX code. Do not pull them into generic transport or orchestration state. + +## Test Plan +- Contracts: + - schema tests for typed push envelopes and structured decode diagnostics + - ordering tests for `sequence` +- Server: + - readiness tests proving `server.welcome` cannot precede runtime readiness + - push bus tests proving terminal/config/orchestration pushes are serialized and typed + - keybindings runtime tests with fake watch source plus one real watcher integration test +- Orchestration: + - receipt tests proving checkpoint refs and projections are complete before completion signals resolve + - replacement of polling-based checkpoint/integration waits with receipt-based waits +- Web: + - transport tests for invalid JSON, invalid envelope, invalid payload, reconnect queue flushing, cached semantic state +- Validation gate: + - `bun run lint` + - `bun run typecheck` + - `mise exec -- bun run test` + - repeated full-suite run after cutover to confirm flake removal + +## Assumptions and Defaults +- This remains a single-provider product during the cutover, but the runtime contracts must stay provider-neutral. +- No backward-compatibility layer is required for old websocket push envelopes. +- The goal is deterministic runtime behavior first; reducing retries and sleeps in tests is a consequence, not the primary mechanism. +- If a completion signal cannot be expressed provider-neutrally, it does not belong in the shared runtime layer and must stay adapter-local. diff --git a/.plans/effect-atom.md b/.plans/effect-atom.md new file mode 100644 index 0000000000..ff6894f563 --- /dev/null +++ b/.plans/effect-atom.md @@ -0,0 +1,89 @@ +# Replace React Query With AtomRpc + Atom State + +## Summary +- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts). +- Keep Zustand for orchestration read model and UI state. +- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs. +- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low. + +## Target Architecture +- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`. +- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`. +- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`. +- Add `platform/desktopBridge.ts` as the only browser/desktop facade. +- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules. + +## Phase 1: Infrastructure First +1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior. +2. Build the AtomRpc client on top of that layer. +3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object. +4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`. +5. Land this as a no-behavior-change PR. + +## Phase 2: Replace `wsNativeApi`-Owned Push State +1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities. +2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`. +3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`. +4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx). +5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms. + +## Phase 3: Replace React Query Domain By Domain +1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first. +2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`. +3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`. +4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior. +5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`. +6. Defer the desktop updater until the last phase. + +## Phase 4: Move Root Invalidation Off `queryClient` +1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers. +2. Keep Zustand orchestration/event application unchanged. +3. Map current effects exactly: +- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}` +- file creation/deletion/restoration touches `project:${cwd}` +- config-affecting server events touch `server-config` + +## Phase 5: Remove Imperative `NativeApi` Usage +1. Create narrow modules instead of a replacement mega-facade: +- `rpc/orchestrationActions.ts` +- `rpc/terminalActions.ts` +- `rpc/gitActions.ts` +- `rpc/projectActions.ts` +- `platform/desktopBridge.ts` +2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers. +3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely. +4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it. + +## Phase 6: Remove React Query Completely +1. Delete `@tanstack/react-query` from `apps/web/package.json`. +2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx). +3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`. +4. Delete the old query-option tests. + +## Public Interfaces And Types +- Preserve the current server-state hook names during the transition. +- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`. +- Do not expose raw AtomRpc clients to components. +- Do not add Suspense as part of this migration. +- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features. + +## Test Plan +- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates. +- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior. +- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`. +- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage. +- Acceptance scenarios: +- welcome still bootstraps snapshot and navigation +- keybindings toast still responds to config stream updates +- git status/branches refresh after checkout/pull/worktree actions +- PR resolve dialog keeps cached result while typing +- `@` path search refreshes after file mutations and orchestration events +- diff panel refreshes when checkpoints arrive +- desktop updater still reflects push events and button actions + +## Assumptions And Defaults +- Zustand stays in scope; only `react-query` is being removed. +- `desktopBridge` remains the only non-RPC boundary. +- The migration lands as 5-6 small PRs, each green independently. +- Invalidations are explicit and scoped; do not recreate a global cache client abstraction. +- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes. diff --git a/.plans/spec-1-1-cutover-plan.md b/.plans/spec-1-1-cutover-plan.md new file mode 100644 index 0000000000..7345995f1e --- /dev/null +++ b/.plans/spec-1-1-cutover-plan.md @@ -0,0 +1,252 @@ +# Spec 1:1 Cutover Plan + +Goal: Align the orchestration model to `SPEC.md` 1:1 and remove legacy persistence/application cruft. + +Execution mode for this plan: + +- Hard cutover only. Existing DB and migration history are disposable. +- Intermediate steps are allowed to break runtime, tests, typecheck, and lint. +- We optimize for small, reviewable work units, not continuous app operability. +- Only the final gate requires everything to run cleanly. + +## 1. Freeze SPEC contract as source of truth + +Work units: + +- Create `.plans/spec-contract-matrix.md` with one row per requirement in `SPEC.md` sections `7.1`-`7.4`. +- Add exact SQL-level requirements per row: table, column, type, nullability, PK/unique, index, and invariants. +- Add app-level requirements per row: writer path, reader path, and owning module. +- Mark each row with status labels: `required`, `implemented`, `to-replace`, `delete`. +- Identify any ambiguous spec lines and record a concrete interpretation in the matrix. + +Deliverables: + +- Complete matrix file with no unclassified rows. +- Single source checklist used by all later steps. + +Breakage allowed: + +- No code changes required yet. + +Exit criteria: + +- Every requirement in `7.1`-`7.4` has exactly one matrix row. + +## 2. Hard cutover migrations (replace current migration set) + +Work units: + +- Delete the current legacy migration files and rewrite migration loader ordering. +- Create `001_orchestration_events.ts` with full envelope columns and required event indexes. +- Create `002_orchestration_command_receipts.ts` with PK + lookup indexes. +- Create `003_checkpoint_diff_blobs.ts` with uniqueness on `(thread_id, from_turn_count, to_turn_count)`. +- Create `004_provider_session_runtime.ts` with PK and runtime lookup indexes. +- Create `005_projections.ts` with all projection tables: + - `projection_projects` + - `projection_threads` + - `projection_thread_messages` + - `projection_thread_activities` + - `projection_thread_sessions` + - `projection_thread_turns` + - `projection_checkpoints` + - `projection_pending_approvals` + - `projection_state` +- Add all required indexes/constraints in `005_projections.ts`. +- Ensure old tables (`projects`, `provider_checkpoints`, `provider_sessions`) are not recreated. + +Deliverables: + +- New 5-file migration chain. +- Updated migration loader references only new migrations. + +Breakage allowed: + +- Repositories/services can be temporarily broken due to removed old tables. + +Exit criteria: + +- Fresh DB initializes with only canonical tables plus migration bookkeeping. + +## 3. Align persistence row/request schemas to DB 1:1 + +Work units: + +- Define row schemas for each canonical table (contracts or persistence layer module). +- Define request schemas for every insert/update/query operation touching canonical tables. +- Remove or deprecate row/request schemas tied to deleted legacy tables. +- Normalize enum and null semantics to match contracts exactly. +- Ensure SQL aliases map 1:1 to schema field names (no implicit shape transforms). + +Deliverables: + +- Canonical row/request schemas committed. +- Zero references to legacy row schemas in active code paths. + +Breakage allowed: + +- Runtime can still fail while query layers are being rewired. + +Exit criteria: + +- Every canonical table used in code has a typed row schema and typed request schema. + +## 4. Rewrite event store for full persisted envelope + +Work units: + +- Refactor append path to write full envelope fields: + - `event_id`, `aggregate_kind`, `stream_id`, `stream_version`, `event_type`, `occurred_at`, `command_id`, `causation_event_id`, `correlation_id`, `actor_kind`, `payload_json`, `metadata_json` +- Implement stream version assignment/checking per aggregate stream. +- Refactor read/replay path to decode payload and metadata from JSON and return `OrchestrationEvent` consistently. +- Remove assumptions from old minimal schema (`aggregate_id`, missing metadata/actor). +- Add explicit SQL ordering guarantees for replay (`ORDER BY sequence ASC`). + +Deliverables: + +- Event store append/replay fully aligned with canonical envelope. + +Breakage allowed: + +- Command dispatch flow can be partially broken until receipts/projectors are updated. + +Exit criteria: + +- Event store no longer depends on legacy event table shape. + +## 5. Add command receipt idempotency + +Work units: + +- Introduce persistence access layer for `orchestration_command_receipts`. +- In command dispatch flow, check existing receipt by `commandId` before append. +- On first execution, persist accepted receipt with `resultSequence`. +- On domain rejection, persist rejected receipt with error payload. +- On duplicate command, return prior result from receipt without re-appending event. +- Ensure receipt write and event append ordering is deterministic. + +Deliverables: + +- Dispatch path with idempotency behavior wired through receipts. + +Breakage allowed: + +- Snapshot/read model may still be inconsistent until projectors are fully wired. + +Exit criteria: + +- Duplicate command IDs no longer create duplicate events. + +## 6. Build DB-backed projection pipeline + +Work units: + +- Create projector runner that consumes events and applies table-specific projections. +- Implement projector handlers for each projection table. +- For each handler, update target row(s) and `projection_state.last_applied_sequence` in the same transaction. +- Define projector names used in `projection_state` and make them stable constants. +- Add replay bootstrap from event store to bring projections up to latest sequence on startup. +- Add safe resume logic from projector `last_applied_sequence`. + +Deliverables: + +- Persistent projector pipeline writing all `projection_*` tables. + +Breakage allowed: + +- Web/API layer may still read old in-memory model until step 7. + +Exit criteria: + +- Events drive projection rows in DB; projection state advances transactionally. + +## 7. Move RPC reads to projections and diff blobs + +Work units: + +- Implement snapshot query service reading only projection tables. +- Build thread hydration from projection rows: messages, activities, checkpoints, session. +- Compute `snapshotSequence` as the minimum required projector sequence from `projection_state`. +- Implement `getTurnDiff` query backed by `checkpoint_diff_blobs` only. +- Remove or bypass in-memory snapshot construction for RPC responses. +- Validate replay handoff contract: snapshot sequence -> replay from `fromSequenceExclusive`. + +Deliverables: + +- `orchestration.getSnapshot` and `orchestration.getTurnDiff` served from DB projections/blob store. + +Breakage allowed: + +- Provider runtime persistence may still be partially legacy until step 8. + +Exit criteria: + +- No orchestration read RPC depends on legacy tables or in-memory-only state. + +## 8. Migrate provider runtime persistence to canonical table + +Work units: + +- Create repository/service for `provider_session_runtime`. +- Update adapter/session manager to persist runtime/resume cursor in new table. +- Ensure domain-visible session state still flows through orchestration events to `projection_thread_sessions`. +- Remove writes to legacy provider session tables. +- Verify restart/resume path reads runtime state from canonical table only. + +Deliverables: + +- Provider runtime state entirely backed by `provider_session_runtime`. + +Breakage allowed: + +- Some legacy interfaces may still exist but should be disconnected. + +Exit criteria: + +- Runtime restore no longer reads/writes legacy provider session persistence. + +## 9. Remove old cruft aggressively + +Work units: + +- Delete legacy repositories/services that map to removed tables. +- Remove dead migration imports and obsolete persistence service interfaces. +- Remove compatibility code paths that translate legacy row shapes. +- Remove unused contracts/types linked to deprecated persistence model. +- Update internal docs/comments to reference canonical projection/event model only. + +Deliverables: + +- Legacy persistence and translation layers removed from active codebase. + +Breakage allowed: + +- Temporary compile failures acceptable while deletion/refactor is in progress. + +Exit criteria: + +- No production code path references deleted legacy tables/services. + +## 10. Final verification gate (first point where green is required) + +Work units: + +- Add migration tests that assert canonical tables, columns, constraints, and indexes. +- Add event store tests for envelope persistence, metadata, actor kind, and replay. +- Add receipt idempotency tests for accept/reject/duplicate paths. +- Add projector tests for transactional row updates + `projection_state` updates. +- Add snapshot tests verifying projection-sourced output and `snapshotSequence` semantics. +- Add turn diff tests verifying `checkpoint_diff_blobs` source of truth. +- Add provider runtime tests for persist + restart + resume behavior. +- Run project lint/typecheck/tests and fix failures. + +Deliverables: + +- Green checks with canonical schema + persistence model in place. + +Breakage allowed: + +- None at end of step. + +Exit criteria: + +- SPEC `7.1`-`7.4` requirements satisfied and validated by tests. diff --git a/.plans/spec-contract-matrix.md b/.plans/spec-contract-matrix.md new file mode 100644 index 0000000000..7cbb9509a6 --- /dev/null +++ b/.plans/spec-contract-matrix.md @@ -0,0 +1,433 @@ +# SPEC Contract Matrix (Sections 7.1-7.4) + +Status legend: + +- `required`: requirement acknowledged, no current implementation claim yet. +- `implemented`: requirement currently satisfied in code + schema. +- `to-replace`: partial/misaligned implementation exists and must be replaced. +- `delete`: current path actively conflicts with SPEC and should be removed. + +## 7.1 Write-Side Persisted Tables + +### W1 + +- Spec ref: `7.1.1 orchestration_events` +- Requirement: append-only event store with canonical envelope columns. +- SQL contract: + - `sequence INTEGER PRIMARY KEY` (global monotonic) + - `event_id TEXT UNIQUE NOT NULL` + - `aggregate_kind TEXT NOT NULL CHECK IN ('project','thread')` + - `stream_id TEXT NOT NULL` + - `stream_version INTEGER NOT NULL` + - `event_type TEXT NOT NULL` + - `occurred_at TEXT NOT NULL` + - `command_id TEXT NULL` + - `causation_event_id TEXT NULL` + - `correlation_id TEXT NULL` + - `actor_kind TEXT NOT NULL CHECK IN ('client','server','provider')` + - `payload_json TEXT NOT NULL` + - `metadata_json TEXT NOT NULL` +- Current writer path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts` +- Current reader path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts` +- Owner module: `apps/server/src/persistence` (event store + migrations) +- Status: `to-replace` +- Notes: current migration/table lacks `stream_id`, `stream_version`, `causation_event_id`, `correlation_id`, `actor_kind`, `metadata_json`. + +### W2 + +- Spec ref: `7.1.2 orchestration_command_receipts` +- Requirement: command idempotency + ack replay receipts table. +- SQL contract: + - `command_id TEXT PRIMARY KEY` + - `aggregate_kind TEXT NOT NULL CHECK IN ('project','thread')` + - `aggregate_id TEXT NOT NULL` + - `accepted_at TEXT NOT NULL` + - `result_sequence INTEGER NOT NULL` + - `status TEXT NOT NULL CHECK IN ('accepted','rejected')` + - `error TEXT NULL` +- Current writer path: none +- Current reader path: none +- Owner module: `apps/server/src/orchestration` dispatch boundary + `apps/server/src/persistence` +- Status: `to-replace` +- Notes: missing table and missing idempotency flow. + +### W3 + +- Spec ref: `7.1.3 checkpoint_diff_blobs` +- Requirement: store large plaintext diffs separate from checkpoint summaries. +- SQL contract: + - `thread_id TEXT NOT NULL` + - `from_turn_count INTEGER NOT NULL` + - `to_turn_count INTEGER NOT NULL` + - `diff TEXT NOT NULL` + - `created_at TEXT NOT NULL` + - `UNIQUE(thread_id, from_turn_count, to_turn_count)` +- Current writer path: none +- Current reader path: none +- Owner module: `apps/server/src/persistence` + turn diff query service +- Status: `to-replace` +- Notes: no canonical diff blob table yet. + +### W4 + +- Spec ref: `7.1.4 provider_session_runtime` +- Requirement: server-internal provider runtime/resume state. +- SQL contract: + - `provider_session_id TEXT PRIMARY KEY` + - `thread_id TEXT NOT NULL` + - `provider_name TEXT NOT NULL` + - `adapter_key TEXT NOT NULL` + - `provider_thread_id TEXT NULL` + - `status TEXT NOT NULL CHECK IN ('starting','running','stopped','error')` + - `last_seen_at TEXT NOT NULL` + - `resume_cursor_json TEXT NULL` + - `runtime_payload_json TEXT NULL` +- Current writer path: legacy provider session persistence (`apps/server/src/persistence/Layers/ProviderSessions.ts`) +- Current reader path: legacy provider session persistence (`apps/server/src/persistence/Layers/ProviderSessions.ts`) +- Owner module: provider runtime manager + persistence runtime repository +- Status: `to-replace` +- Notes: existing `provider_sessions` schema is incompatible and too small. + +## 7.2 Canonical Persisted Event Schema + +### E1 + +- Spec ref: `7.2 OrchestrationPersistedEventSchema` +- Requirement: full typed persisted event envelope in shared contracts. +- SQL contract: envelope fields in W1 must map 1:1 to contracts schema. +- Current writer path: contracts defined in `packages/contracts/src/orchestration.ts` +- Current reader path: used by persistence decode boundaries (partial) +- Owner module: `packages/contracts` +- Status: `implemented` +- Notes: contract schema exists; DB + store mapping still incomplete. + +### E2 + +- Spec ref: `7.2 Rules/payload discriminated by eventType` +- Requirement: `payload` validation keyed by `eventType`. +- SQL contract: `event_type` drives payload decode schema; invalid combinations rejected. +- Current writer path: `packages/contracts/src/orchestration.ts` +- Current reader path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts` decode path +- Owner module: contracts + event store +- Status: `to-replace` +- Notes: decode is present but DB does not persist full envelope columns. + +### E3 + +- Spec ref: `7.2 Rules/provider ids scope` +- Requirement: provider ids live in metadata/provider payload, not as thread identity replacement. +- SQL contract: provider fields persisted inside `metadata_json`; `stream_id` remains project/thread id. +- Current writer path: `apps/server/src/orchestration/decider.ts` (metadata mostly empty) +- Current reader path: projector/event consumers +- Owner module: decider + provider ingestion + event store +- Status: `to-replace` +- Notes: metadata plumbing is incomplete in persistence path. + +### E4 + +- Spec ref: `7.2 Rules/streamVersion concurrency guard` +- Requirement: stream version monotonic per aggregate stream; enforced on write. +- SQL contract: `stream_version INTEGER NOT NULL` + uniqueness/invariant enforcement per stream. +- Current writer path: none +- Current reader path: none +- Owner module: event store append logic + DB constraints +- Status: `to-replace` +- Notes: no stream version assignment/checking today. + +## 7.3 Required Projected Tables (Read Models) + +### P1 + +- Spec ref: `7.3.1 projection_projects` +- Requirement: persisted project projection table. +- SQL contract: + - `project_id TEXT PRIMARY KEY` + - `title TEXT NOT NULL` + - `workspace_root TEXT NOT NULL` + - `default_model TEXT NULL` + - `created_at TEXT NOT NULL` + - `updated_at TEXT NOT NULL` + - `deleted_at TEXT NULL` +- Current writer path: none (in-memory projector only) +- Current reader path: none (snapshot not DB-projected) +- Owner module: projector pipeline + snapshot query +- Status: `to-replace` +- Notes: legacy `projects` table is separate concept and should be removed from orchestration model. + +### P2 + +- Spec ref: `7.3.2 projection_threads` +- Requirement: persisted thread projection table. +- SQL contract: + - `thread_id TEXT PRIMARY KEY` + - `project_id TEXT NOT NULL` + - `title TEXT NOT NULL` + - `model TEXT NOT NULL` + - `branch TEXT NULL` + - `worktree_path TEXT NULL` + - `latest_turn_id TEXT NULL` + - `created_at TEXT NOT NULL` + - `updated_at TEXT NOT NULL` + - `deleted_at TEXT NULL` +- Current writer path: none (in-memory projector only) +- Current reader path: none (snapshot not DB-projected) +- Owner module: projector pipeline + snapshot query +- Status: `to-replace` +- Notes: missing table and projector writes. + +### P3 + +- Spec ref: `7.3.3 projection_thread_messages` +- Requirement: persisted thread message projection table. +- SQL contract: + - `message_id TEXT PRIMARY KEY` + - `thread_id TEXT NOT NULL` + - `turn_id TEXT NULL` + - `role TEXT NOT NULL CHECK IN ('user','assistant','system')` + - `text TEXT NOT NULL` + - `is_streaming INTEGER/BOOLEAN NOT NULL` + - `created_at TEXT NOT NULL` + - `updated_at TEXT NOT NULL` +- Current writer path: none (in-memory projector only) +- Current reader path: none (snapshot not DB-projected) +- Owner module: projector pipeline + snapshot query +- Status: `to-replace` +- Notes: missing table and message projection writes. + +### P4 + +- Spec ref: `7.3.4 projection_thread_activities` +- Requirement: persisted thread activity projection table. +- SQL contract: + - `activity_id TEXT PRIMARY KEY` + - `thread_id TEXT NOT NULL` + - `turn_id TEXT NULL` + - `tone TEXT NOT NULL CHECK IN ('info','tool','approval','error')` + - `kind TEXT NOT NULL` + - `summary TEXT NOT NULL` + - `payload_json TEXT NOT NULL` + - `created_at TEXT NOT NULL` +- Current writer path: none (in-memory projector only) +- Current reader path: none (snapshot not DB-projected) +- Owner module: projector pipeline + snapshot query +- Status: `to-replace` +- Notes: no canonical activity projection persistence. + +### P5 + +- Spec ref: `7.3.5 projection_thread_sessions` +- Requirement: persisted thread session projection table. +- SQL contract: + - `thread_id TEXT PRIMARY KEY` + - `status TEXT NOT NULL CHECK IN ('idle','starting','running','ready','interrupted','stopped','error')` + - `provider_name TEXT NULL` + - `provider_session_id TEXT NULL` + - `provider_thread_id TEXT NULL` + - `active_turn_id TEXT NULL` + - `last_error TEXT NULL` + - `updated_at TEXT NOT NULL` +- Current writer path: none (in-memory projector only) +- Current reader path: none (snapshot not DB-projected) +- Owner module: projector pipeline + snapshot query +- Status: `to-replace` +- Notes: current provider session table is not this domain projection. + +### P6 + +- Spec ref: `7.3.6 projection_thread_turns` +- Requirement: persisted thread turn projection table. +- SQL contract: + - `turn_id TEXT PRIMARY KEY` + - `thread_id TEXT NOT NULL` + - `turn_count INTEGER NOT NULL` + - `status TEXT NOT NULL CHECK IN ('running','completed','interrupted','error')` + - `user_message_id TEXT NULL` + - `assistant_message_id TEXT NULL` + - `started_at TEXT NOT NULL` + - `completed_at TEXT NULL` +- Current writer path: none +- Current reader path: none +- Owner module: projector pipeline + session/turn query helpers +- Status: `to-replace` +- Notes: missing table and projection logic. + +### P7 + +- Spec ref: `7.3.7 projection_checkpoints` +- Requirement: persisted checkpoint summary projection table. +- SQL contract: + - `thread_id TEXT NOT NULL` + - `turn_id TEXT NOT NULL` + - `checkpoint_turn_count INTEGER NOT NULL` + - `checkpoint_ref TEXT NOT NULL` + - `status TEXT NOT NULL CHECK IN ('ready','missing','error')` + - `files_json TEXT NOT NULL` + - `assistant_message_id TEXT NULL` + - `completed_at TEXT NOT NULL` + - `UNIQUE(thread_id, checkpoint_turn_count)` +- Current writer path: legacy `provider_checkpoints` writes in `apps/server/src/persistence/Layers/Checkpoints.ts` +- Current reader path: legacy checkpoint repository +- Owner module: projector pipeline + checkpoint query layer +- Status: `to-replace` +- Notes: current table semantics do not match canonical checkpoint projection schema. + +### P8 + +- Spec ref: `7.3.8 projection_pending_approvals` +- Requirement: persisted pending-approval projection table. +- SQL contract: + - `request_id TEXT PRIMARY KEY` + - `thread_id TEXT NOT NULL` + - `turn_id TEXT NULL` + - `status TEXT NOT NULL CHECK IN ('pending','resolved')` + - `decision TEXT NULL CHECK IN ('accept','acceptForSession','decline','cancel')` + - `created_at TEXT NOT NULL` + - `resolved_at TEXT NULL` +- Current writer path: none +- Current reader path: none +- Owner module: projector pipeline + approval query layer +- Status: `to-replace` +- Notes: missing table and projection logic. + +### P9 + +- Spec ref: `7.3.9 projection_state` +- Requirement: projector progress tracking table. +- SQL contract: + - `projector TEXT PRIMARY KEY` + - `last_applied_sequence INTEGER NOT NULL` + - `updated_at TEXT NOT NULL` +- Current writer path: none +- Current reader path: none +- Owner module: projector runner/checkpointing +- Status: `to-replace` +- Notes: missing table and projector bookkeeping. + +### P10 + +- Spec ref: `7.3 Projection consistency rules` +- Requirement: projector row updates and `projection_state` update must be atomic per event. +- SQL contract: per-projector transaction boundary covering both projection write and state update. +- Current writer path: none (in-memory projector has no SQL transaction) +- Current reader path: none +- Owner module: projector runner +- Status: `to-replace` +- Notes: requires transactional projection executor. + +### P11 + +- Spec ref: `7.3 Optional debug field` +- Requirement: `lastEventSequence` on projection rows is optional and not required for correctness. +- SQL contract: optional; not required in baseline schema. +- Current writer path: none +- Current reader path: none +- Owner module: projector runner +- Status: `required` +- Notes: interpretation: exclude from first cutover unless debugging requires it. + +## 7.4 Snapshot and RPC Requirements + +### R1 + +- Spec ref: `7.4.1` +- Requirement: `orchestration.getSnapshot` fully served from projection tables and returns `snapshotSequence`. +- SQL contract: snapshot query joins/reads only `projection_*` + `projection_state`. +- Current writer path: in-memory model built in `apps/server/src/orchestration/projector.ts` +- Current reader path: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts#getReadModel` +- Owner module: snapshot query service + ws RPC handler +- Status: `delete` +- Notes: current in-memory read model path must be removed for SPEC compliance. + +### R2 + +- Spec ref: `7.4.2` +- Requirement: snapshot `projects[]` source is `projection_projects`. +- SQL contract: `projects` collection assembled from `projection_projects` rows. +- Current writer path: none +- Current reader path: in-memory thread/project arrays +- Owner module: snapshot query service +- Status: `to-replace` +- Notes: no DB project projection reader exists yet. + +### R3 + +- Spec ref: `7.4.3` +- Requirement: thread snapshot `checkpoints[]` source is `projection_checkpoints` with required fields. +- SQL contract: fields `turnId`, `completedAt`, `status`, `files[]`, `checkpointRef`, optional `assistantMessageId`, `checkpointTurnCount`. +- Current writer path: legacy checkpoint repo data model +- Current reader path: in-memory checkpoints from orchestration events +- Owner module: snapshot query service + checkpoint projector +- Status: `to-replace` +- Notes: canonical projection table and reader not implemented. + +### R4 + +- Spec ref: `7.4.4` +- Requirement: no `listCheckpoints` orchestration RPC; list in snapshot + full diff via `getTurnDiff` from diff blobs. +- SQL contract: `getTurnDiff` reads `checkpoint_diff_blobs` only. +- Current writer path: none for diff blobs +- Current reader path: `orchestration.getTurnDiff` schema exists, data backing incomplete +- Owner module: ws RPC handler + diff query service +- Status: `to-replace` +- Notes: current checkpoint repository is not canonical source. + +### R5 + +- Spec ref: `7.4.5` +- Requirement: client acts on `ThreadId`; server resolves provider session via `projection_thread_sessions`. +- SQL contract: session lookup by `thread_id` from projection table. +- Current writer path: mixed provider/session handling paths +- Current reader path: legacy provider session persistence lookups +- Owner module: provider dispatch/session resolution +- Status: `to-replace` +- Notes: remove provider-session-as-routing-key behavior. + +### R6 + +- Spec ref: `7.4.6` +- Requirement: `snapshotSequence` derived from `projection_state` minimum over dependent projectors. +- SQL contract: `MIN(last_applied_sequence)` across required projector keys. +- Current writer path: none +- Current reader path: currently from in-memory event projection sequence +- Owner module: snapshot query service +- Status: `to-replace` +- Notes: must move from in-memory sequence to DB projection-state semantics. + +### R7 + +- Spec ref: `7.4.7` +- Requirement: snapshot/replay handoff has no gap (`getSnapshot` -> subscribe from snapshot sequence). +- SQL contract: read consistency strategy guaranteeing no missing events between snapshot visibility and replay start. +- Current writer path: event stream via `OrchestrationEventStore.readFromSequence` +- Current reader path: ws replay flow in `apps/server/src/wsServer.ts` +- Owner module: ws RPC + event stream handoff layer +- Status: `to-replace` +- Notes: interpretation requires explicit consistency boundary (transaction, sequence fence, or equivalent). + +## Ambiguous/Interpretation Decisions (tracked upfront) + +### A1 + +- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming. +- Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code. + +### A2 + +- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload. +- Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries. + +### A3 + +- Topic: `snapshotSequence` dependency set for min-sequence computation. +- Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`). + +### A4 + +- Topic: no-gap handoff mechanism in `7.4.7`. +- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`. + +## Checklist Completeness Statement + +- Coverage scope: `SPEC.md` sections `7.1`, `7.2`, `7.3`, `7.4`. +- Requirement rows present: `W1-W4`, `E1-E4`, `P1-P11`, `R1-R7`. +- Unclassified rows: `0`. diff --git a/.vscode/settings.json b/.vscode/settings.json index 554e703ccb..752d9a9071 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,5 +4,6 @@ "editor.codeActionsOnSave": { "source.fixAll.oxc": "always" }, - "oxc.unusedDisableDirectives": "warn" + "oxc.unusedDisableDirectives": "warn", + "typescript.tsdk": "node_modules/typescript/lib" } diff --git a/AGENTS.md b/AGENTS.md index affea58d01..cea5090cce 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,8 +1,13 @@ -# CLAUDE.md +# AGENTS.md + +## Task Completion Requirements + +- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed. +- NEVER run `bun test`. Always use `bun run test` (runs Vitest). ## Project Snapshot -T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon). +T3 Code is a minimal web GUI for using coding agents like Codex and Claude. This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged. @@ -14,11 +19,16 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon If a tradeoff is required, choose correctness and robustness over short-term convenience. +## Maintainability + +Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem. + ## Package Roles - `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions. - `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket. -- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. +- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic. +- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index. ## Codex App Server (Important) @@ -29,7 +39,7 @@ How we use it in this codebase: - Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`. - Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`. - WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`. -- Web app consumes provider event streams via WebSocket push on channel `providers.event`. +- Web app consumes orchestration domain events via WebSocket push on channel `orchestration.domainEvent` (provider runtime activity is projected into orchestration events server-side). Docs: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..8b734a99bb --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,65 @@ +# Contributing + +## Read This First + +We are not actively accepting contributions right now. + +You can still open an issue or PR, but please do so knowing there is a high chance we close it, defer it forever, or never look at it. + +If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control. + +PRs are automatically labeled with a `vouch:*` trust status and a `size:*` diff size based on changed lines. + +If you are an external contributor, expect `vouch:unvouched` until we explicitly add you to [.github/VOUCHED.td](.github/VOUCHED.td). + +## What We Are Most Likely To Accept + +Small, focused bug fixes. + +Small reliability fixes. + +Small performance improvements. + +Tightly scoped maintenance work that clearly improves the project without changing its direction. + +## What We Are Least Likely To Accept + +Large PRs. + +Drive-by feature work. + +Opinionated rewrites. + +Anything that expands product scope without us asking for it first. + +If you open a 1,000+ line PR full of new features, we will probably close it quickly and remember that you ignored the clearly written instructions. + +## If You Still Want To Open A PR + +Keep it small. + +Explain exactly what changed. + +Explain exactly why the change should exist. + +Do not mix unrelated fixes together. + +If the PR makes anything resembling a UI change, include clear before/after images. + +If the change depends on motion, timing, transitions, or interaction details, include a short video. + +If we have to guess what changed, we are much less likely to review it. + +## Issues First + +If you are thinking about a non-trivial change, open an issue first. + +That still does not mean we will want the PR, but it gives you a chance to avoid wasting your time. + +## Be Realistic + +Opening a PR does not create an obligation on our side. + +We may close it. We may ignore it. We may ask you to shrink it. We may reimplement the idea ourselves later. + +If you are fine with that, proceed. diff --git a/KEYBINDINGS.md b/KEYBINDINGS.md index a44f1f5f4f..0c00fed4e7 100644 --- a/KEYBINDINGS.md +++ b/KEYBINDINGS.md @@ -51,8 +51,9 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged - `terminal.new`: create new terminal (in focused terminal context by default) - `terminal.close`: close/kill the focused terminal (in focused terminal context by default) - `chat.new`: create a new chat thread preserving the active thread's branch/worktree state -- `chat.newLocal`: create a new local chat thread for the active project (no worktree context) +- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`)) - `editor.openFavorite`: open current project/worktree in the last-used editor +- `script.{id}.run`: run a project script by id (for example `script.test.run`) ### Key Syntax diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..55ee675bb1 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md index ac73a42708..d3a54a1b90 100644 --- a/README.md +++ b/README.md @@ -1,107 +1,54 @@ # T3 Code -T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon. +T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more 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. +## Installation -## Architecture +> [!WARNING] +> T3 Code currently supports Codex and Claude. +> Install and authenticate at least one provider before use: +> +> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login` +> - Claude: install Claude Code and run `claude auth login` -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 +### Run without installing ```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 - -# Or from any project directory after publishing: npx t3 ``` -## Scripts +### Desktop app -- `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. -- `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. +Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry: -### Running multiple dev instances +#### Windows (`winget`) -Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together. +```bash +winget install T3Tools.T3Code +``` -- Default ports: server `3773`, web `5173` -- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`) -- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop` +#### macOS (Homebrew) -If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset. +```bash +brew install --cask t3-code +``` -## Runtime modes +#### Arch Linux (AUR) -T3 Code has a global runtime mode switch in the chat toolbar: +```bash +yay -S t3code-bin +``` -- **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. +## Some notes -## Provider architecture +We are very very early in this project. Expect bugs. -The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol: +We are not accepting contributions yet. -- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }` -- **Push events**: `{ type: "push", channel, data }` for streaming provider events +Observability guide: [docs/observability.md](./docs/observability.md) -Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`: +## If you REALLY want to contribute still.... read this first -- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn` -- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions` -- `shell.openInEditor`, `server.getConfig` +Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR. -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`. +Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv). diff --git a/REMOTE.md b/REMOTE.md new file mode 100644 index 0000000000..9dc15ed1fe --- /dev/null +++ b/REMOTE.md @@ -0,0 +1,68 @@ +# Remote Access Setup + +Use this when you want to open T3 Code from another device (phone, tablet, another laptop). + +## CLI ↔ Env option map + +The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables: + +| CLI flag | Env var | Notes | +| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ | +| `--mode ` | `T3CODE_MODE` | Runtime mode. | +| `--port ` | `T3CODE_PORT` | HTTP/WebSocket port. | +| `--host
` | `T3CODE_HOST` | Bind interface/address. | +| `--base-dir ` | `T3CODE_HOME` | Base directory. | +| `--dev-url ` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. | +| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. | +| `--auth-token ` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. | +| `--bootstrap-fd ` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. | + +> TIP: Use the `--help` flag to see all available options and their descriptions. + +## Security First + +- Always set `--auth-token` before exposing the server outside localhost. + - When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd `. + With `--bootstrap-fd `, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments. +- Treat the token like a password. +- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed. + +## 1) Build + run server for remote access + +Remote access should use the built web app (not local Vite redirect mode). + +```bash +bun run build +TOKEN="$(openssl rand -hex 24)" +bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser +``` + +Then open on your phone: + +`http://:3773` + +Example: + +`http://192.168.1.42:3773` + +Notes: + +- `--host 0.0.0.0` listens on all IPv4 interfaces. +- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions. +- Ensure your OS firewall allows inbound TCP on the selected port. + +## 2) Tailnet / Tailscale access + +If you use Tailscale, you can bind directly to your Tailnet address. + +```bash +TAILNET_IP="$(tailscale ip -4)" +TOKEN="$(openssl rand -hex 24)" +bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser +``` + +Open from any device in your tailnet: + +`http://:3773` + +You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure. diff --git a/TODO.md b/TODO.md index e6ff5a6b7e..3d856996d8 100644 --- a/TODO.md +++ b/TODO.md @@ -2,22 +2,12 @@ ## Small things -- [ ] 1 click copy in codeblocks -- [x] Pasting/adding images to submit with prompts +- [ ] Submitting new messages should scroll to bottom - [ ] 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) -- [ ] Insta focus input on new thread creation -- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it -- [x] Making new thread should auto-focus input box -- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank) ## Bigger things - [ ] Queueing messages -- [ ] External runners (i.e. running the cli on a mac mini) diff --git a/apps/desktop/.gitignore b/apps/desktop/.gitignore index acb4535b60..45b848af65 100644 --- a/apps/desktop/.gitignore +++ b/apps/desktop/.gitignore @@ -1 +1,2 @@ dist-electron/ +.electron-runtime/ diff --git a/apps/desktop/package.json b/apps/desktop/package.json index d6afd21ce9..dfa3bde2f8 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.0.0", + "version": "0.0.15", "private": true, "main": "dist-electron/main.js", "scripts": { @@ -8,20 +8,23 @@ "dev:bundle": "tsdown --watch", "dev:electron": "bun run scripts/dev-electron.mjs", "build": "tsdown", - "start": "electron dist-electron/main.js", + "start": "bun run scripts/start-electron.mjs", "typecheck": "tsc --noEmit", "test": "vitest run --passWithNoTests", "smoke-test": "node scripts/smoke-test.mjs" }, "dependencies": { - "electron": "33.4.11" + "effect": "catalog:", + "electron": "40.6.0", + "electron-updater": "^6.6.2" }, "devDependencies": { - "@types/node": "^22.10.2", - "electronmon": "^2.0.2", - "tsdown": "^0.20.3", - "typescript": "^5.7.3", - "vitest": "^4.0.0", - "wait-on": "^8.0.2" - } + "@t3tools/contracts": "workspace:*", + "@t3tools/shared": "workspace:*", + "@types/node": "catalog:", + "tsdown": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:" + }, + "productName": "T3 Code (Alpha)" } diff --git a/apps/desktop/resources/icon.icns b/apps/desktop/resources/icon.icns new file mode 100644 index 0000000000..da16d12a0c Binary files /dev/null and b/apps/desktop/resources/icon.icns differ diff --git a/apps/desktop/resources/icon.ico b/apps/desktop/resources/icon.ico new file mode 100644 index 0000000000..8298f70d8b Binary files /dev/null and b/apps/desktop/resources/icon.ico differ diff --git a/apps/desktop/resources/icon.png b/apps/desktop/resources/icon.png new file mode 100644 index 0000000000..37f3f756a5 Binary files /dev/null and b/apps/desktop/resources/icon.png differ diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs index be7d8380fb..5244d51dbf 100644 --- a/apps/desktop/scripts/dev-electron.mjs +++ b/apps/desktop/scripts/dev-electron.mjs @@ -1,31 +1,218 @@ -import { spawn } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; +import { watch } from "node:fs"; +import { join } from "node:path"; -import waitOn from "wait-on"; +import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs"; +import { waitForResources } from "./wait-for-resources.mjs"; -const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173); +const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733); const devServerUrl = `http://localhost:${port}`; +const requiredFiles = [ + "dist-electron/main.js", + "dist-electron/preload.js", + "../server/dist/bin.mjs", +]; +const watchedDirectories = [ + { directory: "dist-electron", files: new Set(["main.js", "preload.js"]) }, + { directory: "../server/dist", files: new Set(["bin.mjs"]) }, +]; +const forcedShutdownTimeoutMs = 1_500; +const restartDebounceMs = 120; +const childTreeGracePeriodMs = 1_200; -await waitOn({ - resources: [ - `tcp:${port}`, - "file:dist-electron/main.js", - "file:dist-electron/preload.js", - "file:../server/dist/index.mjs", - ], +await waitForResources({ + baseDir: desktopDir, + files: requiredFiles, + tcpPort: port, }); -const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon"; const childEnv = { ...process.env }; delete childEnv.ELECTRON_RUN_AS_NODE; -const child = spawn(command, ["dist-electron/main.js"], { - stdio: "inherit", - env: { - ...childEnv, - VITE_DEV_SERVER_URL: devServerUrl, - }, -}); +let shuttingDown = false; +let restartTimer = null; +let currentApp = null; +let restartQueue = Promise.resolve(); +const expectedExits = new WeakSet(); +const watchers = []; -child.on("exit", (code) => { - process.exit(code ?? 0); +function killChildTreeByPid(pid, signal) { + if (process.platform === "win32" || typeof pid !== "number") { + return; + } + + spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" }); +} + +function cleanupStaleDevApps() { + if (process.platform === "win32") { + return; + } + + spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" }); +} + +function startApp() { + if (shuttingDown || currentApp !== null) { + return; + } + + const app = spawn( + resolveElectronPath(), + [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"], + { + cwd: desktopDir, + env: { + ...childEnv, + VITE_DEV_SERVER_URL: devServerUrl, + }, + stdio: "inherit", + }, + ); + + currentApp = app; + + app.once("error", () => { + if (currentApp === app) { + currentApp = null; + } + + if (!shuttingDown) { + scheduleRestart(); + } + }); + + app.once("exit", (code, signal) => { + if (currentApp === app) { + currentApp = null; + } + + const exitedAbnormally = signal !== null || code !== 0; + if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) { + scheduleRestart(); + } + }); +} + +async function stopApp() { + const app = currentApp; + if (!app) { + return; + } + + currentApp = null; + expectedExits.add(app); + + await new Promise((resolve) => { + let settled = false; + + const finish = () => { + if (settled) { + return; + } + + settled = true; + resolve(); + }; + + app.once("exit", finish); + app.kill("SIGTERM"); + killChildTreeByPid(app.pid, "TERM"); + + setTimeout(() => { + if (settled) { + return; + } + + app.kill("SIGKILL"); + killChildTreeByPid(app.pid, "KILL"); + finish(); + }, forcedShutdownTimeoutMs).unref(); + }); +} + +function scheduleRestart() { + if (shuttingDown) { + return; + } + + if (restartTimer) { + clearTimeout(restartTimer); + } + + restartTimer = setTimeout(() => { + restartTimer = null; + restartQueue = restartQueue + .catch(() => undefined) + .then(async () => { + await stopApp(); + if (!shuttingDown) { + startApp(); + } + }); + }, restartDebounceMs); +} + +function startWatchers() { + for (const { directory, files } of watchedDirectories) { + const watcher = watch( + join(desktopDir, directory), + { persistent: true }, + (_eventType, filename) => { + if (typeof filename !== "string" || !files.has(filename)) { + return; + } + + scheduleRestart(); + }, + ); + + watchers.push(watcher); + } +} + +function killChildTree(signal) { + if (process.platform === "win32") { + return; + } + + // Kill direct children as a final fallback in case normal shutdown leaves stragglers. + spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" }); +} + +async function shutdown(exitCode) { + if (shuttingDown) return; + shuttingDown = true; + + if (restartTimer) { + clearTimeout(restartTimer); + restartTimer = null; + } + + for (const watcher of watchers) { + watcher.close(); + } + + await stopApp(); + killChildTree("TERM"); + await new Promise((resolve) => { + setTimeout(resolve, childTreeGracePeriodMs); + }); + killChildTree("KILL"); + + process.exit(exitCode); +} + +startWatchers(); +cleanupStaleDevApps(); +startApp(); + +process.once("SIGINT", () => { + void shutdown(130); +}); +process.once("SIGTERM", () => { + void shutdown(143); +}); +process.once("SIGHUP", () => { + void shutdown(129); }); diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjs new file mode 100644 index 0000000000..9d7c522781 --- /dev/null +++ b/apps/desktop/scripts/electron-launcher.mjs @@ -0,0 +1,144 @@ +// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron" + +import { spawnSync } from "node:child_process"; +import { + copyFileSync, + cpSync, + existsSync, + mkdirSync, + readFileSync, + readdirSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL); +const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; +const APP_BUNDLE_ID = "com.t3tools.t3code"; +const LAUNCHER_VERSION = 1; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +export const desktopDir = resolve(__dirname, ".."); + +function setPlistString(plistPath, key, value) { + const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], { + encoding: "utf8", + }); + if (replaceResult.status === 0) { + return; + } + + const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], { + encoding: "utf8", + }); + if (insertResult.status === 0) { + return; + } + + const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n"); + throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim()); +} + +function patchMainBundleInfoPlist(appBundlePath, iconPath) { + const infoPlistPath = join(appBundlePath, "Contents", "Info.plist"); + setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME); + setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME); + setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID); + setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns"); + + const resourcesDir = join(appBundlePath, "Contents", "Resources"); + copyFileSync(iconPath, join(resourcesDir, "icon.icns")); + copyFileSync(iconPath, join(resourcesDir, "electron.icns")); +} + +function patchHelperBundleInfoPlists(appBundlePath) { + const frameworksDir = join(appBundlePath, "Contents", "Frameworks"); + if (!existsSync(frameworksDir)) { + return; + } + + for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) { + if (!entry.isDirectory() || !entry.name.endsWith(".app")) { + continue; + } + if (!entry.name.startsWith("Electron Helper")) { + continue; + } + + const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist"); + if (!existsSync(helperPlistPath)) { + continue; + } + + const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim(); + const helperName = suffix + ? `${APP_DISPLAY_NAME} Helper ${suffix}` + : `${APP_DISPLAY_NAME} Helper`; + const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-"); + const helperBundleId = helperIdSuffix + ? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}` + : `${APP_BUNDLE_ID}.helper`; + + setPlistString(helperPlistPath, "CFBundleDisplayName", helperName); + setPlistString(helperPlistPath, "CFBundleName", helperName); + setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId); + } +} + +function readJson(path) { + try { + return JSON.parse(readFileSync(path, "utf8")); + } catch { + return null; + } +} + +function buildMacLauncher(electronBinaryPath) { + const sourceAppBundlePath = resolve(electronBinaryPath, "../../.."); + const runtimeDir = join(desktopDir, ".electron-runtime"); + const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`); + const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron"); + const iconPath = join(desktopDir, "resources", "icon.icns"); + const metadataPath = join(runtimeDir, "metadata.json"); + + mkdirSync(runtimeDir, { recursive: true }); + + const expectedMetadata = { + launcherVersion: LAUNCHER_VERSION, + sourceAppBundlePath, + sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs, + iconMtimeMs: statSync(iconPath).mtimeMs, + }; + + const currentMetadata = readJson(metadataPath); + if ( + existsSync(targetBinaryPath) && + currentMetadata && + JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata) + ) { + return targetBinaryPath; + } + + rmSync(targetAppBundlePath, { recursive: true, force: true }); + cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true }); + patchMainBundleInfoPlist(targetAppBundlePath, iconPath); + patchHelperBundleInfoPlists(targetAppBundlePath); + writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`); + + return targetBinaryPath; +} + +export function resolveElectronPath() { + const require = createRequire(import.meta.url); + const electronBinaryPath = require("electron"); + + if (process.platform !== "darwin") { + return electronBinaryPath; + } + + return buildMacLauncher(electronBinaryPath); +} diff --git a/apps/desktop/scripts/start-electron.mjs b/apps/desktop/scripts/start-electron.mjs new file mode 100644 index 0000000000..bf93adb6b0 --- /dev/null +++ b/apps/desktop/scripts/start-electron.mjs @@ -0,0 +1,20 @@ +import { spawn } from "node:child_process"; + +import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs"; + +const childEnv = { ...process.env }; +delete childEnv.ELECTRON_RUN_AS_NODE; + +const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], { + stdio: "inherit", + cwd: desktopDir, + env: childEnv, +}); + +child.on("exit", (code, signal) => { + if (signal) { + process.kill(process.pid, signal); + return; + } + process.exit(code ?? 0); +}); diff --git a/apps/desktop/scripts/wait-for-resources.mjs b/apps/desktop/scripts/wait-for-resources.mjs new file mode 100644 index 0000000000..2b0a60c5d9 --- /dev/null +++ b/apps/desktop/scripts/wait-for-resources.mjs @@ -0,0 +1,119 @@ +import * as FileSystem from "node:fs/promises"; +import * as Net from "node:net"; +import * as Path from "node:path"; +import * as Timers from "node:timers/promises"; + +const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"]; + +async function fileExists(filePath) { + try { + await FileSystem.access(filePath); + return true; + } catch { + return false; + } +} + +function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) { + return new Promise((resolveReady) => { + const socket = Net.createConnection({ host, port }); + let settled = false; + + const finish = (ready) => { + if (settled) { + return; + } + + settled = true; + socket.removeAllListeners(); + socket.destroy(); + resolveReady(ready); + }; + + socket.once("connect", () => { + finish(true); + }); + socket.once("timeout", () => { + finish(false); + }); + socket.once("error", () => { + finish(false); + }); + socket.setTimeout(connectTimeoutMs); + }); +} + +async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) { + const pendingFiles = []; + + for (const relativeFilePath of files) { + const ready = await fileExists(Path.resolve(baseDir, relativeFilePath)); + if (!ready) { + pendingFiles.push(relativeFilePath); + } + } + + let tcpReady = false; + for (const host of tcpHosts) { + tcpReady = await tcpPortIsReady({ + host, + port: tcpPort, + connectTimeoutMs, + }); + if (tcpReady) { + break; + } + } + + return { + pendingFiles, + tcpReady, + }; +} + +export async function waitForResources({ + baseDir, + files = [], + intervalMs = 100, + timeoutMs = 120_000, + tcpHost, + tcpPort, + connectTimeoutMs = 500, +}) { + if (!Number.isInteger(tcpPort) || tcpPort <= 0) { + throw new TypeError("waitForResources requires a positive integer tcpPort"); + } + + const startedAt = Date.now(); + const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts; + + while (true) { + const { pendingFiles, tcpReady } = await resolvePendingResources({ + baseDir, + files, + tcpPort, + tcpHosts, + connectTimeoutMs, + }); + + if (pendingFiles.length === 0 && tcpReady) { + return; + } + + if (Date.now() - startedAt >= timeoutMs) { + const pendingResources = []; + if (!tcpReady) { + pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`); + } + for (const filePath of pendingFiles) { + pendingResources.push(`file:${filePath}`); + } + + throw new Error( + `Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`, + ); + } + + await Timers.setTimeout(intervalMs); + } +} diff --git a/apps/desktop/src/confirmDialog.ts b/apps/desktop/src/confirmDialog.ts index 1beda8543b..c941d09065 100644 --- a/apps/desktop/src/confirmDialog.ts +++ b/apps/desktop/src/confirmDialog.ts @@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog( const options = { type: "question" as const, buttons: ["No", "Yes"], - defaultId: CONFIRM_BUTTON_INDEX, + defaultId: 0, cancelId: 0, noLink: true, message: normalizedMessage, diff --git a/apps/desktop/src/fixPath.ts b/apps/desktop/src/fixPath.ts deleted file mode 100644 index 5f708e3c83..0000000000 --- a/apps/desktop/src/fixPath.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { execFileSync } from "node:child_process"; - -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, - }); - if (result) { - process.env.PATH = result; - } - } catch { - // Keep inherited PATH if shell lookup fails. - } -} diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index a1f7a9bf21..3d61571df9 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -1,65 +1,996 @@ -import { spawn, type ChildProcess } from "node:child_process"; -import { randomBytes } from "node:crypto"; -import fs from "node:fs"; -import net from "node:net"; -import os from "node:os"; -import path from "node:path"; +import * as ChildProcess from "node:child_process"; +import * as Crypto from "node:crypto"; +import * as FS from "node:fs"; +import * as OS from "node:os"; +import * as Path from "node:path"; -import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron"; +import { + app, + BrowserWindow, + dialog, + ipcMain, + Menu, + nativeImage, + nativeTheme, + protocol, + shell, +} from "electron"; +import type { MenuItemConstructorOptions } from "electron"; +import * as Effect from "effect/Effect"; +import type { + DesktopTheme, + DesktopUpdateActionResult, + DesktopUpdateCheckResult, + DesktopUpdateState, +} from "@t3tools/contracts"; +import { autoUpdater } from "electron-updater"; +import type { ContextMenuItem } from "@t3tools/contracts"; +import { NetService } from "@t3tools/shared/Net"; +import { RotatingFileSink } from "@t3tools/shared/logging"; +import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; import { showDesktopConfirmDialog } from "./confirmDialog"; -import { fixPath } from "./fixPath"; +import { syncShellEnvironment } from "./syncShellEnvironment"; +import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState"; +import { + createInitialDesktopUpdateState, + reduceDesktopUpdateStateOnCheckFailure, + reduceDesktopUpdateStateOnCheckStart, + reduceDesktopUpdateStateOnDownloadComplete, + reduceDesktopUpdateStateOnDownloadFailure, + reduceDesktopUpdateStateOnDownloadProgress, + reduceDesktopUpdateStateOnDownloadStart, + reduceDesktopUpdateStateOnInstallFailure, + reduceDesktopUpdateStateOnNoUpdate, + reduceDesktopUpdateStateOnUpdateAvailable, +} from "./updateMachine"; +import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch"; -fixPath(); +syncShellEnvironment(); const PICK_FOLDER_CHANNEL = "desktop:pick-folder"; const CONFIRM_CHANNEL = "desktop:confirm"; +const SET_THEME_CHANNEL = "desktop:set-theme"; const CONTEXT_MENU_CHANNEL = "desktop:context-menu"; const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; -const ROOT_DIR = path.resolve(__dirname, "../../.."); -const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs"); -const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html"); -const STATE_DIR = path.join(os.homedir(), ".t3", "userdata"); +const MENU_ACTION_CHANNEL = "desktop:menu-action"; +const UPDATE_STATE_CHANNEL = "desktop:update-state"; +const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; +const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download"; +const UPDATE_INSTALL_CHANNEL = "desktop:update-install"; +const UPDATE_CHECK_CHANNEL = "desktop:update-check"; +const GET_WS_URL_CHANNEL = "desktop:get-ws-url"; +const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3"); +const STATE_DIR = Path.join(BASE_DIR, "userdata"); +const DESKTOP_SCHEME = "t3"; +const ROOT_DIR = Path.resolve(__dirname, "../../.."); const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL); +const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; +const APP_USER_MODEL_ID = "com.t3tools.t3code"; +const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop"; +const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code"; +const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code"; +const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; +const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i; +const COMMIT_HASH_DISPLAY_LENGTH = 12; +const LOG_DIR = Path.join(STATE_DIR, "logs"); +const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024; +const LOG_FILE_MAX_FILES = 10; +const APP_RUN_ID = Crypto.randomBytes(6).toString("hex"); +const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json"); +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"]; +type LinuxDesktopNamedApp = Electron.App & { + setDesktopName?: (desktopName: string) => void; +}; let mainWindow: BrowserWindow | null = null; -let backendProcess: ChildProcess | null = null; +let backendProcess: ChildProcess.ChildProcess | null = null; let backendPort = 0; let backendAuthToken = ""; let backendWsUrl = ""; let restartAttempt = 0; let restartTimer: ReturnType | null = null; let isQuitting = false; +let desktopProtocolRegistered = false; +let aboutCommitHashCache: string | null | undefined; +let desktopLogSink: RotatingFileSink | null = null; +let backendLogSink: RotatingFileSink | null = null; +let restoreStdIoCapture: (() => void) | null = null; +let backendObservabilitySettings = readPersistedBackendObservabilitySettings(); -async function reserveLoopbackPort(): Promise { - return new Promise((resolve, reject) => { - const probe = net.createServer(); - probe.listen(0, "127.0.0.1", () => { - const address = probe.address(); - const port = typeof address === "object" && address !== null ? address.port : 0; - probe.close(() => { - if (port > 0) { - resolve(port); - return; - } - reject(new Error("Failed to reserve backend port")); - }); - }); - probe.on("error", reject); - }); +let destructiveMenuIconCache: Electron.NativeImage | null | undefined; +const expectedBackendExitChildren = new WeakSet(); +const desktopRuntimeInfo = resolveDesktopRuntimeInfo({ + platform: process.platform, + processArch: process.arch, + runningUnderArm64Translation: app.runningUnderARM64Translation === true, +}); +const initialUpdateState = (): DesktopUpdateState => + createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo); + +function logTimestamp(): string { + return new Date().toISOString(); } -function backendEnv(): NodeJS.ProcessEnv { - return { - ...process.env, - T3CODE_MODE: "desktop", - T3CODE_NO_BROWSER: "1", - T3CODE_PORT: String(backendPort), - T3CODE_STATE_DIR: STATE_DIR, - T3CODE_AUTH_TOKEN: backendAuthToken, +function logScope(scope: string): string { + return `${scope} run=${APP_RUN_ID}`; +} + +function sanitizeLogValue(value: string): string { + return value.replace(/\s+/g, " ").trim(); +} + +function readPersistedBackendObservabilitySettings(): { + readonly otlpTracesUrl: string | undefined; + readonly otlpMetricsUrl: string | undefined; +} { + try { + if (!FS.existsSync(SERVER_SETTINGS_PATH)) { + return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined }; + } + return parsePersistedServerObservabilitySettings(FS.readFileSync(SERVER_SETTINGS_PATH, "utf8")); + } catch (error) { + console.warn("[desktop] failed to read persisted backend observability settings", error); + return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined }; + } +} + +function backendChildEnv(): NodeJS.ProcessEnv { + const env = { ...process.env }; + delete env.T3CODE_PORT; + delete env.T3CODE_AUTH_TOKEN; + delete env.T3CODE_MODE; + delete env.T3CODE_NO_BROWSER; + delete env.T3CODE_HOST; + delete env.T3CODE_DESKTOP_WS_URL; + return env; +} + +function writeDesktopLogHeader(message: string): void { + if (!desktopLogSink) return; + desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`); +} + +function writeBackendSessionBoundary(phase: "START" | "END", details: string): void { + if (!backendLogSink) return; + const normalizedDetails = sanitizeLogValue(details); + backendLogSink.write( + `[${logTimestamp()}] ---- APP SESSION ${phase} run=${APP_RUN_ID} ${normalizedDetails} ----\n`, + ); +} + +function formatErrorMessage(error: unknown): string { + if (error instanceof Error) { + return error.message; + } + return String(error); +} + +function getSafeExternalUrl(rawUrl: unknown): string | null { + if (typeof rawUrl !== "string" || rawUrl.length === 0) { + return null; + } + + let parsedUrl: URL; + try { + parsedUrl = new URL(rawUrl); + } catch { + return null; + } + + if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") { + return null; + } + + return parsedUrl.toString(); +} + +function getSafeTheme(rawTheme: unknown): DesktopTheme | null { + if (rawTheme === "light" || rawTheme === "dark" || rawTheme === "system") { + return rawTheme; + } + + return null; +} + +function writeDesktopStreamChunk( + streamName: "stdout" | "stderr", + chunk: unknown, + encoding: BufferEncoding | undefined, +): void { + if (!desktopLogSink) return; + const buffer = Buffer.isBuffer(chunk) + ? chunk + : Buffer.from(String(chunk), typeof chunk === "string" ? encoding : undefined); + desktopLogSink.write(`[${logTimestamp()}] [${logScope(streamName)}] `); + desktopLogSink.write(buffer); + if (buffer.length === 0 || buffer[buffer.length - 1] !== 0x0a) { + desktopLogSink.write("\n"); + } +} + +function installStdIoCapture(): void { + if (!app.isPackaged || desktopLogSink === null || restoreStdIoCapture !== null) { + return; + } + + const originalStdoutWrite = process.stdout.write.bind(process.stdout); + const originalStderrWrite = process.stderr.write.bind(process.stderr); + + const patchWrite = + (streamName: "stdout" | "stderr", originalWrite: typeof process.stdout.write) => + ( + chunk: string | Uint8Array, + encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void), + callback?: (error?: Error | null) => void, + ): boolean => { + const encoding = typeof encodingOrCallback === "string" ? encodingOrCallback : undefined; + writeDesktopStreamChunk(streamName, chunk, encoding); + if (typeof encodingOrCallback === "function") { + return originalWrite(chunk, encodingOrCallback); + } + if (callback !== undefined) { + return originalWrite(chunk, encoding, callback); + } + if (encoding !== undefined) { + return originalWrite(chunk, encoding); + } + return originalWrite(chunk); + }; + + process.stdout.write = patchWrite("stdout", originalStdoutWrite); + process.stderr.write = patchWrite("stderr", originalStderrWrite); + + restoreStdIoCapture = () => { + process.stdout.write = originalStdoutWrite; + process.stderr.write = originalStderrWrite; + restoreStdIoCapture = null; }; } +function initializePackagedLogging(): void { + if (!app.isPackaged) return; + try { + desktopLogSink = new RotatingFileSink({ + filePath: Path.join(LOG_DIR, "desktop-main.log"), + maxBytes: LOG_FILE_MAX_BYTES, + maxFiles: LOG_FILE_MAX_FILES, + }); + backendLogSink = new RotatingFileSink({ + filePath: Path.join(LOG_DIR, "server-child.log"), + maxBytes: LOG_FILE_MAX_BYTES, + maxFiles: LOG_FILE_MAX_FILES, + }); + installStdIoCapture(); + writeDesktopLogHeader(`runtime log capture enabled logDir=${LOG_DIR}`); + } catch (error) { + // Logging setup should never block app startup. + console.error("[desktop] failed to initialize packaged logging", error); + } +} + +function captureBackendOutput(child: ChildProcess.ChildProcess): void { + if (!app.isPackaged || backendLogSink === null) return; + const writeChunk = (chunk: unknown): void => { + if (!backendLogSink) return; + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8"); + backendLogSink.write(buffer); + }; + child.stdout?.on("data", writeChunk); + child.stderr?.on("data", writeChunk); +} + +initializePackagedLogging(); + +if (process.platform === "linux") { + app.commandLine.appendSwitch("class", LINUX_WM_CLASS); +} + +function getDestructiveMenuIcon(): Electron.NativeImage | undefined { + if (process.platform !== "darwin") return undefined; + if (destructiveMenuIconCache !== undefined) { + return destructiveMenuIconCache ?? undefined; + } + try { + const icon = nativeImage.createFromNamedImage("trash").resize({ + width: 14, + height: 14, + }); + if (icon.isEmpty()) { + destructiveMenuIconCache = null; + return undefined; + } + icon.setTemplateImage(true); + destructiveMenuIconCache = icon; + return icon; + } catch { + destructiveMenuIconCache = null; + return undefined; + } +} +let updatePollTimer: ReturnType | null = null; +let updateStartupTimer: ReturnType | null = null; +let updateCheckInFlight = false; +let updateDownloadInFlight = false; +let updateInstallInFlight = false; +let updaterConfigured = false; +let updateState: DesktopUpdateState = initialUpdateState(); + +function resolveUpdaterErrorContext(): DesktopUpdateErrorContext { + if (updateInstallInFlight) return "install"; + if (updateDownloadInFlight) return "download"; + if (updateCheckInFlight) return "check"; + return updateState.errorContext; +} + +protocol.registerSchemesAsPrivileged([ + { + scheme: DESKTOP_SCHEME, + privileges: { + standard: true, + secure: true, + supportFetchAPI: true, + corsEnabled: true, + }, + }, +]); + +function resolveAppRoot(): string { + if (!app.isPackaged) { + return ROOT_DIR; + } + return app.getAppPath(); +} + +/** Read the baked-in app-update.yml config (if applicable). */ +function readAppUpdateYml(): Record | null { + try { + // electron-updater reads from process.resourcesPath in packaged builds, + // or dev-app-update.yml via app.getAppPath() in dev. + const ymlPath = app.isPackaged + ? Path.join(process.resourcesPath, "app-update.yml") + : Path.join(app.getAppPath(), "dev-app-update.yml"); + const raw = FS.readFileSync(ymlPath, "utf-8"); + // The YAML is simple key-value pairs — avoid pulling in a YAML parser by + // doing a line-based parse (fields: provider, owner, repo, releaseType, …). + const entries: Record = {}; + for (const line of raw.split("\n")) { + const match = line.match(/^(\w+):\s*(.+)$/); + if (match?.[1] && match[2]) entries[match[1]] = match[2].trim(); + } + return entries.provider ? entries : null; + } catch { + return null; + } +} + +function normalizeCommitHash(value: unknown): string | null { + if (typeof value !== "string") { + return null; + } + const trimmed = value.trim(); + if (!COMMIT_HASH_PATTERN.test(trimmed)) { + return null; + } + return trimmed.slice(0, COMMIT_HASH_DISPLAY_LENGTH).toLowerCase(); +} + +function resolveEmbeddedCommitHash(): string | null { + const packageJsonPath = Path.join(resolveAppRoot(), "package.json"); + if (!FS.existsSync(packageJsonPath)) { + return null; + } + + try { + const raw = FS.readFileSync(packageJsonPath, "utf8"); + const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown }; + return normalizeCommitHash(parsed.t3codeCommitHash); + } catch { + return null; + } +} + +function resolveAboutCommitHash(): string | null { + if (aboutCommitHashCache !== undefined) { + return aboutCommitHashCache; + } + + const envCommitHash = normalizeCommitHash(process.env.T3CODE_COMMIT_HASH); + if (envCommitHash) { + aboutCommitHashCache = envCommitHash; + return aboutCommitHashCache; + } + + // Only packaged builds are required to expose commit metadata. + if (!app.isPackaged) { + aboutCommitHashCache = null; + return aboutCommitHashCache; + } + + aboutCommitHashCache = resolveEmbeddedCommitHash(); + + return aboutCommitHashCache; +} + +function resolveBackendEntry(): string { + return Path.join(resolveAppRoot(), "apps/server/dist/bin.mjs"); +} + +function resolveBackendCwd(): string { + if (!app.isPackaged) { + return resolveAppRoot(); + } + return OS.homedir(); +} + +function resolveDesktopStaticDir(): string | null { + const appRoot = resolveAppRoot(); + const candidates = [ + Path.join(appRoot, "apps/server/dist/client"), + Path.join(appRoot, "apps/web/dist"), + ]; + + for (const candidate of candidates) { + if (FS.existsSync(Path.join(candidate, "index.html"))) { + return candidate; + } + } + + return null; +} + +function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string { + const url = new URL(requestUrl); + const rawPath = decodeURIComponent(url.pathname); + const normalizedPath = Path.posix.normalize(rawPath).replace(/^\/+/, ""); + if (normalizedPath.includes("..")) { + return Path.join(staticRoot, "index.html"); + } + + const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html"; + const resolvedPath = Path.join(staticRoot, requestedPath); + + if (Path.extname(resolvedPath)) { + return resolvedPath; + } + + const nestedIndex = Path.join(resolvedPath, "index.html"); + if (FS.existsSync(nestedIndex)) { + return nestedIndex; + } + + return Path.join(staticRoot, "index.html"); +} + +function isStaticAssetRequest(requestUrl: string): boolean { + try { + const url = new URL(requestUrl); + return Path.extname(url.pathname).length > 0; + } catch { + return false; + } +} + +function handleFatalStartupError(stage: string, error: unknown): void { + const message = formatErrorMessage(error); + const detail = + error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : ""; + writeDesktopLogHeader(`fatal startup error stage=${stage} message=${message}`); + console.error(`[desktop] fatal startup error (${stage})`, error); + if (!isQuitting) { + isQuitting = true; + dialog.showErrorBox("T3 Code failed to start", `Stage: ${stage}\n${message}${detail}`); + } + stopBackend(); + restoreStdIoCapture?.(); + app.quit(); +} + +function registerDesktopProtocol(): void { + if (isDevelopment || desktopProtocolRegistered) return; + + const staticRoot = resolveDesktopStaticDir(); + if (!staticRoot) { + throw new Error( + "Desktop static bundle missing. Build apps/server (with bundled client) first.", + ); + } + + const staticRootResolved = Path.resolve(staticRoot); + const staticRootPrefix = `${staticRootResolved}${Path.sep}`; + const fallbackIndex = Path.join(staticRootResolved, "index.html"); + + protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => { + try { + const candidate = resolveDesktopStaticPath(staticRootResolved, request.url); + const resolvedCandidate = Path.resolve(candidate); + const isInRoot = + resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix); + const isAssetRequest = isStaticAssetRequest(request.url); + + if (!isInRoot || !FS.existsSync(resolvedCandidate)) { + if (isAssetRequest) { + callback({ error: -6 }); + return; + } + callback({ path: fallbackIndex }); + return; + } + + callback({ path: resolvedCandidate }); + } catch { + callback({ path: fallbackIndex }); + } + }); + + desktopProtocolRegistered = true; +} + +function dispatchMenuAction(action: string): void { + const existingWindow = + BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0]; + const targetWindow = existingWindow ?? createWindow(); + if (!existingWindow) { + mainWindow = targetWindow; + } + + const send = () => { + if (targetWindow.isDestroyed()) return; + targetWindow.webContents.send(MENU_ACTION_CHANNEL, action); + if (!targetWindow.isVisible()) { + targetWindow.show(); + } + targetWindow.focus(); + }; + + if (targetWindow.webContents.isLoadingMainFrame()) { + targetWindow.webContents.once("did-finish-load", send); + return; + } + + send(); +} + +function handleCheckForUpdatesMenuClick(): void { + const disabledReason = getAutoUpdateDisabledReason({ + isDevelopment, + isPackaged: app.isPackaged, + platform: process.platform, + appImage: process.env.APPIMAGE, + disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1", + }); + if (disabledReason) { + console.info("[desktop-updater] Manual update check requested, but updates are disabled."); + void dialog.showMessageBox({ + type: "info", + title: "Updates unavailable", + message: "Automatic updates are not available right now.", + detail: disabledReason, + buttons: ["OK"], + }); + return; + } + + if (!BrowserWindow.getAllWindows().length) { + mainWindow = createWindow(); + } + void checkForUpdatesFromMenu(); +} + +async function checkForUpdatesFromMenu(): Promise { + await checkForUpdates("menu"); + + if (updateState.status === "up-to-date") { + void dialog.showMessageBox({ + type: "info", + title: "You're up to date!", + message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`, + buttons: ["OK"], + }); + } else if (updateState.status === "error") { + void dialog.showMessageBox({ + type: "warning", + title: "Update check failed", + message: "Could not check for updates.", + detail: updateState.message ?? "An unknown error occurred. Please try again later.", + buttons: ["OK"], + }); + } +} + +function configureApplicationMenu(): void { + const template: MenuItemConstructorOptions[] = []; + + if (process.platform === "darwin") { + template.push({ + label: app.name, + submenu: [ + { role: "about" }, + { + label: "Check for Updates...", + click: () => handleCheckForUpdatesMenuClick(), + }, + { type: "separator" }, + { + label: "Settings...", + accelerator: "CmdOrCtrl+,", + click: () => dispatchMenuAction("open-settings"), + }, + { type: "separator" }, + { role: "services" }, + { type: "separator" }, + { role: "hide" }, + { role: "hideOthers" }, + { role: "unhide" }, + { type: "separator" }, + { role: "quit" }, + ], + }); + } + + template.push( + { + label: "File", + submenu: [ + ...(process.platform === "darwin" + ? [] + : [ + { + label: "Settings...", + accelerator: "CmdOrCtrl+,", + click: () => dispatchMenuAction("open-settings"), + }, + { type: "separator" as const }, + ]), + { role: process.platform === "darwin" ? "close" : "quit" }, + ], + }, + { role: "editMenu" }, + { + label: "View", + submenu: [ + { role: "reload" }, + { role: "forceReload" }, + { role: "toggleDevTools" }, + { type: "separator" }, + { role: "resetZoom" }, + { role: "zoomIn", accelerator: "CmdOrCtrl+=" }, + { role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false }, + { role: "zoomOut" }, + { type: "separator" }, + { role: "togglefullscreen" }, + ], + }, + { role: "windowMenu" }, + { + role: "help", + submenu: [ + { + label: "Check for Updates...", + click: () => handleCheckForUpdatesMenuClick(), + }, + ], + }, + ); + + Menu.setApplicationMenu(Menu.buildFromTemplate(template)); +} + +function resolveResourcePath(fileName: string): string | null { + const candidates = [ + Path.join(__dirname, "../resources", fileName), + Path.join(__dirname, "../prod-resources", fileName), + Path.join(process.resourcesPath, "resources", fileName), + Path.join(process.resourcesPath, fileName), + ]; + + for (const candidate of candidates) { + if (FS.existsSync(candidate)) { + return candidate; + } + } + + return null; +} + +function resolveIconPath(ext: "ico" | "icns" | "png"): string | null { + return resolveResourcePath(`icon.${ext}`); +} + +/** + * Resolve the Electron userData directory path. + * + * Electron derives the default userData path from `productName` in + * package.json, which currently produces directories with spaces and + * parentheses (e.g. `~/.config/T3 Code (Alpha)` on Linux). This is + * unfriendly for shell usage and violates Linux naming conventions. + * + * We override it to a clean lowercase name (`t3code`). If the legacy + * directory already exists we keep using it so existing users don't + * lose their Chromium profile data (localStorage, cookies, sessions). + */ +function resolveUserDataPath(): string { + const appDataBase = + process.platform === "win32" + ? process.env.APPDATA || Path.join(OS.homedir(), "AppData", "Roaming") + : process.platform === "darwin" + ? Path.join(OS.homedir(), "Library", "Application Support") + : process.env.XDG_CONFIG_HOME || Path.join(OS.homedir(), ".config"); + + const legacyPath = Path.join(appDataBase, LEGACY_USER_DATA_DIR_NAME); + if (FS.existsSync(legacyPath)) { + return legacyPath; + } + + return Path.join(appDataBase, USER_DATA_DIR_NAME); +} + +function configureAppIdentity(): void { + app.setName(APP_DISPLAY_NAME); + const commitHash = resolveAboutCommitHash(); + app.setAboutPanelOptions({ + applicationName: APP_DISPLAY_NAME, + applicationVersion: app.getVersion(), + version: commitHash ?? "unknown", + }); + + if (process.platform === "win32") { + app.setAppUserModelId(APP_USER_MODEL_ID); + } + + if (process.platform === "linux") { + (app as LinuxDesktopNamedApp).setDesktopName?.(LINUX_DESKTOP_ENTRY_NAME); + } + + if (process.platform === "darwin" && app.dock) { + const iconPath = resolveIconPath("png"); + if (iconPath) { + app.dock.setIcon(iconPath); + } + } +} + +function clearUpdatePollTimer(): void { + if (updateStartupTimer) { + clearTimeout(updateStartupTimer); + updateStartupTimer = null; + } + if (updatePollTimer) { + clearInterval(updatePollTimer); + updatePollTimer = null; + } +} + +function emitUpdateState(): void { + for (const window of BrowserWindow.getAllWindows()) { + if (window.isDestroyed()) continue; + window.webContents.send(UPDATE_STATE_CHANNEL, updateState); + } +} + +function setUpdateState(patch: Partial): void { + updateState = { ...updateState, ...patch }; + emitUpdateState(); +} + +function shouldEnableAutoUpdates(): boolean { + return ( + getAutoUpdateDisabledReason({ + isDevelopment, + isPackaged: app.isPackaged, + platform: process.platform, + appImage: process.env.APPIMAGE, + disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1", + }) === null + ); +} + +async function checkForUpdates(reason: string): Promise { + if (isQuitting || !updaterConfigured || updateCheckInFlight) return false; + if (updateState.status === "downloading" || updateState.status === "downloaded") { + console.info( + `[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`, + ); + return false; + } + updateCheckInFlight = true; + setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString())); + console.info(`[desktop-updater] Checking for updates (${reason})...`); + + try { + await autoUpdater.checkForUpdates(); + return true; + } catch (error: unknown) { + const message = error instanceof Error ? error.message : String(error); + setUpdateState( + reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()), + ); + console.error(`[desktop-updater] Failed to check for updates: ${message}`); + return true; + } finally { + updateCheckInFlight = false; + } +} + +async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> { + if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") { + return { accepted: false, completed: false }; + } + updateDownloadInFlight = true; + setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState)); + autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo); + console.info("[desktop-updater] Downloading update..."); + + try { + await autoUpdater.downloadUpdate(); + return { accepted: true, completed: true }; + } catch (error: unknown) { + const message = error instanceof Error ? error.message : String(error); + setUpdateState(reduceDesktopUpdateStateOnDownloadFailure(updateState, message)); + console.error(`[desktop-updater] Failed to download update: ${message}`); + return { accepted: true, completed: false }; + } finally { + updateDownloadInFlight = false; + } +} + +async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> { + if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") { + return { accepted: false, completed: false }; + } + + isQuitting = true; + updateInstallInFlight = true; + clearUpdatePollTimer(); + try { + await stopBackendAndWaitForExit(); + // Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close. + for (const win of BrowserWindow.getAllWindows()) { + win.destroy(); + } + // `quitAndInstall()` only starts the handoff to the updater. The actual + // install may still fail asynchronously, so keep the action incomplete + // until we either quit or receive an updater error. + autoUpdater.quitAndInstall(true, true); + return { accepted: true, completed: false }; + } catch (error: unknown) { + const message = formatErrorMessage(error); + updateInstallInFlight = false; + isQuitting = false; + setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message)); + console.error(`[desktop-updater] Failed to install update: ${message}`); + return { accepted: true, completed: false }; + } +} + +function configureAutoUpdater(): void { + const enabled = shouldEnableAutoUpdates(); + setUpdateState({ + ...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo), + enabled, + status: enabled ? "idle" : "disabled", + }); + if (!enabled) { + return; + } + updaterConfigured = true; + + const githubToken = + process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || ""; + if (githubToken) { + // When a token is provided, re-configure the feed with `private: true` so + // electron-updater uses the GitHub API (api.github.com) instead of the + // public Atom feed (github.com/…/releases.atom) which rejects Bearer auth. + const appUpdateYml = readAppUpdateYml(); + if (appUpdateYml?.provider === "github") { + autoUpdater.setFeedURL({ + ...appUpdateYml, + provider: "github" as const, + private: true, + token: githubToken, + }); + } + } + + if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) { + autoUpdater.setFeedURL({ + provider: "generic", + url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`, + }); + } + + autoUpdater.autoDownload = false; + autoUpdater.autoInstallOnAppQuit = false; + // 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; + autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo); + let lastLoggedDownloadMilestone = -1; + + if (isArm64HostRunningIntelBuild(desktopRuntimeInfo)) { + console.info( + "[desktop-updater] Apple Silicon host detected while running Intel build; updates will switch to arm64 packages.", + ); + } + + autoUpdater.on("checking-for-update", () => { + console.info("[desktop-updater] Looking for updates..."); + }); + autoUpdater.on("update-available", (info) => { + setUpdateState( + reduceDesktopUpdateStateOnUpdateAvailable( + updateState, + info.version, + new Date().toISOString(), + ), + ); + lastLoggedDownloadMilestone = -1; + console.info(`[desktop-updater] Update available: ${info.version}`); + }); + autoUpdater.on("update-not-available", () => { + setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString())); + lastLoggedDownloadMilestone = -1; + console.info("[desktop-updater] No updates available."); + }); + autoUpdater.on("error", (error) => { + const message = formatErrorMessage(error); + if (updateInstallInFlight) { + updateInstallInFlight = false; + isQuitting = false; + setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message)); + console.error(`[desktop-updater] Updater error: ${message}`); + return; + } + if (!updateCheckInFlight && !updateDownloadInFlight) { + setUpdateState({ + status: "error", + message, + checkedAt: new Date().toISOString(), + downloadPercent: null, + errorContext: resolveUpdaterErrorContext(), + canRetry: updateState.availableVersion !== null || updateState.downloadedVersion !== null, + }); + } + console.error(`[desktop-updater] Updater error: ${message}`); + }); + autoUpdater.on("download-progress", (progress) => { + const percent = Math.floor(progress.percent); + if ( + shouldBroadcastDownloadProgress(updateState, progress.percent) || + updateState.message !== null + ) { + setUpdateState(reduceDesktopUpdateStateOnDownloadProgress(updateState, progress.percent)); + } + const milestone = percent - (percent % 10); + if (milestone > lastLoggedDownloadMilestone) { + lastLoggedDownloadMilestone = milestone; + console.info(`[desktop-updater] Download progress: ${percent}%`); + } + }); + autoUpdater.on("update-downloaded", (info) => { + setUpdateState(reduceDesktopUpdateStateOnDownloadComplete(updateState, info.version)); + console.info(`[desktop-updater] Update downloaded: ${info.version}`); + }); + + clearUpdatePollTimer(); + + updateStartupTimer = setTimeout(() => { + updateStartupTimer = null; + void checkForUpdates("startup"); + }, AUTO_UPDATE_STARTUP_DELAY_MS); + updateStartupTimer.unref(); + + updatePollTimer = setInterval(() => { + void checkForUpdates("poll"); + }, AUTO_UPDATE_POLL_INTERVAL_MS); + updatePollTimer.unref(); +} function scheduleBackendRestart(reason: string): void { if (isQuitting || restartTimer) return; @@ -76,39 +1007,87 @@ function scheduleBackendRestart(reason: string): void { function startBackend(): void { if (isQuitting || backendProcess) return; - if (!fs.existsSync(BACKEND_ENTRY)) { - scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`); + backendObservabilitySettings = readPersistedBackendObservabilitySettings(); + const backendEntry = resolveBackendEntry(); + if (!FS.existsSync(backendEntry)) { + scheduleBackendRestart(`missing server entry at ${backendEntry}`); return; } - const child = spawn(process.execPath, [BACKEND_ENTRY], { - cwd: ROOT_DIR, + const captureBackendLogs = app.isPackaged && backendLogSink !== null; + const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], { + cwd: resolveBackendCwd(), // In Electron main, process.execPath points to the Electron binary. // Run the child in Node mode so this backend process does not become a GUI app instance. env: { - ...backendEnv(), + ...backendChildEnv(), ELECTRON_RUN_AS_NODE: "1", }, - stdio: "inherit", + stdio: captureBackendLogs + ? ["ignore", "pipe", "pipe", "pipe"] + : ["ignore", "inherit", "inherit", "pipe"], }); + const bootstrapStream = child.stdio[3]; + if (bootstrapStream && "write" in bootstrapStream) { + bootstrapStream.write( + `${JSON.stringify({ + mode: "desktop", + noBrowser: true, + port: backendPort, + t3Home: BASE_DIR, + authToken: backendAuthToken, + ...(backendObservabilitySettings.otlpTracesUrl + ? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl } + : {}), + ...(backendObservabilitySettings.otlpMetricsUrl + ? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl } + : {}), + })}\n`, + ); + bootstrapStream.end(); + } else { + child.kill("SIGTERM"); + scheduleBackendRestart("missing desktop bootstrap pipe"); + return; + } backendProcess = child; + let backendSessionClosed = false; + const closeBackendSession = (details: string) => { + if (backendSessionClosed) return; + backendSessionClosed = true; + writeBackendSessionBoundary("END", details); + }; + writeBackendSessionBoundary( + "START", + `pid=${child.pid ?? "unknown"} port=${backendPort} cwd=${resolveBackendCwd()}`, + ); + captureBackendOutput(child); child.once("spawn", () => { restartAttempt = 0; }); child.on("error", (error) => { + const wasExpected = expectedBackendExitChildren.has(child); if (backendProcess === child) { backendProcess = null; } + closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`); + if (wasExpected) { + return; + } scheduleBackendRestart(error.message); }); child.on("exit", (code, signal) => { + const wasExpected = expectedBackendExitChildren.has(child); if (backendProcess === child) { backendProcess = null; } - if (isQuitting) return; + closeBackendSession( + `pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`, + ); + if (isQuitting || wasExpected) return; const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`; scheduleBackendRestart(reason); }); @@ -124,17 +1103,75 @@ function stopBackend(): void { backendProcess = null; if (!child) return; - if (!child.killed) { + if (child.exitCode === null && child.signalCode === null) { + expectedBackendExitChildren.add(child); child.kill("SIGTERM"); setTimeout(() => { - if (!child.killed) { + if (child.exitCode === null && child.signalCode === null) { child.kill("SIGKILL"); } }, 2_000).unref(); } } +async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise { + if (restartTimer) { + clearTimeout(restartTimer); + restartTimer = null; + } + + const child = backendProcess; + backendProcess = null; + if (!child) return; + const backendChild = child; + if (backendChild.exitCode !== null || backendChild.signalCode !== null) return; + expectedBackendExitChildren.add(backendChild); + + await new Promise((resolve) => { + let settled = false; + let forceKillTimer: ReturnType | null = null; + let exitTimeoutTimer: ReturnType | null = null; + + function settle(): void { + if (settled) return; + settled = true; + backendChild.off("exit", onExit); + if (forceKillTimer) { + clearTimeout(forceKillTimer); + } + if (exitTimeoutTimer) { + clearTimeout(exitTimeoutTimer); + } + resolve(); + } + + function onExit(): void { + settle(); + } + + backendChild.once("exit", onExit); + backendChild.kill("SIGTERM"); + + forceKillTimer = setTimeout(() => { + if (backendChild.exitCode === null && backendChild.signalCode === null) { + backendChild.kill("SIGKILL"); + } + }, 2_000); + forceKillTimer.unref(); + + exitTimeoutTimer = setTimeout(() => { + settle(); + }, timeoutMs); + exitTimeoutTimer.unref(); + }); +} + function registerIpcHandlers(): void { + ipcMain.removeAllListeners(GET_WS_URL_CHANNEL); + ipcMain.on(GET_WS_URL_CHANNEL, (event) => { + event.returnValue = backendWsUrl; + }); + ipcMain.removeHandler(PICK_FOLDER_CHANNEL); ipcMain.handle(PICK_FOLDER_CHANNEL, async () => { const owner = BrowserWindow.getFocusedWindow() ?? mainWindow; @@ -159,49 +1196,145 @@ function registerIpcHandlers(): void { return showDesktopConfirmDialog(message, owner); }); - ipcMain.removeHandler(CONTEXT_MENU_CHANNEL); - ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => { - const window = BrowserWindow.getFocusedWindow() ?? mainWindow; - if (!window) return null; + ipcMain.removeHandler(SET_THEME_CHANNEL); + ipcMain.handle(SET_THEME_CHANNEL, async (_event, rawTheme: unknown) => { + const theme = getSafeTheme(rawTheme); + if (!theme) { + return; + } - return new Promise((resolve) => { - const menu = Menu.buildFromTemplate( - items.map((item) => ({ - label: item.label, - click: () => resolve(item.id), - })), - ); - menu.popup({ - window, - callback: () => resolve(null), - }); - }); + nativeTheme.themeSource = theme; }); + ipcMain.removeHandler(CONTEXT_MENU_CHANNEL); + ipcMain.handle( + CONTEXT_MENU_CHANNEL, + async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => { + const normalizedItems = items + .filter((item) => typeof item.id === "string" && typeof item.label === "string") + .map((item) => ({ + id: item.id, + label: item.label, + destructive: item.destructive === true, + disabled: item.disabled === true, + })); + if (normalizedItems.length === 0) { + return null; + } + + const popupPosition = + position && + Number.isFinite(position.x) && + Number.isFinite(position.y) && + position.x >= 0 && + position.y >= 0 + ? { + x: Math.floor(position.x), + y: Math.floor(position.y), + } + : null; + + const window = BrowserWindow.getFocusedWindow() ?? mainWindow; + if (!window) return null; + + return new Promise((resolve) => { + const template: MenuItemConstructorOptions[] = []; + let hasInsertedDestructiveSeparator = false; + for (const item of normalizedItems) { + if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) { + template.push({ type: "separator" }); + hasInsertedDestructiveSeparator = true; + } + const itemOption: MenuItemConstructorOptions = { + label: item.label, + enabled: !item.disabled, + click: () => resolve(item.id), + }; + if (item.destructive) { + const destructiveIcon = getDestructiveMenuIcon(); + if (destructiveIcon) { + itemOption.icon = destructiveIcon; + } + } + template.push(itemOption); + } + + const menu = Menu.buildFromTemplate(template); + menu.popup({ + window, + ...popupPosition, + callback: () => resolve(null), + }); + }); + }, + ); + ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL); ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => { - if (typeof rawUrl !== "string" || rawUrl.length === 0) { - return false; - } - - let parsedUrl: URL; - try { - parsedUrl = new URL(rawUrl); - } catch { - return false; - } - - if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") { + const externalUrl = getSafeExternalUrl(rawUrl); + if (!externalUrl) { return false; } try { - await shell.openExternal(parsedUrl.toString()); + await shell.openExternal(externalUrl); return true; } catch { return false; } }); + + ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL); + ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState); + + ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL); + ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => { + const result = await downloadAvailableUpdate(); + return { + accepted: result.accepted, + completed: result.completed, + state: updateState, + } satisfies DesktopUpdateActionResult; + }); + + ipcMain.removeHandler(UPDATE_INSTALL_CHANNEL); + ipcMain.handle(UPDATE_INSTALL_CHANNEL, async () => { + if (isQuitting) { + return { + accepted: false, + completed: false, + state: updateState, + } satisfies DesktopUpdateActionResult; + } + const result = await installDownloadedUpdate(); + return { + accepted: result.accepted, + completed: result.completed, + state: updateState, + } satisfies DesktopUpdateActionResult; + }); + + ipcMain.removeHandler(UPDATE_CHECK_CHANNEL); + ipcMain.handle(UPDATE_CHECK_CHANNEL, async () => { + if (!updaterConfigured) { + return { + checked: false, + state: updateState, + } satisfies DesktopUpdateCheckResult; + } + const checked = await checkForUpdates("web-ui"); + return { + checked, + state: updateState, + } satisfies DesktopUpdateCheckResult; + }); +} + +function getIconOption(): { icon: string } | Record { + if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle + const ext = process.platform === "win32" ? "ico" : "png"; + const iconPath = resolveIconPath(ext); + return iconPath ? { icon: iconPath } : {}; } function createWindow(): BrowserWindow { @@ -212,17 +1345,62 @@ function createWindow(): BrowserWindow { minHeight: 620, show: false, autoHideMenuBar: true, + ...getIconOption(), + title: APP_DISPLAY_NAME, titleBarStyle: "hiddenInset", trafficLightPosition: { x: 16, y: 18 }, webPreferences: { - preload: path.join(__dirname, "preload.js"), + preload: Path.join(__dirname, "preload.js"), contextIsolation: true, nodeIntegration: false, sandbox: true, }, }); - window.webContents.setWindowOpenHandler(() => ({ action: "deny" })); + window.webContents.on("context-menu", (event, params) => { + event.preventDefault(); + + const menuTemplate: MenuItemConstructorOptions[] = []; + + if (params.misspelledWord) { + for (const suggestion of params.dictionarySuggestions.slice(0, 5)) { + menuTemplate.push({ + label: suggestion, + click: () => window.webContents.replaceMisspelling(suggestion), + }); + } + if (params.dictionarySuggestions.length === 0) { + menuTemplate.push({ label: "No suggestions", enabled: false }); + } + menuTemplate.push({ type: "separator" }); + } + + menuTemplate.push( + { role: "cut", enabled: params.editFlags.canCut }, + { role: "copy", enabled: params.editFlags.canCopy }, + { role: "paste", enabled: params.editFlags.canPaste }, + { role: "selectAll", enabled: params.editFlags.canSelectAll }, + ); + + Menu.buildFromTemplate(menuTemplate).popup({ window }); + }); + + window.webContents.setWindowOpenHandler(({ url }) => { + const externalUrl = getSafeExternalUrl(url); + if (externalUrl) { + void shell.openExternal(externalUrl); + } + return { action: "deny" }; + }); + + window.on("page-title-updated", (event) => { + event.preventDefault(); + window.setTitle(APP_DISPLAY_NAME); + }); + window.webContents.on("did-finish-load", () => { + window.setTitle(APP_DISPLAY_NAME); + emitUpdateState(); + }); window.once("ready-to-show", () => { window.show(); }); @@ -231,10 +1409,7 @@ function createWindow(): BrowserWindow { void window.loadURL(process.env.VITE_DEV_SERVER_URL as string); window.webContents.openDevTools({ mode: "detach" }); } else { - if (!fs.existsSync(WEB_ENTRY)) { - throw new Error(`Web bundle missing at ${WEB_ENTRY}`); - } - void window.loadFile(WEB_ENTRY); + void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`); } window.on("closed", () => { @@ -246,34 +1421,89 @@ function createWindow(): BrowserWindow { return window; } +// Override Electron's userData path before the `ready` event so that +// Chromium session data uses a filesystem-friendly directory name. +// Must be called synchronously at the top level — before `app.whenReady()`. +app.setPath("userData", resolveUserDataPath()); + +configureAppIdentity(); + async function bootstrap(): Promise { - backendPort = await reserveLoopbackPort(); - backendAuthToken = randomBytes(24).toString("hex"); - backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`; - process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl; + writeDesktopLogHeader("bootstrap start"); + backendPort = await Effect.service(NetService).pipe( + Effect.flatMap((net) => net.reserveLoopbackPort()), + Effect.provide(NetService.layer), + Effect.runPromise, + ); + writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`); + backendAuthToken = Crypto.randomBytes(24).toString("hex"); + const baseUrl = `ws://127.0.0.1:${backendPort}`; + backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`; + writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`); registerIpcHandlers(); + writeDesktopLogHeader("bootstrap ipc handlers registered"); startBackend(); + writeDesktopLogHeader("bootstrap backend start requested"); mainWindow = createWindow(); + writeDesktopLogHeader("bootstrap main window created"); } app.on("before-quit", () => { isQuitting = true; + updateInstallInFlight = false; + writeDesktopLogHeader("before-quit received"); + clearUpdatePollTimer(); stopBackend(); + restoreStdIoCapture?.(); }); -app.whenReady().then(() => { - void bootstrap(); +app + .whenReady() + .then(() => { + writeDesktopLogHeader("app ready"); + configureAppIdentity(); + configureApplicationMenu(); + registerDesktopProtocol(); + configureAutoUpdater(); + void bootstrap().catch((error) => { + handleFatalStartupError("bootstrap", error); + }); - app.on("activate", () => { - if (BrowserWindow.getAllWindows().length === 0) { - mainWindow = createWindow(); - } + app.on("activate", () => { + if (BrowserWindow.getAllWindows().length === 0) { + mainWindow = createWindow(); + } + }); + }) + .catch((error) => { + handleFatalStartupError("whenReady", error); }); -}); app.on("window-all-closed", () => { - if (process.platform !== "darwin") { + if (process.platform !== "darwin" && !isQuitting) { app.quit(); } }); + +if (process.platform !== "win32") { + process.on("SIGINT", () => { + if (isQuitting) return; + isQuitting = true; + writeDesktopLogHeader("SIGINT received"); + clearUpdatePollTimer(); + stopBackend(); + restoreStdIoCapture?.(); + app.quit(); + }); + + process.on("SIGTERM", () => { + if (isQuitting) return; + isQuitting = true; + writeDesktopLogHeader("SIGTERM received"); + clearUpdatePollTimer(); + stopBackend(); + restoreStdIoCapture?.(); + app.quit(); + }); +} diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index fb90831fc0..3d59db1714 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -1,16 +1,53 @@ import { contextBridge, ipcRenderer } from "electron"; +import type { DesktopBridge } from "@t3tools/contracts"; const PICK_FOLDER_CHANNEL = "desktop:pick-folder"; const CONFIRM_CHANNEL = "desktop:confirm"; +const SET_THEME_CHANNEL = "desktop:set-theme"; const CONTEXT_MENU_CHANNEL = "desktop:context-menu"; const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; -const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null; +const MENU_ACTION_CHANNEL = "desktop:menu-action"; +const UPDATE_STATE_CHANNEL = "desktop:update-state"; +const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; +const UPDATE_CHECK_CHANNEL = "desktop:update-check"; +const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download"; +const UPDATE_INSTALL_CHANNEL = "desktop:update-install"; +const GET_WS_URL_CHANNEL = "desktop:get-ws-url"; contextBridge.exposeInMainWorld("desktopBridge", { - getWsUrl: () => wsUrl, - pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise, - confirm: (message: string) => ipcRenderer.invoke(CONFIRM_CHANNEL, message) as Promise, - showContextMenu: (items: { id: string; label: string }[]) => - ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise, - openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise, -}); + getWsUrl: () => { + const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL); + return typeof result === "string" ? result : null; + }, + pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL), + confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message), + setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme), + showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position), + openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url), + onMenuAction: (listener) => { + const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => { + if (typeof action !== "string") return; + listener(action); + }; + + ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener); + return () => { + ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener); + }; + }, + getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL), + checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL), + downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL), + installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL), + onUpdateState: (listener) => { + const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => { + if (typeof state !== "object" || state === null) return; + listener(state as Parameters[0]); + }; + + ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener); + return () => { + ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener); + }; + }, +} satisfies DesktopBridge); diff --git a/apps/desktop/src/rotatingFileSink.test.ts b/apps/desktop/src/rotatingFileSink.test.ts new file mode 100644 index 0000000000..53dd98ade8 --- /dev/null +++ b/apps/desktop/src/rotatingFileSink.test.ts @@ -0,0 +1,74 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { RotatingFileSink } from "@t3tools/shared/logging"; +import { afterEach, describe, expect, it } from "vitest"; + +const tempRoots: string[] = []; + +function makeTempDir(): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-")); + tempRoots.push(dir); + return dir; +} + +afterEach(() => { + for (const dir of tempRoots.splice(0)) { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +describe("RotatingFileSink", () => { + it("rotates when writes exceed max bytes", () => { + const dir = makeTempDir(); + const logPath = path.join(dir, "desktop-main.log"); + const sink = new RotatingFileSink({ + filePath: logPath, + maxBytes: 10, + maxFiles: 3, + }); + + sink.write("12345"); + sink.write("67890"); + sink.write("abc"); + + expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc"); + expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890"); + }); + + it("retains only maxFiles backups", () => { + const dir = makeTempDir(); + const logPath = path.join(dir, "server-child.log"); + const sink = new RotatingFileSink({ + filePath: logPath, + maxBytes: 4, + maxFiles: 2, + }); + + sink.write("aaaa"); + sink.write("bbbb"); + sink.write("cccc"); + sink.write("dddd"); + + expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true); + expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true); + expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false); + }); + + it("prunes stale backups above maxFiles on startup", () => { + const dir = makeTempDir(); + const logPath = path.join(dir, "desktop-main.log"); + fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first"); + fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale"); + + const sink = new RotatingFileSink({ + filePath: logPath, + maxBytes: 16, + maxFiles: 2, + }); + sink.write("hello"); + + expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false); + }); +}); diff --git a/apps/desktop/src/runtimeArch.test.ts b/apps/desktop/src/runtimeArch.test.ts new file mode 100644 index 0000000000..258a8fb215 --- /dev/null +++ b/apps/desktop/src/runtimeArch.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vitest"; + +import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch"; + +describe("resolveDesktopRuntimeInfo", () => { + it("detects Rosetta-translated Intel builds on Apple Silicon", () => { + const runtimeInfo = resolveDesktopRuntimeInfo({ + platform: "darwin", + processArch: "x64", + runningUnderArm64Translation: true, + }); + + expect(runtimeInfo).toEqual({ + hostArch: "arm64", + appArch: "x64", + runningUnderArm64Translation: true, + }); + expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(true); + }); + + it("detects native Apple Silicon builds", () => { + const runtimeInfo = resolveDesktopRuntimeInfo({ + platform: "darwin", + processArch: "arm64", + runningUnderArm64Translation: false, + }); + + expect(runtimeInfo).toEqual({ + hostArch: "arm64", + appArch: "arm64", + runningUnderArm64Translation: false, + }); + expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(false); + }); + + it("passes through non-mac builds without translation", () => { + const runtimeInfo = resolveDesktopRuntimeInfo({ + platform: "linux", + processArch: "x64", + runningUnderArm64Translation: true, + }); + + expect(runtimeInfo).toEqual({ + hostArch: "x64", + appArch: "x64", + runningUnderArm64Translation: false, + }); + }); +}); diff --git a/apps/desktop/src/runtimeArch.ts b/apps/desktop/src/runtimeArch.ts new file mode 100644 index 0000000000..127abf51ab --- /dev/null +++ b/apps/desktop/src/runtimeArch.ts @@ -0,0 +1,39 @@ +import type { DesktopRuntimeArch, DesktopRuntimeInfo } from "@t3tools/contracts"; + +interface ResolveDesktopRuntimeInfoInput { + readonly platform: NodeJS.Platform; + readonly processArch: string; + readonly runningUnderArm64Translation: boolean; +} + +function normalizeDesktopArch(arch: string): DesktopRuntimeArch { + if (arch === "arm64") return "arm64"; + if (arch === "x64") return "x64"; + return "other"; +} + +export function resolveDesktopRuntimeInfo( + input: ResolveDesktopRuntimeInfoInput, +): DesktopRuntimeInfo { + const appArch = normalizeDesktopArch(input.processArch); + + if (input.platform !== "darwin") { + return { + hostArch: appArch, + appArch, + runningUnderArm64Translation: false, + }; + } + + const hostArch = appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch; + + return { + hostArch, + appArch, + runningUnderArm64Translation: input.runningUnderArm64Translation, + }; +} + +export function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean { + return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64"; +} diff --git a/apps/desktop/src/syncShellEnvironment.test.ts b/apps/desktop/src/syncShellEnvironment.test.ts new file mode 100644 index 0000000000..cda78a20b2 --- /dev/null +++ b/apps/desktop/src/syncShellEnvironment.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it, vi } from "vitest"; + +import { syncShellEnvironment } from "./syncShellEnvironment"; + +describe("syncShellEnvironment", () => { + it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + }; + const readEnvironment = vi.fn(() => ({ + PATH: "/opt/homebrew/bin:/usr/bin", + SSH_AUTH_SOCK: "/tmp/secretive.sock", + })); + + syncShellEnvironment(env, { + platform: "darwin", + readEnvironment, + }); + + expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]); + expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin"); + expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock"); + }); + + it("preserves an inherited SSH_AUTH_SOCK value", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + SSH_AUTH_SOCK: "/tmp/inherited.sock", + }; + const readEnvironment = vi.fn(() => ({ + PATH: "/opt/homebrew/bin:/usr/bin", + SSH_AUTH_SOCK: "/tmp/login-shell.sock", + })); + + syncShellEnvironment(env, { + platform: "darwin", + readEnvironment, + }); + + expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin"); + expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock"); + }); + + it("preserves inherited values when the login shell omits them", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + SSH_AUTH_SOCK: "/tmp/inherited.sock", + }; + const readEnvironment = vi.fn(() => ({ + PATH: "/opt/homebrew/bin:/usr/bin", + })); + + syncShellEnvironment(env, { + platform: "darwin", + readEnvironment, + }); + + expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin"); + expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock"); + }); + + it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + }; + const readEnvironment = vi.fn(() => ({ + PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin", + SSH_AUTH_SOCK: "/tmp/secretive.sock", + })); + + syncShellEnvironment(env, { + platform: "linux", + readEnvironment, + }); + + expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]); + expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin"); + expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock"); + }); + + it("does nothing outside macOS and linux", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "C:/Program Files/Git/bin/bash.exe", + PATH: "C:\\Windows\\System32", + SSH_AUTH_SOCK: "/tmp/inherited.sock", + }; + const readEnvironment = vi.fn(() => ({ + PATH: "/usr/local/bin:/usr/bin", + SSH_AUTH_SOCK: "/tmp/secretive.sock", + })); + + syncShellEnvironment(env, { + platform: "win32", + readEnvironment, + }); + + expect(readEnvironment).not.toHaveBeenCalled(); + expect(env.PATH).toBe("C:\\Windows\\System32"); + expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock"); + }); +}); diff --git a/apps/desktop/src/syncShellEnvironment.ts b/apps/desktop/src/syncShellEnvironment.ts new file mode 100644 index 0000000000..13036149b8 --- /dev/null +++ b/apps/desktop/src/syncShellEnvironment.ts @@ -0,0 +1,36 @@ +import { + readEnvironmentFromLoginShell, + resolveLoginShell, + ShellEnvironmentReader, +} from "@t3tools/shared/shell"; + +export function syncShellEnvironment( + env: NodeJS.ProcessEnv = process.env, + options: { + platform?: NodeJS.Platform; + readEnvironment?: ShellEnvironmentReader; + } = {}, +): void { + const platform = options.platform ?? process.platform; + if (platform !== "darwin" && platform !== "linux") return; + + try { + const shell = resolveLoginShell(platform, env.SHELL); + if (!shell) return; + + const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [ + "PATH", + "SSH_AUTH_SOCK", + ]); + + if (shellEnvironment.PATH) { + env.PATH = shellEnvironment.PATH; + } + + if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) { + env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK; + } + } catch { + // Keep inherited environment if shell lookup fails. + } +} diff --git a/apps/desktop/src/updateMachine.test.ts b/apps/desktop/src/updateMachine.test.ts new file mode 100644 index 0000000000..7fbc982eff --- /dev/null +++ b/apps/desktop/src/updateMachine.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from "vitest"; + +import { + createInitialDesktopUpdateState, + reduceDesktopUpdateStateOnCheckFailure, + reduceDesktopUpdateStateOnCheckStart, + reduceDesktopUpdateStateOnDownloadComplete, + reduceDesktopUpdateStateOnDownloadFailure, + reduceDesktopUpdateStateOnDownloadProgress, + reduceDesktopUpdateStateOnDownloadStart, + reduceDesktopUpdateStateOnInstallFailure, + reduceDesktopUpdateStateOnNoUpdate, + reduceDesktopUpdateStateOnUpdateAvailable, +} from "./updateMachine"; + +const runtimeInfo = { + hostArch: "x64", + appArch: "x64", + runningUnderArm64Translation: false, +} as const; + +describe("updateMachine", () => { + it("clears transient errors when a check starts", () => { + const state = reduceDesktopUpdateStateOnCheckStart( + { + ...createInitialDesktopUpdateState("1.0.0", runtimeInfo), + enabled: true, + status: "error", + message: "network", + errorContext: "check", + canRetry: true, + }, + "2026-03-04T00:00:00.000Z", + ); + + expect(state.status).toBe("checking"); + expect(state.message).toBeNull(); + expect(state.errorContext).toBeNull(); + expect(state.canRetry).toBe(false); + }); + + it("records a check failure without exposing an action", () => { + const state = reduceDesktopUpdateStateOnCheckFailure( + { + ...createInitialDesktopUpdateState("1.0.0", runtimeInfo), + enabled: true, + status: "checking", + }, + "network unavailable", + "2026-03-04T00:00:00.000Z", + ); + + expect(state.status).toBe("error"); + expect(state.errorContext).toBe("check"); + expect(state.canRetry).toBe(true); + }); + + it("preserves available version on download failure for retry", () => { + const state = reduceDesktopUpdateStateOnDownloadFailure( + { + ...createInitialDesktopUpdateState("1.0.0", runtimeInfo), + enabled: true, + status: "downloading", + availableVersion: "1.1.0", + downloadPercent: 43, + }, + "checksum mismatch", + ); + + expect(state.status).toBe("available"); + expect(state.availableVersion).toBe("1.1.0"); + expect(state.errorContext).toBe("download"); + expect(state.canRetry).toBe(true); + }); + + it("transitions to downloaded and then preserves install retry state", () => { + const downloaded = reduceDesktopUpdateStateOnDownloadComplete( + { + ...createInitialDesktopUpdateState("1.0.0", runtimeInfo), + enabled: true, + status: "downloading", + availableVersion: "1.1.0", + }, + "1.1.0", + ); + const failedInstall = reduceDesktopUpdateStateOnInstallFailure( + downloaded, + "backend shutdown timed out", + ); + + expect(downloaded.status).toBe("downloaded"); + expect(downloaded.downloadedVersion).toBe("1.1.0"); + expect(failedInstall.status).toBe("downloaded"); + expect(failedInstall.errorContext).toBe("install"); + expect(failedInstall.canRetry).toBe(true); + }); + + it("clears stale download state when no update is available", () => { + const state = reduceDesktopUpdateStateOnNoUpdate( + { + ...createInitialDesktopUpdateState("1.0.0", runtimeInfo), + enabled: true, + status: "error", + availableVersion: "1.1.0", + downloadedVersion: "1.1.0", + message: "old failure", + errorContext: "download", + canRetry: true, + }, + "2026-03-04T00:00:00.000Z", + ); + + expect(state.status).toBe("up-to-date"); + expect(state.availableVersion).toBeNull(); + expect(state.downloadedVersion).toBeNull(); + expect(state.message).toBeNull(); + expect(state.errorContext).toBeNull(); + }); + + it("tracks available, download start, and progress cleanly", () => { + const available = reduceDesktopUpdateStateOnUpdateAvailable( + { + ...createInitialDesktopUpdateState("1.0.0", runtimeInfo), + enabled: true, + status: "checking", + }, + "1.1.0", + "2026-03-04T00:00:00.000Z", + ); + const downloading = reduceDesktopUpdateStateOnDownloadStart(available); + const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5); + + expect(available.status).toBe("available"); + expect(downloading.status).toBe("downloading"); + expect(downloading.downloadPercent).toBe(0); + expect(progress.downloadPercent).toBe(55.5); + expect(progress.errorContext).toBeNull(); + }); +}); diff --git a/apps/desktop/src/updateMachine.ts b/apps/desktop/src/updateMachine.ts new file mode 100644 index 0000000000..f13b420281 --- /dev/null +++ b/apps/desktop/src/updateMachine.ts @@ -0,0 +1,160 @@ +import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts"; + +import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState"; + +export function createInitialDesktopUpdateState( + currentVersion: string, + runtimeInfo: DesktopRuntimeInfo, +): DesktopUpdateState { + return { + enabled: false, + status: "disabled", + currentVersion, + hostArch: runtimeInfo.hostArch, + appArch: runtimeInfo.appArch, + runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation, + availableVersion: null, + downloadedVersion: null, + downloadPercent: null, + checkedAt: null, + message: null, + errorContext: null, + canRetry: false, + }; +} + +export function reduceDesktopUpdateStateOnCheckStart( + state: DesktopUpdateState, + checkedAt: string, +): DesktopUpdateState { + return { + ...state, + status: "checking", + checkedAt, + message: null, + downloadPercent: null, + errorContext: null, + canRetry: false, + }; +} + +export function reduceDesktopUpdateStateOnCheckFailure( + state: DesktopUpdateState, + message: string, + checkedAt: string, +): DesktopUpdateState { + return { + ...state, + status: "error", + message, + checkedAt, + downloadPercent: null, + errorContext: "check", + canRetry: true, + }; +} + +export function reduceDesktopUpdateStateOnUpdateAvailable( + state: DesktopUpdateState, + version: string, + checkedAt: string, +): DesktopUpdateState { + return { + ...state, + status: "available", + availableVersion: version, + downloadedVersion: null, + downloadPercent: null, + checkedAt, + message: null, + errorContext: null, + canRetry: false, + }; +} + +export function reduceDesktopUpdateStateOnNoUpdate( + state: DesktopUpdateState, + checkedAt: string, +): DesktopUpdateState { + return { + ...state, + status: "up-to-date", + availableVersion: null, + downloadedVersion: null, + downloadPercent: null, + checkedAt, + message: null, + errorContext: null, + canRetry: false, + }; +} + +export function reduceDesktopUpdateStateOnDownloadStart( + state: DesktopUpdateState, +): DesktopUpdateState { + return { + ...state, + status: "downloading", + downloadPercent: 0, + message: null, + errorContext: null, + canRetry: false, + }; +} + +export function reduceDesktopUpdateStateOnDownloadFailure( + state: DesktopUpdateState, + message: string, +): DesktopUpdateState { + return { + ...state, + status: nextStatusAfterDownloadFailure(state), + message, + downloadPercent: null, + errorContext: "download", + canRetry: getCanRetryAfterDownloadFailure(state), + }; +} + +export function reduceDesktopUpdateStateOnDownloadProgress( + state: DesktopUpdateState, + percent: number, +): DesktopUpdateState { + return { + ...state, + status: "downloading", + downloadPercent: percent, + message: null, + errorContext: null, + canRetry: false, + }; +} + +export function reduceDesktopUpdateStateOnDownloadComplete( + state: DesktopUpdateState, + version: string, +): DesktopUpdateState { + return { + ...state, + status: "downloaded", + availableVersion: version, + downloadedVersion: version, + downloadPercent: 100, + message: null, + errorContext: null, + canRetry: true, + }; +} + +export function reduceDesktopUpdateStateOnInstallFailure( + state: DesktopUpdateState, + message: string, +): DesktopUpdateState { + return { + ...state, + status: "downloaded", + message, + errorContext: "install", + canRetry: true, + }; +} diff --git a/apps/desktop/src/updateState.test.ts b/apps/desktop/src/updateState.test.ts new file mode 100644 index 0000000000..43b718bd00 --- /dev/null +++ b/apps/desktop/src/updateState.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from "vitest"; +import type { DesktopUpdateState } from "@t3tools/contracts"; + +import { + getCanRetryAfterDownloadFailure, + getAutoUpdateDisabledReason, + nextStatusAfterDownloadFailure, + shouldBroadcastDownloadProgress, +} from "./updateState"; + +const baseState: DesktopUpdateState = { + enabled: true, + status: "idle", + currentVersion: "1.0.0", + hostArch: "x64", + appArch: "x64", + runningUnderArm64Translation: false, + availableVersion: null, + downloadedVersion: null, + downloadPercent: null, + checkedAt: null, + message: null, + errorContext: null, + canRetry: false, +}; + +describe("shouldBroadcastDownloadProgress", () => { + it("broadcasts the first downloading progress update", () => { + expect( + shouldBroadcastDownloadProgress( + { ...baseState, status: "downloading", downloadPercent: null }, + 1, + ), + ).toBe(true); + }); + + it("skips progress updates within the same 10% bucket", () => { + expect( + shouldBroadcastDownloadProgress( + { ...baseState, status: "downloading", downloadPercent: 11.2 }, + 18.7, + ), + ).toBe(false); + }); + + it("broadcasts progress updates when a new 10% bucket is reached", () => { + expect( + shouldBroadcastDownloadProgress( + { ...baseState, status: "downloading", downloadPercent: 19.9 }, + 20.1, + ), + ).toBe(true); + }); + + it("broadcasts progress updates when a retry resets the download percentage", () => { + expect( + shouldBroadcastDownloadProgress( + { ...baseState, status: "downloading", downloadPercent: 50.4 }, + 0.2, + ), + ).toBe(true); + }); +}); + +describe("getAutoUpdateDisabledReason", () => { + it("reports development builds as disabled", () => { + expect( + getAutoUpdateDisabledReason({ + isDevelopment: true, + isPackaged: false, + platform: "darwin", + appImage: undefined, + disabledByEnv: false, + }), + ).toContain("packaged production builds"); + }); + + it("reports env-disabled auto updates", () => { + expect( + getAutoUpdateDisabledReason({ + isDevelopment: false, + isPackaged: true, + platform: "darwin", + appImage: undefined, + disabledByEnv: true, + }), + ).toContain("T3CODE_DISABLE_AUTO_UPDATE"); + }); + + it("reports linux non-AppImage builds as disabled", () => { + expect( + getAutoUpdateDisabledReason({ + isDevelopment: false, + isPackaged: true, + platform: "linux", + appImage: undefined, + disabledByEnv: false, + }), + ).toContain("AppImage"); + }); +}); + +describe("nextStatusAfterDownloadFailure", () => { + it("returns available when an update version is still known", () => { + expect( + nextStatusAfterDownloadFailure({ + ...baseState, + status: "downloading", + availableVersion: "1.1.0", + }), + ).toBe("available"); + }); + + it("returns error when no update version can be retried", () => { + expect( + nextStatusAfterDownloadFailure({ + ...baseState, + status: "downloading", + availableVersion: null, + }), + ).toBe("error"); + }); +}); + +describe("getCanRetryAfterDownloadFailure", () => { + it("returns true when an available version is still present", () => { + expect( + getCanRetryAfterDownloadFailure({ + ...baseState, + status: "downloading", + availableVersion: "1.1.0", + }), + ).toBe(true); + }); + + it("returns false when no version is available to retry", () => { + expect( + getCanRetryAfterDownloadFailure({ + ...baseState, + status: "downloading", + availableVersion: null, + }), + ).toBe(false); + }); +}); diff --git a/apps/desktop/src/updateState.ts b/apps/desktop/src/updateState.ts new file mode 100644 index 0000000000..8c8ef1ddc9 --- /dev/null +++ b/apps/desktop/src/updateState.ts @@ -0,0 +1,48 @@ +import type { DesktopUpdateState } from "@t3tools/contracts"; + +export function shouldBroadcastDownloadProgress( + currentState: DesktopUpdateState, + nextPercent: number, +): boolean { + if (currentState.status !== "downloading") { + return true; + } + + const currentPercent = currentState.downloadPercent; + if (currentPercent === null) { + return true; + } + + const previousStep = Math.floor(currentPercent / 10); + const nextStep = Math.floor(nextPercent / 10); + return nextStep !== previousStep || nextPercent === 100; +} + +export function nextStatusAfterDownloadFailure( + currentState: DesktopUpdateState, +): DesktopUpdateState["status"] { + return currentState.availableVersion ? "available" : "error"; +} + +export function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean { + return currentState.availableVersion !== null; +} + +export function getAutoUpdateDisabledReason(args: { + isDevelopment: boolean; + isPackaged: boolean; + platform: NodeJS.Platform; + appImage?: string | undefined; + disabledByEnv: boolean; +}): string | null { + if (args.isDevelopment || !args.isPackaged) { + return "Automatic updates are only available in packaged production builds."; + } + if (args.disabledByEnv) { + return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting."; + } + if (args.platform === "linux" && !args.appImage) { + return "Automatic updates on Linux require running the AppImage build."; + } + return null; +} diff --git a/apps/desktop/tsdown.config.ts b/apps/desktop/tsdown.config.ts index 4cffbb2587..f3ebc97325 100644 --- a/apps/desktop/tsdown.config.ts +++ b/apps/desktop/tsdown.config.ts @@ -12,7 +12,7 @@ export default defineConfig([ ...shared, entry: ["src/main.ts"], clean: true, - noExternal: ["@t3tools/contracts"], + noExternal: (id) => id.startsWith("@t3tools/"), }, { ...shared, diff --git a/apps/marketing/astro.config.mjs b/apps/marketing/astro.config.mjs new file mode 100644 index 0000000000..6f37ae922d --- /dev/null +++ b/apps/marketing/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from "astro/config"; + +export default defineConfig({ + server: { + port: Number(process.env.PORT ?? 4173), + }, +}); diff --git a/apps/marketing/package.json b/apps/marketing/package.json new file mode 100644 index 0000000000..1763a00102 --- /dev/null +++ b/apps/marketing/package.json @@ -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": "^6.0.4" + }, + "devDependencies": { + "@astrojs/check": "^0.9.7", + "typescript": "catalog:" + } +} diff --git a/apps/marketing/public/apple-touch-icon.png b/apps/marketing/public/apple-touch-icon.png new file mode 100644 index 0000000000..9c593ce352 Binary files /dev/null and b/apps/marketing/public/apple-touch-icon.png differ diff --git a/apps/marketing/public/favicon-16x16.png b/apps/marketing/public/favicon-16x16.png new file mode 100644 index 0000000000..f85017caf7 Binary files /dev/null and b/apps/marketing/public/favicon-16x16.png differ diff --git a/apps/marketing/public/favicon-32x32.png b/apps/marketing/public/favicon-32x32.png new file mode 100644 index 0000000000..fae2d285b7 Binary files /dev/null and b/apps/marketing/public/favicon-32x32.png differ diff --git a/apps/marketing/public/favicon.ico b/apps/marketing/public/favicon.ico new file mode 100644 index 0000000000..e3ab4ae5e0 Binary files /dev/null and b/apps/marketing/public/favicon.ico differ diff --git a/apps/marketing/public/icon.png b/apps/marketing/public/icon.png new file mode 100644 index 0000000000..0a6e1cbfcf Binary files /dev/null and b/apps/marketing/public/icon.png differ diff --git a/apps/marketing/public/screenshot.jpeg b/apps/marketing/public/screenshot.jpeg new file mode 100644 index 0000000000..0844b50ad5 Binary files /dev/null and b/apps/marketing/public/screenshot.jpeg differ diff --git a/apps/marketing/src/layouts/Layout.astro b/apps/marketing/src/layouts/Layout.astro new file mode 100644 index 0000000000..b4fa945e25 --- /dev/null +++ b/apps/marketing/src/layouts/Layout.astro @@ -0,0 +1,228 @@ +--- +interface Props { + title?: string; + description?: string; +} + +const { + title = "T3 Code", + description = "T3 Code — The best way to code with AI.", +} = Astro.props; +--- + + + + + + + + + + + + + + {title} + + +
+ + +
+ +
+ +
+ © {new Date().getFullYear()} T3 Tools Inc + +
+
+ + + + + + diff --git a/apps/marketing/src/lib/releases.ts b/apps/marketing/src/lib/releases.ts new file mode 100644 index 0000000000..5f3209acf8 --- /dev/null +++ b/apps/marketing/src/lib/releases.ts @@ -0,0 +1,30 @@ +const REPO = "pingdotgg/t3code"; + +export const RELEASES_URL = `https://github.com/${REPO}/releases`; + +const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`; +const CACHE_KEY = "t3code-latest-release"; + +export interface ReleaseAsset { + name: string; + browser_download_url: string; +} + +export interface Release { + tag_name: string; + html_url: string; + assets: ReleaseAsset[]; +} + +export async function fetchLatestRelease(): Promise { + const cached = sessionStorage.getItem(CACHE_KEY); + if (cached) return JSON.parse(cached); + + const data = await fetch(API_URL).then((r) => r.json()); + + if (data?.assets) { + sessionStorage.setItem(CACHE_KEY, JSON.stringify(data)); + } + + return data; +} diff --git a/apps/marketing/src/pages/download.astro b/apps/marketing/src/pages/download.astro new file mode 100644 index 0000000000..0cf31a82e4 --- /dev/null +++ b/apps/marketing/src/pages/download.astro @@ -0,0 +1,271 @@ +--- +import Layout from "../layouts/Layout.astro"; +--- + + +

Download T3 Code

+

+ Loading latest release… + +

+ +
+ +
+
+ +

macOS

+
+ +
+ + +
+
+ +

Windows

+
+ +
+ + +
+
+ +

Linux

+
+ +
+
+ + +
+ + + + diff --git a/apps/marketing/src/pages/index.astro b/apps/marketing/src/pages/index.astro new file mode 100644 index 0000000000..3a2111f4f8 --- /dev/null +++ b/apps/marketing/src/pages/index.astro @@ -0,0 +1,237 @@ +--- +import Layout from "../layouts/Layout.astro"; +--- + + +

T3 Code is the best way to code with AI.

+ + + + + + Download now + + + Other platforms + +
+ T3 Code +
+
+ + + + diff --git a/apps/marketing/tsconfig.json b/apps/marketing/tsconfig.json new file mode 100644 index 0000000000..bcbf8b5090 --- /dev/null +++ b/apps/marketing/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "astro/tsconfigs/strict" +} diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts new file mode 100644 index 0000000000..152ed1d608 --- /dev/null +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -0,0 +1,519 @@ +import { execFileSync } from "node:child_process"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + ApprovalRequestId, + ProviderKind, + type OrchestrationEvent, + type OrchestrationThread, +} from "@t3tools/contracts"; +import { + Effect, + Exit, + FileSystem, + Layer, + ManagedRuntime, + Option, + Path, + Ref, + Schedule, + Schema, + Scope, + Stream, +} from "effect"; + +import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts"; +import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts"; +import { GitCoreLive } from "../src/git/Layers/GitCore.ts"; +import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts"; +import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts"; +import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts"; +import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts"; +import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts"; +import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts"; +import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts"; +import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts"; +import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts"; +import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts"; +import { ProviderUnsupportedError } from "../src/provider/Errors.ts"; +import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts"; +import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts"; +import { ServerSettingsService } from "../src/serverSettings.ts"; +import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts"; +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"; +import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts"; +import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts"; +import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts"; +import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts"; +import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts"; +import { + OrchestrationEngineService, + type OrchestrationEngineShape, +} from "../src/orchestration/Services/OrchestrationEngine.ts"; +import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts"; +import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts"; +import { + RuntimeReceiptBus, + type OrchestrationRuntimeReceipt, +} from "../src/orchestration/Services/RuntimeReceiptBus.ts"; + +import { + makeTestProviderAdapterHarness, + type TestProviderAdapterHarness, +} from "./TestProviderAdapter.integration.ts"; +import { deriveServerPaths, ServerConfig } from "../src/config.ts"; +import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts"; +import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts"; + +function runGit(cwd: string, args: ReadonlyArray) { + return execFileSync("git", args, { + cwd, + stdio: ["ignore", "pipe", "pipe"], + encoding: "utf8", + }); +} + +const initializeGitWorkspace = Effect.fn(function* (cwd: string) { + runGit(cwd, ["init", "--initial-branch=main"]); + runGit(cwd, ["config", "user.email", "test@example.com"]); + runGit(cwd, ["config", "user.name", "Test User"]); + const fileSystem = yield* FileSystem.FileSystem; + const { join } = yield* Path.Path; + yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n"); + runGit(cwd, ["add", "."]); + runGit(cwd, ["commit", "-m", "Initial"]); +}); + +export function gitRefExists(cwd: string, ref: string): boolean { + try { + runGit(cwd, ["show-ref", "--verify", "--quiet", ref]); + return true; + } catch { + return false; + } +} + +export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string { + return runGit(cwd, ["show", `${ref}:${filePath}`]); +} + +class WaitForTimeoutError extends Schema.TaggedErrorClass()( + "WaitForTimeoutError", + { + description: Schema.String, + }, +) {} + +function waitFor( + read: Effect.Effect, + predicate: (value: A) => boolean, + description: string, + timeoutMs?: number, +): Effect.Effect; +function waitFor( + read: Effect.Effect, + predicate: (value: A) => value is B, + description: string, + timeoutMs?: number, +): Effect.Effect; +function waitFor( + read: Effect.Effect, + predicate: (value: A) => boolean, + description: string, + timeoutMs = 40_000, +): Effect.Effect { + const RETRY_SIGNAL = "wait_for_retry"; + const retryIntervalMs = 10; + const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs)); + const retrySchedule = Schedule.spaced(`${retryIntervalMs} millis`); + + return read.pipe( + Effect.filterOrFail(predicate, () => RETRY_SIGNAL), + Effect.retry({ + schedule: retrySchedule, + times: maxRetries, + while: (error) => error === RETRY_SIGNAL, + }), + Effect.mapError((error) => + error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error, + ), + Effect.orDie, + ); +} + +class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass()( + "OrchestrationHarnessRuntimeError", + { + operation: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) {} + +const tryRuntimePromise = (operation: string, run: () => Promise) => + Effect.tryPromise({ + try: run, + catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }), + }); + +export interface OrchestrationIntegrationHarness { + readonly rootDir: string; + readonly workspaceDir: string; + readonly dbPath: string; + readonly adapterHarness: TestProviderAdapterHarness | null; + readonly engine: OrchestrationEngineShape; + readonly snapshotQuery: ProjectionSnapshotQuery["Service"]; + readonly providerService: ProviderService["Service"]; + readonly checkpointStore: CheckpointStore["Service"]; + readonly checkpointRepository: ProjectionCheckpointRepository["Service"]; + readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"]; + readonly waitForThread: ( + threadId: string, + predicate: (thread: OrchestrationThread) => boolean, + timeoutMs?: number, + ) => Effect.Effect; + readonly waitForDomainEvent: ( + predicate: (event: OrchestrationEvent) => boolean, + timeoutMs?: number, + ) => Effect.Effect, never>; + readonly waitForPendingApproval: ( + requestId: string, + predicate: (row: { + readonly status: "pending" | "resolved"; + readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null; + readonly resolvedAt: string | null; + }) => boolean, + timeoutMs?: number, + ) => Effect.Effect< + { + readonly status: "pending" | "resolved"; + readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null; + readonly resolvedAt: string | null; + }, + never + >; + readonly waitForReceipt: { + ( + predicate: (receipt: OrchestrationRuntimeReceipt) => boolean, + timeoutMs?: number, + ): Effect.Effect; + ( + predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt, + timeoutMs?: number, + ): Effect.Effect; + }; + readonly dispose: Effect.Effect; +} + +interface MakeOrchestrationIntegrationHarnessOptions { + readonly provider?: ProviderKind; + readonly realCodex?: boolean; +} + +export const makeOrchestrationIntegrationHarness = ( + options?: MakeOrchestrationIntegrationHarnessOptions, +) => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + + const provider = options?.provider ?? "codex"; + const useRealCodex = options?.realCodex === true; + const adapterHarness = useRealCodex + ? null + : yield* makeTestProviderAdapterHarness({ + provider, + }); + const fakeRegistry = adapterHarness + ? Layer.succeed(ProviderAdapterRegistry, { + getByProvider: (resolvedProvider) => + resolvedProvider === adapterHarness.provider + ? Effect.succeed(adapterHarness.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })), + listProviders: () => Effect.succeed([adapterHarness.provider]), + } as typeof ProviderAdapterRegistry.Service) + : null; + const rootDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-orchestration-integration-", + }); + const workspaceDir = path.join(rootDir, "workspace"); + const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe( + Effect.provideService(Path.Path, path), + ); + yield* fileSystem.makeDirectory(workspaceDir, { recursive: true }); + yield* fileSystem.makeDirectory(stateDir, { recursive: true }); + yield* initializeGitWorkspace(workspaceDir); + + const persistenceLayer = makeSqlitePersistenceLive(dbPath); + const orchestrationLayer = OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionPipelineLive), + Layer.provide(OrchestrationEventStoreLive), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + ); + const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(ProviderSessionRuntimeRepositoryLive), + ); + const realCodexRegistry = Layer.effect( + ProviderAdapterRegistry, + Effect.gen(function* () { + const codexAdapter = yield* CodexAdapter; + return { + getByProvider: (resolvedProvider) => + resolvedProvider === "codex" + ? Effect.succeed(codexAdapter) + : Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })), + listProviders: () => Effect.succeed(["codex"] as const), + } as typeof ProviderAdapterRegistry.Service; + }), + ).pipe( + Layer.provide(makeCodexAdapterLive()), + Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)), + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(providerSessionDirectoryLayer), + ); + const providerLayer = useRealCodex + ? 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 checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive)); + const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive; + const runtimeServicesLayer = Layer.mergeAll( + projectionSnapshotQueryLayer, + orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)), + ProjectionCheckpointRepositoryLive, + ProjectionPendingApprovalRepositoryLive, + checkpointStoreLayer, + providerLayer, + RuntimeReceiptBusLive, + ); + const serverSettingsLayer = ServerSettingsService.layerTest(); + const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe( + Layer.provideMerge(runtimeServicesLayer), + Layer.provideMerge(serverSettingsLayer), + ); + const gitCoreLayer = Layer.succeed(GitCore, { + renameBranch: (input: Parameters[0]) => + Effect.succeed({ branch: input.newBranch }), + } as unknown as GitCoreShape); + const textGenerationLayer = Layer.succeed(TextGeneration, { + generateBranchName: () => Effect.succeed({ branch: "update" }), + generateThreadTitle: () => Effect.succeed({ title: "New thread" }), + } as unknown as TextGenerationShape); + const providerCommandReactorLayer = ProviderCommandReactorLive.pipe( + Layer.provideMerge(runtimeServicesLayer), + Layer.provideMerge(gitCoreLayer), + Layer.provideMerge(textGenerationLayer), + Layer.provideMerge(serverSettingsLayer), + ); + const checkpointReactorLayer = CheckpointReactorLive.pipe( + Layer.provideMerge(runtimeServicesLayer), + Layer.provideMerge( + WorkspaceEntriesLive.pipe( + Layer.provide(WorkspacePathsLive), + Layer.provideMerge(gitCoreLayer), + Layer.provide(NodeServices.layer), + ), + ), + Layer.provideMerge(WorkspacePathsLive), + ); + const orchestrationReactorLayer = OrchestrationReactorLive.pipe( + Layer.provideMerge(runtimeIngestionLayer), + Layer.provideMerge(providerCommandReactorLayer), + Layer.provideMerge(checkpointReactorLayer), + ); + const layer = Layer.empty.pipe( + Layer.provideMerge(runtimeServicesLayer), + Layer.provideMerge(orchestrationReactorLayer), + Layer.provide(persistenceLayer), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)), + Layer.provideMerge(NodeServices.layer), + ); + + const runtime = ManagedRuntime.make(layer); + const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () => + runtime.runPromise(Effect.service(OrchestrationEngineService)), + ).pipe(Effect.orDie); + const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () => + runtime.runPromise(Effect.service(OrchestrationReactor)), + ).pipe(Effect.orDie); + const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () => + runtime.runPromise(Effect.service(ProjectionSnapshotQuery)), + ).pipe(Effect.orDie); + const providerService = yield* tryRuntimePromise("load ProviderService service", () => + runtime.runPromise(Effect.service(ProviderService)), + ).pipe(Effect.orDie); + const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () => + runtime.runPromise(Effect.service(CheckpointStore)), + ).pipe(Effect.orDie); + const checkpointRepository = yield* tryRuntimePromise( + "load ProjectionCheckpointRepository service", + () => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)), + ).pipe(Effect.orDie); + const pendingApprovalRepository = yield* tryRuntimePromise( + "load ProjectionPendingApprovalRepository service", + () => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)), + ).pipe(Effect.orDie); + const runtimeReceiptBus = yield* tryRuntimePromise("load RuntimeReceiptBus service", () => + runtime.runPromise(Effect.service(RuntimeReceiptBus)), + ).pipe(Effect.orDie); + + const scope = yield* Scope.make("sequential"); + yield* tryRuntimePromise("start OrchestrationReactor", () => + runtime.runPromise(reactor.start().pipe(Scope.provide(scope))), + ).pipe(Effect.orDie); + const receiptHistory = yield* Ref.make>([]); + yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) => + Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid), + ).pipe(Effect.forkIn(scope)); + yield* Effect.sleep(10); + + const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = ( + threadId, + predicate, + timeoutMs, + ) => + waitFor( + snapshotQuery + .getSnapshot() + .pipe( + Effect.map( + (snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null, + ), + ), + (thread): thread is OrchestrationThread => thread !== null && predicate(thread), + `projected thread '${threadId}'`, + timeoutMs, + ) as Effect.Effect; + + const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = ( + predicate, + timeoutMs, + ) => + waitFor( + Stream.runCollect(engine.readEvents(0)).pipe( + Effect.map((chunk): ReadonlyArray => Array.from(chunk)), + ), + (events) => events.some(predicate), + "domain event", + timeoutMs, + ); + + const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = ( + requestId, + predicate, + timeoutMs, + ) => + waitFor( + pendingApprovalRepository + .getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) }) + .pipe( + Effect.map((row) => + Option.match(row, { + onNone: () => null, + onSome: (value) => ({ + status: value.status, + decision: value.decision, + resolvedAt: value.resolvedAt, + }), + }), + ), + ), + ( + row, + ): row is { + readonly status: "pending" | "resolved"; + readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null; + readonly resolvedAt: string | null; + } => row !== null && predicate(row), + `pending approval '${requestId}'`, + timeoutMs, + ) as Effect.Effect< + { + readonly status: "pending" | "resolved"; + readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null; + readonly resolvedAt: string | null; + }, + never + >; + + function waitForReceipt( + predicate: (receipt: OrchestrationRuntimeReceipt) => boolean, + timeoutMs?: number, + ): Effect.Effect; + function waitForReceipt( + predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt, + timeoutMs?: number, + ): Effect.Effect; + function waitForReceipt( + predicate: (receipt: OrchestrationRuntimeReceipt) => boolean, + timeoutMs?: number, + ) { + const readMatchingReceipt = Ref.get(receiptHistory).pipe( + Effect.map((history) => history.find(predicate)), + ); + + return waitFor( + readMatchingReceipt, + (receipt): receipt is OrchestrationRuntimeReceipt => receipt !== undefined, + "runtime receipt", + timeoutMs, + ); + } + + let disposed = false; + const dispose = Effect.gen(function* () { + if (disposed) { + return; + } + disposed = true; + + const shutdown = Effect.gen(function* () { + const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void)); + const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose())); + + const failureCause = Exit.isFailure(closeScopeExit) + ? closeScopeExit.cause + : Exit.isFailure(disposeRuntimeExit) + ? disposeRuntimeExit.cause + : null; + + if (failureCause) { + return yield* Effect.failCause(failureCause); + } + }); + + yield* shutdown; + }); + + return { + rootDir, + workspaceDir, + dbPath, + adapterHarness, + engine, + snapshotQuery, + providerService, + checkpointStore, + checkpointRepository, + pendingApprovalRepository, + waitForThread, + waitForDomainEvent, + waitForPendingApproval, + waitForReceipt, + dispose, + } satisfies OrchestrationIntegrationHarness; + }); diff --git a/apps/server/integration/TestProviderAdapter.integration.ts b/apps/server/integration/TestProviderAdapter.integration.ts new file mode 100644 index 0000000000..9c87d9821a --- /dev/null +++ b/apps/server/integration/TestProviderAdapter.integration.ts @@ -0,0 +1,561 @@ +import { randomUUID } from "node:crypto"; + +import { + ApprovalRequestId, + EventId, + ProviderApprovalDecision, + ProviderRuntimeEvent, + RuntimeSessionId, + ProviderSession, + ProviderTurnStartResult, + ThreadId, + TurnId, + ProviderKind, +} from "@t3tools/contracts"; +import { Effect, Queue, Stream } from "effect"; + +import { + ProviderAdapterSessionNotFoundError, + ProviderAdapterValidationError, + type ProviderAdapterError, +} from "../src/provider/Errors.ts"; +import type { + ProviderAdapterShape, + ProviderThreadSnapshot, + ProviderThreadTurnSnapshot, +} from "../src/provider/Services/ProviderAdapter.ts"; + +export interface TestTurnResponse { + readonly events: ReadonlyArray; + readonly mutateWorkspace?: (input: { + readonly cwd: string; + readonly turnCount: number; + }) => Effect.Effect; +} + +export type FixtureProviderRuntimeEvent = { + readonly type: string; + readonly eventId: EventId; + readonly provider: ProviderKind; + readonly createdAt: string; + readonly threadId: string; + readonly turnId?: string | undefined; + readonly itemId?: string | undefined; + readonly requestId?: string | undefined; + readonly payload?: unknown | undefined; + readonly [key: string]: unknown; +}; + +// Temporary alias while fixtures migrate to the new name. +export type LegacyProviderRuntimeEvent = FixtureProviderRuntimeEvent; + +interface SessionState { + readonly session: ProviderSession; + snapshot: ProviderThreadSnapshot; + turnCount: number; + readonly queuedResponses: Array; + readonly rollbackCalls: Array; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupted" | "cancelled" { + if ( + value === "completed" || + value === "failed" || + value === "interrupted" || + value === "cancelled" + ) { + return value; + } + return "completed"; +} + +function mapRequestType( + requestKind: unknown, +): "command_execution_approval" | "file_change_approval" | "unknown" { + if (requestKind === "command") { + return "command_execution_approval"; + } + if (requestKind === "file-change") { + return "file_change_approval"; + } + return "unknown"; +} + +function mapItemType(toolKind: unknown): "command_execution" | "file_change" | "unknown" { + if (toolKind === "command") { + return "command_execution"; + } + if (toolKind === "file-change") { + return "file_change"; + } + return "unknown"; +} + +function normalizeFixtureEvent(rawEvent: Record): ProviderRuntimeEvent { + const type = typeof rawEvent.type === "string" ? rawEvent.type : ""; + switch (type) { + case "turn.started": + return { + ...rawEvent, + type: "turn.started", + payload: isRecord(rawEvent.payload) ? rawEvent.payload : {}, + } as ProviderRuntimeEvent; + case "turn.completed": + return { + ...rawEvent, + type: "turn.completed", + payload: isRecord(rawEvent.payload) + ? rawEvent.payload + : { + state: normalizeTurnState(rawEvent.status), + }, + } as ProviderRuntimeEvent; + case "message.delta": + return { + ...rawEvent, + type: "content.delta", + payload: { + streamKind: "assistant_text", + delta: typeof rawEvent.delta === "string" ? rawEvent.delta : "", + }, + } as ProviderRuntimeEvent; + case "message.completed": + return { + ...rawEvent, + type: "item.completed", + payload: { + itemType: "assistant_message", + ...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}), + }, + } as ProviderRuntimeEvent; + case "tool.started": + return { + ...rawEvent, + type: "item.started", + payload: { + itemType: mapItemType(rawEvent.toolKind), + ...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}), + ...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}), + }, + } as ProviderRuntimeEvent; + case "tool.completed": + return { + ...rawEvent, + type: "item.completed", + payload: { + itemType: mapItemType(rawEvent.toolKind), + status: "completed", + ...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}), + ...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}), + }, + } as ProviderRuntimeEvent; + case "approval.requested": + return { + ...rawEvent, + type: "request.opened", + payload: { + requestType: mapRequestType(rawEvent.requestKind), + ...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}), + }, + } as ProviderRuntimeEvent; + case "approval.resolved": + return { + ...rawEvent, + type: "request.resolved", + payload: { + requestType: mapRequestType(rawEvent.requestKind), + ...(typeof rawEvent.decision === "string" ? { decision: rawEvent.decision } : {}), + }, + } as ProviderRuntimeEvent; + default: + return rawEvent as ProviderRuntimeEvent; + } +} + +export interface TestProviderAdapterHarness { + readonly adapter: ProviderAdapterShape; + readonly provider: ProviderKind; + readonly queueTurnResponse: ( + threadId: ThreadId, + response: TestTurnResponse, + ) => Effect.Effect; + readonly queueTurnResponseForNextSession: ( + response: TestTurnResponse, + ) => Effect.Effect; + readonly getStartCount: () => number; + readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray; + readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray; + readonly listActiveSessionIds: () => ReadonlyArray; + readonly getApprovalResponses: (threadId: ThreadId) => ReadonlyArray<{ + readonly threadId: ThreadId; + readonly requestId: ApprovalRequestId; + readonly decision: ProviderApprovalDecision; + }>; +} + +interface MakeTestProviderAdapterHarnessOptions { + readonly provider?: ProviderKind; +} + +function nowIso(): string { + return new Date().toISOString(); +} + +function sessionNotFound( + provider: ProviderKind, + threadId: ThreadId, +): ProviderAdapterSessionNotFoundError { + return new ProviderAdapterSessionNotFoundError({ + provider, + threadId: String(threadId), + }); +} + +function missingSessionEffect( + provider: ProviderKind, + threadId: ThreadId, +): Effect.Effect { + return Effect.fail(sessionNotFound(provider, threadId)); +} + +export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) => + Effect.gen(function* () { + const provider = options?.provider ?? "codex"; + const runtimeEvents = yield* Queue.unbounded(); + let sessionCount = 0; + const sessions = new Map(); + const queuedResponsesForNextSession: TestTurnResponse[] = []; + const interruptCallsBySession = new Map>(); + const approvalResponsesBySession = new Map< + ThreadId, + Array<{ + readonly threadId: ThreadId; + readonly requestId: ApprovalRequestId; + readonly decision: ProviderApprovalDecision; + }> + >(); + + const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event); + + const startSession: ProviderAdapterShape["startSession"] = (input) => + Effect.gen(function* () { + if (input.provider !== undefined && input.provider !== provider) { + return yield* new ProviderAdapterValidationError({ + provider, + operation: "startSession", + issue: `Expected provider '${provider}' but received '${input.provider}'.`, + }); + } + + sessionCount += 1; + const threadId = input.threadId; + const createdAt = nowIso(); + + const session: ProviderSession = { + provider, + status: "ready", + runtimeMode: input.runtimeMode, + threadId, + cwd: input.cwd, + resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount }, + createdAt, + updatedAt: createdAt, + }; + + sessions.set(threadId, { + session, + snapshot: { + threadId, + turns: [], + }, + turnCount: 0, + queuedResponses: queuedResponsesForNextSession.splice(0), + rollbackCalls: [], + }); + + return session; + }); + + const sendTurn: ProviderAdapterShape["sendTurn"] = (input) => + Effect.gen(function* () { + const state = sessions.get(input.threadId); + if (!state) { + return yield* missingSessionEffect(provider, input.threadId); + } + + state.turnCount += 1; + const turnCount = state.turnCount; + const turnId = TurnId.makeUnsafe(`turn-${turnCount}`); + + const response = state.queuedResponses.shift(); + if (!response) { + return yield* new ProviderAdapterValidationError({ + provider, + operation: "sendTurn", + issue: `No queued turn response for thread ${input.threadId}.`, + }); + } + + const assistantDeltas: string[] = []; + const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = []; + for (const fixtureEvent of response.events) { + const rawEvent: Record = { + ...(fixtureEvent as Record), + eventId: randomUUID(), + provider, + sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)), + createdAt: nowIso(), + }; + rawEvent.threadId = state.snapshot.threadId; + if (Object.hasOwn(rawEvent, "turnId")) { + rawEvent.turnId = turnId; + } + + const runtimeEvent = normalizeFixtureEvent(rawEvent); + const runtimeType = (runtimeEvent as { type: string }).type; + if (runtimeType === "content.delta") { + const payload = runtimeEvent.payload as { delta?: unknown } | undefined; + if (typeof payload?.delta === "string") { + assistantDeltas.push(payload.delta); + } + } else if (runtimeType === "message.delta") { + const legacyDelta = (runtimeEvent as { delta?: unknown }).delta; + if (typeof legacyDelta === "string") { + assistantDeltas.push(legacyDelta); + } + } + if (runtimeEvent.type === "turn.completed") { + deferredTurnCompletedEvents.push(runtimeEvent); + continue; + } + + yield* emit(runtimeEvent); + } + + if (response.mutateWorkspace && state.session.cwd) { + yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount }); + } + + const userItem = { + type: "userMessage", + content: [{ type: "text", text: input.input }], + } as const; + const assistantText = assistantDeltas.join(""); + const nextItems: Array = + assistantText.length > 0 + ? [userItem, { type: "agentMessage", text: assistantText }] + : [userItem]; + + const nextTurn: ProviderThreadTurnSnapshot = { + id: turnId, + items: nextItems, + }; + + state.snapshot = { + threadId: state.snapshot.threadId, + turns: [...state.snapshot.turns, nextTurn], + }; + + if (deferredTurnCompletedEvents.length === 0) { + yield* emit({ + type: "turn.completed", + eventId: EventId.makeUnsafe(randomUUID()), + provider, + createdAt: nowIso(), + threadId: state.snapshot.threadId, + turnId, + payload: { + state: "completed", + }, + }); + } else { + for (const completedEvent of deferredTurnCompletedEvents) { + yield* emit(completedEvent); + } + } + + return { + threadId: state.snapshot.threadId, + turnId, + } satisfies ProviderTurnStartResult; + }); + + const interruptTurn: ProviderAdapterShape["interruptTurn"] = ( + threadId, + turnId, + ) => + sessions.has(threadId) + ? Effect.sync(() => { + const existing = interruptCallsBySession.get(threadId) ?? []; + existing.push(turnId); + interruptCallsBySession.set(threadId, existing); + }) + : missingSessionEffect(provider, threadId); + + const respondToRequest: ProviderAdapterShape["respondToRequest"] = ( + threadId, + requestId, + decision, + ) => + sessions.has(threadId) + ? Effect.sync(() => { + const existing = approvalResponsesBySession.get(threadId) ?? []; + existing.push({ + threadId, + requestId, + decision, + }); + approvalResponsesBySession.set(threadId, existing); + }) + : missingSessionEffect(provider, threadId); + + const respondToUserInput: ProviderAdapterShape["respondToUserInput"] = ( + threadId, + _requestId, + _answers, + ) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId)); + + const stopSession: ProviderAdapterShape["stopSession"] = (threadId) => + Effect.sync(() => { + sessions.delete(threadId); + }); + + const listSessions: ProviderAdapterShape["listSessions"] = () => + Effect.sync(() => Array.from(sessions.values(), (state) => state.session)); + + const hasSession: ProviderAdapterShape["hasSession"] = (threadId) => + Effect.succeed(sessions.has(threadId)); + + const readThread: ProviderAdapterShape["readThread"] = (threadId) => { + const state = sessions.get(threadId); + if (!state) { + return missingSessionEffect(provider, threadId); + } + return Effect.succeed(state.snapshot); + }; + + const rollbackThread: ProviderAdapterShape["rollbackThread"] = ( + threadId, + numTurns, + ) => { + const state = sessions.get(threadId); + if (!state) { + return missingSessionEffect(provider, threadId); + } + if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) { + return Effect.fail( + new ProviderAdapterValidationError({ + provider, + operation: "rollbackThread", + issue: "numTurns must be an integer between 0 and current turn count.", + }), + ); + } + + return Effect.sync(() => { + state.rollbackCalls.push(numTurns); + state.snapshot = { + threadId: state.snapshot.threadId, + turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns), + }; + state.turnCount = state.snapshot.turns.length; + return state.snapshot; + }); + }; + + const stopAll: ProviderAdapterShape["stopAll"] = () => + Effect.sync(() => { + sessions.clear(); + }); + + const adapter: ProviderAdapterShape = { + provider, + capabilities: { + sessionModelSwitch: "in-session", + }, + startSession, + sendTurn, + interruptTurn, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + hasSession, + readThread, + rollbackThread, + stopAll, + streamEvents: Stream.fromQueue(runtimeEvents), + }; + + const queueTurnResponse = ( + threadId: ThreadId, + response: TestTurnResponse, + ): Effect.Effect => + Effect.sync(() => sessions.get(threadId)).pipe( + Effect.flatMap((state) => + state + ? Effect.sync(() => { + state.queuedResponses.push(response); + }) + : Effect.fail(sessionNotFound(provider, threadId)), + ), + ); + + const queueTurnResponseForNextSession = ( + response: TestTurnResponse, + ): Effect.Effect => + Effect.sync(() => { + queuedResponsesForNextSession.push(response); + }); + + const getRollbackCalls = (threadId: ThreadId): ReadonlyArray => { + const state = sessions.get(threadId); + if (!state) { + return []; + } + return [...state.rollbackCalls]; + }; + + const getStartCount = (): number => sessionCount; + + const getInterruptCalls = (threadId: ThreadId): ReadonlyArray => { + const calls = interruptCallsBySession.get(threadId); + if (!calls) { + return []; + } + return [...calls]; + }; + + const listActiveSessionIds = (): ReadonlyArray => + Array.from(sessions.values(), (state) => state.session.threadId); + + const getApprovalResponses = ( + threadId: ThreadId, + ): ReadonlyArray<{ + readonly threadId: ThreadId; + readonly requestId: ApprovalRequestId; + readonly decision: ProviderApprovalDecision; + }> => { + const responses = approvalResponsesBySession.get(threadId); + if (!responses) { + return []; + } + return [...responses]; + }; + + return { + adapter, + provider, + queueTurnResponse, + queueTurnResponseForNextSession, + getStartCount, + getRollbackCalls, + getInterruptCalls, + listActiveSessionIds, + getApprovalResponses, + } satisfies TestProviderAdapterHarness; + }); diff --git a/apps/server/integration/fixtures/providerRuntime.ts b/apps/server/integration/fixtures/providerRuntime.ts new file mode 100644 index 0000000000..42e7ecd87d --- /dev/null +++ b/apps/server/integration/fixtures/providerRuntime.ts @@ -0,0 +1,162 @@ +import { EventId, RuntimeRequestId } from "@t3tools/contracts"; +import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts"; + +const PROVIDER = "codex" as const; +const SESSION_ID = "fixture-session"; +const THREAD_ID = "fixture-thread"; +const TURN_ID = "fixture-turn"; +const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1"); + +function baseEvent( + eventId: string, + createdAt: string, +): Pick { + return { + eventId: EventId.makeUnsafe(eventId), + provider: PROVIDER, + sessionId: SESSION_ID, + createdAt, + }; +} + +export const codexTurnTextFixture = [ + { + type: "turn.started", + ...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: {}, + }, + { + type: "content.delta", + ...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: { + streamKind: "assistant_text", + delta: "I will make a small update.\n", + }, + }, + { + type: "content.delta", + ...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: { + streamKind: "assistant_text", + delta: "Done.\n", + }, + }, + { + type: "turn.completed", + ...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: { + state: "completed", + }, + }, +] satisfies ReadonlyArray; + +export const codexTurnToolFixture = [ + { + type: "turn.started", + ...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: {}, + }, + { + type: "item.started", + ...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: { + itemType: "command_execution", + title: "Ran command", + detail: "echo integration", + }, + }, + { + type: "item.completed", + ...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: { + itemType: "command_execution", + status: "completed", + title: "Ran command", + detail: "echo integration", + }, + }, + { + type: "content.delta", + ...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: { + streamKind: "assistant_text", + delta: "Applied the requested edit.\n", + }, + }, + { + type: "turn.completed", + ...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: { + state: "completed", + }, + }, +] satisfies ReadonlyArray; + +export const codexTurnApprovalFixture = [ + { + type: "turn.started", + ...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: {}, + }, + { + type: "request.opened", + ...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + requestId: REQUEST_ID, + payload: { + requestType: "command_execution_approval", + detail: "Please approve command", + }, + }, + { + type: "request.resolved", + ...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + requestId: REQUEST_ID, + payload: { + requestType: "command_execution_approval", + decision: "accept", + }, + }, + { + type: "content.delta", + ...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: { + streamKind: "assistant_text", + delta: "Approval received and command executed.\n", + }, + }, + { + type: "turn.completed", + ...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"), + threadId: THREAD_ID, + turnId: TURN_ID, + payload: { + state: "completed", + }, + }, +] satisfies ReadonlyArray; diff --git a/apps/server/integration/orchestrationEngine.integration.test.ts b/apps/server/integration/orchestrationEngine.integration.test.ts new file mode 100644 index 0000000000..a5cc8f8cc6 --- /dev/null +++ b/apps/server/integration/orchestrationEngine.integration.test.ts @@ -0,0 +1,1336 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { + ApprovalRequestId, + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + DEFAULT_MODEL_BY_PROVIDER, + EventId, + MessageId, + ProjectId, + ProviderKind, + ThreadId, + ModelSelection, +} from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import { Effect, Option, Schema } from "effect"; + +import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts"; +import { + gitRefExists, + gitShowFileAtRef, + makeOrchestrationIntegrationHarness, + type OrchestrationIntegrationHarness, +} from "./OrchestrationEngineHarness.integration.ts"; +import { checkpointRefForThreadTurn } from "../src/checkpointing/Utils.ts"; +import type { + CheckpointDiffFinalizedReceipt, + TurnProcessingQuiescedReceipt, +} from "../src/orchestration/Services/RuntimeReceiptBus.ts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; + +const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); +const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); +const asEventId = (value: string): EventId => EventId.makeUnsafe(value); +const asApprovalRequestId = (value: string): ApprovalRequestId => + ApprovalRequestId.makeUnsafe(value); + +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 = ProviderKind; + +function nowIso() { + return new Date().toISOString(); +} + +class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass()( + "IntegrationWaitTimeoutError", + { + description: Schema.String, + }, +) {} + +function waitForSync( + read: () => A, + predicate: (value: A) => boolean, + description: string, + timeoutMs = 10_000, +): Effect.Effect { + return Effect.gen(function* () { + const deadline = Date.now() + timeoutMs; + + while (true) { + const value = read(); + if (predicate(value)) { + return value; + } + if (Date.now() >= deadline) { + return yield* Effect.die(new IntegrationWaitTimeoutError({ description })); + } + yield* Effect.sleep(10); + } + }); +} + +function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") { + return { + eventId: asEventId(eventId), + provider, + createdAt, + }; +} + +function withHarness( + use: (harness: OrchestrationIntegrationHarness) => Effect.Effect, + provider: IntegrationProvider = "codex", +) { + return Effect.acquireUseRelease( + makeOrchestrationIntegrationHarness({ provider }), + use, + (harness) => harness.dispose, + ).pipe(Effect.provide(NodeServices.layer)); +} + +function withRealCodexHarness( + use: (harness: OrchestrationIntegrationHarness) => Effect.Effect, +) { + return Effect.acquireUseRelease( + makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }), + use, + (harness) => harness.dispose, + ).pipe(Effect.provide(NodeServices.layer)); +} + +const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => + Effect.gen(function* () { + const createdAt = nowIso(); + const provider = harness.adapterHarness?.provider ?? "codex"; + const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider]; + + yield* harness.engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-create"), + projectId: PROJECT_ID, + title: "Integration Project", + workspaceRoot: harness.workspaceDir, + defaultModelSelection: { + provider, + model: defaultModel, + }, + createdAt, + }); + + yield* harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-create"), + threadId: THREAD_ID, + projectId: PROJECT_ID, + title: "Integration Thread", + modelSelection: { + provider, + model: defaultModel, + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: harness.workspaceDir, + createdAt, + }); + }); + +const startTurn = (input: { + readonly harness: OrchestrationIntegrationHarness; + readonly commandId: string; + readonly messageId: string; + readonly text: string; + readonly modelSelection?: ModelSelection; +}) => + input.harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe(input.commandId), + threadId: THREAD_ID, + message: { + messageId: asMessageId(input.messageId), + role: "user", + text: input.text, + attachments: [], + }, + ...(input.modelSelection !== undefined + ? { + modelSelection: input.modelSelection, + } + : {}), + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: nowIso(), + }); + +it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () => + withHarness((harness) => + Effect.gen(function* () { + yield* seedProjectAndThread(harness); + + const turnResponse: TestTurnResponse = { + events: [ + { + type: "turn.started", + ...runtimeBase("evt-single-1", "2026-02-24T10:00:00.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-single-2", "2026-02-24T10:00:00.100Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + delta: "Single turn response.\n", + }, + { + type: "turn.completed", + ...runtimeBase("evt-single-3", "2026-02-24T10:00:00.200Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + status: "completed", + }, + ], + }; + + yield* harness.adapterHarness!.queueTurnResponseForNextSession(turnResponse); + yield* startTurn({ + harness, + commandId: "cmd-turn-start-single", + messageId: "msg-user-single", + text: "Say hello", + }); + const finalizedReceipt = yield* harness.waitForReceipt( + (receipt): receipt is CheckpointDiffFinalizedReceipt => + receipt.type === "checkpoint.diff.finalized" && + receipt.threadId === THREAD_ID && + receipt.checkpointTurnCount === 1, + ); + if (finalizedReceipt.type !== "checkpoint.diff.finalized") { + throw new Error("Expected checkpoint.diff.finalized receipt."); + } + assert.equal(finalizedReceipt.status, "ready"); + yield* harness.waitForReceipt( + (receipt): receipt is TurnProcessingQuiescedReceipt => + receipt.type === "turn.processing.quiesced" && + receipt.threadId === THREAD_ID && + receipt.checkpointTurnCount === 1, + ); + + const thread = yield* harness.waitForThread( + THREAD_ID, + (entry) => + entry.session?.status === "ready" && + entry.messages.some( + (message) => message.role === "assistant" && message.streaming === false, + ) && + entry.checkpoints.length === 1, + ); + assert.equal(thread.checkpoints[0]?.status, "ready"); + assert.equal(thread.checkpoints[0]?.checkpointTurnCount, 1); + + const checkpointRows = yield* harness.checkpointRepository.listByThreadId({ + threadId: THREAD_ID, + }); + assert.equal(checkpointRows.length, 1); + assert.equal(checkpointRows[0]?.checkpointTurnCount, 1); + assert.equal(checkpointRows[0]?.status, "ready"); + assert.deepEqual(checkpointRows[0]?.files, []); + + const ref0 = checkpointRefForThreadTurn(THREAD_ID, 0); + const ref1 = checkpointRefForThreadTurn(THREAD_ID, 1); + assert.equal(gitRefExists(harness.workspaceDir, ref0), true); + assert.equal(gitRefExists(harness.workspaceDir, ref1), true); + assert.equal(gitShowFileAtRef(harness.workspaceDir, ref0, "README.md"), "v1\n"); + assert.equal(gitShowFileAtRef(harness.workspaceDir, ref1, "README.md"), "v1\n"); + }), + ), +); + +it.live.skipIf(!process.env.CODEX_BINARY_PATH)( + "keeps the same Codex provider thread across runtime mode switches", + () => + withRealCodexHarness((harness) => + Effect.gen(function* () { + const createdAt = nowIso(); + + yield* harness.engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"), + projectId: PROJECT_ID, + title: "Integration Project", + workspaceRoot: harness.workspaceDir, + defaultModelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + }, + createdAt, + }); + + yield* harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"), + threadId: THREAD_ID, + projectId: PROJECT_ID, + title: "Integration Thread", + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: harness.workspaceDir, + createdAt, + }); + + yield* harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"), + threadId: THREAD_ID, + message: { + messageId: asMessageId("msg-real-codex-1"), + role: "user", + text: "Reply with exactly ALPHA.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + createdAt: nowIso(), + }); + + const firstThread = yield* harness.waitForThread( + THREAD_ID, + (entry) => + entry.session?.status === "ready" && + entry.session.providerName === "codex" && + entry.messages.some( + (message) => message.role === "assistant" && message.streaming === false, + ), + 180_000, + ); + assert.equal(firstThread.session?.threadId, "thread-1"); + + yield* harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"), + threadId: THREAD_ID, + message: { + messageId: asMessageId("msg-real-codex-2"), + role: "user", + text: "Reply with exactly BETA.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: nowIso(), + }); + + const secondThread = yield* harness.waitForThread( + THREAD_ID, + (entry) => + entry.session?.status === "ready" && + entry.session.providerName === "codex" && + entry.session.runtimeMode === "approval-required" && + entry.messages.some( + (message) => message.role === "assistant" && message.text.includes("BETA"), + ), + 180_000, + ); + assert.equal(secondThread.session?.threadId, "thread-1"); + }), + ), +); + +it.live("runs multi-turn file edits and persists checkpoint diffs", () => + withHarness((harness) => + Effect.gen(function* () { + yield* seedProjectAndThread(harness); + + yield* harness.adapterHarness!.queueTurnResponseForNextSession({ + events: [ + { + type: "turn.started", + ...runtimeBase("evt-multi-1", "2026-02-24T10:01:00.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "tool.started", + ...runtimeBase("evt-multi-2", "2026-02-24T10:01:00.100Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + toolKind: "command", + title: "Edit file", + detail: "README.md", + }, + { + type: "tool.completed", + ...runtimeBase("evt-multi-3", "2026-02-24T10:01:00.200Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + toolKind: "command", + title: "Edit file", + detail: "README.md", + }, + { + type: "message.delta", + ...runtimeBase("evt-multi-4", "2026-02-24T10:01:00.300Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + delta: "Updated README to v2.\n", + }, + { + type: "turn.completed", + ...runtimeBase("evt-multi-5", "2026-02-24T10:01:00.400Z"), + 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-multi-1", + messageId: "msg-user-multi-1", + text: "Make first edit", + }); + yield* harness.waitForReceipt( + (receipt): receipt is CheckpointDiffFinalizedReceipt => + receipt.type === "checkpoint.diff.finalized" && + receipt.threadId === THREAD_ID && + receipt.checkpointTurnCount === 1, + ); + + yield* harness.waitForThread( + THREAD_ID, + (entry) => entry.checkpoints.length === 1 && entry.session?.threadId === "thread-1", + ); + + yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, { + events: [ + { + type: "turn.started", + ...runtimeBase("evt-multi-6", "2026-02-24T10:02:00.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-multi-7", "2026-02-24T10:02:00.100Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + delta: "Updated README to v3.\n", + }, + { + type: "turn.completed", + ...runtimeBase("evt-multi-8", "2026-02-24T10:02:00.200Z"), + 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-multi-2", + messageId: "msg-user-multi-2", + text: "Make second edit", + }); + const secondReceipt = yield* harness.waitForReceipt( + (receipt): receipt is CheckpointDiffFinalizedReceipt => + receipt.type === "checkpoint.diff.finalized" && + receipt.threadId === THREAD_ID && + receipt.checkpointTurnCount === 2, + ); + if (secondReceipt.type !== "checkpoint.diff.finalized") { + throw new Error("Expected checkpoint.diff.finalized receipt."); + } + assert.equal(secondReceipt.status, "ready"); + yield* harness.waitForReceipt( + (receipt): receipt is TurnProcessingQuiescedReceipt => + receipt.type === "turn.processing.quiesced" && + receipt.threadId === THREAD_ID && + receipt.checkpointTurnCount === 2, + ); + + const secondTurnThread = yield* harness.waitForThread( + THREAD_ID, + (entry) => + entry.latestTurn?.turnId === "turn-2" && + entry.checkpoints.length === 2 && + entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2), + ); + const secondCheckpoint = secondTurnThread.checkpoints.find( + (checkpoint) => checkpoint.checkpointTurnCount === 2, + ); + assert.equal( + secondCheckpoint?.files.some((file) => file.path === "README.md"), + true, + ); + + const checkpointRows = yield* harness.checkpointRepository.listByThreadId({ + threadId: THREAD_ID, + }); + assert.deepEqual( + checkpointRows.map((row) => row.checkpointTurnCount), + [1, 2], + ); + + const incrementalDiff = yield* harness.checkpointStore.diffCheckpoints({ + cwd: harness.workspaceDir, + fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1), + toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2), + fallbackFromToHead: false, + }); + assert.equal(incrementalDiff.includes("README.md"), true); + + const fullDiff = yield* harness.checkpointStore.diffCheckpoints({ + cwd: harness.workspaceDir, + fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0), + toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2), + fallbackFromToHead: false, + }); + assert.equal(fullDiff.includes("README.md"), true); + + assert.equal( + gitShowFileAtRef( + harness.workspaceDir, + checkpointRefForThreadTurn(THREAD_ID, 1), + "README.md", + ), + "v2\n", + ); + assert.equal( + gitShowFileAtRef( + harness.workspaceDir, + checkpointRefForThreadTurn(THREAD_ID, 2), + "README.md", + ), + "v3\n", + ); + }), + ), +); + +it.live("tracks approval requests and resolves pending approvals on user response", () => + withHarness((harness) => + Effect.gen(function* () { + yield* seedProjectAndThread(harness); + + yield* harness.adapterHarness!.queueTurnResponseForNextSession({ + events: [ + { + type: "turn.started", + ...runtimeBase("evt-approval-1", "2026-02-24T10:03:00.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "approval.requested", + ...runtimeBase("evt-approval-2", "2026-02-24T10:03:00.100Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + requestId: APPROVAL_REQUEST_ID, + requestKind: "command", + detail: "Approve command execution", + }, + { + type: "turn.completed", + ...runtimeBase("evt-approval-3", "2026-02-24T10:03:00.200Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + status: "completed", + }, + ], + }); + + yield* startTurn({ + harness, + commandId: "cmd-turn-start-approval", + messageId: "msg-user-approval", + text: "Run command needing approval", + }); + + const thread = yield* harness.waitForThread(THREAD_ID, (entry) => + entry.activities.some((activity) => activity.kind === "approval.requested"), + ); + assert.equal( + thread.activities.some((activity) => activity.kind === "approval.requested"), + true, + ); + + const pendingRow = yield* harness.waitForPendingApproval( + "req-approval-1", + (row) => row.status === "pending" && row.decision === null, + ); + assert.equal(pendingRow.status, "pending"); + + yield* harness.engine.dispatch({ + type: "thread.approval.respond", + commandId: CommandId.makeUnsafe("cmd-approval-respond"), + threadId: THREAD_ID, + requestId: APPROVAL_REQUEST_ID, + decision: "accept", + createdAt: nowIso(), + }); + + const resolvedRow = yield* harness.waitForPendingApproval( + "req-approval-1", + (row) => row.status === "resolved" && row.decision === "accept", + ); + assert.equal(resolvedRow.status, "resolved"); + assert.equal(resolvedRow.decision, "accept"); + + const approvalResponses = yield* waitForSync( + () => harness.adapterHarness!.getApprovalResponses(THREAD_ID), + (responses) => responses.length === 1, + "provider approval response", + ); + assert.equal(approvalResponses.length, 1); + assert.equal(approvalResponses[0]?.requestId, "req-approval-1"); + assert.equal(approvalResponses[0]?.decision, "accept"); + }), + ), +); + +it.live("records failed turn runtime state and checkpoint status as error", () => + withHarness((harness) => + Effect.gen(function* () { + yield* seedProjectAndThread(harness); + + yield* harness.adapterHarness!.queueTurnResponseForNextSession({ + events: [ + { + type: "turn.started", + ...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "content.delta", + ...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + payload: { + streamKind: "assistant_text", + delta: "Partial output before failure.\n", + }, + }, + { + type: "runtime.error", + ...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + payload: { + message: "Sandbox command failed.", + }, + }, + { + type: "turn.completed", + ...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + payload: { + state: "failed", + errorMessage: "Sandbox command failed.", + }, + }, + ], + }); + + yield* startTurn({ + harness, + commandId: "cmd-turn-start-failure", + messageId: "msg-user-failure", + text: "Run risky command", + }); + + const thread = yield* harness.waitForThread( + THREAD_ID, + (entry) => + entry.session?.status === "error" && + entry.session?.lastError === "Sandbox command failed." && + entry.activities.some((activity) => activity.kind === "runtime.error") && + entry.checkpoints.length === 1, + ); + assert.equal(thread.session?.status, "error"); + assert.equal(thread.checkpoints[0]?.status, "error"); + + const checkpointRow = yield* harness.checkpointRepository.getByThreadAndTurnCount({ + threadId: THREAD_ID, + checkpointTurnCount: 1, + }); + assert.equal(Option.isSome(checkpointRow), true); + if (Option.isSome(checkpointRow)) { + assert.equal(checkpointRow.value.status, "error"); + } + assert.equal( + gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)), + true, + ); + }), + ), +); + +it.live("reverts to an earlier checkpoint and trims checkpoint projections + git refs", () => + withHarness((harness) => + Effect.gen(function* () { + yield* seedProjectAndThread(harness); + + yield* harness.adapterHarness!.queueTurnResponseForNextSession({ + events: [ + { + type: "turn.started", + ...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "tool.started", + ...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + toolKind: "command", + title: "Edit file", + detail: "README.md", + }, + { + type: "tool.completed", + ...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + toolKind: "command", + title: "Edit file", + detail: "README.md", + }, + { + type: "message.delta", + ...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + delta: "Updated README to v2.\n", + }, + { + type: "turn.completed", + ...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"), + 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-revert-1", + messageId: "msg-user-revert-1", + text: "First edit", + }); + + yield* harness.waitForThread( + THREAD_ID, + (entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1, + ); + + yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, { + events: [ + { + type: "turn.started", + ...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "tool.started", + ...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + toolKind: "command", + title: "Edit file", + detail: "README.md", + }, + { + type: "tool.completed", + ...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + toolKind: "command", + title: "Edit file", + detail: "README.md", + }, + { + type: "message.delta", + ...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + delta: "Updated README to v3.\n", + }, + { + type: "turn.completed", + ...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"), + 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-revert-2", + messageId: "msg-user-revert-2", + text: "Second edit", + }); + + yield* harness.waitForThread( + THREAD_ID, + (entry) => + entry.latestTurn?.turnId === "turn-2" && + entry.checkpoints.length === 2 && + entry.activities.some((activity) => activity.turnId === "turn-2"), + 8000, + ); + + yield* harness.engine.dispatch({ + type: "thread.checkpoint.revert", + commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"), + threadId: THREAD_ID, + turnCount: 1, + createdAt: nowIso(), + }); + + yield* harness.waitForDomainEvent((event) => event.type === "thread.reverted"); + 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.deepEqual( + revertedThread.messages.map((message) => ({ role: message.role, text: message.text })), + [ + { role: "user", text: "First edit" }, + { role: "assistant", text: "Updated README to v2.\n" }, + ], + ); + assert.equal( + revertedThread.activities.some((activity) => activity.turnId === "turn-2"), + false, + ); + assert.equal( + revertedThread.activities.some( + (activity) => activity.turnId === "turn-1" && activity.kind === "tool.started", + ), + true, + ); + assert.equal( + revertedThread.activities.some( + (activity) => activity.turnId === "turn-1" && activity.kind === "tool.completed", + ), + true, + ); + assert.equal(fs.readFileSync(path.join(harness.workspaceDir, "README.md"), "utf8"), "v2\n"); + assert.equal( + gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)), + false, + ); + assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]); + + const checkpointRows = yield* harness.checkpointRepository.listByThreadId({ + threadId: THREAD_ID, + }); + assert.equal(checkpointRows.length, 1); + }), + ), +); + +it.live( + "appends checkpoint.revert.failed activity when revert is requested without an active session", + () => + withHarness((harness) => + Effect.gen(function* () { + yield* seedProjectAndThread(harness); + + yield* harness.engine.dispatch({ + type: "thread.checkpoint.revert", + commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"), + threadId: THREAD_ID, + turnCount: 0, + createdAt: nowIso(), + }); + + const thread = yield* harness.waitForThread(THREAD_ID, (entry) => + entry.activities.some( + (activity) => + activity.kind === "checkpoint.revert.failed" && + typeof activity.payload === "object" && + activity.payload !== null, + ), + ); + const failureActivity = thread.activities.find( + (activity) => activity.kind === "checkpoint.revert.failed", + ); + assert.equal(failureActivity !== undefined, true); + assert.equal( + String( + (failureActivity?.payload as { readonly detail?: string } | undefined)?.detail, + ).includes("No active provider session"), + true, + ); + }), + ), +); + +it.live("starts a claudeAgent 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", "claudeAgent"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"), + 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", "claudeAgent"), + 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", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + const thread = yield* harness.waitForThread( + THREAD_ID, + (entry) => + entry.session?.providerName === "claudeAgent" && + entry.session.status === "ready" && + entry.messages.some( + (message) => message.role === "assistant" && message.text === "Claude first turn.\n", + ), + ); + assert.equal(thread.session?.providerName, "claudeAgent"); + }), + "claudeAgent", + ), +); + +it.live("recovers claudeAgent 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", "claudeAgent"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"), + 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", "claudeAgent"), + 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", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + yield* harness.waitForThread( + THREAD_ID, + (entry) => + entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1", + ); + + yield* harness.adapterHarness!.adapter.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", "claudeAgent"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"), + 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", "claudeAgent"), + 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 === "claudeAgent" && + 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, "claudeAgent"); + assert.equal(recoveredThread.session?.threadId, "thread-1"); + }), + "claudeAgent", + ), +); + +it.live("forwards claudeAgent 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", "claudeAgent"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "approval.requested", + ...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"), + 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", "claudeAgent"), + 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", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + 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"); + }), + "claudeAgent", + ), +); + +it.live("forwards thread.turn.interrupt to claudeAgent 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", "claudeAgent"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"), + 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", "claudeAgent"), + 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", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + 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); + }), + "claudeAgent", + ), +); + +it.live("reverts claudeAgent 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", "claudeAgent"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"), + 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", "claudeAgent"), + 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", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + 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", "claudeAgent"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"), + 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", "claudeAgent"), + 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 === "claudeAgent", + ); + + 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]); + }), + "claudeAgent", + ), +); diff --git a/apps/server/integration/providerService.integration.test.ts b/apps/server/integration/providerService.integration.test.ts new file mode 100644 index 0000000000..ef03a1ab5c --- /dev/null +++ b/apps/server/integration/providerService.integration.test.ts @@ -0,0 +1,300 @@ +import type { ProviderRuntimeEvent } from "@t3tools/contracts"; +import { ThreadId } from "@t3tools/contracts"; +import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, assert } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect"; + +import { ProviderUnsupportedError } from "../src/provider/Errors.ts"; +import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts"; +import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts"; +import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts"; +import { + ProviderService, + type ProviderServiceShape, +} from "../src/provider/Services/ProviderService.ts"; +import { ServerSettingsService } from "../src/serverSettings.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"; + +import { + makeTestProviderAdapterHarness, + type TestProviderAdapterHarness, + type TestTurnResponse, +} from "./TestProviderAdapter.integration.ts"; +import { + codexTurnApprovalFixture, + codexTurnToolFixture, + codexTurnTextFixture, +} from "./fixtures/providerRuntime.ts"; + +const makeWorkspaceDirectory = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + const cwd = yield* fs.makeTempDirectory(); + yield* fs.writeFileString(pathService.join(cwd, "README.md"), "v1\n"); + return cwd; +}).pipe(Effect.provide(NodeServices.layer)); + +interface IntegrationFixture { + readonly cwd: string; + readonly harness: TestProviderAdapterHarness; + readonly layer: Layer.Layer; +} + +const makeIntegrationFixture = Effect.gen(function* () { + const cwd = yield* makeWorkspaceDirectory; + const harness = yield* makeTestProviderAdapterHarness(); + + const registry: typeof ProviderAdapterRegistry.Service = { + getByProvider: (provider) => + provider === "codex" + ? Effect.succeed(harness.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed(["codex"]), + }; + + const directoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(ProviderSessionRuntimeRepositoryLive), + ); + + const shared = Layer.mergeAll( + directoryLayer, + Layer.succeed(ProviderAdapterRegistry, registry), + ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS), + AnalyticsService.layerTest, + ).pipe(Layer.provide(SqlitePersistenceMemory)); + + const layer = makeProviderServiceLive().pipe(Layer.provide(shared)); + + return { + cwd, + harness, + layer, + } satisfies IntegrationFixture; +}); + +const collectEventsDuring = ( + stream: Stream.Stream, + count: number, + action: Effect.Effect, +) => + Effect.gen(function* () { + const queue = yield* Queue.unbounded(); + yield* Stream.runForEach(stream, (event) => Queue.offer(queue, event).pipe(Effect.asVoid)).pipe( + Effect.forkScoped, + ); + + yield* action; + + return yield* Effect.forEach( + Array.from({ length: count }, () => undefined), + () => Queue.take(queue), + { discard: false }, + ); + }); + +const runTurn = (input: { + readonly provider: ProviderServiceShape; + readonly harness: TestProviderAdapterHarness; + readonly threadId: ThreadId; + readonly userText: string; + readonly response: TestTurnResponse; +}) => + Effect.gen(function* () { + yield* input.harness.queueTurnResponse(input.threadId, input.response); + + return yield* collectEventsDuring( + input.provider.streamEvents, + input.response.events.length, + input.provider.sendTurn({ + threadId: input.threadId, + input: input.userText, + attachments: [], + }), + ); + }); + +it.effect("replays typed runtime fixture events", () => + Effect.gen(function* () { + const fixture = yield* makeIntegrationFixture; + + yield* Effect.gen(function* () { + const provider = yield* ProviderService; + const session = yield* provider.startSession( + ThreadId.makeUnsafe("thread-integration-typed"), + { + threadId: ThreadId.makeUnsafe("thread-integration-typed"), + provider: "codex", + cwd: fixture.cwd, + runtimeMode: "full-access", + }, + ); + assert.equal((session.threadId ?? "").length > 0, true); + + const observedEvents = yield* runTurn({ + provider, + harness: fixture.harness, + threadId: session.threadId, + userText: "hello", + response: { events: codexTurnTextFixture }, + }); + + assert.deepEqual( + observedEvents.map((event) => event.type), + codexTurnTextFixture.map((event) => event.type), + ); + }).pipe(Effect.provide(fixture.layer)); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("replays file-changing fixture turn events", () => + Effect.gen(function* () { + const fixture = yield* makeIntegrationFixture; + const { join } = yield* Path.Path; + const { writeFileString } = yield* FileSystem.FileSystem; + + yield* Effect.gen(function* () { + const provider = yield* ProviderService; + const session = yield* provider.startSession( + ThreadId.makeUnsafe("thread-integration-tools"), + { + threadId: ThreadId.makeUnsafe("thread-integration-tools"), + provider: "codex", + cwd: fixture.cwd, + runtimeMode: "full-access", + }, + ); + assert.equal((session.threadId ?? "").length > 0, true); + + const observedEvents = yield* runTurn({ + provider, + harness: fixture.harness, + threadId: session.threadId, + userText: "make a small change", + response: { + events: codexTurnToolFixture, + mutateWorkspace: ({ cwd }) => + writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore), + }, + }); + + assert.deepEqual( + observedEvents.map((event) => event.type), + codexTurnToolFixture.map((event) => event.type), + ); + }).pipe(Effect.provide(fixture.layer)); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("runs multi-turn tool/approval flow", () => + Effect.gen(function* () { + const fixture = yield* makeIntegrationFixture; + const { join } = yield* Path.Path; + const { writeFileString } = yield* FileSystem.FileSystem; + + yield* Effect.gen(function* () { + const provider = yield* ProviderService; + const session = yield* provider.startSession( + ThreadId.makeUnsafe("thread-integration-multi"), + { + threadId: ThreadId.makeUnsafe("thread-integration-multi"), + provider: "codex", + cwd: fixture.cwd, + runtimeMode: "full-access", + }, + ); + assert.equal((session.threadId ?? "").length > 0, true); + + const firstTurnEvents = yield* runTurn({ + provider, + harness: fixture.harness, + threadId: session.threadId, + userText: "turn 1", + response: { + events: codexTurnToolFixture, + mutateWorkspace: ({ cwd }) => + writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore), + }, + }); + assert.deepEqual( + firstTurnEvents.map((event) => event.type), + codexTurnToolFixture.map((event) => event.type), + ); + + const secondTurnEvents = yield* runTurn({ + provider, + harness: fixture.harness, + threadId: session.threadId, + userText: "turn 2 approval", + response: { + events: codexTurnApprovalFixture, + mutateWorkspace: ({ cwd }) => + writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore), + }, + }); + assert.deepEqual( + secondTurnEvents.map((event) => event.type), + codexTurnApprovalFixture.map((event) => event.type), + ); + }).pipe(Effect.provide(fixture.layer)); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("rolls back provider conversation state only", () => + Effect.gen(function* () { + const fixture = yield* makeIntegrationFixture; + const { join } = yield* Path.Path; + const { writeFileString, readFileString } = yield* FileSystem.FileSystem; + + yield* Effect.gen(function* () { + const provider = yield* ProviderService; + const session = yield* provider.startSession( + ThreadId.makeUnsafe("thread-integration-rollback"), + { + threadId: ThreadId.makeUnsafe("thread-integration-rollback"), + provider: "codex", + cwd: fixture.cwd, + runtimeMode: "full-access", + }, + ); + assert.equal((session.threadId ?? "").length > 0, true); + + yield* runTurn({ + provider, + harness: fixture.harness, + threadId: session.threadId, + userText: "turn 1", + response: { + events: codexTurnToolFixture, + mutateWorkspace: ({ cwd }) => + writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore), + }, + }); + + yield* runTurn({ + provider, + harness: fixture.harness, + threadId: session.threadId, + userText: "turn 2 approval", + response: { + events: codexTurnApprovalFixture, + mutateWorkspace: ({ cwd }) => + writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore), + }, + }); + + yield* provider.rollbackConversation({ + threadId: session.threadId, + numTurns: 1, + }); + + const rollbackCalls = fixture.harness.getRollbackCalls(session.threadId); + assert.deepEqual(rollbackCalls, [1]); + + const readme = yield* readFileString(join(fixture.cwd, "README.md")); + assert.equal(readme, "v3\n"); + }).pipe(Effect.provide(fixture.layer)); + }).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/package.json b/apps/server/package.json index 69ac42c480..e59c7c208c 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -1,32 +1,50 @@ { "name": "t3", - "version": "0.1.0", + "version": "0.0.15", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/pingdotgg/t3code", + "directory": "apps/server" + }, "bin": { - "t3": "./dist/index.mjs" + "t3": "./dist/bin.mjs" }, "files": [ "dist" ], "type": "module", - "main": "./dist/index.mjs", "scripts": { - "dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.ts", - "build": "tsdown && node scripts/bundle-client.mjs", - "start": "node dist/index.mjs", + "dev": "bun run src/bin.ts", + "build": "node scripts/cli.ts build", + "start": "node dist/bin.mjs", + "prepare": "effect-language-service patch", "typecheck": "tsc --noEmit", "test": "vitest run" }, "dependencies": { + "@anthropic-ai/claude-agent-sdk": "^0.2.77", + "@effect/platform-bun": "catalog:", + "@effect/platform-node": "catalog:", + "@effect/sql-sqlite-bun": "catalog:", + "@pierre/diffs": "^1.1.0-beta.16", + "effect": "catalog:", "node-pty": "^1.1.0", - "open": "^10.1.0", - "ws": "^8.18.0" + "open": "^10.1.0" }, "devDependencies": { + "@effect/language-service": "catalog:", + "@effect/vitest": "catalog:", "@t3tools/contracts": "workspace:*", + "@t3tools/shared": "workspace:*", "@t3tools/web": "workspace:*", - "@types/node": "^22.10.2", - "@types/ws": "^8.5.13", - "tsdown": "^0.20.3", - "typescript": "^5.7.3" + "@types/bun": "catalog:", + "@types/node": "catalog:", + "tsdown": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:" + }, + "engines": { + "node": "^22.16 || ^23.11 || >=24.10" } } diff --git a/apps/server/scripts/bundle-client.mjs b/apps/server/scripts/bundle-client.mjs deleted file mode 100644 index 33b44cd5e7..0000000000 --- a/apps/server/scripts/bundle-client.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copies the built web app into dist/client/ so the published npm package - * includes the web UI. This runs as a post-build step. - */ -import fs from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); -const webDist = path.resolve(__dirname, "../../web/dist"); -const target = path.resolve(__dirname, "../dist/client"); - -if (!fs.existsSync(webDist)) { - console.log( - "⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.", - ); - process.exit(0); -} - -fs.cpSync(webDist, target, { recursive: true }); -console.log("✓ Bundled web app into dist/client"); diff --git a/apps/server/scripts/cli.ts b/apps/server/scripts/cli.ts new file mode 100644 index 0000000000..21bc515aa7 --- /dev/null +++ b/apps/server/scripts/cli.ts @@ -0,0 +1,266 @@ +#!/usr/bin/env node + +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +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" }; + +class CliError extends Data.TaggedError("CliError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +const RepoRoot = Effect.service(Path.Path).pipe( + Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))), +); + +const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner.spawn(command); + const exitCode = yield* child.exitCode; + + if (exitCode !== 0) { + return yield* new CliError({ + message: `Command exited with non-zero exit code (${exitCode})`, + }); + } +}); + +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; +}); + +const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* ( + backups: ReadonlyArray, +) { + 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 +// --------------------------------------------------------------------------- + +const buildCmd = Command.make( + "build", + { + verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)), + }, + (config) => + Effect.gen(function* () { + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; + const repoRoot = yield* RepoRoot; + const serverDir = path.join(repoRoot, "apps/server"); + + yield* Effect.log("[cli] Running tsdown..."); + yield* runCommand( + ChildProcess.make({ + cwd: serverDir, + stdout: config.verbose ? "inherit" : "ignore", + stderr: "inherit", + // Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd). + shell: process.platform === "win32", + })`bun tsdown`, + ); + + const webDist = path.join(repoRoot, "apps/web/dist"); + const clientTarget = path.join(serverDir, "dist/client"); + + 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."); + } + }), +).pipe(Command.withDescription("Build the server package (tsdown + bundle web client).")); + +// --------------------------------------------------------------------------- +// publish subcommand +// --------------------------------------------------------------------------- + +const publishCmd = Command.make( + "publish", + { + tag: Flag.string("tag").pipe(Flag.withDefault("latest")), + access: Flag.string("access").pipe(Flag.withDefault("public")), + appVersion: Flag.string("app-version").pipe(Flag.optional), + provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)), + dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)), + verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)), + }, + (config) => + Effect.gen(function* () { + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; + const repoRoot = yield* RepoRoot; + const serverDir = path.join(repoRoot, "apps/server"); + const packageJsonPath = path.join(serverDir, "package.json"); + const backupPath = `${packageJsonPath}.bak`; + + // Assert build assets exist + for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) { + const abs = path.join(serverDir, relPath); + if (!(yield* fs.exists(abs))) { + return yield* new CliError({ + message: `Missing build asset: ${abs}. Run the build subcommand first.`, + }); + } + } + + yield* Effect.acquireUseRelease( + // Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts + Effect.gen(function* () { + // Resolve catalog dependencies before any file mutations. If this throws, + // acquire fails and no release hook runs, so filesystem must still be untouched. + const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version); + const pkg = { + name: serverPackageJson.name, + repository: serverPackageJson.repository, + bin: serverPackageJson.bin, + type: serverPackageJson.type, + version, + engines: serverPackageJson.engines, + files: serverPackageJson.files, + dependencies: serverPackageJson.dependencies as Record, + }; + + 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 + () => + Effect.gen(function* () { + const args = ["publish", "--access", config.access, "--tag", config.tag]; + if (config.provenance) args.push("--provenance"); + if (config.dryRun) args.push("--dry-run"); + + yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`); + yield* runCommand( + ChildProcess.make("npm", [...args], { + cwd: serverDir, + stdout: config.verbose ? "inherit" : "ignore", + stderr: "inherit", + // Windows needs shell mode to resolve .cmd shims. + shell: process.platform === "win32", + }), + ); + }), + // Release: restore + (resource: { readonly iconBackups: ReadonlyArray }) => + 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"); + }), + ); + }), +).pipe(Command.withDescription("Publish the server package to npm.")); + +// --------------------------------------------------------------------------- +// root command +// --------------------------------------------------------------------------- + +const cli = Command.make("cli").pipe( + Command.withDescription("T3 server build & publish CLI."), + Command.withSubcommands([buildCmd, publishCmd]), +); + +Command.run(cli, { version: "0.0.0" }).pipe( + Effect.scoped, + Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]), + NodeRuntime.runMain, +); diff --git a/apps/server/src/attachmentPaths.ts b/apps/server/src/attachmentPaths.ts new file mode 100644 index 0000000000..cd7e1faec8 --- /dev/null +++ b/apps/server/src/attachmentPaths.ts @@ -0,0 +1,28 @@ +import path from "node:path"; + +export const ATTACHMENTS_ROUTE_PREFIX = "/attachments"; + +export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null { + const normalized = path.normalize(rawRelativePath).replace(/^[/\\]+/, ""); + if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) { + return null; + } + return normalized.replace(/\\/g, "/"); +} + +export function resolveAttachmentRelativePath(input: { + readonly attachmentsDir: string; + readonly relativePath: string; +}): string | null { + const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath); + if (!normalizedRelativePath) { + return null; + } + + const attachmentsRoot = path.resolve(input.attachmentsDir); + const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath)); + if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) { + return null; + } + return filePath; +} diff --git a/apps/server/src/attachmentStore.test.ts b/apps/server/src/attachmentStore.test.ts new file mode 100644 index 0000000000..e92c3d219d --- /dev/null +++ b/apps/server/src/attachmentStore.test.ts @@ -0,0 +1,75 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { + createAttachmentId, + parseThreadSegmentFromAttachmentId, + resolveAttachmentPathById, +} from "./attachmentStore.ts"; + +describe("attachmentStore", () => { + it("sanitizes thread ids when creating attachment ids", () => { + const attachmentId = createAttachmentId("thread.folder/unsafe space"); + expect(attachmentId).toBeTruthy(); + if (!attachmentId) { + return; + } + + const threadSegment = parseThreadSegmentFromAttachmentId(attachmentId); + expect(threadSegment).toBeTruthy(); + expect(threadSegment).toMatch(/^[a-z0-9_-]+$/i); + expect(threadSegment).not.toContain("."); + expect(threadSegment).not.toContain("%"); + expect(threadSegment).not.toContain("/"); + }); + + it("parses exact thread segments from attachment ids without prefix collisions", () => { + const fooId = "foo-00000000-0000-4000-8000-000000000001"; + const fooBarId = "foo-bar-00000000-0000-4000-8000-000000000002"; + + expect(parseThreadSegmentFromAttachmentId(fooId)).toBe("foo"); + expect(parseThreadSegmentFromAttachmentId(fooBarId)).toBe("foo-bar"); + }); + + it("normalizes created thread segments to lowercase", () => { + const attachmentId = createAttachmentId("Thread.Foo"); + expect(attachmentId).toBeTruthy(); + if (!attachmentId) { + return; + } + expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo"); + }); + + it("resolves attachment path by id using the extension that exists on disk", () => { + const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-")); + try { + const attachmentId = "thread-1-attachment"; + const pngPath = path.join(attachmentsDir, `${attachmentId}.png`); + fs.writeFileSync(pngPath, Buffer.from("hello")); + + const resolved = resolveAttachmentPathById({ + attachmentsDir, + attachmentId, + }); + expect(resolved).toBe(pngPath); + } finally { + fs.rmSync(attachmentsDir, { recursive: true, force: true }); + } + }); + + it("returns null when no attachment file exists for the id", () => { + const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-")); + try { + const resolved = resolveAttachmentPathById({ + attachmentsDir, + attachmentId: "thread-1-missing", + }); + expect(resolved).toBeNull(); + } finally { + fs.rmSync(attachmentsDir, { recursive: true, force: true }); + } + }); +}); diff --git a/apps/server/src/attachmentStore.ts b/apps/server/src/attachmentStore.ts new file mode 100644 index 0000000000..aa85b8c51a --- /dev/null +++ b/apps/server/src/attachmentStore.ts @@ -0,0 +1,109 @@ +import { randomUUID } from "node:crypto"; +import { existsSync } from "node:fs"; + +import type { ChatAttachment } from "@t3tools/contracts"; + +import { + normalizeAttachmentRelativePath, + resolveAttachmentRelativePath, +} from "./attachmentPaths.ts"; +import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts"; + +const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"]; +const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80; +const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*"; +const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; +const ATTACHMENT_ID_PATTERN = new RegExp( + `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`, + "i", +); + +export function toSafeThreadAttachmentSegment(threadId: string): string | null { + const segment = threadId + .trim() + .toLowerCase() + .replace(/[^a-z0-9_-]+/gi, "-") + .replace(/-+/g, "-") + .replace(/^[-_]+|[-_]+$/g, "") + .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS) + .replace(/[-_]+$/g, ""); + if (segment.length === 0) { + return null; + } + return segment; +} + +export function createAttachmentId(threadId: string): string | null { + const threadSegment = toSafeThreadAttachmentSegment(threadId); + if (!threadSegment) { + return null; + } + return `${threadSegment}-${randomUUID()}`; +} + +export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null { + const normalizedId = normalizeAttachmentRelativePath(attachmentId); + if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) { + return null; + } + const match = normalizedId.match(ATTACHMENT_ID_PATTERN); + if (!match) { + return null; + } + return match[1]?.toLowerCase() ?? null; +} + +export function attachmentRelativePath(attachment: ChatAttachment): string { + switch (attachment.type) { + case "image": { + const extension = inferImageExtension({ + mimeType: attachment.mimeType, + fileName: attachment.name, + }); + return `${attachment.id}${extension}`; + } + } +} + +export function resolveAttachmentPath(input: { + readonly attachmentsDir: string; + readonly attachment: ChatAttachment; +}): string | null { + return resolveAttachmentRelativePath({ + attachmentsDir: input.attachmentsDir, + relativePath: attachmentRelativePath(input.attachment), + }); +} + +export function resolveAttachmentPathById(input: { + readonly attachmentsDir: string; + readonly attachmentId: string; +}): string | null { + const normalizedId = normalizeAttachmentRelativePath(input.attachmentId); + if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) { + return null; + } + for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) { + const maybePath = resolveAttachmentRelativePath({ + attachmentsDir: input.attachmentsDir, + relativePath: `${normalizedId}${extension}`, + }); + if (maybePath && existsSync(maybePath)) { + return maybePath; + } + } + return null; +} + +export function parseAttachmentIdFromRelativePath(relativePath: string): string | null { + const normalized = normalizeAttachmentRelativePath(relativePath); + if (!normalized || normalized.includes("/")) { + return null; + } + const extensionIndex = normalized.lastIndexOf("."); + if (extensionIndex <= 0) { + return null; + } + const id = normalized.slice(0, extensionIndex); + return id.length > 0 && !id.includes(".") ? id : null; +} diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts new file mode 100644 index 0000000000..063d43326c --- /dev/null +++ b/apps/server/src/bin.ts @@ -0,0 +1,17 @@ +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { Command } from "effect/unstable/cli"; + +import { NetService } from "@t3tools/shared/Net"; +import { cli } from "./cli"; +import { version } from "../package.json" with { type: "json" }; + +const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); + +Command.run(cli, { version }).pipe( + Effect.scoped, + Effect.provide(CliRuntimeLayer), + NodeRuntime.runMain, +); diff --git a/apps/server/src/bootstrap.test.ts b/apps/server/src/bootstrap.test.ts new file mode 100644 index 0000000000..3fce6af9c4 --- /dev/null +++ b/apps/server/src/bootstrap.test.ts @@ -0,0 +1,149 @@ +import * as NFS from "node:fs"; +import * as path from "node:path"; +import { execFileSync, spawn } from "node:child_process"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { FileSystem, Schema } from "effect"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import { TestClock } from "effect/testing"; +import { vi } from "vitest"; + +import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap"; +import { assertNone, assertSome } from "@effect/vitest/utils"; + +const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null })); + +vi.mock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + openSync: (...args: Parameters) => { + const [filePath, flags] = args; + if ( + typeof filePath === "string" && + filePath === openSyncInterceptor.failPath && + flags === "r" + ) { + const error = new Error("no such device or address"); + Object.assign(error, { code: "ENXIO" }); + throw error; + } + return (actual.openSync as (...a: typeof args) => number)(...args); + }, + }; +}); + +const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String }); + +it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => { + it.effect("uses platform-specific fd paths", () => + Effect.sync(() => { + assert.equal(resolveFdPath(3, "linux"), "/proc/self/fd/3"); + assert.equal(resolveFdPath(3, "darwin"), "/dev/fd/3"); + assert.equal(resolveFdPath(3, "win32"), undefined); + }), + ); + + it.effect("reads a bootstrap envelope from a provided fd", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" }); + + yield* fs.writeFileString( + filePath, + `${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({ + mode: "desktop", + })}\n`, + ); + + const fd = yield* Effect.acquireRelease( + Effect.sync(() => NFS.openSync(filePath, "r")), + (fd) => Effect.sync(() => NFS.closeSync(fd)), + ); + + const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 }); + assertSome(payload, { + mode: "desktop", + }); + }), + ); + + it.effect("falls back to reading the inherited fd when path duplication fails", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" }); + + yield* fs.writeFileString( + filePath, + `${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({ + mode: "desktop", + })}\n`, + ); + + // Open without acquireRelease: the direct-stream fallback uses autoClose: true, + // so the stream owns the fd lifecycle and closes it asynchronously on end. + // Attempting to also close it synchronously in a finalizer races with the + // stream's async close and produces an uncaught EBADF. + const fd = NFS.openSync(filePath, "r"); + + openSyncInterceptor.failPath = `/proc/self/fd/${fd}`; + try { + const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 }); + assertSome(payload, { + mode: "desktop", + }); + } finally { + openSyncInterceptor.failPath = null; + } + }), + ); + + it.effect("returns none when the fd is unavailable", () => + Effect.gen(function* () { + const fd = NFS.openSync("/dev/null", "r"); + NFS.closeSync(fd); + + const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 }); + assertNone(payload); + }), + ); + + it.effect("returns none when the bootstrap read times out before any value arrives", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" }); + const fifoPath = path.join(tempDir, "bootstrap.pipe"); + + yield* Effect.sync(() => execFileSync("mkfifo", [fifoPath])); + + const _writer = yield* Effect.acquireRelease( + Effect.sync(() => + spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], { + stdio: ["ignore", "ignore", "ignore"], + }), + ), + (writer) => + Effect.sync(() => { + writer.kill("SIGKILL"); + }), + ); + + const fd = yield* Effect.acquireRelease( + Effect.sync(() => NFS.openSync(fifoPath, "r")), + (fd) => Effect.sync(() => NFS.closeSync(fd)), + ); + + const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { + timeoutMs: 100, + }).pipe(Effect.forkScoped); + + yield* Effect.yieldNow; + yield* TestClock.adjust(Duration.millis(100)); + + const payload = yield* Fiber.join(fiber); + assertNone(payload); + }).pipe(Effect.provide(TestClock.layer())), + ); +}); diff --git a/apps/server/src/bootstrap.ts b/apps/server/src/bootstrap.ts new file mode 100644 index 0000000000..0fb1352268 --- /dev/null +++ b/apps/server/src/bootstrap.ts @@ -0,0 +1,173 @@ +import * as NFS from "node:fs"; +import * as Net from "node:net"; +import * as readline from "node:readline"; +import type { Readable } from "node:stream"; + +import { Data, Effect, Option, Predicate, Result, Schema } from "effect"; +import { decodeJsonResult } from "@t3tools/shared/schemaJson"; + +class BootstrapError extends Data.TaggedError("BootstrapError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* ( + schema: Schema.Codec, + fd: number, + options?: { + timeoutMs?: number; + }, +): Effect.fn.Return, BootstrapError> { + const fdReady = yield* isFdReady(fd); + if (!fdReady) return Option.none(); + + const stream = yield* makeBootstrapInputStream(fd); + + const timeoutMs = options?.timeoutMs ?? 1000; + + return yield* Effect.callback, BootstrapError>((resume) => { + const input = readline.createInterface({ + input: stream, + crlfDelay: Infinity, + }); + + const cleanup = () => { + stream.removeListener("error", handleError); + input.removeListener("line", handleLine); + input.removeListener("close", handleClose); + input.close(); + stream.destroy(); + }; + + const handleError = (error: Error) => { + if (isUnavailableBootstrapFdError(error)) { + resume(Effect.succeedNone); + return; + } + resume( + Effect.fail( + new BootstrapError({ + message: "Failed to read bootstrap envelope.", + cause: error, + }), + ), + ); + }; + + const handleLine = (line: string) => { + const parsed = decodeJsonResult(schema)(line); + if (Result.isSuccess(parsed)) { + resume(Effect.succeedSome(parsed.success)); + } else { + resume( + Effect.fail( + new BootstrapError({ + message: "Failed to decode bootstrap envelope.", + cause: parsed.failure, + }), + ), + ); + } + }; + + const handleClose = () => { + resume(Effect.succeedNone); + }; + + stream.once("error", handleError); + input.once("line", handleLine); + input.once("close", handleClose); + + return Effect.sync(cleanup); + }).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten)); +}); + +const isUnavailableBootstrapFdError = Predicate.compose( + Predicate.hasProperty("code"), + (_) => _.code === "EBADF" || _.code === "ENOENT", +); + +const isFdReady = (fd: number) => + Effect.try({ + try: () => NFS.fstatSync(fd), + catch: (error) => + new BootstrapError({ + message: "Failed to stat bootstrap fd.", + cause: error, + }), + }).pipe( + Effect.as(true), + Effect.catchIf( + (error) => isUnavailableBootstrapFdError(error.cause), + () => Effect.succeed(false), + ), + ); + +const makeBootstrapInputStream = (fd: number) => + Effect.try({ + try: () => { + const fdPath = resolveFdPath(fd); + if (fdPath === undefined) { + return makeDirectBootstrapStream(fd); + } + + let streamFd: number | undefined; + try { + streamFd = NFS.openSync(fdPath, "r"); + return NFS.createReadStream("", { + fd: streamFd, + encoding: "utf8", + autoClose: true, + }); + } catch (error) { + if (isBootstrapFdPathDuplicationError(error)) { + if (streamFd !== undefined) { + NFS.closeSync(streamFd); + } + return makeDirectBootstrapStream(fd); + } + throw error; + } + }, + catch: (error) => + new BootstrapError({ + message: "Failed to duplicate bootstrap fd.", + cause: error, + }), + }); + +const makeDirectBootstrapStream = (fd: number): Readable => { + try { + return NFS.createReadStream("", { + fd, + encoding: "utf8", + autoClose: true, + }); + } catch { + const stream = new Net.Socket({ + fd, + readable: true, + writable: false, + }); + stream.setEncoding("utf8"); + return stream; + } +}; + +const isBootstrapFdPathDuplicationError = Predicate.compose( + Predicate.hasProperty("code"), + (_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM", +); + +export function resolveFdPath( + fd: number, + platform: NodeJS.Platform = process.platform, +): string | undefined { + if (platform === "linux") { + return `/proc/self/fd/${fd}`; + } + if (platform === "win32") { + return undefined; + } + return `/dev/fd/${fd}`; +} diff --git a/apps/server/src/checkpointing/Diffs.test.ts b/apps/server/src/checkpointing/Diffs.test.ts new file mode 100644 index 0000000000..e81e509364 --- /dev/null +++ b/apps/server/src/checkpointing/Diffs.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vitest"; + +import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts"; + +describe("parseTurnDiffFilesFromUnifiedDiff", () => { + it("returns empty list for empty diff", () => { + expect(parseTurnDiffFilesFromUnifiedDiff("")).toEqual([]); + }); + + it("parses per-file additions and deletions", () => { + const diff = [ + "diff --git a/a.txt b/a.txt", + "index 1111111..2222222 100644", + "--- a/a.txt", + "+++ b/a.txt", + "@@ -1,2 +1,3 @@", + " one", + "-two", + "+two updated", + "+three", + "diff --git a/src/b.ts b/src/b.ts", + "index 3333333..4444444 100644", + "--- a/src/b.ts", + "+++ b/src/b.ts", + "@@ -3,2 +3,0 @@", + "-old", + "-stale", + "", + ].join("\n"); + + expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([ + { path: "a.txt", additions: 2, deletions: 1 }, + { path: "src/b.ts", additions: 0, deletions: 2 }, + ]); + }); + + it("parses rename-only diffs with zero line changes", () => { + const diff = [ + "diff --git a/src/old.ts b/src/new.ts", + "similarity index 100%", + "rename from src/old.ts", + "rename to src/new.ts", + "", + ].join("\n"); + + expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([ + { path: "src/new.ts", additions: 0, deletions: 0 }, + ]); + }); + + it("normalizes CRLF input before parsing", () => { + const diff = [ + "diff --git a/a.txt b/a.txt", + "index 1111111..2222222 100644", + "--- a/a.txt", + "+++ b/a.txt", + "@@ -1 +1,2 @@", + "-one", + "+one updated", + "+two", + "", + ].join("\r\n"); + + expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([ + { path: "a.txt", additions: 2, deletions: 1 }, + ]); + }); +}); diff --git a/apps/server/src/checkpointing/Diffs.ts b/apps/server/src/checkpointing/Diffs.ts new file mode 100644 index 0000000000..c2f867b96e --- /dev/null +++ b/apps/server/src/checkpointing/Diffs.ts @@ -0,0 +1,27 @@ +import { parsePatchFiles } from "@pierre/diffs"; + +export interface TurnDiffFileSummary { + readonly path: string; + readonly additions: number; + readonly deletions: number; +} + +export function parseTurnDiffFilesFromUnifiedDiff( + diff: string, +): ReadonlyArray { + const normalized = diff.replace(/\r\n/g, "\n").trim(); + if (normalized.length === 0) { + return []; + } + + const parsedPatches = parsePatchFiles(normalized); + const files = parsedPatches.flatMap((patch) => + patch.files.map((file) => ({ + path: file.name, + additions: file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0), + deletions: file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0), + })), + ); + + return files.toSorted((left, right) => left.path.localeCompare(right.path)); +} diff --git a/apps/server/src/checkpointing/Errors.ts b/apps/server/src/checkpointing/Errors.ts new file mode 100644 index 0000000000..cb873559c1 --- /dev/null +++ b/apps/server/src/checkpointing/Errors.ts @@ -0,0 +1,43 @@ +import { Schema } from "effect"; +import type { ProjectionRepositoryError } from "../persistence/Errors.ts"; +import { GitCommandError } from "@t3tools/contracts"; + +/** + * CheckpointUnavailableError - Expected checkpoint does not exist. + */ +export class CheckpointUnavailableError extends Schema.TaggedErrorClass()( + "CheckpointUnavailableError", + { + threadId: Schema.String, + turnCount: Schema.Number, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Checkpoint unavailable for thread ${this.threadId} turn ${this.turnCount}: ${this.detail}`; + } +} + +/** + * CheckpointInvariantError - Inconsistent provider/filesystem/catalog state. + */ +export class CheckpointInvariantError extends Schema.TaggedErrorClass()( + "CheckpointInvariantError", + { + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Checkpoint invariant violation in ${this.operation}: ${this.detail}`; + } +} + +export type CheckpointStoreError = + | GitCommandError + | CheckpointInvariantError + | CheckpointUnavailableError; + +export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError; diff --git a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts new file mode 100644 index 0000000000..c66c529b9a --- /dev/null +++ b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts @@ -0,0 +1,160 @@ +import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; +import { Effect, Layer, Option } from "effect"; +import { describe, expect, it } from "vitest"; + +import { + ProjectionSnapshotQuery, + type ProjectionThreadCheckpointContext, +} from "../../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { checkpointRefForThreadTurn } from "../Utils.ts"; +import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts"; +import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts"; +import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts"; + +function makeThreadCheckpointContext(input: { + readonly projectId: ProjectId; + readonly threadId: ThreadId; + readonly workspaceRoot: string; + readonly worktreePath: string | null; + readonly checkpointTurnCount: number; + readonly checkpointRef: CheckpointRef; +}): ProjectionThreadCheckpointContext { + return { + threadId: input.threadId, + projectId: input.projectId, + workspaceRoot: input.workspaceRoot, + worktreePath: input.worktreePath, + checkpoints: [ + { + turnId: TurnId.makeUnsafe("turn-1"), + checkpointTurnCount: input.checkpointTurnCount, + checkpointRef: input.checkpointRef, + status: "ready", + files: [], + assistantMessageId: null, + completedAt: "2026-01-01T00:00:00.000Z", + }, + ], + }; +} + +describe("CheckpointDiffQueryLive", () => { + it("computes diffs using canonical turn-0 checkpoint refs", async () => { + const projectId = ProjectId.makeUnsafe("project-1"); + const threadId = ThreadId.makeUnsafe("thread-1"); + const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1); + const hasCheckpointRefCalls: Array = []; + const diffCheckpointsCalls: Array<{ + readonly fromCheckpointRef: CheckpointRef; + readonly toCheckpointRef: CheckpointRef; + readonly cwd: string; + }> = []; + + const threadCheckpointContext = makeThreadCheckpointContext({ + projectId, + threadId, + workspaceRoot: "/tmp/workspace", + worktreePath: null, + checkpointTurnCount: 1, + checkpointRef: toCheckpointRef, + }); + + const checkpointStore: CheckpointStoreShape = { + isGitRepository: () => Effect.succeed(true), + captureCheckpoint: () => Effect.void, + hasCheckpointRef: ({ checkpointRef }) => + Effect.sync(() => { + hasCheckpointRefCalls.push(checkpointRef); + return true; + }), + restoreCheckpoint: () => Effect.succeed(true), + diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) => + Effect.sync(() => { + diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd }); + return "diff patch"; + }), + deleteCheckpointRefs: () => Effect.void, + }; + + const layer = CheckpointDiffQueryLive.pipe( + Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)), + Layer.provideMerge( + Layer.succeed(ProjectionSnapshotQuery, { + getSnapshot: () => + Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"), + getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), + getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), + getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), + getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)), + }), + ), + ); + + const result = await Effect.runPromise( + Effect.gen(function* () { + const query = yield* CheckpointDiffQuery; + return yield* query.getTurnDiff({ + threadId, + fromTurnCount: 0, + toTurnCount: 1, + }); + }).pipe(Effect.provide(layer)), + ); + + const expectedFromRef = checkpointRefForThreadTurn(threadId, 0); + expect(hasCheckpointRefCalls).toEqual([expectedFromRef, toCheckpointRef]); + expect(diffCheckpointsCalls).toEqual([ + { + cwd: "/tmp/workspace", + fromCheckpointRef: expectedFromRef, + toCheckpointRef, + }, + ]); + expect(result).toEqual({ + threadId, + fromTurnCount: 0, + toTurnCount: 1, + diff: "diff patch", + }); + }); + + it("fails when the thread is missing from the snapshot", async () => { + const threadId = ThreadId.makeUnsafe("thread-missing"); + + const checkpointStore: CheckpointStoreShape = { + isGitRepository: () => Effect.succeed(true), + captureCheckpoint: () => Effect.void, + hasCheckpointRef: () => Effect.succeed(true), + restoreCheckpoint: () => Effect.succeed(true), + diffCheckpoints: () => Effect.succeed(""), + deleteCheckpointRefs: () => Effect.void, + }; + + const layer = CheckpointDiffQueryLive.pipe( + Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)), + Layer.provideMerge( + Layer.succeed(ProjectionSnapshotQuery, { + getSnapshot: () => + Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"), + getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), + getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), + getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), + getThreadCheckpointContext: () => Effect.succeed(Option.none()), + }), + ), + ); + + await expect( + Effect.runPromise( + Effect.gen(function* () { + const query = yield* CheckpointDiffQuery; + return yield* query.getTurnDiff({ + threadId, + fromTurnCount: 0, + toTurnCount: 1, + }); + }).pipe(Effect.provide(layer)), + ), + ).rejects.toThrow("Thread 'thread-missing' not found."); + }); +}); diff --git a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts new file mode 100644 index 0000000000..1c2edee469 --- /dev/null +++ b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts @@ -0,0 +1,168 @@ +import { + OrchestrationGetTurnDiffResult, + type OrchestrationGetFullThreadDiffInput, + type OrchestrationGetFullThreadDiffResult, + type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType, +} from "@t3tools/contracts"; +import { Effect, Layer, Option, Schema } from "effect"; + +import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts"; +import { checkpointRefForThreadTurn } from "../Utils.ts"; +import { CheckpointStore } from "../Services/CheckpointStore.ts"; +import { + CheckpointDiffQuery, + type CheckpointDiffQueryShape, +} from "../Services/CheckpointDiffQuery.ts"; + +const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult); + +const make = Effect.gen(function* () { + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + const checkpointStore = yield* CheckpointStore; + + const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")( + function* (input) { + const operation = "CheckpointDiffQuery.getTurnDiff"; + + if (input.fromTurnCount === input.toTurnCount) { + const emptyDiff: OrchestrationGetTurnDiffResultType = { + threadId: input.threadId, + fromTurnCount: input.fromTurnCount, + toTurnCount: input.toTurnCount, + diff: "", + }; + if (!isTurnDiffResult(emptyDiff)) { + return yield* new CheckpointInvariantError({ + operation, + detail: "Computed turn diff result does not satisfy contract schema.", + }); + } + return emptyDiff; + } + + const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext( + input.threadId, + ); + if (Option.isNone(threadContext)) { + return yield* new CheckpointInvariantError({ + operation, + detail: `Thread '${input.threadId}' not found.`, + }); + } + + const maxTurnCount = threadContext.value.checkpoints.reduce( + (max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount), + 0, + ); + if (input.toTurnCount > maxTurnCount) { + return yield* new CheckpointUnavailableError({ + threadId: input.threadId, + turnCount: input.toTurnCount, + detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${maxTurnCount}.`, + }); + } + + const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot; + if (!workspaceCwd) { + return yield* new CheckpointInvariantError({ + operation, + detail: `Workspace path missing for thread '${input.threadId}' when computing turn diff.`, + }); + } + + const fromCheckpointRef = + input.fromTurnCount === 0 + ? checkpointRefForThreadTurn(input.threadId, 0) + : threadContext.value.checkpoints.find( + (checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount, + )?.checkpointRef; + if (!fromCheckpointRef) { + return yield* new CheckpointUnavailableError({ + threadId: input.threadId, + turnCount: input.fromTurnCount, + detail: `Checkpoint ref is unavailable for turn ${input.fromTurnCount}.`, + }); + } + + const toCheckpointRef = threadContext.value.checkpoints.find( + (checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount, + )?.checkpointRef; + if (!toCheckpointRef) { + return yield* new CheckpointUnavailableError({ + threadId: input.threadId, + turnCount: input.toTurnCount, + detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`, + }); + } + + const [fromExists, toExists] = yield* Effect.all( + [ + checkpointStore.hasCheckpointRef({ + cwd: workspaceCwd, + checkpointRef: fromCheckpointRef, + }), + checkpointStore.hasCheckpointRef({ + cwd: workspaceCwd, + checkpointRef: toCheckpointRef, + }), + ], + { concurrency: "unbounded" }, + ); + + if (!fromExists) { + return yield* new CheckpointUnavailableError({ + threadId: input.threadId, + turnCount: input.fromTurnCount, + detail: `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount}.`, + }); + } + + if (!toExists) { + return yield* new CheckpointUnavailableError({ + threadId: input.threadId, + turnCount: input.toTurnCount, + detail: `Filesystem checkpoint is unavailable for turn ${input.toTurnCount}.`, + }); + } + + const diff = yield* checkpointStore.diffCheckpoints({ + cwd: workspaceCwd, + fromCheckpointRef, + toCheckpointRef, + fallbackFromToHead: false, + }); + + const turnDiff: OrchestrationGetTurnDiffResultType = { + threadId: input.threadId, + fromTurnCount: input.fromTurnCount, + toTurnCount: input.toTurnCount, + diff, + }; + if (!isTurnDiffResult(turnDiff)) { + return yield* new CheckpointInvariantError({ + operation, + detail: "Computed turn diff result does not satisfy contract schema.", + }); + } + + return turnDiff; + }, + ); + + const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = ( + input: OrchestrationGetFullThreadDiffInput, + ) => + getTurnDiff({ + threadId: input.threadId, + fromTurnCount: 0, + toTurnCount: input.toTurnCount, + }).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result)); + + return { + getTurnDiff, + getFullThreadDiff, + } satisfies CheckpointDiffQueryShape; +}); + +export const CheckpointDiffQueryLive = Layer.effect(CheckpointDiffQuery, make); diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts new file mode 100644 index 0000000000..6e7b18277c --- /dev/null +++ b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts @@ -0,0 +1,122 @@ +import path from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it } from "@effect/vitest"; +import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; +import { describe, expect } from "vitest"; + +import { checkpointRefForThreadTurn } from "../Utils.ts"; +import { CheckpointStoreLive } from "./CheckpointStore.ts"; +import { CheckpointStore } from "../Services/CheckpointStore.ts"; +import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { GitCore } from "../../git/Services/GitCore.ts"; +import { GitCommandError } from "@t3tools/contracts"; +import { ServerConfig } from "../../config.ts"; +import { ThreadId } from "@t3tools/contracts"; + +const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-checkpoint-store-test-", +}); +const GitCoreTestLayer = GitCoreLive.pipe( + Layer.provide(ServerConfigLayer), + Layer.provide(NodeServices.layer), +); +const CheckpointStoreTestLayer = CheckpointStoreLive.pipe( + Layer.provide(GitCoreTestLayer), + Layer.provide(NodeServices.layer), +); +const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer); + +function makeTmpDir( + prefix = "checkpoint-store-test-", +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ prefix }); + }); +} + +function writeTextFile( + filePath: string, + contents: string, +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.writeFileString(filePath, contents); + }); +} + +function git( + cwd: string, + args: ReadonlyArray, +): Effect.Effect { + return Effect.gen(function* () { + const gitCore = yield* GitCore; + const result = yield* gitCore.execute({ + operation: "CheckpointStore.test.git", + cwd, + args, + timeoutMs: 10_000, + }); + return result.stdout.trim(); + }); +} + +function initRepoWithCommit( + cwd: string, +): Effect.Effect< + void, + GitCommandError | PlatformError.PlatformError, + GitCore | FileSystem.FileSystem +> { + return Effect.gen(function* () { + const core = yield* GitCore; + yield* core.initRepo({ cwd }); + yield* git(cwd, ["config", "user.email", "test@test.com"]); + yield* git(cwd, ["config", "user.name", "Test"]); + yield* writeTextFile(path.join(cwd, "README.md"), "# test\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "initial commit"]); + }); +} + +function buildLargeText(lineCount = 5_000): string { + return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`) + .join("\n") + .concat("\n"); +} + +it.layer(TestLayer)("CheckpointStoreLive", (it) => { + describe("diffCheckpoints", () => { + it.effect("returns full oversized checkpoint diffs without truncation", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const checkpointStore = yield* CheckpointStore; + const threadId = ThreadId.makeUnsafe("thread-checkpoint-store"); + const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0); + const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1); + + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: fromCheckpointRef, + }); + yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText()); + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: toCheckpointRef, + }); + + const diff = yield* checkpointStore.diffCheckpoints({ + cwd: tmp, + fromCheckpointRef, + toCheckpointRef, + }); + + expect(diff).toContain("diff --git"); + expect(diff).not.toContain("[truncated]"); + expect(diff).toContain("+line 04999"); + }), + ); + }); +}); diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.ts new file mode 100644 index 0000000000..184ec96323 --- /dev/null +++ b/apps/server/src/checkpointing/Layers/CheckpointStore.ts @@ -0,0 +1,282 @@ +/** + * CheckpointStoreLive - Filesystem checkpoint store adapter layer. + * + * Implements hidden Git-ref checkpoint capture/restore directly with + * Effect-native child process execution (`effect/unstable/process`). + * + * This layer owns filesystem/Git interactions only; it does not persist + * checkpoint metadata and does not coordinate provider rollback semantics. + * + * @module CheckpointStoreLive + */ +import { randomUUID } from "node:crypto"; + +import { Effect, Layer, FileSystem, Path } from "effect"; + +import { CheckpointInvariantError } from "../Errors.ts"; +import { GitCommandError } from "@t3tools/contracts"; +import { GitCore } from "../../git/Services/GitCore.ts"; +import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts"; +import { CheckpointRef } from "@t3tools/contracts"; + +const makeCheckpointStore = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const git = yield* GitCore; + + const resolveHeadCommit = (cwd: string): Effect.Effect => + git + .execute({ + operation: "CheckpointStore.resolveHeadCommit", + cwd, + args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], + allowNonZeroExit: true, + }) + .pipe( + Effect.map((result) => { + if (result.code !== 0) { + return null; + } + const commit = result.stdout.trim(); + return commit.length > 0 ? commit : null; + }), + ); + + const hasHeadCommit = (cwd: string): Effect.Effect => + git + .execute({ + operation: "CheckpointStore.hasHeadCommit", + cwd, + args: ["rev-parse", "--verify", "HEAD"], + allowNonZeroExit: true, + }) + .pipe(Effect.map((result) => result.code === 0)); + + const resolveCheckpointCommit = ( + cwd: string, + checkpointRef: CheckpointRef, + ): Effect.Effect => + git + .execute({ + operation: "CheckpointStore.resolveCheckpointCommit", + cwd, + args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`], + allowNonZeroExit: true, + }) + .pipe( + Effect.map((result) => { + if (result.code !== 0) { + return null; + } + const commit = result.stdout.trim(); + return commit.length > 0 ? commit : null; + }), + ); + + const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) => + git + .execute({ + operation: "CheckpointStore.isGitRepository", + cwd, + args: ["rev-parse", "--is-inside-work-tree"], + allowNonZeroExit: true, + }) + .pipe( + Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"), + Effect.catch(() => Effect.succeed(false)), + ); + + const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn( + "captureCheckpoint", + )(function* (input) { + const operation = "CheckpointStore.captureCheckpoint"; + + yield* Effect.acquireUseRelease( + fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }), + Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) { + const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`); + const commitEnv: NodeJS.ProcessEnv = { + ...process.env, + GIT_INDEX_FILE: tempIndexPath, + GIT_AUTHOR_NAME: "T3 Code", + GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", + GIT_COMMITTER_NAME: "T3 Code", + GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", + }; + + const headExists = yield* hasHeadCommit(input.cwd); + if (headExists) { + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["read-tree", "HEAD"], + env: commitEnv, + }); + } + + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["add", "-A", "--", "."], + env: commitEnv, + }); + + const writeTreeResult = yield* git.execute({ + operation, + cwd: input.cwd, + args: ["write-tree"], + env: commitEnv, + }); + const treeOid = writeTreeResult.stdout.trim(); + if (treeOid.length === 0) { + return yield* new GitCommandError({ + operation, + command: "git write-tree", + cwd: input.cwd, + detail: "git write-tree returned an empty tree oid.", + }); + } + + const message = `t3 checkpoint ref=${input.checkpointRef}`; + const commitTreeResult = yield* git.execute({ + operation, + cwd: input.cwd, + args: ["commit-tree", treeOid, "-m", message], + env: commitEnv, + }); + const commitOid = commitTreeResult.stdout.trim(); + if (commitOid.length === 0) { + return yield* new GitCommandError({ + operation, + command: "git commit-tree", + cwd: input.cwd, + detail: "git commit-tree returned an empty commit oid.", + }); + } + + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["update-ref", input.checkpointRef, commitOid], + }); + }), + (tempDir) => fs.remove(tempDir, { recursive: true }), + ).pipe( + Effect.catchTags({ + PlatformError: (error) => + Effect.fail( + new CheckpointInvariantError({ + operation: "CheckpointStore.captureCheckpoint", + detail: "Failed to capture checkpoint.", + cause: error, + }), + ), + }), + ); + }); + + const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) => + resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe( + Effect.map((commit) => commit !== null), + ); + + const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn( + "restoreCheckpoint", + )(function* (input) { + const operation = "CheckpointStore.restoreCheckpoint"; + + let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef); + + if (!commitOid && input.fallbackToHead === true) { + commitOid = yield* resolveHeadCommit(input.cwd); + } + + if (!commitOid) { + return false; + } + + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."], + }); + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["clean", "-fd", "--", "."], + }); + + const headExists = yield* hasHeadCommit(input.cwd); + if (headExists) { + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["reset", "--quiet", "--", "."], + }); + } + + return true; + }); + + const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")( + function* (input) { + const operation = "CheckpointStore.diffCheckpoints"; + + let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef); + const toCommitOid = yield* resolveCheckpointCommit(input.cwd, input.toCheckpointRef); + + if (!fromCommitOid && input.fallbackFromToHead === true) { + const headCommit = yield* resolveHeadCommit(input.cwd); + if (headCommit) { + fromCommitOid = headCommit; + } + } + + if (!fromCommitOid || !toCommitOid) { + return yield* new GitCommandError({ + operation, + command: "git diff", + cwd: input.cwd, + detail: "Checkpoint ref is unavailable for diff operation.", + }); + } + + const result = yield* git.execute({ + operation, + cwd: input.cwd, + args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid], + }); + + return result.stdout; + }, + ); + + const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn( + "deleteCheckpointRefs", + )(function* (input) { + const operation = "CheckpointStore.deleteCheckpointRefs"; + + yield* Effect.forEach( + input.checkpointRefs, + (checkpointRef) => + git.execute({ + operation, + cwd: input.cwd, + args: ["update-ref", "-d", checkpointRef], + allowNonZeroExit: true, + }), + { discard: true }, + ); + }); + + return { + isGitRepository, + captureCheckpoint, + hasCheckpointRef, + restoreCheckpoint, + diffCheckpoints, + deleteCheckpointRefs, + } satisfies CheckpointStoreShape; +}); + +export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore); diff --git a/apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts new file mode 100644 index 0000000000..2204294a43 --- /dev/null +++ b/apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts @@ -0,0 +1,49 @@ +/** + * CheckpointDiffQuery - Query interface for computed checkpoint diffs. + * + * Provides read-only diff operations across checkpoint snapshots used by + * orchestration APIs. + * + * @module CheckpointDiffQuery + */ +import type { + OrchestrationGetFullThreadDiffInput, + OrchestrationGetFullThreadDiffResult, + OrchestrationGetTurnDiffInput, + OrchestrationGetTurnDiffResult, +} from "@t3tools/contracts"; +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { CheckpointServiceError } from "../Errors.ts"; + +/** + * CheckpointDiffQueryShape - Service API for checkpoint diff queries. + */ +export interface CheckpointDiffQueryShape { + /** + * Read the patch diff for a single turn checkpoint transition. + * + * Verifies checkpoint availability in both projection state and filesystem. + */ + readonly getTurnDiff: ( + input: OrchestrationGetTurnDiffInput, + ) => Effect.Effect; + + /** + * Read the full patch diff across a thread range of checkpoints. + * + * Delegates to turn diff with `fromTurnCount = 0`. + */ + readonly getFullThreadDiff: ( + input: OrchestrationGetFullThreadDiffInput, + ) => Effect.Effect; +} + +/** + * CheckpointDiffQuery - Service tag for checkpoint diff queries. + */ +export class CheckpointDiffQuery extends ServiceMap.Service< + CheckpointDiffQuery, + CheckpointDiffQueryShape +>()("t3/checkpointing/Services/CheckpointDiffQuery") {} diff --git a/apps/server/src/checkpointing/Services/CheckpointStore.ts b/apps/server/src/checkpointing/Services/CheckpointStore.ts new file mode 100644 index 0000000000..284198c145 --- /dev/null +++ b/apps/server/src/checkpointing/Services/CheckpointStore.ts @@ -0,0 +1,100 @@ +/** + * CheckpointStore - Repository interface for filesystem-backed workspace checkpoints. + * + * Owns hidden Git-ref checkpoint capture/restore and diff computation for a + * workspace thread timeline. It does not store user-facing checkpoint metadata + * and does not coordinate provider conversation rollback. + * + * Uses Effect `ServiceMap.Service` for dependency injection and exposes typed + * domain errors for checkpoint storage operations. + * + * @module CheckpointStore + */ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { CheckpointStoreError } from "../Errors.ts"; +import { CheckpointRef } from "@t3tools/contracts"; + +export interface CaptureCheckpointInput { + readonly cwd: string; + readonly checkpointRef: CheckpointRef; +} + +export interface RestoreCheckpointInput { + readonly cwd: string; + readonly checkpointRef: CheckpointRef; + readonly fallbackToHead?: boolean; +} + +export interface DiffCheckpointsInput { + readonly cwd: string; + readonly fromCheckpointRef: CheckpointRef; + readonly toCheckpointRef: CheckpointRef; + readonly fallbackFromToHead?: boolean; +} + +export interface DeleteCheckpointRefsInput { + readonly cwd: string; + readonly checkpointRefs: ReadonlyArray; +} + +/** + * CheckpointStoreShape - Service API for checkpoint capture/restore and diff access. + */ +export interface CheckpointStoreShape { + /** + * Check whether cwd is inside a Git worktree. + */ + readonly isGitRepository: (cwd: string) => Effect.Effect; + + /** + * Capture a checkpoint commit and store it at the provided checkpoint ref. + * + * Uses an isolated temporary Git index and writes a hidden ref. + */ + readonly captureCheckpoint: ( + input: CaptureCheckpointInput, + ) => Effect.Effect; + + /** + * Check whether a checkpoint ref exists. + */ + readonly hasCheckpointRef: ( + input: Omit, + ) => Effect.Effect; + + /** + * Restore workspace/staging state to a checkpoint. + * + * Optionally falls back to current `HEAD` when the checkpoint ref is missing. + */ + readonly restoreCheckpoint: ( + input: RestoreCheckpointInput, + ) => Effect.Effect; + + /** + * Compute patch diff between two checkpoint refs. + * + * Can optionally treat missing "from" ref as `HEAD`. + */ + readonly diffCheckpoints: ( + input: DiffCheckpointsInput, + ) => Effect.Effect; + + /** + * Delete the provided checkpoint refs. + * + * Best-effort delete: missing refs are tolerated. + */ + readonly deleteCheckpointRefs: ( + input: DeleteCheckpointRefsInput, + ) => Effect.Effect; +} + +/** + * CheckpointStore - Service tag for checkpoint persistence and restore operations. + */ +export class CheckpointStore extends ServiceMap.Service()( + "t3/checkpointing/Services/CheckpointStore", +) {} diff --git a/apps/server/src/checkpointing/Utils.ts b/apps/server/src/checkpointing/Utils.ts new file mode 100644 index 0000000000..3cd92f8510 --- /dev/null +++ b/apps/server/src/checkpointing/Utils.ts @@ -0,0 +1,28 @@ +import { Encoding } from "effect"; +import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts"; + +export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints"; + +export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef { + return CheckpointRef.makeUnsafe( + `${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`, + ); +} + +export function resolveThreadWorkspaceCwd(input: { + readonly thread: { + readonly projectId: ProjectId; + readonly worktreePath: string | null; + }; + readonly projects: ReadonlyArray<{ + readonly id: ProjectId; + readonly workspaceRoot: string; + }>; +}): string | undefined { + const worktreeCwd = input.thread.worktreePath ?? undefined; + if (worktreeCwd) { + return worktreeCwd; + } + + return input.projects.find((project) => project.id === input.thread.projectId)?.workspaceRoot; +} diff --git a/apps/server/src/cli-config.test.ts b/apps/server/src/cli-config.test.ts new file mode 100644 index 0000000000..ef2f9f55d8 --- /dev/null +++ b/apps/server/src/cli-config.test.ts @@ -0,0 +1,411 @@ +import os from "node:os"; + +import { assert, expect, it } from "@effect/vitest"; +import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect"; + +import { NetService } from "@t3tools/shared/Net"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { deriveServerPaths } from "./config"; +import { resolveServerConfig } from "./cli"; + +it.layer(NodeServices.layer)("cli config resolution", (it) => { + const defaultObservabilityConfig = { + traceMinLevel: "Info", + traceTimingEnabled: true, + traceBatchWindowMs: 200, + traceMaxBytes: 10 * 1024 * 1024, + traceMaxFiles: 10, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpExportIntervalMs: 10_000, + otlpServiceName: "t3-server", + } as const; + + const openBootstrapFd = Effect.fn(function* (payload: Record) { + const fs = yield* FileSystem.FileSystem; + const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" }); + yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`); + const { fd } = yield* fs.open(filePath, { flag: "r" }); + return fd; + }); + + it.effect("falls back to effect/config values when flags are omitted", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const baseDir = join(os.tmpdir(), "t3-cli-config-env-base"); + const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173")); + const resolved = yield* resolveServerConfig( + { + mode: Option.none(), + port: Option.none(), + host: Option.none(), + baseDir: Option.none(), + cwd: Option.none(), + devUrl: Option.none(), + noBrowser: Option.none(), + authToken: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.none(), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + T3CODE_LOG_LEVEL: "Warn", + T3CODE_MODE: "desktop", + T3CODE_PORT: "4001", + T3CODE_HOST: "0.0.0.0", + T3CODE_HOME: baseDir, + VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", + T3CODE_NO_BROWSER: "true", + T3CODE_AUTH_TOKEN: "env-token", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", + T3CODE_LOG_WS_EVENTS: "true", + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Warn", + ...defaultObservabilityConfig, + mode: "desktop", + port: 4001, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "0.0.0.0", + staticDir: undefined, + devUrl: new URL("http://127.0.0.1:5173"), + noBrowser: true, + authToken: "env-token", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: true, + }); + }), + ); + + it.effect("uses CLI flags when provided", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const baseDir = join(os.tmpdir(), "t3-cli-config-flags-base"); + const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173")); + const resolved = yield* resolveServerConfig( + { + mode: Option.some("web"), + port: Option.some(8788), + host: Option.some("127.0.0.1"), + baseDir: Option.some(baseDir), + cwd: Option.none(), + devUrl: Option.some(new URL("http://127.0.0.1:4173")), + noBrowser: Option.some(true), + authToken: Option.some("flag-token"), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.some(true), + logWebSocketEvents: Option.some(true), + }, + Option.some("Debug"), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + T3CODE_LOG_LEVEL: "Warn", + T3CODE_MODE: "desktop", + T3CODE_PORT: "4001", + T3CODE_HOST: "0.0.0.0", + T3CODE_HOME: join(os.tmpdir(), "ignored-base"), + VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", + T3CODE_NO_BROWSER: "false", + T3CODE_AUTH_TOKEN: "ignored-token", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", + T3CODE_LOG_WS_EVENTS: "false", + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Debug", + ...defaultObservabilityConfig, + mode: "web", + port: 8788, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "127.0.0.1", + staticDir: undefined, + devUrl: new URL("http://127.0.0.1:4173"), + noBrowser: true, + authToken: "flag-token", + autoBootstrapProjectFromCwd: true, + logWebSocketEvents: true, + }); + }), + ); + + it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const baseDir = "/tmp/t3-bootstrap-home"; + const fd = yield* openBootstrapFd({ + mode: "desktop", + port: 4888, + host: "127.0.0.2", + t3Home: baseDir, + devUrl: "http://127.0.0.1:5173", + noBrowser: true, + authToken: "bootstrap-token", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: true, + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }); + const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173")); + + const resolved = yield* resolveServerConfig( + { + mode: Option.none(), + port: Option.none(), + host: Option.none(), + baseDir: Option.none(), + cwd: Option.none(), + devUrl: Option.none(), + noBrowser: Option.none(), + authToken: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.none(), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + T3CODE_BOOTSTRAP_FD: String(fd), + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Info", + ...defaultObservabilityConfig, + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + mode: "desktop", + port: 4888, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "127.0.0.2", + staticDir: undefined, + devUrl: new URL("http://127.0.0.1:5173"), + noBrowser: true, + authToken: "bootstrap-token", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: true, + }); + assert.equal(join(baseDir, "dev"), resolved.stateDir); + }), + ); + + it.effect("creates derived runtime directories during config resolution", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" }); + const customCwd = path.join(baseDir, "nested", "project"); + + const resolved = yield* resolveServerConfig( + { + mode: Option.some("desktop"), + port: Option.some(4888), + host: Option.none(), + baseDir: Option.some(baseDir), + cwd: Option.some(customCwd), + devUrl: Option.some(new URL("http://127.0.0.1:5173")), + noBrowser: Option.none(), + authToken: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.none(), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + NetService.layer, + ), + ), + ); + + for (const directory of [ + customCwd, + resolved.stateDir, + resolved.logsDir, + resolved.providerLogsDir, + resolved.terminalLogsDir, + resolved.attachmentsDir, + resolved.worktreesDir, + path.dirname(resolved.serverLogPath), + path.dirname(resolved.serverTracePath), + ]) { + expect(yield* fs.exists(directory)).toBe(true); + } + expect(resolved.cwd).toBe(path.resolve(customCwd)); + }), + ); + + it.effect("applies flag then env precedence over bootstrap envelope values", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const baseDir = join(os.tmpdir(), "t3-cli-config-env-wins"); + const fd = yield* openBootstrapFd({ + mode: "desktop", + port: 4888, + host: "127.0.0.2", + t3Home: "/tmp/t3-bootstrap-home", + devUrl: "http://127.0.0.1:5173", + noBrowser: false, + authToken: "bootstrap-token", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + }); + const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173")); + + const resolved = yield* resolveServerConfig( + { + mode: Option.none(), + port: Option.some(8788), + host: Option.some("127.0.0.1"), + baseDir: Option.none(), + cwd: Option.none(), + devUrl: Option.some(new URL("http://127.0.0.1:4173")), + noBrowser: Option.none(), + authToken: Option.some("flag-token"), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.some("Debug"), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + T3CODE_MODE: "web", + T3CODE_BOOTSTRAP_FD: String(fd), + T3CODE_HOME: baseDir, + T3CODE_NO_BROWSER: "true", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true", + T3CODE_LOG_WS_EVENTS: "true", + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Debug", + ...defaultObservabilityConfig, + mode: "web", + port: 8788, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "127.0.0.1", + staticDir: undefined, + devUrl: new URL("http://127.0.0.1:4173"), + noBrowser: true, + authToken: "flag-token", + autoBootstrapProjectFromCwd: true, + logWebSocketEvents: true, + }); + }), + ); + + it.effect("falls back to persisted observability settings when env vars are absent", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" }); + const derivedPaths = yield* deriveServerPaths(baseDir, undefined); + yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }); + yield* fs.writeFileString( + derivedPaths.settingsPath, + `${JSON.stringify({ + observability: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, + })}\n`, + ); + + const resolved = yield* resolveServerConfig( + { + mode: Option.some("desktop"), + port: Option.some(4888), + host: Option.none(), + baseDir: Option.some(baseDir), + cwd: Option.none(), + devUrl: Option.none(), + noBrowser: Option.none(), + authToken: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.none(), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + NetService.layer, + ), + ), + ); + + expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces"); + expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics"); + expect(resolved).toEqual({ + logLevel: "Info", + ...defaultObservabilityConfig, + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + mode: "desktop", + port: 4888, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "127.0.0.1", + staticDir: resolved.staticDir, + devUrl: undefined, + noBrowser: true, + authToken: undefined, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + }); + }), + ); +}); diff --git a/apps/server/src/cli.test.ts b/apps/server/src/cli.test.ts new file mode 100644 index 0000000000..fbbe26e6cf --- /dev/null +++ b/apps/server/src/cli.test.ts @@ -0,0 +1,37 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { NetService } from "@t3tools/shared/Net"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as CliError from "effect/unstable/cli/CliError"; +import { Command } from "effect/unstable/cli"; + +import { cli } from "./cli.ts"; + +const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); + +it.layer(NodeServices.layer)("cli log-level parsing", (it) => { + it.effect("accepts the built-in lowercase log-level flag values", () => + Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe( + Effect.provide(CliRuntimeLayer), + ), + ); + + it.effect("rejects invalid log-level casing before launching the server", () => + Effect.gen(function* () { + const error = yield* Command.runWith(cli, { version: "0.0.0" })([ + "--log-level", + "Debug", + ]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip); + + if (!CliError.isCliError(error)) { + assert.fail(`Expected CliError, got ${String(error)}`); + } + if (error._tag !== "InvalidValue") { + assert.fail(`Expected InvalidValue, got ${error._tag}`); + } + assert.equal(error.option, "log-level"); + assert.equal(error.value, "Debug"); + }), + ); +}); diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts new file mode 100644 index 0000000000..9ece02a0d3 --- /dev/null +++ b/apps/server/src/cli.ts @@ -0,0 +1,368 @@ +import { NetService } from "@t3tools/shared/Net"; +import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; +import { Config, Effect, FileSystem, LogLevel, Option, Path, Schema } from "effect"; +import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli"; + +import { + DEFAULT_PORT, + deriveServerPaths, + ensureServerDirectories, + resolveStaticDir, + ServerConfig, + RuntimeMode, + type ServerConfigShape, +} from "./config"; +import { readBootstrapEnvelope } from "./bootstrap"; +import { expandHomePath, resolveBaseDir } from "./os-jank"; +import { runServer } from "./server"; + +const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })); + +const BootstrapEnvelopeSchema = Schema.Struct({ + mode: Schema.optional(RuntimeMode), + port: Schema.optional(PortSchema), + host: Schema.optional(Schema.String), + t3Home: Schema.optional(Schema.String), + devUrl: Schema.optional(Schema.URLFromString), + noBrowser: Schema.optional(Schema.Boolean), + authToken: Schema.optional(Schema.String), + autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean), + logWebSocketEvents: Schema.optional(Schema.Boolean), + otlpTracesUrl: Schema.optional(Schema.String), + otlpMetricsUrl: Schema.optional(Schema.String), +}); + +const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe( + Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."), + Flag.optional, +); +const portFlag = Flag.integer("port").pipe( + Flag.withSchema(PortSchema), + Flag.withDescription("Port for the HTTP/WebSocket server."), + Flag.optional, +); +const hostFlag = Flag.string("host").pipe( + Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."), + Flag.optional, +); +const baseDirFlag = Flag.string("base-dir").pipe( + Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."), + Flag.optional, +); +const devUrlFlag = Flag.string("dev-url").pipe( + Flag.withSchema(Schema.URLFromString), + Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."), + Flag.optional, +); +const noBrowserFlag = Flag.boolean("no-browser").pipe( + Flag.withDescription("Disable automatic browser opening."), + Flag.optional, +); +const authTokenFlag = Flag.string("auth-token").pipe( + Flag.withDescription("Auth token required for WebSocket connections."), + Flag.withAlias("token"), + Flag.optional, +); +const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe( + Flag.withSchema(Schema.Int), + Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."), + Flag.optional, +); +const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe( + Flag.withDescription( + "Create a project for the current working directory on startup when missing.", + ), + Flag.optional, +); +const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe( + Flag.withDescription( + "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).", + ), + Flag.withAlias("log-ws-events"), + Flag.optional, +); + +const EnvServerConfig = Config.all({ + logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")), + traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")), + traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)), + traceFile: Config.string("T3CODE_TRACE_FILE").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)), + traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)), + traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)), + otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe( + Config.withDefault(10_000), + ), + otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")), + mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)), + host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)), + t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)), + devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)), + noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + authToken: Config.string("T3CODE_AUTH_TOKEN").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), +}); + +interface CliServerFlags { + readonly mode: Option.Option; + readonly port: Option.Option; + readonly host: Option.Option; + readonly baseDir: Option.Option; + readonly cwd: Option.Option; + readonly devUrl: Option.Option; + readonly noBrowser: Option.Option; + readonly authToken: Option.Option; + readonly bootstrapFd: Option.Option; + readonly autoBootstrapProjectFromCwd: Option.Option; + readonly logWebSocketEvents: Option.Option; +} + +const resolveBooleanFlag = (flag: Option.Option, envValue: boolean) => + Option.getOrElse(Option.filter(flag, Boolean), () => envValue); + +const resolveOptionPrecedence = ( + ...values: ReadonlyArray> +): Option.Option => Option.firstSomeOf(values); + +const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) { + const fs = yield* FileSystem.FileSystem; + const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false)); + if (!exists) { + return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined }; + } + + const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => "")); + return parsePersistedServerObservabilitySettings(raw); +}); + +export const resolveServerConfig = ( + flags: CliServerFlags, + cliLogLevel: Option.Option, +) => + Effect.gen(function* () { + const { findAvailablePort } = yield* NetService; + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; + const env = yield* EnvServerConfig; + const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd; + const bootstrapEnvelope = + bootstrapFd !== undefined + ? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd) + : Option.none(); + + const mode: RuntimeMode = Option.getOrElse( + resolveOptionPrecedence( + flags.mode, + Option.fromUndefinedOr(env.mode), + Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)), + ), + () => "web", + ); + + const port = yield* Option.match( + resolveOptionPrecedence( + flags.port, + Option.fromUndefinedOr(env.port), + Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)), + ), + { + onSome: (value) => Effect.succeed(value), + onNone: () => { + if (mode === "desktop") { + return Effect.succeed(DEFAULT_PORT); + } + return findAvailablePort(DEFAULT_PORT); + }, + }, + ); + const devUrl = Option.getOrElse( + resolveOptionPrecedence( + flags.devUrl, + Option.fromUndefinedOr(env.devUrl), + Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)), + ), + () => undefined, + ); + const baseDir = yield* resolveBaseDir( + Option.getOrUndefined( + resolveOptionPrecedence( + flags.baseDir, + Option.fromUndefinedOr(env.t3Home), + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.t3Home), + ), + ), + ), + ); + const rawCwd = Option.getOrElse(flags.cwd, () => process.cwd()); + const cwd = path.resolve(yield* expandHomePath(rawCwd.trim())); + yield* fs.makeDirectory(cwd, { recursive: true }); + const derivedPaths = yield* deriveServerPaths(baseDir, devUrl); + yield* ensureServerDirectories(derivedPaths); + const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings( + derivedPaths.settingsPath, + ); + const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath; + yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true }); + const noBrowser = resolveBooleanFlag( + flags.noBrowser, + Option.getOrElse( + resolveOptionPrecedence( + Option.fromUndefinedOr(env.noBrowser), + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.noBrowser), + ), + ), + () => mode === "desktop", + ), + ); + const authToken = Option.getOrUndefined( + resolveOptionPrecedence( + flags.authToken, + Option.fromUndefinedOr(env.authToken), + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.authToken), + ), + ), + ); + const autoBootstrapProjectFromCwd = resolveBooleanFlag( + flags.autoBootstrapProjectFromCwd, + Option.getOrElse( + resolveOptionPrecedence( + Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd), + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd), + ), + ), + () => mode === "web", + ), + ); + const logWebSocketEvents = resolveBooleanFlag( + flags.logWebSocketEvents, + Option.getOrElse( + resolveOptionPrecedence( + Option.fromUndefinedOr(env.logWebSocketEvents), + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.logWebSocketEvents), + ), + ), + () => Boolean(devUrl), + ), + ); + const staticDir = devUrl ? undefined : yield* resolveStaticDir(); + const host = Option.getOrElse( + resolveOptionPrecedence( + flags.host, + Option.fromUndefinedOr(env.host), + Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)), + ), + () => (mode === "desktop" ? "127.0.0.1" : undefined), + ); + const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel); + + const config: ServerConfigShape = { + logLevel, + traceMinLevel: env.traceMinLevel, + traceTimingEnabled: env.traceTimingEnabled, + traceBatchWindowMs: env.traceBatchWindowMs, + traceMaxBytes: env.traceMaxBytes, + traceMaxFiles: env.traceMaxFiles, + otlpTracesUrl: + env.otlpTracesUrl ?? + Option.getOrUndefined( + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.otlpTracesUrl), + ), + ) ?? + persistedObservabilitySettings.otlpTracesUrl, + otlpMetricsUrl: + env.otlpMetricsUrl ?? + Option.getOrUndefined( + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.otlpMetricsUrl), + ), + ) ?? + persistedObservabilitySettings.otlpMetricsUrl, + otlpExportIntervalMs: env.otlpExportIntervalMs, + otlpServiceName: env.otlpServiceName, + mode, + port, + cwd, + baseDir, + ...derivedPaths, + serverTracePath, + host, + staticDir, + devUrl, + noBrowser, + authToken, + autoBootstrapProjectFromCwd, + logWebSocketEvents, + }; + + return config; + }); + +const commandFlags = { + mode: modeFlag, + port: portFlag, + host: hostFlag, + baseDir: baseDirFlag, + cwd: Argument.string("cwd").pipe( + Argument.withDescription( + "Working directory for provider sessions (defaults to the current directory).", + ), + Argument.optional, + ), + devUrl: devUrlFlag, + noBrowser: noBrowserFlag, + authToken: authTokenFlag, + bootstrapFd: bootstrapFdFlag, + autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag, + logWebSocketEvents: logWebSocketEventsFlag, +} as const; + +const rootCommand = Command.make("t3", commandFlags).pipe( + Command.withDescription("Run the T3 Code server."), + Command.withHandler((flags) => + Effect.gen(function* () { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveServerConfig(flags, logLevel); + return yield* runServer.pipe(Effect.provideService(ServerConfig, config)); + }), + ), +); + +export const cli = rootCommand; diff --git a/apps/server/src/codexAppServerManager.test.ts b/apps/server/src/codexAppServerManager.test.ts index 4a97814a73..2f740a7407 100644 --- a/apps/server/src/codexAppServerManager.test.ts +++ b/apps/server/src/codexAppServerManager.test.ts @@ -1,23 +1,43 @@ import { describe, expect, it, vi } from "vitest"; +import { randomUUID } from "node:crypto"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +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); + 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, + }, + collabReceiverTurns: new Map(), }; const requireSession = vi @@ -43,6 +63,118 @@ function createSendTurnHarness() { return { manager, context, requireSession, sendRequest, updateSession }; } +function createThreadControlHarness() { + const manager = new CodexAppServerManager(); + const context = { + session: { + 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", + }, + collabReceiverTurns: new Map(), + }; + + const requireSession = vi + .spyOn( + manager as unknown as { requireSession: (sessionId: string) => unknown }, + "requireSession", + ) + .mockReturnValue(context); + const sendRequest = vi.spyOn( + manager as unknown as { sendRequest: (...args: unknown[]) => Promise }, + "sendRequest", + ); + const updateSession = vi + .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession") + .mockImplementation(() => {}); + + return { manager, context, requireSession, sendRequest, updateSession }; +} + +function createPendingUserInputHarness() { + const manager = new CodexAppServerManager(); + const context = { + session: { + 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", + }, + pendingUserInputs: new Map([ + [ + ApprovalRequestId.makeUnsafe("req-user-input-1"), + { + requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"), + jsonRpcId: 42, + threadId: asThreadId("thread_1"), + }, + ], + ]), + collabReceiverTurns: new Map(), + }; + + const requireSession = vi + .spyOn( + manager as unknown as { requireSession: (sessionId: string) => unknown }, + "requireSession", + ) + .mockReturnValue(context); + const writeMessage = vi + .spyOn(manager as unknown as { writeMessage: (...args: unknown[]) => void }, "writeMessage") + .mockImplementation(() => {}); + const emitEvent = vi + .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent") + .mockImplementation(() => {}); + + return { manager, context, requireSession, writeMessage, emitEvent }; +} + +function createCollabNotificationHarness() { + const manager = new CodexAppServerManager(); + const context = { + session: { + provider: "codex", + status: "running", + threadId: asThreadId("thread_1"), + runtimeMode: "full-access", + model: "gpt-5.3-codex", + activeTurnId: "turn_parent", + resumeCursor: { threadId: "provider_parent" }, + createdAt: "2026-02-10T00:00:00.000Z", + updatedAt: "2026-02-10T00:00:00.000Z", + }, + account: { + type: "unknown", + planType: null, + sparkEnabled: true, + }, + pending: new Map(), + pendingApprovals: new Map(), + pendingUserInputs: new Map(), + collabReceiverTurns: new Map(), + nextRequestId: 1, + stopping: false, + }; + + const emitEvent = vi + .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent") + .mockImplementation(() => {}); + const updateSession = vi + .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession") + .mockImplementation(() => {}); + + return { manager, context, emitEvent, updateSession }; +} + describe("classifyCodexStderrLine", () => { it("ignores empty lines", () => { expect(classifyCodexStderrLine(" ")).toBeNull(); @@ -75,6 +207,42 @@ describe("classifyCodexStderrLine", () => { }); }); +describe("process stderr events", () => { + it("emits classified stderr lines as notifications", () => { + const manager = new CodexAppServerManager(); + const emitEvent = vi + .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent") + .mockImplementation(() => {}); + + ( + manager as unknown as { + emitNotificationEvent: ( + context: { session: { threadId: ThreadId } }, + method: string, + message: string, + ) => void; + } + ).emitNotificationEvent( + { + session: { + threadId: asThreadId("thread-1"), + }, + }, + "process/stderr", + "fatal: permission denied", + ); + + expect(emitEvent).toHaveBeenCalledWith( + expect.objectContaining({ + kind: "notification", + method: "process/stderr", + threadId: "thread-1", + message: "fatal: permission denied", + }), + ); + }); +}); + describe("normalizeCodexModelSlug", () => { it("maps 5.3 aliases to gpt-5.3-codex", () => { expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex"); @@ -113,32 +281,222 @@ describe("isRecoverableThreadResumeError", () => { }); }); +describe("readCodexAccountSnapshot", () => { + it("disables spark for chatgpt plus accounts", () => { + expect( + readCodexAccountSnapshot({ + type: "chatgpt", + email: "plus@example.com", + planType: "plus", + }), + ).toEqual({ + type: "chatgpt", + planType: "plus", + sparkEnabled: false, + }); + }); + + it("keeps spark enabled for chatgpt pro accounts", () => { + expect( + readCodexAccountSnapshot({ + type: "chatgpt", + email: "pro@example.com", + planType: "pro", + }), + ).toEqual({ + type: "chatgpt", + planType: "pro", + sparkEnabled: true, + }); + }); + + it("disables spark for api key accounts", () => { + expect( + readCodexAccountSnapshot({ + type: "apiKey", + }), + ).toEqual({ + type: "apiKey", + planType: null, + sparkEnabled: false, + }); + }); + + it("disables spark for unknown chatgpt plans", () => { + expect( + readCodexAccountSnapshot({ + type: "chatgpt", + email: "unknown@example.com", + }), + ).toEqual({ + type: "chatgpt", + planType: "unknown", + sparkEnabled: false, + }); + }); +}); + +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"); + }); + + it("falls back from spark to default for api key auth", () => { + expect( + resolveCodexModelForAccount("gpt-5.3-codex-spark", { + type: "apiKey", + planType: null, + sparkEnabled: false, + }), + ).toBe("gpt-5.3-codex"); + }); +}); + +describe("startSession", () => { + it("enables Codex experimental api capabilities during initialize", () => { + expect(buildCodexInitializeParams()).toEqual({ + clientInfo: { + name: "t3code_desktop", + title: "T3 Code Desktop", + version: "0.1.0", + }, + capabilities: { + experimentalApi: true, + }, + }); + }); + + it("emits session/startFailed when resolving cwd throws before process launch", async () => { + const manager = new CodexAppServerManager(); + const events: Array<{ method: string; kind: string; message?: string }> = []; + manager.on("event", (event) => { + events.push({ + method: event.method, + kind: event.kind, + ...(event.message ? { message: event.message } : {}), + }); + }); + + const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => { + throw new Error("cwd missing"); + }); + try { + await expect( + manager.startSession({ + threadId: asThreadId("thread-1"), + provider: "codex", + binaryPath: "codex", + runtimeMode: "full-access", + }), + ).rejects.toThrow("cwd missing"); + expect(events).toHaveLength(1); + expect(events[0]).toEqual({ + method: "session/startFailed", + kind: "error", + message: "cwd missing", + }); + } finally { + processCwd.mockRestore(); + manager.stopAll(); + } + }); + + 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", + binaryPath: "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", () => { it("sends text and image user input items to turn/start", async () => { const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness(); const result = await manager.sendTurn({ - sessionId: "sess_1", + threadId: asThreadId("thread_1"), input: "Inspect this image", attachments: [ { type: "image", - name: "error.png", - mimeType: "image/png", - sizeBytes: 1_024, - dataUrl: "data:image/png;base64,AAAA", + url: "data:image/png;base64,AAAA", }, ], model: "gpt-5.3", + serviceTier: "fast", effort: "high", }); expect(result).toEqual({ threadId: "thread_1", turnId: "turn_1", + resumeCursor: { threadId: "thread_1" }, }); - expect(requireSession).toHaveBeenCalledWith("sess_1"); + expect(requireSession).toHaveBeenCalledWith("thread_1"); expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", { threadId: "thread_1", input: [ @@ -153,11 +511,13 @@ describe("sendTurn", () => { }, ], model: "gpt-5.3-codex", + serviceTier: "fast", effort: "high", }); expect(updateSession).toHaveBeenCalledWith(context, { status: "running", activeTurnId: "turn_1", + resumeCursor: { threadId: "thread_1" }, }); }); @@ -165,14 +525,11 @@ describe("sendTurn", () => { const { manager, context, sendRequest } = createSendTurnHarness(); await manager.sendTurn({ - sessionId: "sess_1", + threadId: asThreadId("thread_1"), attachments: [ { type: "image", - name: "diagram.png", - mimeType: "image/png", - sizeBytes: 256, - dataUrl: "data:image/png;base64,BBBB", + url: "data:image/png;base64,BBBB", }, ], }); @@ -185,6 +542,98 @@ describe("sendTurn", () => { url: "data:image/png;base64,BBBB", }, ], + model: "gpt-5.3-codex", + }); + }); + + it("passes Codex plan mode as a collaboration preset on turn/start", async () => { + const { manager, context, sendRequest } = createSendTurnHarness(); + + await manager.sendTurn({ + threadId: asThreadId("thread_1"), + input: "Plan the work", + interactionMode: "plan", + }); + + expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", { + threadId: "thread_1", + input: [ + { + type: "text", + text: "Plan the work", + text_elements: [], + }, + ], + model: "gpt-5.3-codex", + collaborationMode: { + mode: "plan", + settings: { + model: "gpt-5.3-codex", + reasoning_effort: "medium", + developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, + }, + }, + }); + }); + + 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, + }, + }, }); }); @@ -193,8 +642,429 @@ describe("sendTurn", () => { await expect( manager.sendTurn({ - sessionId: "sess_1", + threadId: asThreadId("thread_1"), }), ).rejects.toThrow("Turn input must include text or attachments."); }); }); + +describe("thread checkpoint control", () => { + it("reads thread turns from thread/read", async () => { + const { manager, context, requireSession, sendRequest } = createThreadControlHarness(); + sendRequest.mockResolvedValue({ + thread: { + id: "thread_1", + turns: [ + { + id: "turn_1", + items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }], + }, + ], + }, + }); + + const result = await manager.readThread(asThreadId("thread_1")); + + expect(requireSession).toHaveBeenCalledWith("thread_1"); + expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", { + threadId: "thread_1", + includeTurns: true, + }); + expect(result).toEqual({ + threadId: "thread_1", + turns: [ + { + id: "turn_1", + items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }], + }, + ], + }); + }); + + it("reads thread turns from flat thread/read responses", async () => { + const { manager, context, sendRequest } = createThreadControlHarness(); + sendRequest.mockResolvedValue({ + threadId: "thread_1", + turns: [ + { + id: "turn_1", + items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }], + }, + ], + }); + + const result = await manager.readThread(asThreadId("thread_1")); + + expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", { + threadId: "thread_1", + includeTurns: true, + }); + expect(result).toEqual({ + threadId: "thread_1", + turns: [ + { + id: "turn_1", + items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }], + }, + ], + }); + }); + + it("rolls back turns via thread/rollback and resets session running state", async () => { + const { manager, context, sendRequest, updateSession } = createThreadControlHarness(); + sendRequest.mockResolvedValue({ + thread: { + id: "thread_1", + turns: [], + }, + }); + + const result = await manager.rollbackThread(asThreadId("thread_1"), 2); + + expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", { + threadId: "thread_1", + numTurns: 2, + }); + expect(updateSession).toHaveBeenCalledWith(context, { + status: "ready", + activeTurnId: undefined, + }); + expect(result).toEqual({ + threadId: "thread_1", + turns: [], + }); + }); +}); + +describe("respondToUserInput", () => { + it("serializes canonical answers to Codex native answer objects", async () => { + const { manager, context, requireSession, writeMessage, emitEvent } = + createPendingUserInputHarness(); + + await manager.respondToUserInput( + asThreadId("thread_1"), + ApprovalRequestId.makeUnsafe("req-user-input-1"), + { + scope: "All request methods", + compat: "Keep current envelope", + }, + ); + + expect(requireSession).toHaveBeenCalledWith("thread_1"); + expect(writeMessage).toHaveBeenCalledWith(context, { + id: 42, + result: { + answers: { + scope: { answers: ["All request methods"] }, + compat: { answers: ["Keep current envelope"] }, + }, + }, + }); + expect(emitEvent).toHaveBeenCalledWith( + expect.objectContaining({ + method: "item/tool/requestUserInput/answered", + payload: { + requestId: "req-user-input-1", + answers: { + scope: { answers: ["All request methods"] }, + compat: { answers: ["Keep current envelope"] }, + }, + }, + }), + ); + }); + + 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(), + collabReceiverTurns: 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, + ) => 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("collab child conversation routing", () => { + it("rewrites child notification turn ids onto the parent turn", () => { + const { manager, context, emitEvent } = createCollabNotificationHarness(); + + ( + manager as unknown as { + handleServerNotification: (context: unknown, notification: Record) => void; + } + ).handleServerNotification(context, { + method: "item/completed", + params: { + item: { + type: "collabAgentToolCall", + id: "call_collab_1", + receiverThreadIds: ["child_provider_1"], + }, + threadId: "provider_parent", + turnId: "turn_parent", + }, + }); + + ( + manager as unknown as { + handleServerNotification: (context: unknown, notification: Record) => void; + } + ).handleServerNotification(context, { + method: "item/agentMessage/delta", + params: { + threadId: "child_provider_1", + turnId: "turn_child_1", + itemId: "msg_child_1", + delta: "working", + }, + }); + + expect(emitEvent).toHaveBeenLastCalledWith( + expect.objectContaining({ + method: "item/agentMessage/delta", + turnId: "turn_parent", + itemId: "msg_child_1", + }), + ); + }); + + it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => { + const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness(); + + ( + manager as unknown as { + handleServerNotification: (context: unknown, notification: Record) => void; + } + ).handleServerNotification(context, { + method: "item/completed", + params: { + item: { + type: "collabAgentToolCall", + id: "call_collab_1", + receiverThreadIds: ["child_provider_1"], + }, + threadId: "provider_parent", + turnId: "turn_parent", + }, + }); + emitEvent.mockClear(); + updateSession.mockClear(); + + ( + manager as unknown as { + handleServerNotification: (context: unknown, notification: Record) => void; + } + ).handleServerNotification(context, { + method: "turn/started", + params: { + threadId: "child_provider_1", + turn: { id: "turn_child_1" }, + }, + }); + + ( + manager as unknown as { + handleServerNotification: (context: unknown, notification: Record) => void; + } + ).handleServerNotification(context, { + method: "turn/completed", + params: { + threadId: "child_provider_1", + turn: { id: "turn_child_1", status: "completed" }, + }, + }); + + expect(emitEvent).not.toHaveBeenCalled(); + expect(updateSession).not.toHaveBeenCalled(); + }); + + it("rewrites child approval requests onto the parent turn", () => { + const { manager, context, emitEvent } = createCollabNotificationHarness(); + + ( + manager as unknown as { + handleServerNotification: (context: unknown, notification: Record) => void; + } + ).handleServerNotification(context, { + method: "item/completed", + params: { + item: { + type: "collabAgentToolCall", + id: "call_collab_1", + receiverThreadIds: ["child_provider_1"], + }, + threadId: "provider_parent", + turnId: "turn_parent", + }, + }); + emitEvent.mockClear(); + + ( + manager as unknown as { + handleServerRequest: (context: unknown, request: Record) => void; + } + ).handleServerRequest(context, { + id: 42, + method: "item/commandExecution/requestApproval", + params: { + threadId: "child_provider_1", + turnId: "turn_child_1", + itemId: "call_child_1", + command: "bun install", + }, + }); + + expect(Array.from(context.pendingApprovals.values())[0]).toEqual( + expect.objectContaining({ + turnId: "turn_parent", + itemId: "call_child_1", + }), + ); + expect(emitEvent).toHaveBeenCalledWith( + expect.objectContaining({ + method: "item/commandExecution/requestApproval", + turnId: "turn_parent", + itemId: "call_child_1", + }), + ); + }); +}); + +describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => { + it("keeps prior thread history when resuming with a changed runtime mode", async () => { + const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-")); + writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8"); + + const manager = new CodexAppServerManager(); + + try { + const firstSession = await manager.startSession({ + threadId: asThreadId("thread-live"), + provider: "codex", + cwd: workspaceDir, + runtimeMode: "full-access", + binaryPath: process.env.CODEX_BINARY_PATH!, + ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}), + }); + + const firstTurn = await manager.sendTurn({ + threadId: firstSession.threadId, + input: `Reply with exactly the word ALPHA ${randomUUID()}`, + }); + + expect(firstTurn.threadId).toBe(firstSession.threadId); + + await vi.waitFor( + async () => { + const snapshot = await manager.readThread(firstSession.threadId); + expect(snapshot.turns.length).toBeGreaterThan(0); + }, + { timeout: 120_000, interval: 1_000 }, + ); + + const firstSnapshot = await manager.readThread(firstSession.threadId); + const originalThreadId = firstSnapshot.threadId; + const originalTurnCount = firstSnapshot.turns.length; + + manager.stopSession(firstSession.threadId); + + const resumedSession = await manager.startSession({ + threadId: firstSession.threadId, + provider: "codex", + cwd: workspaceDir, + runtimeMode: "approval-required", + resumeCursor: firstSession.resumeCursor, + binaryPath: process.env.CODEX_BINARY_PATH!, + ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}), + }); + + expect(resumedSession.threadId).toBe(originalThreadId); + + const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId); + expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId); + expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount); + + await manager.sendTurn({ + threadId: resumedSession.threadId, + input: `Reply with exactly the word BETA ${randomUUID()}`, + }); + + await vi.waitFor( + async () => { + const snapshot = await manager.readThread(resumedSession.threadId); + expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount); + }, + { timeout: 120_000, interval: 1_000 }, + ); + } finally { + manager.stopAll(); + rmSync(workspaceDir, { recursive: true, force: true }); + } + }, 180_000); +}); diff --git a/apps/server/src/codexAppServerManager.ts b/apps/server/src/codexAppServerManager.ts index 27da26fb0b..3145038647 100644 --- a/apps/server/src/codexAppServerManager.ts +++ b/apps/server/src/codexAppServerManager.ts @@ -1,18 +1,40 @@ -import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; +import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process"; import { randomUUID } from "node:crypto"; import { EventEmitter } from "node:events"; import readline from "node:readline"; -import type { - ProviderApprovalDecision, - ProviderEvent, +import { + ApprovalRequestId, + EventId, + ProviderItemId, ProviderRequestKind, - ProviderSendTurnInput, - ProviderSession, - ProviderSessionStartInput, - ProviderTurnStartResult, + type ProviderUserInputAnswers, + ThreadId, + TurnId, + type ProviderApprovalDecision, + type ProviderEvent, + type ProviderSession, + type ProviderTurnStartResult, + RuntimeMode, + ProviderInteractionMode, } from "@t3tools/contracts"; -import { normalizeModelSlug } from "@t3tools/contracts"; +import { normalizeModelSlug } from "@t3tools/shared/model"; +import { Effect, ServiceMap } from "effect"; + +import { + formatCodexCliUpgradeMessage, + isCodexCliVersionSupported, + parseCodexCliVersion, +} from "./provider/codexCliVersion"; +import { + readCodexAccountSnapshot, + resolveCodexModelForAccount, + type CodexAccountSnapshot, +} from "./provider/codexAccount"; +import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer"; + +export { buildCodexInitializeParams } from "./provider/codexAppServer"; +export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount"; type PendingRequestKey = string; @@ -24,21 +46,39 @@ interface PendingRequest { } interface PendingApprovalRequest { - requestId: string; + 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?: string; - turnId?: string; - itemId?: string; + threadId: ThreadId; + turnId?: TurnId; + itemId?: ProviderItemId; +} + +interface PendingUserInputRequest { + requestId: ApprovalRequestId; + jsonRpcId: string | number; + threadId: ThreadId; + turnId?: TurnId; + itemId?: ProviderItemId; +} + +interface CodexUserInputAnswer { + answers: string[]; } interface CodexSessionContext { session: ProviderSession; + account: CodexAccountSnapshot; child: ChildProcessWithoutNullStreams; output: readline.Interface; pending: Map; - pendingApprovals: Map; + pendingApprovals: Map; + pendingUserInputs: Map; + collabReceiverTurns: Map; nextRequestId: number; stopping: boolean; } @@ -65,6 +105,40 @@ interface JsonRpcNotification { params?: unknown; } +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 interactionMode?: ProviderInteractionMode; +} + +export interface CodexAppServerStartSessionInput { + readonly threadId: ThreadId; + readonly provider?: "codex"; + readonly cwd?: string; + readonly model?: string; + readonly serviceTier?: string; + readonly resumeCursor?: unknown; + readonly binaryPath: string; + readonly homePath?: string; + readonly runtimeMode: RuntimeMode; +} + +export interface CodexThreadTurnSnapshot { + id: TurnId; + items: unknown[]; +} + +export interface CodexThreadSnapshot { + threadId: string; + 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 = @@ -80,6 +154,166 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [ "unknown thread", "does not exist", ]; +export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `# 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. + +## Mode rules (strict) + +You are in **Plan Mode** until a developer message explicitly ends it. + +Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it. + +## Plan Mode vs update_plan tool + +Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`\` block. + +Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error. + +## Execution vs. mutation in Plan Mode + +You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions. + +### Allowed (non-mutating, plan-improving) + +Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples: + +* Reading or searching files, configs, schemas, types, manifests, and docs +* Static analysis, inspection, and repo exploration +* Dry-run style commands when they do not edit repo-tracked files +* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files + +### Not allowed (mutating, plan-executing) + +Actions that implement the plan or change repo-tracked state. Examples: + +* Editing or writing files +* Running formatters or linters that rewrite files +* Applying patches, migrations, or codegen that updates repo-tracked files +* Side-effectful commands whose purpose is to carry out the plan rather than refine it + +When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it. + +## PHASE 1 - Ground in the environment (explore first, ask second) + +Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged. + +Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available. + +Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first. + +Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration. + +## PHASE 2 - Intent chat (what they actually want) + +* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs. +* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask. + +## PHASE 3 - Implementation chat (what/how we'll build) + +* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints. + +## Asking questions + +Critical rules: + +* Strongly prefer using the \`request_user_input\` tool to ask any questions. +* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant. +* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool. + +You SHOULD ask many questions, but each question must: + +* materially change the spec/plan, OR +* confirm/lock an assumption, OR +* choose between meaningful tradeoffs. +* not be answerable by non-mutating commands. + +Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration. + +## Two kinds of unknowns (treat differently) + +1. **Discoverable facts** (repo/system truth): explore first. + + * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants). + * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent. + * If asking, present concrete candidates (paths/service names) + recommend one. + * Never ask questions you can answer from your environment (e.g., "where is this struct"). + +2. **Preferences/tradeoffs** (not discoverable): ask early. + + * These are intent or implementation preferences that cannot be derived from exploration. + * Provide 2-4 mutually exclusive options + a recommended default. + * If unanswered, proceed with the recommended option and record it as an assumption in the final plan. + +## Finalization rule + +Only output the final plan when it is decision complete and leaves no decisions to the implementer. + +When you present the official plan, wrap it in a \`\` block so the client can render it specially: + +1) The opening tag must be on its own line. +2) Start the plan content on the next line (no text on the same line as the tag). +3) The closing tag must be on its own line. +4) Use Markdown inside the block. +5) Keep the tags exactly as \`\` and \`\` (do not translate or rename them), even if the plan content is in another language. + +Example: + + +plan content + + +plan content should be human and agent digestible. The final plan must be plan-only and include: + +* A clear title +* A brief summary section +* Important changes or additions to public APIs/interfaces/types +* Test cases and scenarios +* Explicit assumptions and defaults chosen where needed + +Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan. + +Only produce at most one \`\` block per turn, and only when you are presenting a complete spec. +`; + +export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `# 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 \`...\` 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. +`; + +function mapCodexRuntimeMode(runtimeMode: RuntimeMode): { + readonly approvalPolicy: "on-request" | "never"; + readonly sandbox: "workspace-write" | "danger-full-access"; +} { + if (runtimeMode === "approval-required") { + return { + approvalPolicy: "on-request", + sandbox: "workspace-write", + }; + } + + return { + approvalPolicy: "never", + sandbox: "danger-full-access", + }; +} + +/** + * On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe` + * wrapper, leaving the actual command running. Use `taskkill /T` to kill the + * entire process tree instead. + */ +function killChildTree(child: ChildProcessWithoutNullStreams): void { + killCodexChildProcess(child); +} export function normalizeCodexModelSlug( model: string | undefined | null, @@ -97,6 +331,69 @@ export function normalizeCodexModelSlug( return normalized; } +function buildCodexCollaborationMode(input: { + readonly interactionMode?: "default" | "plan"; + readonly model?: string; + readonly effort?: string; +}): + | { + mode: "default" | "plan"; + settings: { + model: string; + reasoning_effort: string; + developer_instructions: string; + }; + } + | undefined { + if (input.interactionMode === undefined) { + return undefined; + } + const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex"; + return { + mode: input.interactionMode, + settings: { + model, + reasoning_effort: input.effort ?? "medium", + developer_instructions: + input.interactionMode === "plan" + ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS + : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, + }, + }; +} + +function toCodexUserInputAnswer(value: unknown): CodexUserInputAnswer { + if (typeof value === "string") { + return { answers: [value] }; + } + + if (Array.isArray(value)) { + const answers = value.filter((entry): entry is string => typeof entry === "string"); + return { answers }; + } + + if (value && typeof value === "object") { + const maybeAnswers = (value as { answers?: unknown }).answers; + if (Array.isArray(maybeAnswers)) { + const answers = maybeAnswers.filter((entry): entry is string => typeof entry === "string"); + return { answers }; + } + } + + throw new Error("User input answers must be strings or arrays of strings."); +} + +function toCodexUserInputAnswers( + answers: ProviderUserInputAnswers, +): Record { + return Object.fromEntries( + Object.entries(answers).map(([questionId, value]) => [ + questionId, + toCodexUserInputAnswer(value), + ]), + ); +} + export function classifyCodexStderrLine(rawLine: string): { message: string } | null { const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim(); if (!line) { @@ -133,82 +430,149 @@ export interface CodexAppServerManagerEvents { } export class CodexAppServerManager extends EventEmitter { - private readonly sessions = new Map(); + private readonly sessions = new Map(); - async startSession(input: ProviderSessionStartInput): Promise { - const sessionId = randomUUID(); + private runPromise: (effect: Effect.Effect) => Promise; + constructor(services?: ServiceMap.ServiceMap) { + super(); + this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise; + } + + async startSession(input: CodexAppServerStartSessionInput): Promise { + const threadId = input.threadId; const now = new Date().toISOString(); - - const session: ProviderSession = { - sessionId, - provider: "codex", - status: "connecting", - model: normalizeCodexModelSlug(input.model), - cwd: input.cwd, - createdAt: now, - updatedAt: now, - }; - - const child = spawn("codex", ["app-server"], { - cwd: input.cwd, - env: process.env, - stdio: ["pipe", "pipe", "pipe"], - }); - const output = readline.createInterface({ input: child.stdout }); - - const context: CodexSessionContext = { - session, - child, - output, - pending: new Map(), - pendingApprovals: new Map(), - nextRequestId: 1, - stopping: false, - }; - - this.sessions.set(sessionId, context); - this.attachProcessListeners(context); - - this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server"); + let context: CodexSessionContext | undefined; try { - await this.sendRequest(context, "initialize", { - clientInfo: { - name: "t3code_desktop", - title: "T3 Code Desktop", - version: "0.1.0", - }, - capabilities: { - experimentalApi: false, - }, + const resolvedCwd = input.cwd ?? process.cwd(); + + const session: ProviderSession = { + provider: "codex", + status: "connecting", + runtimeMode: input.runtimeMode, + model: normalizeCodexModelSlug(input.model), + cwd: resolvedCwd, + threadId, + createdAt: now, + updatedAt: now, + }; + + const codexBinaryPath = input.binaryPath; + const codexHomePath = input.homePath; + this.assertSupportedCodexCliVersion({ + binaryPath: codexBinaryPath, + cwd: resolvedCwd, + ...(codexHomePath ? { homePath: codexHomePath } : {}), }); + const child = spawn(codexBinaryPath, ["app-server"], { + cwd: resolvedCwd, + env: { + ...process.env, + ...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}), + }, + stdio: ["pipe", "pipe", "pipe"], + shell: process.platform === "win32", + }); + const output = readline.createInterface({ input: child.stdout }); + + context = { + session, + account: { + type: "unknown", + planType: null, + sparkEnabled: true, + }, + child, + output, + pending: new Map(), + pendingApprovals: new Map(), + pendingUserInputs: new Map(), + collabReceiverTurns: new Map(), + nextRequestId: 1, + stopping: false, + }; + + this.sessions.set(threadId, context); + this.attachProcessListeners(context); + + this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server"); + + 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, + ...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}), cwd: input.cwd ?? null, - approvalPolicy: input.approvalPolicy, - sandbox: input.sandboxMode, + ...mapCodexRuntimeMode(input.runtimeMode ?? "full-access"), }; const threadStartParams = { ...sessionOverrides, experimentalRawEvents: false, }; + const resumeThreadId = readResumeThreadId(input); + this.emitLifecycleEvent( + context, + "session/threadOpenRequested", + resumeThreadId + ? `Attempting to resume thread ${resumeThreadId}.` + : "Starting a new Codex thread.", + ); + await Effect.logInfo("codex app-server opening thread", { + threadId, + requestedRuntimeMode: input.runtimeMode, + requestedModel: normalizedModel ?? null, + requestedCwd: resolvedCwd, + resumeThreadId: resumeThreadId ?? null, + }).pipe(this.runPromise); let threadOpenMethod: "thread/start" | "thread/resume" = "thread/start"; let threadOpenResponse: unknown; - if (input.resumeThreadId) { + if (resumeThreadId) { try { threadOpenMethod = "thread/resume"; threadOpenResponse = await this.sendRequest(context, "thread/resume", { ...sessionOverrides, - threadId: input.resumeThreadId, + threadId: resumeThreadId, }); } catch (error) { if (!isRecoverableThreadResumeError(error)) { + this.emitErrorEvent( + context, + "session/threadResumeFailed", + error instanceof Error ? error.message : "Codex thread resume failed.", + ); + await Effect.logWarning("codex app-server thread resume failed", { + threadId, + requestedRuntimeMode: input.runtimeMode, + resumeThreadId, + recoverable: false, + cause: error instanceof Error ? error.message : String(error), + }).pipe(this.runPromise); throw error; } @@ -216,8 +580,15 @@ export class CodexAppServerManager extends EventEmitter { - const context = this.requireSession(input.sessionId); - if (!context.session.threadId) { - throw new Error("Session is missing a thread id."); - } + async sendTurn(input: CodexAppServerSendTurnInput): Promise { + const context = this.requireSession(input.threadId); + context.collabReceiverTurns.clear(); const turnInput: Array< { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string } @@ -271,7 +665,7 @@ export class CodexAppServerManager extends EventEmitter; model?: string; + serviceTier?: string | null; effort?: string; + collaborationMode?: { + mode: "default" | "plan"; + settings: { + model: string; + reasoning_effort: string; + developer_instructions: string; + }; + }; } = { - threadId: context.session.threadId, + threadId: providerThreadId, input: turnInput, }; - const normalizedModel = normalizeCodexModelSlug(input.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; } + const collaborationMode = buildCodexCollaborationMode({ + ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}), + ...(normalizedModel !== undefined ? { model: normalizedModel } : {}), + ...(input.effort !== undefined ? { effort: input.effort } : {}), + }); + if (collaborationMode) { + if (!turnStartParams.model) { + turnStartParams.model = collaborationMode.settings.model; + } + turnStartParams.collaborationMode = collaborationMode; + } const response = await this.sendRequest(context, "turn/start", turnStartParams); const turn = this.readObject(this.readObject(response), "turn"); - const turnId = this.readString(turn, "id"); - if (!turnId) { + const turnIdRaw = this.readString(turn, "id"); + if (!turnIdRaw) { throw new Error("turn/start response did not include a turn id."); } + const turnId = TurnId.makeUnsafe(turnIdRaw); this.updateSession(context, { status: "running", activeTurnId: turnId, + ...(context.session.resumeCursor !== undefined + ? { resumeCursor: context.session.resumeCursor } + : {}), }); return { threadId: context.session.threadId, turnId, + ...(context.session.resumeCursor !== undefined + ? { resumeCursor: context.session.resumeCursor } + : {}), }; } - async interruptTurn(sessionId: string, turnId?: string): Promise { - const context = this.requireSession(sessionId); + async interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise { + const context = this.requireSession(threadId); const effectiveTurnId = turnId ?? context.session.activeTurnId; - if (!effectiveTurnId || !context.session.threadId) { + const providerThreadId = readResumeThreadId({ + threadId: context.session.threadId, + runtimeMode: context.session.runtimeMode, + resumeCursor: context.session.resumeCursor, + }); + if (!effectiveTurnId || !providerThreadId) { return; } await this.sendRequest(context, "turn/interrupt", { - threadId: context.session.threadId, + threadId: providerThreadId, turnId: effectiveTurnId, }); } + async readThread(threadId: ThreadId): Promise { + const context = this.requireSession(threadId); + const providerThreadId = readResumeThreadId({ + threadId: context.session.threadId, + runtimeMode: context.session.runtimeMode, + resumeCursor: context.session.resumeCursor, + }); + if (!providerThreadId) { + throw new Error("Session is missing a provider resume thread id."); + } + + const response = await this.sendRequest(context, "thread/read", { + threadId: providerThreadId, + includeTurns: true, + }); + return this.parseThreadSnapshot("thread/read", response); + } + + async rollbackThread(threadId: ThreadId, numTurns: number): Promise { + const context = this.requireSession(threadId); + const providerThreadId = readResumeThreadId({ + threadId: context.session.threadId, + runtimeMode: context.session.runtimeMode, + resumeCursor: context.session.resumeCursor, + }); + if (!providerThreadId) { + throw new Error("Session is missing a provider resume thread id."); + } + if (!Number.isInteger(numTurns) || numTurns < 1) { + throw new Error("numTurns must be an integer >= 1."); + } + + const response = await this.sendRequest(context, "thread/rollback", { + threadId: providerThreadId, + numTurns, + }); + this.updateSession(context, { + status: "ready", + activeTurnId: undefined, + }); + return this.parseThreadSnapshot("thread/rollback", response); + } + async respondToRequest( - sessionId: string, - requestId: string, + threadId: ThreadId, + requestId: ApprovalRequestId, decision: ProviderApprovalDecision, ): Promise { - const context = this.requireSession(sessionId); + const context = this.requireSession(threadId); const pendingRequest = context.pendingApprovals.get(requestId); if (!pendingRequest) { throw new Error(`Unknown pending approval request: ${requestId}`); @@ -351,13 +834,12 @@ export class CodexAppServerManager extends EventEmitter { + const context = this.requireSession(threadId); + const pendingRequest = context.pendingUserInputs.get(requestId); + if (!pendingRequest) { + throw new Error(`Unknown pending user input request: ${requestId}`); + } + + context.pendingUserInputs.delete(requestId); + const codexAnswers = toCodexUserInputAnswers(answers); + this.writeMessage(context, { + id: pendingRequest.jsonRpcId, + result: { + answers: codexAnswers, + }, + }); + + this.emitEvent({ + id: EventId.makeUnsafe(randomUUID()), + kind: "notification", + provider: "codex", + threadId: context.session.threadId, + createdAt: new Date().toISOString(), + method: "item/tool/requestUserInput/answered", + turnId: pendingRequest.turnId, + itemId: pendingRequest.itemId, + requestId: pendingRequest.requestId, + payload: { + requestId: pendingRequest.requestId, + answers: codexAnswers, + }, + }); + } + + stopSession(threadId: ThreadId): void { + const context = this.sessions.get(threadId); if (!context) { return; } @@ -384,11 +903,12 @@ export class CodexAppServerManager extends EventEmitter): void { context.session = { ...context.session, @@ -735,6 +1311,10 @@ export class CodexAppServerManager extends EventEmitter { + const turn = this.readObject(turnValue); + const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`; + const turnId = TurnId.makeUnsafe(turnIdRaw); + const items = this.readArray(turn, "items") ?? []; + return { + id: turnId, + items, + }; + }); + + return { + threadId: threadIdRaw, + turns, + }; + } + private isServerRequest(value: unknown): value is JsonRpcRequest { if (!value || typeof value !== "object") { return false; @@ -775,27 +1382,20 @@ export class CodexAppServerManager extends EventEmitter (typeof value === "string" ? value : null)) + .filter((value): value is string => value !== null) ?? []; + for (const receiverThreadId of receiverThreadIds) { + context.collabReceiverTurns.set(receiverThreadId, parentTurnId); + } + } + + private shouldSuppressChildConversationNotification(method: string): boolean { + return ( + method === "thread/started" || + method === "thread/status/changed" || + method === "thread/archived" || + method === "thread/unarchived" || + method === "thread/closed" || + method === "thread/compacted" || + method === "thread/name/updated" || + method === "thread/tokenUsage/updated" || + method === "turn/started" || + method === "turn/completed" || + method === "turn/aborted" || + method === "turn/plan/updated" || + method === "item/plan/delta" + ); + } + private readObject(value: unknown, key?: string): Record | undefined { const target = key === undefined @@ -823,6 +1481,16 @@ export class CodexAppServerManager extends EventEmitter; } + private readArray(value: unknown, key?: string): unknown[] | undefined { + const target = + key === undefined + ? value + : value && typeof value === "object" + ? (value as Record)[key] + : undefined; + return Array.isArray(target) ? target : undefined; + } + private readString(value: unknown, key: string): string | undefined { if (!value || typeof value !== "object") { return undefined; @@ -841,3 +1509,84 @@ export class CodexAppServerManager extends EventEmitter( + value: string | undefined, + maker: (value: string) => T, +): T | undefined { + const normalized = value?.trim(); + return normalized?.length ? maker(normalized) : undefined; +} + +function normalizeProviderThreadId(value: string | undefined): string | undefined { + return brandIfNonEmpty(value, (normalized) => normalized); +} + +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; + } + const rawThreadId = (resumeCursor as Record).threadId; + return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined; +} + +function readResumeThreadId(input: { + readonly resumeCursor?: unknown; + readonly threadId?: ThreadId; + readonly runtimeMode?: RuntimeMode; +}): string | undefined { + return readResumeCursorThreadId(input.resumeCursor); +} + +function toTurnId(value: string | undefined): TurnId | undefined { + return brandIfNonEmpty(value, TurnId.makeUnsafe); +} + +function toProviderItemId(value: string | undefined): ProviderItemId | undefined { + return brandIfNonEmpty(value, ProviderItemId.makeUnsafe); +} diff --git a/apps/server/src/codexTextGenerator.ts b/apps/server/src/codexTextGenerator.ts deleted file mode 100644 index 51166b380f..0000000000 --- a/apps/server/src/codexTextGenerator.ts +++ /dev/null @@ -1,252 +0,0 @@ -import { randomUUID } from "node:crypto"; -import fs from "node:fs/promises"; -import os from "node:os"; -import path from "node:path"; - -import type { - CommitMessageGenerationInput, - CommitMessageGenerationResult, - PrContentGenerationInput, - PrContentGenerationResult, - TextGenerationService, -} from "./coreServices"; -import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner"; - -type ProcessRunner = ( - command: string, - args: readonly string[], - options?: ProcessRunOptions, -) => Promise; - -const CODEX_MODEL = "gpt-5.3-codex"; -const CODEX_REASONING_EFFORT = "low"; - -const COMMIT_OUTPUT_SCHEMA_JSON = { - type: "object", - properties: { - subject: { type: "string" }, - body: { type: "string" }, - }, - required: ["subject", "body"], - additionalProperties: false, -} as const; - -const PR_OUTPUT_SCHEMA_JSON = { - type: "object", - properties: { - title: { type: "string" }, - body: { type: "string" }, - }, - required: ["title", "body"], - additionalProperties: false, -} as const; - -function parseCommitOutput(raw: unknown): { subject: string; body: string } { - if (!raw || typeof raw !== "object") { - throw new Error("Codex returned a non-object commit message payload."); - } - const record = raw as Record; - const subject = typeof record.subject === "string" ? record.subject.trim() : ""; - const body = typeof record.body === "string" ? record.body : ""; - if (subject.length === 0) { - throw new Error("Codex returned an empty commit subject."); - } - return { subject, body }; -} - -function parsePrOutput(raw: unknown): { title: string; body: string } { - if (!raw || typeof raw !== "object") { - throw new Error("Codex returned a non-object PR payload."); - } - const record = raw as Record; - const title = typeof record.title === "string" ? record.title.trim() : ""; - const body = typeof record.body === "string" ? record.body.trim() : ""; - if (title.length === 0 || body.length === 0) { - throw new Error("Codex returned an invalid PR title/body payload."); - } - return { title, body }; -} - -function limitSection(value: string, maxChars: number): string { - if (value.length <= maxChars) return value; - const truncated = value.slice(0, maxChars); - return `${truncated}\n\n[truncated]`; -} - -async function writeTempFile(prefix: string, content: string): Promise { - const filePath = path.join(os.tmpdir(), `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`); - await fs.writeFile(filePath, content, "utf8"); - return filePath; -} - -async function safeUnlink(filePath: string): Promise { - try { - await fs.unlink(filePath); - } catch { - // Best-effort cleanup. - } -} - -function sanitizeCommitSubject(raw: string): string { - const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? ""; - const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim(); - if (withoutTrailingPeriod.length === 0) { - return "Update project files"; - } - - if (withoutTrailingPeriod.length <= 72) { - return withoutTrailingPeriod; - } - return withoutTrailingPeriod.slice(0, 72).trimEnd(); -} - -function sanitizePrTitle(raw: string): string { - const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? ""; - if (singleLine.length > 0) { - return singleLine; - } - return "Update project changes"; -} - -async function runCodexJson({ - cwd, - prompt, - outputSchemaJson, - parse, - run, -}: { - cwd: string; - prompt: string; - outputSchemaJson: object; - parse: (raw: unknown) => T; - run: ProcessRunner; -}): Promise { - const schemaPath = await writeTempFile("codex-schema", JSON.stringify(outputSchemaJson)); - let outputPath: string | null = null; - - try { - outputPath = await writeTempFile("codex-output", ""); - await run( - "codex", - [ - "exec", - "--ephemeral", - "-s", - "read-only", - "--model", - CODEX_MODEL, - "--config", - `model_reasoning_effort="${CODEX_REASONING_EFFORT}"`, - "--output-schema", - schemaPath, - "--output-last-message", - outputPath, - "-", - ], - { - cwd, - timeoutMs: 180_000, - stdin: prompt, - }, - ); - - const rawOutput = (await fs.readFile(outputPath, "utf8")).trim(); - if (rawOutput.length === 0) { - throw new Error("Codex returned an empty response."); - } - - let parsedJson: unknown; - try { - parsedJson = JSON.parse(rawOutput); - } catch { - throw new Error("Codex returned invalid JSON output."); - } - - return parse(parsedJson); - } finally { - await Promise.all([safeUnlink(schemaPath), ...(outputPath ? [safeUnlink(outputPath)] : [])]); - } -} - -interface CodexTextGeneratorDeps { - runProcess?: ProcessRunner; -} - -export class CodexTextGenerator implements TextGenerationService { - private readonly run: ProcessRunner; - - constructor(deps: CodexTextGeneratorDeps = {}) { - this.run = deps.runProcess ?? runProcess; - } - - async generateCommitMessage( - input: CommitMessageGenerationInput, - ): Promise { - const prompt = [ - "You write concise git commit messages.", - "Return a JSON object with keys: subject, body.", - "Rules:", - "- subject must be imperative, <= 72 chars, and no trailing period", - "- body can be empty string or short bullet points", - "- capture the primary user-visible or developer-visible change", - "", - `Branch: ${input.branch ?? "(detached)"}`, - "", - "Staged files:", - limitSection(input.stagedSummary, 6_000), - "", - "Staged patch:", - limitSection(input.stagedPatch, 40_000), - ].join("\n"); - - const generated = await runCodexJson({ - cwd: input.cwd, - prompt, - outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON, - parse: (raw) => parseCommitOutput(raw), - run: this.run, - }); - - return { - subject: sanitizeCommitSubject(generated.subject), - body: generated.body.trim(), - }; - } - - async generatePrContent(input: PrContentGenerationInput): Promise { - const prompt = [ - "You write GitHub pull request content.", - "Return a JSON object with keys: title, body.", - "Rules:", - "- title should be concise and specific", - "- body must be markdown and include headings '## Summary' and '## Testing'", - "- under Summary, provide short bullet points", - "- under Testing, include bullet points with concrete checks or 'Not run' where appropriate", - "", - `Base branch: ${input.baseBranch}`, - `Head branch: ${input.headBranch}`, - "", - "Commits:", - limitSection(input.commitSummary, 12_000), - "", - "Diff stat:", - limitSection(input.diffSummary, 12_000), - "", - "Diff patch:", - limitSection(input.diffPatch, 40_000), - ].join("\n"); - - const generated = await runCodexJson({ - cwd: input.cwd, - prompt, - outputSchemaJson: PR_OUTPUT_SCHEMA_JSON, - parse: (raw) => parsePrOutput(raw), - run: this.run, - }); - - return { - title: sanitizePrTitle(generated.title), - body: generated.body.trim(), - }; - } -} diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts new file mode 100644 index 0000000000..9ceea4c13c --- /dev/null +++ b/apps/server/src/config.ts @@ -0,0 +1,176 @@ +/** + * ServerConfig - Runtime configuration services. + * + * Defines process-level server configuration and networking helpers used by + * startup and runtime layers. + * + * @module ServerConfig + */ +import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect"; + +export const DEFAULT_PORT = 3773; + +export const RuntimeMode = Schema.Literals(["web", "desktop"]); +export type RuntimeMode = typeof RuntimeMode.Type; + +/** + * ServerDerivedPaths - Derived paths from the base directory. + */ +export interface ServerDerivedPaths { + readonly stateDir: string; + readonly dbPath: string; + readonly keybindingsConfigPath: string; + readonly settingsPath: string; + readonly worktreesDir: string; + readonly attachmentsDir: string; + readonly logsDir: string; + readonly serverLogPath: string; + readonly serverTracePath: string; + readonly providerLogsDir: string; + readonly providerEventLogPath: string; + readonly terminalLogsDir: string; + readonly anonymousIdPath: string; +} + +/** + * ServerConfigShape - Process/runtime configuration required by the server. + */ +export interface ServerConfigShape extends ServerDerivedPaths { + readonly logLevel: LogLevel.LogLevel; + readonly traceMinLevel: LogLevel.LogLevel; + readonly traceTimingEnabled: boolean; + readonly traceBatchWindowMs: number; + readonly traceMaxBytes: number; + readonly traceMaxFiles: number; + readonly otlpTracesUrl: string | undefined; + readonly otlpMetricsUrl: string | undefined; + readonly otlpExportIntervalMs: number; + readonly otlpServiceName: string; + readonly mode: RuntimeMode; + readonly port: number; + readonly host: string | undefined; + readonly cwd: string; + readonly baseDir: string; + readonly staticDir: string | undefined; + readonly devUrl: URL | undefined; + readonly noBrowser: boolean; + readonly authToken: string | undefined; + readonly autoBootstrapProjectFromCwd: boolean; + readonly logWebSocketEvents: boolean; +} + +export const deriveServerPaths = Effect.fn(function* ( + baseDir: ServerConfigShape["baseDir"], + devUrl: ServerConfigShape["devUrl"], +): Effect.fn.Return { + const { join } = yield* Path.Path; + const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata"); + const dbPath = join(stateDir, "state.sqlite"); + const attachmentsDir = join(stateDir, "attachments"); + const logsDir = join(stateDir, "logs"); + const providerLogsDir = join(logsDir, "provider"); + return { + stateDir, + dbPath, + keybindingsConfigPath: join(stateDir, "keybindings.json"), + settingsPath: join(stateDir, "settings.json"), + worktreesDir: join(baseDir, "worktrees"), + attachmentsDir, + logsDir, + serverLogPath: join(logsDir, "server.log"), + serverTracePath: join(logsDir, "server.trace.ndjson"), + providerLogsDir, + providerEventLogPath: join(providerLogsDir, "events.log"), + terminalLogsDir: join(logsDir, "terminals"), + anonymousIdPath: join(stateDir, "anonymous-id"), + }; +}); + +export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + yield* Effect.all( + [ + fs.makeDirectory(derivedPaths.stateDir, { recursive: true }), + fs.makeDirectory(derivedPaths.logsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }), + fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }), + fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }), + fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }), + ], + { concurrency: "unbounded" }, + ); +}); + +/** + * ServerConfig - Service tag for server runtime configuration. + */ +export class ServerConfig extends ServiceMap.Service()( + "t3/config/ServerConfig", +) { + static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) => + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const devUrl = undefined; + + const fs = yield* FileSystem.FileSystem; + const baseDir = + typeof baseDirOrPrefix === "string" + ? baseDirOrPrefix + : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix }); + const derivedPaths = yield* deriveServerPaths(baseDir, devUrl); + yield* ensureServerDirectories(derivedPaths); + + return { + logLevel: "Error", + traceMinLevel: "Info", + traceTimingEnabled: true, + traceBatchWindowMs: 200, + traceMaxBytes: 10 * 1024 * 1024, + traceMaxFiles: 10, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpExportIntervalMs: 10_000, + otlpServiceName: "t3-server", + cwd, + baseDir, + ...derivedPaths, + mode: "web", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + port: 0, + host: undefined, + authToken: undefined, + staticDir: undefined, + devUrl, + noBrowser: false, + } satisfies ServerConfigShape; + }), + ); +} + +export const resolveStaticDir = Effect.fn(function* () { + const { join, resolve } = yield* Path.Path; + const { exists } = yield* FileSystem.FileSystem; + const bundledClient = resolve(join(import.meta.dirname, "client")); + const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe( + Effect.orElseSucceed(() => false), + ); + if (bundledStat) { + return bundledClient; + } + + const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist")); + const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe( + Effect.orElseSucceed(() => false), + ); + if (monorepoStat) { + return monorepoClient; + } + return undefined; +}); diff --git a/apps/server/src/coreServices.ts b/apps/server/src/coreServices.ts deleted file mode 100644 index 887ff36a4b..0000000000 --- a/apps/server/src/coreServices.ts +++ /dev/null @@ -1,32 +0,0 @@ -export interface CommitMessageGenerationInput { - cwd: string; - branch: string | null; - stagedSummary: string; - stagedPatch: string; -} - -export interface CommitMessageGenerationResult { - subject: string; - body: string; -} - -export interface PrContentGenerationInput { - cwd: string; - baseBranch: string; - headBranch: string; - commitSummary: string; - diffSummary: string; - diffPatch: string; -} - -export interface PrContentGenerationResult { - title: string; - body: string; -} - -export interface TextGenerationService { - generateCommitMessage( - input: CommitMessageGenerationInput, - ): Promise; - generatePrContent(input: PrContentGenerationInput): Promise; -} diff --git a/apps/server/src/fixPath.ts b/apps/server/src/fixPath.ts deleted file mode 100644 index be7ea9447c..0000000000 --- a/apps/server/src/fixPath.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { execFileSync } from "node:child_process"; - -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, - }); - if (result) { - process.env.PATH = result; - } - } catch { - // Silently ignore — keep default PATH - } -} diff --git a/apps/server/src/git.test.ts b/apps/server/src/git.test.ts deleted file mode 100644 index 515a763cf7..0000000000 --- a/apps/server/src/git.test.ts +++ /dev/null @@ -1,857 +0,0 @@ -import { existsSync } from "node:fs"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import path from "node:path"; -import { describe, expect, it, vi } from "vitest"; - -import { - GitCoreService, - checkoutGitBranch, - createGitBranch, - createGitWorktree, - initGitRepo, - listGitBranches, - pullGitBranch, - removeGitWorktree, - runTerminalCommand, -} from "./git"; - -// ── Helpers ── - -/** Run a raw git command for test setup (not under test). */ -async function git(cwd: string, command: string): Promise { - const result = await runTerminalCommand({ - command: `git ${command}`, - cwd, - timeoutMs: 10_000, - }); - if (result.code !== 0) { - throw new Error(`git ${command} failed: ${result.stderr}`); - } - return result.stdout.trim(); -} - -/** Create a disposable temp directory that cleans up automatically. */ -async function makeTmpDir() { - const dir = await mkdtemp(path.join(tmpdir(), "git-test-")); - return { - path: dir, - [Symbol.asyncDispose]: async () => { - await rm(dir, { recursive: true, force: true }); - }, - }; -} - -/** Create a repo with an initial commit so branches work. */ -async function initRepoWithCommit(cwd: string): Promise { - await initGitRepo({ cwd }); - await git(cwd, "config user.email 'test@test.com'"); - await git(cwd, "config user.name 'Test'"); - await writeFile(path.join(cwd, "README.md"), "# test\n"); - await git(cwd, "add ."); - await git(cwd, "commit -m 'initial commit'"); -} - -async function commitWithDate( - cwd: string, - fileName: string, - fileContents: string, - dateIsoString: string, - message: string, -): Promise { - await writeFile(path.join(cwd, fileName), fileContents); - await git(cwd, `add ${fileName}`); - const commitResult = await runTerminalCommand({ - command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`, - cwd, - timeoutMs: 10_000, - }); - if (commitResult.code !== 0) { - throw new Error(`git dated commit failed: ${commitResult.stderr}`); - } -} - -// ── Tests ── - -describe("git integration", () => { - describe("runTerminalCommand", () => { - it("caps captured output when maxOutputBytes is exceeded", async () => { - const result = await runTerminalCommand({ - command: `node -e "process.stdout.write('x'.repeat(2000))"`, - cwd: process.cwd(), - timeoutMs: 10_000, - maxOutputBytes: 128, - }); - - expect(result.code).toBe(0); - expect(result.stdout.length).toBeLessThanOrEqual(128); - expect(result.stderr).toContain("output truncated"); - }); - }); - - // ── initGitRepo ── - - describe("initGitRepo", () => { - it("creates a valid git repo", async () => { - await using tmp = await makeTmpDir(); - await initGitRepo({ cwd: tmp.path }); - expect(existsSync(path.join(tmp.path, ".git"))).toBe(true); - }); - - it("listGitBranches reports isRepo: true after init + commit", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - const result = await listGitBranches({ cwd: tmp.path }); - expect(result.isRepo).toBe(true); - expect(result.branches.length).toBeGreaterThanOrEqual(1); - }); - }); - - // ── listGitBranches ── - - describe("listGitBranches", () => { - it("returns isRepo: false for non-git directory", async () => { - await using tmp = await makeTmpDir(); - const result = await listGitBranches({ cwd: tmp.path }); - expect(result.isRepo).toBe(false); - expect(result.branches).toEqual([]); - }); - - it("returns the current branch with current: true", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - const result = await listGitBranches({ cwd: tmp.path }); - const current = result.branches.find((b) => b.current); - expect(current).toBeDefined(); - expect(current!.current).toBe(true); - }); - - it("keeps current branch first and sorts the remaining branches by recency", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find( - (branch) => branch.current, - )!.name; - - await createGitBranch({ cwd: tmp.path, branch: "older-branch" }); - await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" }); - await commitWithDate( - tmp.path, - "older.txt", - "older branch change\n", - "Thu, 1 Jan 2037 00:00:00 +0000", - "older branch change", - ); - - await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch }); - await createGitBranch({ cwd: tmp.path, branch: "newer-branch" }); - await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" }); - await commitWithDate( - tmp.path, - "newer.txt", - "newer branch change\n", - "Fri, 1 Jan 2038 00:00:00 +0000", - "newer branch change", - ); - - // Switch away to show current branch is pinned, then remaining branches are recency-sorted. - await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" }); - - const result = await listGitBranches({ cwd: tmp.path }); - expect(result.branches[0]!.name).toBe("older-branch"); - expect(result.branches[1]!.name).toBe("newer-branch"); - }); - - it("keeps default branch right after current branch", async () => { - await using tmp = await makeTmpDir(); - await using remote = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find( - (branch) => branch.current, - )!.name; - - await git(remote.path, "init --bare"); - await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`); - await git(tmp.path, `push -u origin ${defaultBranch}`); - await git(tmp.path, `remote set-head origin ${defaultBranch}`); - - await createGitBranch({ cwd: tmp.path, branch: "current-branch" }); - await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" }); - await commitWithDate( - tmp.path, - "current.txt", - "current change\n", - "Thu, 1 Jan 2037 00:00:00 +0000", - "current change", - ); - - await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch }); - await createGitBranch({ cwd: tmp.path, branch: "newer-branch" }); - await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" }); - await commitWithDate( - tmp.path, - "newer.txt", - "newer change\n", - "Fri, 1 Jan 2038 00:00:00 +0000", - "newer change", - ); - - await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" }); - - const result = await listGitBranches({ cwd: tmp.path }); - expect(result.branches[0]!.name).toBe("current-branch"); - expect(result.branches[1]!.name).toBe(defaultBranch); - expect(result.branches[2]!.name).toBe("newer-branch"); - }); - - it("lists multiple branches after creating them", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await createGitBranch({ cwd: tmp.path, branch: "feature-a" }); - await createGitBranch({ cwd: tmp.path, branch: "feature-b" }); - - const result = await listGitBranches({ cwd: tmp.path }); - const names = result.branches.map((b) => b.name); - expect(names).toContain("feature-a"); - expect(names).toContain("feature-b"); - }); - - it("isDefault is false when no remote exists", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - const result = await listGitBranches({ cwd: tmp.path }); - expect(result.branches.every((b) => b.isDefault === false)).toBe(true); - }); - }); - - // ── checkoutGitBranch ── - - describe("checkoutGitBranch", () => { - it("checks out an existing branch", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await createGitBranch({ cwd: tmp.path, branch: "feature" }); - - await checkoutGitBranch({ cwd: tmp.path, branch: "feature" }); - - const result = await listGitBranches({ cwd: tmp.path }); - const current = result.branches.find((b) => b.current); - expect(current!.name).toBe("feature"); - }); - - it("refreshes upstream behind count after checkout when remote branch advanced", async () => { - await using remote = await makeTmpDir(); - await using source = await makeTmpDir(); - await using clone = await makeTmpDir(); - await git(remote.path, "init --bare"); - - await initRepoWithCommit(source.path); - const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find( - (branch) => branch.current, - )!.name; - await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`); - await git(source.path, `push -u origin ${defaultBranch}`); - - const featureBranch = "feature-behind"; - await createGitBranch({ cwd: source.path, branch: featureBranch }); - await checkoutGitBranch({ cwd: source.path, branch: featureBranch }); - await writeFile(path.join(source.path, "feature.txt"), "feature base\n"); - await git(source.path, "add feature.txt"); - await git(source.path, "commit -m 'feature base'"); - await git(source.path, `push -u origin ${featureBranch}`); - await checkoutGitBranch({ cwd: source.path, branch: defaultBranch }); - - await git(clone.path, `clone ${JSON.stringify(remote.path)} .`); - await git(clone.path, "config user.email 'test@test.com'"); - await git(clone.path, "config user.name 'Test'"); - await git(clone.path, `checkout -b ${featureBranch} --track origin/${featureBranch}`); - await writeFile(path.join(clone.path, "feature.txt"), "feature from remote\n"); - await git(clone.path, "add feature.txt"); - await git(clone.path, "commit -m 'remote feature update'"); - await git(clone.path, `push origin ${featureBranch}`); - - await checkoutGitBranch({ cwd: source.path, branch: featureBranch }); - const core = new GitCoreService(); - await vi.waitFor(async () => { - const details = await core.statusDetails(source.path); - expect(details.branch).toBe(featureBranch); - expect(details.aheadCount).toBe(0); - expect(details.behindCount).toBe(1); - }); - }); - - it("keeps checkout successful when upstream refresh fails", async () => { - await using remote = await makeTmpDir(); - await using source = await makeTmpDir(); - await git(remote.path, "init --bare"); - - await initRepoWithCommit(source.path); - const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find( - (branch) => branch.current, - )!.name; - await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`); - await git(source.path, `push -u origin ${defaultBranch}`); - - const featureBranch = "feature-refresh-failure"; - await git(source.path, `branch ${featureBranch}`); - await git(source.path, `checkout ${featureBranch}`); - await writeFile(path.join(source.path, "feature.txt"), "feature base\n"); - await git(source.path, "add feature.txt"); - await git(source.path, "commit -m 'feature base'"); - await git(source.path, `push -u origin ${featureBranch}`); - await git(source.path, `checkout ${defaultBranch}`); - - class RefreshFailingGitCoreService extends GitCoreService { - refreshFetchAttempts = 0; - - override async git( - cwd: string, - args: readonly string[], - allowNonZeroExit = false, - ): Promise { - if (args[0] === "fetch") { - this.refreshFetchAttempts += 1; - throw new Error("simulated fetch timeout"); - } - await super.git(cwd, args, allowNonZeroExit); - } - } - - const core = new RefreshFailingGitCoreService(); - await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe( - undefined, - ); - await vi.waitFor(() => { - expect(core.refreshFetchAttempts).toBe(1); - }); - expect(await git(source.path, "branch --show-current")).toBe(featureBranch); - }); - - it("refresh fetch is scoped to the checked out branch upstream refspec", async () => { - await using remote = await makeTmpDir(); - await using source = await makeTmpDir(); - await git(remote.path, "init --bare"); - - await initRepoWithCommit(source.path); - const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find( - (branch) => branch.current, - )!.name; - await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`); - await git(source.path, `push -u origin ${defaultBranch}`); - - const featureBranch = "feature/scoped-fetch"; - await git(source.path, `checkout -b ${featureBranch}`); - await writeFile(path.join(source.path, "feature.txt"), "feature base\n"); - await git(source.path, "add feature.txt"); - await git(source.path, "commit -m 'feature base'"); - await git(source.path, `push -u origin ${featureBranch}`); - await git(source.path, `checkout ${defaultBranch}`); - - class FetchRecordingGitCoreService extends GitCoreService { - fetchArgs: readonly string[] | null = null; - - override async git( - cwd: string, - args: readonly string[], - allowNonZeroExit = false, - ): Promise { - if (args[0] === "fetch") { - this.fetchArgs = args; - return; - } - await super.git(cwd, args, allowNonZeroExit); - } - } - - const core = new FetchRecordingGitCoreService(); - await core.checkoutBranch({ cwd: source.path, branch: featureBranch }); - await vi.waitFor(() => { - expect(core.fetchArgs).not.toBeNull(); - }); - - expect(await git(source.path, "branch --show-current")).toBe(featureBranch); - expect(core.fetchArgs).toEqual([ - "fetch", - "--quiet", - "--no-tags", - "origin", - `+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`, - ]); - }); - - it("returns checkout result before background upstream refresh completes", async () => { - await using remote = await makeTmpDir(); - await using source = await makeTmpDir(); - await git(remote.path, "init --bare"); - - await initRepoWithCommit(source.path); - const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find( - (branch) => branch.current, - )!.name; - await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`); - await git(source.path, `push -u origin ${defaultBranch}`); - - const featureBranch = "feature/background-refresh"; - await git(source.path, `checkout -b ${featureBranch}`); - await writeFile(path.join(source.path, "feature.txt"), "feature base\n"); - await git(source.path, "add feature.txt"); - await git(source.path, "commit -m 'feature base'"); - await git(source.path, `push -u origin ${featureBranch}`); - await git(source.path, `checkout ${defaultBranch}`); - - class SlowRefreshGitCoreService extends GitCoreService { - fetchStarted = false; - private readonly waitForReleasePromise: Promise; - private releaseWait: () => void = () => undefined; - - constructor() { - super(); - this.waitForReleasePromise = new Promise((resolve) => { - this.releaseWait = resolve; - }); - } - - releaseFetch(): void { - this.releaseWait(); - } - - override async git( - cwd: string, - args: readonly string[], - allowNonZeroExit = false, - ): Promise { - if (args[0] === "fetch") { - this.fetchStarted = true; - await this.waitForReleasePromise; - return; - } - await super.git(cwd, args, allowNonZeroExit); - } - } - - const core = new SlowRefreshGitCoreService(); - await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe( - undefined, - ); - await vi.waitFor(() => { - expect(core.fetchStarted).toBe(true); - }); - expect(await git(source.path, "branch --show-current")).toBe(featureBranch); - core.releaseFetch(); - }); - - it("throws when branch does not exist", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await expect(checkoutGitBranch({ cwd: tmp.path, branch: "nonexistent" })).rejects.toThrow(); - }); - - it("throws when checkout would overwrite uncommitted changes", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await createGitBranch({ cwd: tmp.path, branch: "other" }); - - // Create a conflicting change: modify README on current branch - await writeFile(path.join(tmp.path, "README.md"), "modified\n"); - await git(tmp.path, "add README.md"); - - // First, checkout other branch cleanly - await git(tmp.path, "stash"); - await checkoutGitBranch({ cwd: tmp.path, branch: "other" }); - await writeFile(path.join(tmp.path, "README.md"), "other content\n"); - await git(tmp.path, "add ."); - await git(tmp.path, "commit -m 'other change'"); - - // Go back to default branch - const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find( - (b) => !b.current, - )!.name; - await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch }); - - // Make uncommitted changes to the same file - await writeFile(path.join(tmp.path, "README.md"), "conflicting local\n"); - - // Checkout should fail due to uncommitted changes - await expect(checkoutGitBranch({ cwd: tmp.path, branch: "other" })).rejects.toThrow(); - }); - }); - - // ── createGitBranch ── - - describe("createGitBranch", () => { - it("creates a new branch visible in listGitBranches", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await createGitBranch({ cwd: tmp.path, branch: "new-feature" }); - - const result = await listGitBranches({ cwd: tmp.path }); - expect(result.branches.some((b) => b.name === "new-feature")).toBe(true); - }); - - it("throws when branch already exists", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await createGitBranch({ cwd: tmp.path, branch: "dupe" }); - await expect(createGitBranch({ cwd: tmp.path, branch: "dupe" })).rejects.toThrow(); - }); - }); - - // ── createGitWorktree + removeGitWorktree ── - - describe("createGitWorktree", () => { - it("creates a worktree with a new branch from the base branch", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - - const wtPath = path.join(tmp.path, "worktree-out"); - const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find( - (b) => b.current, - )!.name; - - const result = await createGitWorktree({ - cwd: tmp.path, - branch: currentBranch, - newBranch: "wt-branch", - path: wtPath, - }); - - expect(result.worktree.path).toBe(wtPath); - expect(result.worktree.branch).toBe("wt-branch"); - expect(existsSync(wtPath)).toBe(true); - expect(existsSync(path.join(wtPath, "README.md"))).toBe(true); - - // Clean up worktree before tmp dir disposal - await removeGitWorktree({ cwd: tmp.path, path: wtPath }); - }); - - it("worktree has the new branch checked out", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - - const wtPath = path.join(tmp.path, "wt-check-dir"); - const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find( - (b) => b.current, - )!.name; - - await createGitWorktree({ - cwd: tmp.path, - branch: currentBranch, - newBranch: "wt-check", - path: wtPath, - }); - - // Verify the worktree is on the new branch - const branchOutput = await git(wtPath, "branch --show-current"); - expect(branchOutput).toBe("wt-check"); - - await removeGitWorktree({ cwd: tmp.path, path: wtPath }); - }); - - it("throws when new branch name already exists", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await createGitBranch({ cwd: tmp.path, branch: "existing" }); - - const wtPath = path.join(tmp.path, "wt-conflict"); - const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find( - (b) => b.current, - )!.name; - - await expect( - createGitWorktree({ - cwd: tmp.path, - branch: currentBranch, - newBranch: "existing", - path: wtPath, - }), - ).rejects.toThrow(); - }); - - it("listGitBranches from worktree cwd reports worktree branch as current", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - - const wtPath = path.join(tmp.path, "wt-list-dir"); - const mainBranch = (await listGitBranches({ cwd: tmp.path })).branches.find( - (b) => b.current, - )!.name; - - await createGitWorktree({ - cwd: tmp.path, - branch: mainBranch, - newBranch: "wt-list", - path: wtPath, - }); - - // listGitBranches from the worktree should show wt-list as current - const wtBranches = await listGitBranches({ cwd: wtPath }); - expect(wtBranches.isRepo).toBe(true); - const wtCurrent = wtBranches.branches.find((b) => b.current); - expect(wtCurrent!.name).toBe("wt-list"); - - // Main repo should still show the original branch as current - const mainBranches = await listGitBranches({ cwd: tmp.path }); - const mainCurrent = mainBranches.branches.find((b) => b.current); - expect(mainCurrent!.name).toBe(mainBranch); - - await removeGitWorktree({ cwd: tmp.path, path: wtPath }); - }); - - it("removeGitWorktree cleans up the worktree", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - - const wtPath = path.join(tmp.path, "wt-remove-dir"); - const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find( - (b) => b.current, - )!.name; - - await createGitWorktree({ - cwd: tmp.path, - branch: currentBranch, - newBranch: "wt-remove", - path: wtPath, - }); - expect(existsSync(wtPath)).toBe(true); - - await removeGitWorktree({ cwd: tmp.path, path: wtPath }); - expect(existsSync(wtPath)).toBe(false); - }); - }); - - // ── Full flow: local branch checkout ── - - describe("full flow: local branch checkout", () => { - it("init → commit → create branch → checkout → verify current", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await createGitBranch({ cwd: tmp.path, branch: "feature-login" }); - await checkoutGitBranch({ cwd: tmp.path, branch: "feature-login" }); - - const result = await listGitBranches({ cwd: tmp.path }); - const current = result.branches.find((b) => b.current); - expect(current!.name).toBe("feature-login"); - }); - }); - - // ── Full flow: worktree creation from base branch ── - - describe("full flow: worktree creation", () => { - it("creates worktree with new branch from current branch", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - - const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find( - (b) => b.current, - )!.name; - - const wtPath = path.join(tmp.path, "my-worktree"); - const result = await createGitWorktree({ - cwd: tmp.path, - branch: currentBranch, - newBranch: "feature-wt", - path: wtPath, - }); - - // Worktree exists - expect(existsSync(result.worktree.path)).toBe(true); - - // Main repo still on original branch - const mainBranches = await listGitBranches({ cwd: tmp.path }); - const mainCurrent = mainBranches.branches.find((b) => b.current); - expect(mainCurrent!.name).toBe(currentBranch); - - // Worktree is on the new branch - const wtBranch = await git(wtPath, "branch --show-current"); - expect(wtBranch).toBe("feature-wt"); - - await removeGitWorktree({ cwd: tmp.path, path: wtPath }); - }); - }); - - // ── Full flow: thread switching simulation ── - - describe("full flow: thread switching (checkout toggling)", () => { - it("checkout a → checkout b → checkout a → current matches", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await createGitBranch({ cwd: tmp.path, branch: "branch-a" }); - await createGitBranch({ cwd: tmp.path, branch: "branch-b" }); - - // Simulate switching to thread A's branch - await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" }); - let branches = await listGitBranches({ cwd: tmp.path }); - expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a"); - - // Simulate switching to thread B's branch - await checkoutGitBranch({ cwd: tmp.path, branch: "branch-b" }); - branches = await listGitBranches({ cwd: tmp.path }); - expect(branches.branches.find((b) => b.current)!.name).toBe("branch-b"); - - // Switch back to thread A - await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" }); - branches = await listGitBranches({ cwd: tmp.path }); - expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a"); - }); - }); - - // ── Full flow: checkout conflict ── - - describe("full flow: checkout conflict", () => { - it("uncommitted changes prevent checkout to a diverged branch", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await createGitBranch({ cwd: tmp.path, branch: "diverged" }); - - // Make diverged branch have different file content - await checkoutGitBranch({ cwd: tmp.path, branch: "diverged" }); - await writeFile(path.join(tmp.path, "README.md"), "diverged content\n"); - await git(tmp.path, "add ."); - await git(tmp.path, "commit -m 'diverge'"); - - // Actually, let's just get back to the initial branch explicitly - const allBranches = await listGitBranches({ cwd: tmp.path }); - const initialBranch = allBranches.branches.find((b) => b.name !== "diverged")!.name; - await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch }); - - // Make local uncommitted changes to the same file - await writeFile(path.join(tmp.path, "README.md"), "local uncommitted\n"); - - // Attempt checkout should fail - await expect(checkoutGitBranch({ cwd: tmp.path, branch: "diverged" })).rejects.toThrow(); - - // Current branch should still be the initial one - const result = await listGitBranches({ cwd: tmp.path }); - expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch); - }); - }); - - describe("GitCoreService", () => { - it("supports branch lifecycle operations through the service API", async () => { - await using tmp = await makeTmpDir(); - const core = new GitCoreService(); - - await core.initRepo({ cwd: tmp.path }); - await git(tmp.path, "config user.email 'test@test.com'"); - await git(tmp.path, "config user.name 'Test'"); - await writeFile(path.join(tmp.path, "README.md"), "# test\n"); - await git(tmp.path, "add ."); - await git(tmp.path, "commit -m 'initial commit'"); - - await core.createBranch({ cwd: tmp.path, branch: "feature/service-api" }); - await core.checkoutBranch({ cwd: tmp.path, branch: "feature/service-api" }); - const branches = await core.listBranches({ cwd: tmp.path }); - - expect(branches.isRepo).toBe(true); - expect(branches.branches.find((branch) => branch.current)?.name).toBe("feature/service-api"); - }); - - it("reports status details and dirty state", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - const core = new GitCoreService(); - - const clean = await core.status({ cwd: tmp.path }); - expect(clean.hasWorkingTreeChanges).toBe(false); - expect(clean.branch).toBeTruthy(); - - await writeFile(path.join(tmp.path, "README.md"), "updated\n"); - const dirty = await core.statusDetails(tmp.path); - expect(dirty.hasWorkingTreeChanges).toBe(true); - }); - - it("prepares commit context by auto-staging and creates commit", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - const core = new GitCoreService(); - - await writeFile(path.join(tmp.path, "README.md"), "new content\n"); - const context = await core.prepareCommitContext(tmp.path); - expect(context).not.toBeNull(); - expect(context!.stagedSummary.length).toBeGreaterThan(0); - expect(context!.stagedPatch.length).toBeGreaterThan(0); - - const created = await core.commit(tmp.path, "Add README update", "- include updated content"); - expect(created.commitSha.length).toBeGreaterThan(0); - expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update"); - }); - - it("pushes with upstream setup and then skips when up to date", async () => { - await using tmp = await makeTmpDir(); - await using remote = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await git(remote.path, "init --bare"); - await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`); - await createGitBranch({ cwd: tmp.path, branch: "feature/core-push" }); - await checkoutGitBranch({ cwd: tmp.path, branch: "feature/core-push" }); - - await writeFile(path.join(tmp.path, "feature.txt"), "push me\n"); - const core = new GitCoreService(); - const context = await core.prepareCommitContext(tmp.path); - expect(context).not.toBeNull(); - await core.commit(tmp.path, "Add feature file", ""); - - const pushed = await core.pushCurrentBranch(tmp.path, null); - expect(pushed.status).toBe("pushed"); - expect(pushed.setUpstream).toBe(true); - expect(await git(tmp.path, "rev-parse --abbrev-ref @{upstream}")).toBe( - "origin/feature/core-push", - ); - - const skipped = await core.pushCurrentBranch(tmp.path, null); - expect(skipped.status).toBe("skipped_up_to_date"); - }); - - it("pulls behind branch and then reports up-to-date", async () => { - await using remote = await makeTmpDir(); - await using source = await makeTmpDir(); - await using clone = await makeTmpDir(); - await git(remote.path, "init --bare"); - - await initRepoWithCommit(source.path); - const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find( - (branch) => branch.current, - )!.name; - await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`); - await git(source.path, `push -u origin ${initialBranch}`); - - await git(clone.path, `clone ${JSON.stringify(remote.path)} .`); - await git(clone.path, "config user.email 'test@test.com'"); - await git(clone.path, "config user.name 'Test'"); - await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n"); - await git(clone.path, "add CHANGELOG.md"); - await git(clone.path, "commit -m 'remote update'"); - await git(clone.path, `push origin ${initialBranch}`); - - const core = new GitCoreService(); - const pulled = await core.pullCurrentBranch(source.path); - expect(pulled.status).toBe("pulled"); - expect((await core.statusDetails(source.path)).behindCount).toBe(0); - - const skipped = await core.pullCurrentBranch(source.path); - expect(skipped.status).toBe("skipped_up_to_date"); - }); - - it("top-level pullGitBranch rejects when no upstream exists", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream"); - }); - - it("lists branches when recency lookup fails", async () => { - await using tmp = await makeTmpDir(); - await initRepoWithCommit(tmp.path); - const core = new GitCoreService(); - const recencySpy = vi - .spyOn(core as any, "readBranchRecency") - .mockRejectedValueOnce(new Error("timeout")); - - const result = await core.listBranches({ cwd: tmp.path }); - - expect(result.isRepo).toBe(true); - expect(result.branches.length).toBeGreaterThan(0); - expect(result.branches[0]?.current).toBe(true); - recencySpy.mockRestore(); - }); - }); -}); diff --git a/apps/server/src/git.ts b/apps/server/src/git.ts deleted file mode 100644 index 1fbd86c7be..0000000000 --- a/apps/server/src/git.ts +++ /dev/null @@ -1,672 +0,0 @@ -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { - gitPullInputSchema, - gitPullResultSchema, - gitStatusInputSchema, - gitStatusResultSchema, - type GitCheckoutInput, - type GitCreateBranchInput, - type GitCreateWorktreeInput, - type GitCreateWorktreeResult, - type GitInitInput, - type GitListBranchesInput, - type GitListBranchesResult, - type GitPullInput, - type GitPullResult, - type GitRemoveWorktreeInput, - type GitStatusInput, - type GitStatusResult, -} from "@t3tools/contracts"; -import { type ProcessRunResult, runProcess } from "./processRunner"; - -export interface TerminalCommandInput { - command: string; - cwd: string; - timeoutMs?: number; - maxOutputBytes?: number; -} - -export type TerminalCommandResult = ProcessRunResult; - -export interface GitStatusDetails extends Omit { - upstreamRef: string | null; -} - -export interface GitPreparedCommitContext { - stagedSummary: string; - stagedPatch: string; -} - -export interface GitPushResult { - status: "pushed" | "skipped_up_to_date"; - branch: string; - upstreamBranch?: string | undefined; - setUpstream?: boolean | undefined; -} - -export interface GitRangeContext { - commitSummary: string; - diffSummary: string; - diffPatch: string; -} - -interface RunGitOptions { - timeoutMs?: number | undefined; - allowNonZeroExit?: boolean | undefined; -} - -interface ExecuteGitOptions { - timeoutMs?: number | undefined; - allowNonZeroExit?: boolean | undefined; - fallbackErrorMessage?: string | undefined; -} - -const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000; - -/** Spawn git directly with an argv array — no shell, no quoting needed. */ -function runGit( - args: readonly string[], - cwd: string, - timeoutMs = 30_000, -): Promise { - return runProcess("git", args, { - cwd, - timeoutMs, - allowNonZeroExit: true, - maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES, - outputMode: "truncate", - }); -} - -function trimStdout(value: string): string { - return value.trim(); -} - -function parseBranchAb(value: string): { ahead: number; behind: number } { - const match = value.match(/^\+(\d+)\s+-(\d+)$/); - if (!match) return { ahead: 0, behind: 0 }; - return { - ahead: Number(match[1] ?? "0"), - behind: Number(match[2] ?? "0"), - }; -} - -function parseNumstatEntries( - stdout: string, -): Array<{ path: string; insertions: number; deletions: number }> { - const entries: Array<{ path: string; insertions: number; deletions: number }> = []; - for (const line of stdout.split(/\r?\n/g)) { - if (line.trim().length === 0) continue; - const [addedRaw, deletedRaw, ...pathParts] = line.split("\t"); - const rawPath = - pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim(); - if (rawPath.length === 0) continue; - const added = Number.parseInt(addedRaw ?? "0", 10); - const deleted = Number.parseInt(deletedRaw ?? "0", 10); - const renameArrowIndex = rawPath.indexOf(" => "); - const normalizedPath = - renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath; - entries.push({ - path: normalizedPath.length > 0 ? normalizedPath : rawPath, - insertions: Number.isFinite(added) ? added : 0, - deletions: Number.isFinite(deleted) ? deleted : 0, - }); - } - return entries; -} - -function parsePorcelainPath(line: string): string | null { - if (line.startsWith("? ") || line.startsWith("! ")) { - const simple = line.slice(2).trim(); - return simple.length > 0 ? simple : null; - } - - if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) { - return null; - } - - const tabIndex = line.indexOf("\t"); - if (tabIndex >= 0) { - const fromTab = line.slice(tabIndex + 1); - const [path] = fromTab.split("\t"); - return path?.trim().length ? path.trim() : null; - } - - const parts = line.trim().split(/\s+/g); - const path = parts.at(-1) ?? ""; - return path.length > 0 ? path : null; -} - -function commandLabel(args: readonly string[]): string { - return `git ${args.join(" ")}`; -} - -function normalizeGitSpawnError(cwd: string, error: unknown): Error { - if (!(error instanceof Error)) { - return new Error("Failed to run git command."); - } - if (!fs.existsSync(cwd)) { - return new Error(`Working directory does not exist: ${cwd}`); - } - if (error.message.includes("Command not found: git")) { - return new Error("Git is required but not available on PATH."); - } - return new Error(`Failed to run git command: ${error.message}`); -} - -function normalizeGitExecutionError(args: readonly string[], result: TerminalCommandResult): Error { - const stderr = result.stderr.trim(); - if (stderr.toLowerCase().includes("not a git repository")) { - return new Error("Current folder is not a git repository."); - } - if (result.timedOut) { - return new Error(`${commandLabel(args)} timed out.`); - } - const detail = - stderr.length > 0 ? stderr : `code=${result.code ?? "null"}, signal=${result.signal ?? "null"}`; - return new Error(`${commandLabel(args)} failed: ${detail}`); -} - -async function runGitOrThrow( - cwd: string, - args: readonly string[], - options: RunGitOptions = {}, -): Promise { - let result: TerminalCommandResult; - try { - result = await runGit(args, cwd, options.timeoutMs); - } catch (error) { - throw normalizeGitSpawnError(cwd, error); - } - - if (result.timedOut) { - throw normalizeGitExecutionError(args, result); - } - if (!options.allowNonZeroExit && result.code !== 0) { - throw normalizeGitExecutionError(args, result); - } - return result; -} - -async function executeGit( - cwd: string, - args: readonly string[], - options: ExecuteGitOptions = {}, -): Promise { - const result = await runGitOrThrow(cwd, args, { - timeoutMs: options.timeoutMs, - allowNonZeroExit: true, - }); - - if (options.allowNonZeroExit || result.code === 0) { - return result; - } - - const stderr = result.stderr.trim(); - if (stderr.length > 0) { - throw new Error(stderr); - } - if (options.fallbackErrorMessage) { - throw new Error(options.fallbackErrorMessage); - } - throw normalizeGitExecutionError(args, result); -} - -export class GitCoreService { - async status(raw: GitStatusInput): Promise { - const input = gitStatusInputSchema.parse(raw); - const details = await this.statusDetails(input.cwd); - return gitStatusResultSchema.parse({ - branch: details.branch, - hasWorkingTreeChanges: details.hasWorkingTreeChanges, - workingTree: details.workingTree, - hasUpstream: details.hasUpstream, - aheadCount: details.aheadCount, - behindCount: details.behindCount, - openPr: null, - }); - } - - async statusDetails(cwd: string): Promise { - const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([ - this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]), - this.gitStdout(cwd, ["diff", "--numstat"]), - this.gitStdout(cwd, ["diff", "--cached", "--numstat"]), - ]); - - let branch: string | null = null; - let upstreamRef: string | null = null; - let aheadCount = 0; - let behindCount = 0; - let hasWorkingTreeChanges = false; - const changedFilesWithoutNumstat = new Set(); - - for (const line of statusStdout.split(/\r?\n/g)) { - if (line.startsWith("# branch.head ")) { - const value = line.slice("# branch.head ".length).trim(); - branch = value.startsWith("(") ? null : value; - continue; - } - if (line.startsWith("# branch.upstream ")) { - const value = line.slice("# branch.upstream ".length).trim(); - upstreamRef = value.length > 0 ? value : null; - continue; - } - if (line.startsWith("# branch.ab ")) { - const value = line.slice("# branch.ab ".length).trim(); - const parsed = parseBranchAb(value); - aheadCount = parsed.ahead; - behindCount = parsed.behind; - continue; - } - if (line.trim().length > 0 && !line.startsWith("#")) { - hasWorkingTreeChanges = true; - const pathValue = parsePorcelainPath(line); - if (pathValue) changedFilesWithoutNumstat.add(pathValue); - } - } - const stagedEntries = parseNumstatEntries(stagedNumstatStdout); - const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout); - const fileStatMap = new Map(); - for (const entry of [...stagedEntries, ...unstagedEntries]) { - const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 }; - existing.insertions += entry.insertions; - existing.deletions += entry.deletions; - fileStatMap.set(entry.path, existing); - } - - let insertions = 0; - let deletions = 0; - const files = Array.from(fileStatMap.entries()) - .map(([path, stat]) => { - insertions += stat.insertions; - deletions += stat.deletions; - return { path, insertions: stat.insertions, deletions: stat.deletions }; - }) - .toSorted((a, b) => a.path.localeCompare(b.path)); - - for (const filePath of changedFilesWithoutNumstat) { - if (fileStatMap.has(filePath)) continue; - files.push({ path: filePath, insertions: 0, deletions: 0 }); - } - files.sort((a, b) => a.path.localeCompare(b.path)); - - return { - branch, - upstreamRef, - hasWorkingTreeChanges, - workingTree: { - files, - insertions, - deletions, - }, - hasUpstream: upstreamRef !== null, - aheadCount, - behindCount, - }; - } - - async prepareCommitContext(cwd: string): Promise { - await this.git(cwd, ["add", "-A"]); - - const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]); - if (trimStdout(stagedSummary).length === 0) { - return null; - } - - const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]); - - return { - stagedSummary, - stagedPatch, - }; - } - - async commit(cwd: string, subject: string, body: string): Promise<{ commitSha: string }> { - const args = ["commit", "-m", subject]; - const trimmedBody = body.trim(); - if (trimmedBody.length > 0) { - args.push("-m", trimmedBody); - } - await this.git(cwd, args); - const commitSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"])); - return { commitSha }; - } - - async pushCurrentBranch(cwd: string, fallbackBranch: string | null): Promise { - const details = await this.statusDetails(cwd); - const branch = details.branch ?? fallbackBranch; - if (!branch) { - throw new Error("Cannot push from detached HEAD."); - } - - if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) { - return { - status: "skipped_up_to_date", - branch, - ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), - }; - } - - if (!details.hasUpstream) { - await this.git(cwd, ["push", "-u", "origin", branch]); - return { - status: "pushed", - branch, - upstreamBranch: `origin/${branch}`, - setUpstream: true, - }; - } - - await this.git(cwd, ["push"]); - return { - status: "pushed", - branch, - ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), - setUpstream: false, - }; - } - - async pullCurrentBranch(cwd: string): Promise { - const details = await this.statusDetails(cwd); - const branch = details.branch; - if (!branch) { - throw new Error("Cannot pull from detached HEAD."); - } - if (!details.hasUpstream) { - throw new Error("Current branch has no upstream configured. Push with upstream first."); - } - const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true)); - await executeGit(cwd, ["pull", "--ff-only"], { - timeoutMs: 30_000, - fallbackErrorMessage: "git pull failed", - }); - const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true)); - const refreshed = await this.statusDetails(cwd); - return gitPullResultSchema.parse({ - status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled", - branch, - ...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}), - }); - } - - async readRangeContext(cwd: string, baseBranch: string): Promise { - const range = `${baseBranch}..HEAD`; - const [commitSummary, diffSummary, diffPatch] = await Promise.all([ - this.gitStdout(cwd, ["log", "--oneline", range]), - this.gitStdout(cwd, ["diff", "--stat", range]), - this.gitStdout(cwd, ["diff", "--patch", "--minimal", range]), - ]); - - return { - commitSummary, - diffSummary, - diffPatch, - }; - } - - async readConfigValue(cwd: string, key: string): Promise { - const stdout = await this.gitStdout(cwd, ["config", "--get", key], true); - const value = trimStdout(stdout); - return value.length > 0 ? value : null; - } - - private async readBranchRecency(cwd: string): Promise> { - const branchRecency = await executeGit( - cwd, - ["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"], - { - timeoutMs: 15_000, - allowNonZeroExit: true, - }, - ); - - const branchLastCommit = new Map(); - if (branchRecency.code !== 0) { - return branchLastCommit; - } - - for (const line of branchRecency.stdout.split("\n")) { - if (line.length === 0) { - continue; - } - const [name, lastCommitRaw] = line.split("\t"); - if (!name) { - continue; - } - const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10); - branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0); - } - - return branchLastCommit; - } - - async listBranches(input: GitListBranchesInput): Promise { - const branchRecencyPromise = this.readBranchRecency(input.cwd).catch( - () => new Map(), - ); - const result = await executeGit(input.cwd, ["branch", "--no-color"], { - timeoutMs: 10_000, - allowNonZeroExit: true, - }); - - if (result.code !== 0) { - const stderr = result.stderr.trim(); - if (stderr.toLowerCase().includes("not a git repository")) { - return { branches: [], isRepo: false }; - } - throw new Error(stderr || "git branch failed"); - } - - const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([ - executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], { - timeoutMs: 5_000, - allowNonZeroExit: true, - }), - executeGit(input.cwd, ["worktree", "list", "--porcelain"], { - timeoutMs: 5_000, - allowNonZeroExit: true, - }), - branchRecencyPromise, - ]); - const defaultBranch = - defaultRef.code === 0 - ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") - : null; - - const worktreeMap = new Map(); - if (worktreeList.code === 0) { - let currentPath: string | null = null; - for (const line of worktreeList.stdout.split("\n")) { - if (line.startsWith("worktree ")) { - const candidatePath = line.slice("worktree ".length); - currentPath = fs.existsSync(candidatePath) ? candidatePath : null; - } else if (line.startsWith("branch refs/heads/") && currentPath) { - worktreeMap.set(line.slice("branch refs/heads/".length), currentPath); - } else if (line === "") { - currentPath = null; - } - } - } - - const branches = result.stdout - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0) - .map((line) => { - const name = line.replace(/^[*+]\s+/, ""); - return { - name, - current: line.startsWith("* "), - isDefault: name === defaultBranch, - worktreePath: worktreeMap.get(name) ?? null, - }; - }) - .toSorted((a, b) => { - const aPriority = a.current ? 0 : a.isDefault ? 1 : 2; - const bPriority = b.current ? 0 : b.isDefault ? 1 : 2; - if (aPriority !== bPriority) return aPriority - bPriority; - - const aLastCommit = branchLastCommit.get(a.name) ?? 0; - const bLastCommit = branchLastCommit.get(b.name) ?? 0; - if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; - return a.name.localeCompare(b.name); - }); - - return { branches, isRepo: true }; - } - - async createWorktree(input: GitCreateWorktreeInput): Promise { - const sanitizedBranch = input.newBranch.replace(/\//g, "-"); - const repoName = path.basename(input.cwd); - const worktreePath = - input.path ?? path.join(os.homedir(), ".t3", "worktrees", repoName, sanitizedBranch); - - await executeGit( - input.cwd, - ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch], - { fallbackErrorMessage: "git worktree add failed" }, - ); - - return { - worktree: { - path: worktreePath, - branch: input.newBranch, - }, - }; - } - - async removeWorktree(input: GitRemoveWorktreeInput): Promise { - await executeGit(input.cwd, ["worktree", "remove", input.path], { - timeoutMs: 15_000, - fallbackErrorMessage: "git worktree remove failed", - }); - } - - async createBranch(input: GitCreateBranchInput): Promise { - await executeGit(input.cwd, ["branch", input.branch], { - timeoutMs: 10_000, - fallbackErrorMessage: "git branch create failed", - }); - } - - private async refreshCheckedOutBranchUpstream(cwd: string): Promise { - const upstreamRef = trimStdout( - await this.gitStdout( - cwd, - ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], - true, - ), - ); - if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { - return; - } - - const separatorIndex = upstreamRef.indexOf("/"); - if (separatorIndex <= 0) { - return; - } - const remoteName = upstreamRef.slice(0, separatorIndex); - const upstreamBranch = upstreamRef.slice(separatorIndex + 1); - if (remoteName.length === 0) { - return; - } - if (upstreamBranch.length === 0) { - return; - } - - const refspec = `+refs/heads/${upstreamBranch}:refs/remotes/${upstreamRef}`; - await this.git(cwd, ["fetch", "--quiet", "--no-tags", remoteName, refspec], true); - } - - async checkoutBranch(input: GitCheckoutInput): Promise { - await executeGit(input.cwd, ["checkout", input.branch], { - timeoutMs: 10_000, - fallbackErrorMessage: "git checkout failed", - }); - // Refresh upstream refs in the background so checkout remains responsive. - void this.refreshCheckedOutBranchUpstream(input.cwd).catch(() => undefined); - } - - async initRepo(input: GitInitInput): Promise { - await executeGit(input.cwd, ["init"], { - timeoutMs: 10_000, - fallbackErrorMessage: "git init failed", - }); - } - - async git(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise { - await executeGit(cwd, args, { allowNonZeroExit }); - } - - async gitStdout(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise { - const result = await executeGit(cwd, args, { allowNonZeroExit }); - return result.stdout; - } -} - -const defaultGitCoreService = new GitCoreService(); - -export async function runTerminalCommand( - input: TerminalCommandInput, -): Promise { - const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; - const shellPath = - process.platform === "win32" - ? (process.env.ComSpec ?? "cmd.exe") - : (process.env.SHELL ?? "/bin/sh"); - - const args = - process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command]; - - const result = await runProcess(shellPath, args, { - cwd: input.cwd, - timeoutMs: input.timeoutMs ?? 30_000, - allowNonZeroExit: true, - maxBufferBytes: maxOutputBytes, - outputMode: "truncate", - }); - - if (!result.stdoutTruncated && !result.stderrTruncated) { - return result; - } - - return { - ...result, - stderr: `${result.stderr}\n[output truncated at ${maxOutputBytes} bytes]`, - }; -} - -export async function listGitBranches(input: GitListBranchesInput): Promise { - return defaultGitCoreService.listBranches(input); -} - -export async function pullGitBranch(raw: GitPullInput): Promise { - const input = gitPullInputSchema.parse(raw); - return defaultGitCoreService.pullCurrentBranch(input.cwd); -} - -export async function createGitWorktree( - input: GitCreateWorktreeInput, -): Promise { - return defaultGitCoreService.createWorktree(input); -} - -export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise { - await defaultGitCoreService.removeWorktree(input); -} - -export async function createGitBranch(input: GitCreateBranchInput): Promise { - await defaultGitCoreService.createBranch(input); -} - -export async function checkoutGitBranch(input: GitCheckoutInput): Promise { - await defaultGitCoreService.checkoutBranch(input); -} - -export async function initGitRepo(input: GitInitInput): Promise { - await defaultGitCoreService.initRepo(input); -} diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts new file mode 100644 index 0000000000..0847134698 --- /dev/null +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts @@ -0,0 +1,309 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; +import { expect } from "vitest"; + +import { ServerConfig } from "../../config.ts"; +import { TextGeneration } from "../Services/TextGeneration.ts"; +import { sanitizeThreadTitle } from "../Utils.ts"; +import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; + +const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe( + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3code-claude-text-generation-test-", + }), + ), + Layer.provideMerge(NodeServices.layer), +); + +function makeFakeClaudeBinary(dir: string) { + return Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = path.join(dir, "bin"); + const claudePath = path.join(binDir, "claude"); + yield* fs.makeDirectory(binDir, { recursive: true }); + + yield* fs.writeFileString( + claudePath, + [ + "#!/bin/sh", + 'args="$*"', + 'stdin_content="$(cat)"', + 'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then', + ' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {', + ' printf "%s\\n" "args missing expected content" >&2', + " exit 2", + " }", + "fi", + 'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then', + ' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then', + ' printf "%s\\n" "args contained forbidden content" >&2', + " exit 3", + " fi", + "fi", + 'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then', + ' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {', + ' printf "%s\\n" "stdin missing expected content" >&2', + " exit 4", + " }", + "fi", + 'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then', + ' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2', + "fi", + 'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"', + 'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"', + "", + ].join("\n"), + ); + yield* fs.chmod(claudePath, 0o755); + return binDir; + }); +} + +function withFakeClaudeEnv( + input: { + output: string; + exitCode?: number; + stderr?: string; + argsMustContain?: string; + argsMustNotContain?: string; + stdinMustContain?: string; + }, + effect: Effect.Effect, +) { + return Effect.acquireUseRelease( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" }); + const binDir = yield* makeFakeClaudeBinary(tempDir); + const previousPath = process.env.PATH; + const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT; + const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE; + const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR; + const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; + const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; + const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; + + yield* Effect.sync(() => { + process.env.PATH = `${binDir}:${previousPath ?? ""}`; + process.env.T3_FAKE_CLAUDE_OUTPUT = input.output; + + if (input.exitCode !== undefined) { + process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode); + } else { + delete process.env.T3_FAKE_CLAUDE_EXIT_CODE; + } + + if (input.stderr !== undefined) { + process.env.T3_FAKE_CLAUDE_STDERR = input.stderr; + } else { + delete process.env.T3_FAKE_CLAUDE_STDERR; + } + + if (input.argsMustContain !== undefined) { + process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain; + } else { + delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; + } + + if (input.argsMustNotContain !== undefined) { + process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain; + } else { + delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; + } + + if (input.stdinMustContain !== undefined) { + process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain; + } else { + delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; + } + }); + + return { + previousPath, + previousOutput, + previousExitCode, + previousStderr, + previousArgsMustContain, + previousArgsMustNotContain, + previousStdinMustContain, + }; + }), + () => effect, + (previous) => + Effect.sync(() => { + process.env.PATH = previous.previousPath; + + if (previous.previousOutput === undefined) { + delete process.env.T3_FAKE_CLAUDE_OUTPUT; + } else { + process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput; + } + + if (previous.previousExitCode === undefined) { + delete process.env.T3_FAKE_CLAUDE_EXIT_CODE; + } else { + process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode; + } + + if (previous.previousStderr === undefined) { + delete process.env.T3_FAKE_CLAUDE_STDERR; + } else { + process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr; + } + + if (previous.previousArgsMustContain === undefined) { + delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; + } else { + process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain; + } + + if (previous.previousArgsMustNotContain === undefined) { + delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; + } else { + process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain; + } + + if (previous.previousStdinMustContain === undefined) { + delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; + } else { + process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain; + } + }), + ); +} + +it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => { + it.effect("forwards Claude thinking settings for Haiku without passing effort", () => + withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + subject: "Add important change", + body: "", + }, + }), + argsMustContain: '--settings {"alwaysThinkingEnabled":false}', + argsMustNotContain: "--effort", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/claude-effect", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: { + provider: "claudeAgent", + model: "claude-haiku-4-5", + options: { + thinking: false, + effort: "high", + }, + }, + }); + + expect(generated.subject).toBe("Add important change"); + }), + ), + ); + + it.effect("forwards Claude fast mode and supported effort", () => + withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + title: "Improve orchestration flow", + body: "Body", + }, + }), + argsMustContain: '--effort max --settings {"fastMode":true}', + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generatePrContent({ + cwd: process.cwd(), + baseBranch: "main", + headBranch: "feature/claude-effect", + commitSummary: "Improve orchestration", + diffSummary: "1 file changed", + diffPatch: "diff --git a/README.md b/README.md", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + effort: "max", + fastMode: true, + }, + }, + }); + + expect(generated.title).toBe("Improve orchestration flow"); + }), + ), + ); + + it.effect("generates thread titles through the Claude provider", () => + withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + title: + ' "Reconnect failures after restart because the session state does not recover" ', + }, + }), + stdinMustContain: "You write concise thread titles for coding conversations.", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Please investigate reconnect failures after restarting the session.", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + expect(generated.title).toBe( + sanitizeThreadTitle( + '"Reconnect failures after restart because the session state does not recover"', + ), + ); + }), + ), + ); + + it.effect("falls back when Claude thread title normalization becomes whitespace-only", () => + withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + title: ' """ """ ', + }, + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + expect(generated.title).toBe("New thread"); + }), + ), + ); +}); diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.ts new file mode 100644 index 0000000000..99ca21b06d --- /dev/null +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.ts @@ -0,0 +1,339 @@ +/** + * ClaudeTextGeneration – Text generation layer using the Claude CLI. + * + * Implements the same TextGenerationShape contract as CodexTextGeneration but + * delegates to the `claude` CLI (`claude -p`) with structured JSON output + * instead of the `codex exec` CLI. + * + * @module ClaudeTextGeneration + */ +import { Effect, Layer, Option, Schema, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { ClaudeModelSelection } from "@t3tools/contracts"; +import { resolveApiModelId } from "@t3tools/shared/model"; +import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; + +import { TextGenerationError } from "@t3tools/contracts"; +import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts"; +import { + buildBranchNamePrompt, + buildCommitMessagePrompt, + buildPrContentPrompt, + buildThreadTitlePrompt, +} from "../Prompts.ts"; +import { + normalizeCliError, + sanitizeCommitSubject, + sanitizePrTitle, + sanitizeThreadTitle, + toJsonSchemaObject, +} from "../Utils.ts"; +import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts"; + +const CLAUDE_TIMEOUT_MS = 180_000; + +/** + * Schema for the wrapper JSON returned by `claude -p --output-format json`. + * We only care about `structured_output`. + */ +const ClaudeOutputEnvelope = Schema.Struct({ + structured_output: Schema.Unknown, +}); + +const makeClaudeTextGeneration = Effect.gen(function* () { + const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const serverSettingsService = yield* Effect.service(ServerSettingsService); + + const readStreamAsString = ( + operation: string, + stream: Stream.Stream, + ): Effect.Effect => + stream.pipe( + Stream.decodeText(), + Stream.runFold( + () => "", + (acc, chunk) => acc + chunk, + ), + Effect.mapError((cause) => + normalizeCliError("claude", operation, cause, "Failed to collect process output"), + ), + ); + + /** + * Spawn the Claude CLI with structured JSON output and return the parsed, + * schema-validated result. + */ + const runClaudeJson = Effect.fn("runClaudeJson")(function* ({ + operation, + cwd, + prompt, + outputSchemaJson, + modelSelection, + }: { + operation: + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle"; + cwd: string; + prompt: string; + outputSchemaJson: S; + modelSelection: ClaudeModelSelection; + }): Effect.fn.Return { + const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson)); + const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities( + getClaudeModelCapabilities(modelSelection.model), + modelSelection.options, + ); + const settings = { + ...(typeof normalizedOptions?.thinking === "boolean" + ? { alwaysThinkingEnabled: normalizedOptions.thinking } + : {}), + ...(normalizedOptions?.fastMode ? { fastMode: true } : {}), + }; + + const claudeSettings = yield* Effect.map( + serverSettingsService.getSettings, + (settings) => settings.providers.claudeAgent, + ).pipe(Effect.catch(() => Effect.undefined)); + + const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () { + const command = ChildProcess.make( + claudeSettings?.binaryPath || "claude", + [ + "-p", + "--output-format", + "json", + "--json-schema", + jsonSchemaStr, + "--model", + resolveApiModelId(modelSelection), + ...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []), + ...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []), + "--dangerously-skip-permissions", + ], + { + cwd, + shell: process.platform === "win32", + stdin: { + stream: Stream.encodeText(Stream.make(prompt)), + }, + }, + ); + + const child = yield* commandSpawner + .spawn(command) + .pipe( + Effect.mapError((cause) => + normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"), + ), + ); + + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + readStreamAsString(operation, child.stdout), + readStreamAsString(operation, child.stderr), + child.exitCode.pipe( + Effect.mapError((cause) => + normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"), + ), + ), + ], + { concurrency: "unbounded" }, + ); + + if (exitCode !== 0) { + const stderrDetail = stderr.trim(); + const stdoutDetail = stdout.trim(); + const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail; + return yield* new TextGenerationError({ + operation, + detail: + detail.length > 0 + ? `Claude CLI command failed: ${detail}` + : `Claude CLI command failed with code ${exitCode}.`, + }); + } + + return stdout; + }); + + const rawStdout = yield* runClaudeCommand().pipe( + Effect.scoped, + Effect.timeoutOption(CLAUDE_TIMEOUT_MS), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail( + new TextGenerationError({ operation, detail: "Claude CLI request timed out." }), + ), + onSome: (value) => Effect.succeed(value), + }), + ), + ); + + const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))( + rawStdout, + ).pipe( + Effect.catchTag("SchemaError", (cause) => + Effect.fail( + new TextGenerationError({ + operation, + detail: "Claude CLI returned unexpected output format.", + cause, + }), + ), + ), + ); + + return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe( + Effect.catchTag("SchemaError", (cause) => + Effect.fail( + new TextGenerationError({ + operation, + detail: "Claude returned invalid structured output.", + cause, + }), + ), + ), + ); + }); + + // --------------------------------------------------------------------------- + // TextGenerationShape methods + // --------------------------------------------------------------------------- + + const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn( + "ClaudeTextGeneration.generateCommitMessage", + )(function* (input) { + const { prompt, outputSchema } = buildCommitMessagePrompt({ + branch: input.branch, + stagedSummary: input.stagedSummary, + stagedPatch: input.stagedPatch, + includeBranch: input.includeBranch === true, + }); + + if (input.modelSelection.provider !== "claudeAgent") { + return yield* new TextGenerationError({ + operation: "generateCommitMessage", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runClaudeJson({ + operation: "generateCommitMessage", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + modelSelection: input.modelSelection, + }); + + return { + subject: sanitizeCommitSubject(generated.subject), + body: generated.body.trim(), + ...("branch" in generated && typeof generated.branch === "string" + ? { branch: sanitizeFeatureBranchName(generated.branch) } + : {}), + }; + }); + + const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn( + "ClaudeTextGeneration.generatePrContent", + )(function* (input) { + const { prompt, outputSchema } = buildPrContentPrompt({ + baseBranch: input.baseBranch, + headBranch: input.headBranch, + commitSummary: input.commitSummary, + diffSummary: input.diffSummary, + diffPatch: input.diffPatch, + }); + + if (input.modelSelection.provider !== "claudeAgent") { + return yield* new TextGenerationError({ + operation: "generatePrContent", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runClaudeJson({ + operation: "generatePrContent", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + modelSelection: input.modelSelection, + }); + + return { + title: sanitizePrTitle(generated.title), + body: generated.body.trim(), + }; + }); + + const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn( + "ClaudeTextGeneration.generateBranchName", + )(function* (input) { + const { prompt, outputSchema } = buildBranchNamePrompt({ + message: input.message, + attachments: input.attachments, + }); + + if (input.modelSelection.provider !== "claudeAgent") { + return yield* new TextGenerationError({ + operation: "generateBranchName", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runClaudeJson({ + operation: "generateBranchName", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + modelSelection: input.modelSelection, + }); + + return { + branch: sanitizeBranchFragment(generated.branch), + }; + }); + + const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn( + "ClaudeTextGeneration.generateThreadTitle", + )(function* (input) { + const { prompt, outputSchema } = buildThreadTitlePrompt({ + message: input.message, + attachments: input.attachments, + }); + + if (input.modelSelection.provider !== "claudeAgent") { + return yield* new TextGenerationError({ + operation: "generateThreadTitle", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runClaudeJson({ + operation: "generateThreadTitle", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + modelSelection: input.modelSelection, + }); + + return { + title: sanitizeThreadTitle(generated.title), + }; + }); + + return { + generateCommitMessage, + generatePrContent, + generateBranchName, + generateThreadTitle, + } satisfies TextGenerationShape; +}); + +export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration); diff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/git/Layers/CodexTextGeneration.test.ts new file mode 100644 index 0000000000..a07505f025 --- /dev/null +++ b/apps/server/src/git/Layers/CodexTextGeneration.test.ts @@ -0,0 +1,637 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path, Result } from "effect"; +import { expect } from "vitest"; + +import { ServerConfig } from "../../config.ts"; +import { CodexTextGenerationLive } from "./CodexTextGeneration.ts"; +import { TextGenerationError } from "@t3tools/contracts"; +import { TextGeneration } from "../Services/TextGeneration.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; + +const DEFAULT_TEST_MODEL_SELECTION = { + provider: "codex" as const, + model: "gpt-5.4-mini", +}; + +const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe( + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3code-codex-text-generation-test-", + }), + ), + Layer.provideMerge(NodeServices.layer), +); + +function makeFakeCodexBinary( + dir: string, + input: { + output: string; + exitCode?: number; + stderr?: string; + requireImage?: boolean; + requireFastServiceTier?: boolean; + requireReasoningEffort?: string; + forbidReasoningEffort?: boolean; + stdinMustContain?: string; + stdinMustNotContain?: string; + }, +) { + return Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = path.join(dir, "bin"); + const codexPath = path.join(binDir, "codex"); + yield* fs.makeDirectory(binDir, { recursive: true }); + + yield* fs.writeFileString( + codexPath, + [ + "#!/bin/sh", + 'output_path=""', + 'seen_image="0"', + 'seen_fast_service_tier="0"', + 'seen_reasoning_effort=""', + "while [ $# -gt 0 ]; do", + ' if [ "$1" = "--image" ]; then', + " shift", + ' if [ -n "$1" ]; then', + ' seen_image="1"', + " fi", + " shift", + " continue", + " fi", + ' if [ "$1" = "--config" ]; then', + " shift", + ' if [ "$1" = "service_tier=\\"fast\\"" ]; then', + ' seen_fast_service_tier="1"', + " fi", + ' case "$1" in', + " model_reasoning_effort=*)", + ' seen_reasoning_effort="$1"', + " ;;", + " esac", + " shift", + " continue", + " fi", + ' if [ "$1" = "--output-last-message" ]; then', + " shift", + ' output_path="$1"', + " shift", + " continue", + " fi", + " shift", + "done", + 'stdin_content="$(cat)"', + ...(input.requireImage + ? [ + 'if [ "$seen_image" != "1" ]; then', + ' printf "%s\\n" "missing --image input" >&2', + ` exit 2`, + "fi", + ] + : []), + ...(input.requireFastServiceTier + ? [ + 'if [ "$seen_fast_service_tier" != "1" ]; then', + ' printf "%s\\n" "missing fast service tier config" >&2', + ` exit 5`, + "fi", + ] + : []), + ...(input.requireReasoningEffort !== undefined + ? [ + `if [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"${input.requireReasoningEffort}\\"" ]; then`, + ' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2', + ` exit 6`, + "fi", + ] + : []), + ...(input.forbidReasoningEffort + ? [ + 'if [ -n "$seen_reasoning_effort" ]; then', + ' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2', + ` exit 7`, + "fi", + ] + : []), + ...(input.stdinMustContain !== undefined + ? [ + `if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`, + ' printf "%s\\n" "stdin missing expected content" >&2', + ` exit 3`, + "fi", + ] + : []), + ...(input.stdinMustNotContain !== undefined + ? [ + `if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`, + ' printf "%s\\n" "stdin contained forbidden content" >&2', + ` exit 4`, + "fi", + ] + : []), + ...(input.stderr !== undefined + ? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`] + : []), + 'if [ -n "$output_path" ]; then', + " cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'", + input.output, + "__T3CODE_FAKE_CODEX_OUTPUT__", + "fi", + `exit ${input.exitCode ?? 0}`, + "", + ].join("\n"), + ); + yield* fs.chmod(codexPath, 0o755); + return codexPath; + }); +} + +function withFakeCodexEnv( + input: { + output: string; + exitCode?: number; + stderr?: string; + requireImage?: boolean; + requireFastServiceTier?: boolean; + requireReasoningEffort?: string; + forbidReasoningEffort?: boolean; + stdinMustContain?: string; + stdinMustNotContain?: string; + }, + effect: Effect.Effect, +) { + return Effect.acquireUseRelease( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" }); + const codexPath = yield* makeFakeCodexBinary(tempDir, input); + const serverSettings = yield* ServerSettingsService; + const previousSettings = yield* serverSettings.getSettings; + yield* serverSettings.updateSettings({ + providers: { + codex: { + binaryPath: codexPath, + }, + }, + }); + return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath }; + }), + () => effect, + ({ serverSettings, previousBinaryPath }) => + serverSettings + .updateSettings({ + providers: { + codex: { + binaryPath: previousBinaryPath, + }, + }, + }) + .pipe(Effect.asVoid), + ); +} + +it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { + it.effect("generates and sanitizes commit messages without branch by default", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + subject: + " Add important change to the system with too much detail and a trailing period.\nsecondary line", + body: "\n- added migration\n- updated tests\n", + }), + stdinMustNotContain: "branch must be a short semantic git branch fragment", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/codex-effect", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.subject.length).toBeLessThanOrEqual(72); + expect(generated.subject.endsWith(".")).toBe(false); + expect(generated.body).toBe("- added migration\n- updated tests"); + expect(generated.branch).toBeUndefined(); + }), + ), + ); + + it.effect( + "forwards codex fast mode and non-default reasoning effort into codex exec config", + () => + withFakeCodexEnv( + { + output: JSON.stringify({ + subject: "Add important change", + body: "", + }), + requireFastServiceTier: true, + requireReasoningEffort: "xhigh", + stdinMustNotContain: "branch must be a short semantic git branch fragment", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/codex-effect", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: { + provider: "codex", + model: "gpt-5.4", + options: { + reasoningEffort: "xhigh", + fastMode: true, + }, + }, + }); + }), + ), + ); + + it.effect("defaults git text generation codex effort to low", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + subject: "Add important change", + body: "", + }), + requireReasoningEffort: "low", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/codex-effect", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + }), + ), + ); + + it.effect("generates commit message with branch when includeBranch is true", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + subject: "Add important change", + body: "", + branch: "fix/important-system-change", + }), + stdinMustContain: "branch must be a short semantic git branch fragment", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/codex-effect", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + includeBranch: true, + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.subject).toBe("Add important change"); + expect(generated.branch).toBe("feature/fix/important-system-change"); + }), + ), + ); + + it.effect("generates PR content and trims markdown body", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: " Improve orchestration flow\nwith ignored suffix", + body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n", + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generatePrContent({ + cwd: process.cwd(), + baseBranch: "main", + headBranch: "feature/codex-effect", + commitSummary: "feat: improve orchestration flow", + diffSummary: "2 files changed", + diffPatch: "diff --git a/a.ts b/a.ts", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.title).toBe("Improve orchestration flow"); + expect(generated.body.startsWith("## Summary")).toBe(true); + expect(generated.body.endsWith("\n\n")).toBe(false); + }), + ), + ); + + it.effect("generates branch names and normalizes branch fragments", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + branch: " Feat/Session ", + }), + stdinMustNotContain: "Image attachments supplied to the model", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateBranchName({ + cwd: process.cwd(), + message: "Please update session handling.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.branch).toBe("feat/session"); + }), + ), + ); + + it.effect("generates thread titles and trims them for sidebar use", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: + ' "Investigate websocket reconnect regressions after worktree restore" \nignored line', + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Please investigate websocket reconnect regressions after a worktree restore.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.title).toBe("Investigate websocket reconnect regressions aft..."); + }), + ), + ); + + it.effect("falls back when thread title normalization becomes whitespace-only", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: ' """ """ ', + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.title).toBe("New thread"); + }), + ), + ); + + it.effect("trims whitespace exposed after quote removal in thread titles", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: ` "' hello world '" `, + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.title).toBe("hello world"); + }), + ), + ); + + it.effect("omits attachment metadata section when no attachments are provided", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + branch: "fix/session-timeout", + }), + stdinMustNotContain: "Attachment metadata:", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateBranchName({ + cwd: process.cwd(), + message: "Fix timeout behavior.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.branch).toBe("fix/session-timeout"); + }), + ), + ); + + it.effect("passes image attachments through as codex image inputs", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + branch: "fix/ui-regression", + }), + requireImage: true, + stdinMustContain: "Attachment metadata:", + }, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { attachmentsDir } = yield* ServerConfig; + const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; + const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`); + yield* fs.makeDirectory(attachmentsDir, { recursive: true }); + yield* fs.writeFile(attachmentPath, Buffer.from("hello")); + + const textGeneration = yield* TextGeneration; + const generated = yield* textGeneration.generateBranchName({ + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + cwd: process.cwd(), + message: "Fix layout bug from screenshot.", + attachments: [ + { + type: "image", + id: attachmentId, + name: "bug.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + }); + + expect(generated.branch).toBe("fix/ui-regression"); + }), + ), + ); + + it.effect("resolves persisted attachment ids to files for codex image inputs", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + branch: "fix/ui-regression", + }), + requireImage: true, + }, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { attachmentsDir } = yield* ServerConfig; + const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; + const imagePath = path.join(attachmentsDir, `${attachmentId}.png`); + yield* fs.makeDirectory(attachmentsDir, { recursive: true }); + yield* fs.writeFile(imagePath, Buffer.from("hello")); + + const textGeneration = yield* TextGeneration; + const generated = yield* textGeneration + .generateBranchName({ + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + cwd: process.cwd(), + message: "Fix layout bug from screenshot.", + attachments: [ + { + type: "image", + id: attachmentId, + name: "bug.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + }) + .pipe( + Effect.tap(() => + fs.stat(imagePath).pipe( + Effect.map((fileInfo) => { + expect(fileInfo.type).toBe("File"); + }), + ), + ), + Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))), + ); + + expect(generated.branch).toBe("fix/ui-regression"); + }), + ), + ); + + it.effect("ignores missing attachment ids for codex image inputs", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + branch: "fix/ui-regression", + }), + requireImage: true, + }, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { attachmentsDir } = yield* ServerConfig; + const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; + const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`); + yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void)); + + const textGeneration = yield* TextGeneration; + const result = yield* textGeneration + .generateBranchName({ + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + cwd: process.cwd(), + message: "Fix layout bug from screenshot.", + attachments: [ + { + type: "image", + id: missingAttachmentId, + name: "outside.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + }) + .pipe(Effect.result); + + expect(Result.isFailure(result)).toBe(true); + if (Result.isFailure(result)) { + expect(result.failure).toBeInstanceOf(TextGenerationError); + expect(result.failure.message).toContain("missing --image input"); + } + }), + ), + ); + + it.effect( + "fails with typed TextGenerationError when codex returns wrong branch payload shape", + () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: "This is not a branch payload", + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const result = yield* textGeneration + .generateBranchName({ + cwd: process.cwd(), + message: "Fix websocket reconnect flake", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }) + .pipe(Effect.result); + + expect(Result.isFailure(result)).toBe(true); + if (Result.isFailure(result)) { + expect(result.failure).toBeInstanceOf(TextGenerationError); + expect(result.failure.message).toContain("Codex returned invalid structured output"); + } + }), + ), + ); + + it.effect("returns typed TextGenerationError when codex exits non-zero", () => + withFakeCodexEnv( + { + output: JSON.stringify({ subject: "ignored", body: "" }), + exitCode: 1, + stderr: "codex execution failed", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const result = yield* textGeneration + .generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/codex-error", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }) + .pipe(Effect.result); + + expect(Result.isFailure(result)).toBe(true); + if (Result.isFailure(result)) { + expect(result.failure).toBeInstanceOf(TextGenerationError); + expect(result.failure.message).toContain( + "Codex CLI command failed: codex execution failed", + ); + } + }), + ), + ); +}); diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts new file mode 100644 index 0000000000..52ddf55453 --- /dev/null +++ b/apps/server/src/git/Layers/CodexTextGeneration.ts @@ -0,0 +1,416 @@ +import { randomUUID } from "node:crypto"; + +import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { CodexModelSelection } from "@t3tools/contracts"; +import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; + +import { resolveAttachmentPath } from "../../attachmentStore.ts"; +import { ServerConfig } from "../../config.ts"; +import { TextGenerationError } from "@t3tools/contracts"; +import { + type BranchNameGenerationInput, + type ThreadTitleGenerationResult, + type TextGenerationShape, + TextGeneration, +} from "../Services/TextGeneration.ts"; +import { + buildBranchNamePrompt, + buildCommitMessagePrompt, + buildPrContentPrompt, + buildThreadTitlePrompt, +} from "../Prompts.ts"; +import { + normalizeCliError, + sanitizeCommitSubject, + sanitizePrTitle, + sanitizeThreadTitle, + toJsonSchemaObject, +} from "../Utils.ts"; +import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model"; + +const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low"; +const CODEX_TIMEOUT_MS = 180_000; +const makeCodexTextGeneration = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const serverConfig = yield* Effect.service(ServerConfig); + const serverSettingsService = yield* Effect.service(ServerSettingsService); + + type MaterializedImageAttachments = { + readonly imagePaths: ReadonlyArray; + }; + + const readStreamAsString = ( + operation: string, + stream: Stream.Stream, + ): Effect.Effect => + stream.pipe( + Stream.decodeText(), + Stream.runFold( + () => "", + (acc, chunk) => acc + chunk, + ), + Effect.mapError((cause) => + normalizeCliError("codex", operation, cause, "Failed to collect process output"), + ), + ); + + const writeTempFile = ( + operation: string, + prefix: string, + content: string, + ): Effect.Effect => { + return fileSystem + .makeTempFileScoped({ + prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`, + }) + .pipe( + Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)), + Effect.mapError( + (cause) => + new TextGenerationError({ + operation, + detail: `Failed to write temp file`, + cause, + }), + ), + ); + }; + + const safeUnlink = (filePath: string): Effect.Effect => + fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void)); + + const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* ( + _operation: + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle", + attachments: BranchNameGenerationInput["attachments"], + ): Effect.fn.Return { + if (!attachments || attachments.length === 0) { + return { imagePaths: [] }; + } + + const imagePaths: string[] = []; + for (const attachment of attachments) { + if (attachment.type !== "image") { + continue; + } + + const resolvedPath = resolveAttachmentPath({ + attachmentsDir: serverConfig.attachmentsDir, + attachment, + }); + if (!resolvedPath || !path.isAbsolute(resolvedPath)) { + continue; + } + const fileInfo = yield* fileSystem + .stat(resolvedPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!fileInfo || fileInfo.type !== "File") { + continue; + } + imagePaths.push(resolvedPath); + } + return { imagePaths }; + }); + + const runCodexJson = Effect.fn("runCodexJson")(function* ({ + operation, + cwd, + prompt, + outputSchemaJson, + imagePaths = [], + cleanupPaths = [], + modelSelection, + }: { + operation: + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle"; + cwd: string; + prompt: string; + outputSchemaJson: S; + imagePaths?: ReadonlyArray; + cleanupPaths?: ReadonlyArray; + modelSelection: CodexModelSelection; + }): Effect.fn.Return { + const schemaPath = yield* writeTempFile( + operation, + "codex-schema", + JSON.stringify(toJsonSchemaObject(outputSchemaJson)), + ); + const outputPath = yield* writeTempFile(operation, "codex-output", ""); + + const codexSettings = yield* Effect.map( + serverSettingsService.getSettings, + (settings) => settings.providers.codex, + ).pipe(Effect.catch(() => Effect.undefined)); + + const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () { + const normalizedOptions = normalizeCodexModelOptionsWithCapabilities( + getCodexModelCapabilities(modelSelection.model), + modelSelection.options, + ); + const reasoningEffort = + modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; + const command = ChildProcess.make( + codexSettings?.binaryPath || "codex", + [ + "exec", + "--ephemeral", + "-s", + "read-only", + "--model", + modelSelection.model, + "--config", + `model_reasoning_effort="${reasoningEffort}"`, + ...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []), + "--output-schema", + schemaPath, + "--output-last-message", + outputPath, + ...imagePaths.flatMap((imagePath) => ["--image", imagePath]), + "-", + ], + { + env: { + ...process.env, + ...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}), + }, + cwd, + shell: process.platform === "win32", + stdin: { + stream: Stream.encodeText(Stream.make(prompt)), + }, + }, + ); + + const child = yield* commandSpawner + .spawn(command) + .pipe( + Effect.mapError((cause) => + normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"), + ), + ); + + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + readStreamAsString(operation, child.stdout), + readStreamAsString(operation, child.stderr), + child.exitCode.pipe( + Effect.mapError((cause) => + normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"), + ), + ), + ], + { concurrency: "unbounded" }, + ); + + if (exitCode !== 0) { + const stderrDetail = stderr.trim(); + const stdoutDetail = stdout.trim(); + const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail; + return yield* new TextGenerationError({ + operation, + detail: + detail.length > 0 + ? `Codex CLI command failed: ${detail}` + : `Codex CLI command failed with code ${exitCode}.`, + }); + } + }); + + const cleanup = Effect.all( + [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)), + { + concurrency: "unbounded", + }, + ).pipe(Effect.asVoid); + + return yield* Effect.gen(function* () { + yield* runCodexCommand().pipe( + Effect.scoped, + Effect.timeoutOption(CODEX_TIMEOUT_MS), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail( + new TextGenerationError({ operation, detail: "Codex CLI request timed out." }), + ), + onSome: () => Effect.void, + }), + ), + ); + + return yield* fileSystem.readFileString(outputPath).pipe( + Effect.mapError( + (cause) => + new TextGenerationError({ + operation, + detail: "Failed to read Codex output file.", + cause, + }), + ), + Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))), + Effect.catchTag("SchemaError", (cause) => + Effect.fail( + new TextGenerationError({ + operation, + detail: "Codex returned invalid structured output.", + cause, + }), + ), + ), + ); + }).pipe(Effect.ensuring(cleanup)); + }); + + const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn( + "CodexTextGeneration.generateCommitMessage", + )(function* (input) { + const { prompt, outputSchema } = buildCommitMessagePrompt({ + branch: input.branch, + stagedSummary: input.stagedSummary, + stagedPatch: input.stagedPatch, + includeBranch: input.includeBranch === true, + }); + + if (input.modelSelection.provider !== "codex") { + return yield* new TextGenerationError({ + operation: "generateCommitMessage", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runCodexJson({ + operation: "generateCommitMessage", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + modelSelection: input.modelSelection, + }); + + return { + subject: sanitizeCommitSubject(generated.subject), + body: generated.body.trim(), + ...("branch" in generated && typeof generated.branch === "string" + ? { branch: sanitizeFeatureBranchName(generated.branch) } + : {}), + }; + }); + + const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn( + "CodexTextGeneration.generatePrContent", + )(function* (input) { + const { prompt, outputSchema } = buildPrContentPrompt({ + baseBranch: input.baseBranch, + headBranch: input.headBranch, + commitSummary: input.commitSummary, + diffSummary: input.diffSummary, + diffPatch: input.diffPatch, + }); + + if (input.modelSelection.provider !== "codex") { + return yield* new TextGenerationError({ + operation: "generatePrContent", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runCodexJson({ + operation: "generatePrContent", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + modelSelection: input.modelSelection, + }); + + return { + title: sanitizePrTitle(generated.title), + body: generated.body.trim(), + }; + }); + + const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn( + "CodexTextGeneration.generateBranchName", + )(function* (input) { + const { imagePaths } = yield* materializeImageAttachments( + "generateBranchName", + input.attachments, + ); + const { prompt, outputSchema } = buildBranchNamePrompt({ + message: input.message, + attachments: input.attachments, + }); + + if (input.modelSelection.provider !== "codex") { + return yield* new TextGenerationError({ + operation: "generateBranchName", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runCodexJson({ + operation: "generateBranchName", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + imagePaths, + modelSelection: input.modelSelection, + }); + + return { + branch: sanitizeBranchFragment(generated.branch), + }; + }); + + const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn( + "CodexTextGeneration.generateThreadTitle", + )(function* (input) { + const { imagePaths } = yield* materializeImageAttachments( + "generateThreadTitle", + input.attachments, + ); + const { prompt, outputSchema } = buildThreadTitlePrompt({ + message: input.message, + attachments: input.attachments, + }); + + if (input.modelSelection.provider !== "codex") { + return yield* new TextGenerationError({ + operation: "generateThreadTitle", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runCodexJson({ + operation: "generateThreadTitle", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + imagePaths, + modelSelection: input.modelSelection, + }); + + return { + title: sanitizeThreadTitle(generated.title), + } satisfies ThreadTitleGenerationResult; + }); + + return { + generateCommitMessage, + generatePrContent, + generateBranchName, + generateThreadTitle, + } satisfies TextGenerationShape; +}); + +export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration); diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts new file mode 100644 index 0000000000..5e4416d8b9 --- /dev/null +++ b/apps/server/src/git/Layers/GitCore.test.ts @@ -0,0 +1,2213 @@ +import { existsSync } from "node:fs"; +import path from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it } from "@effect/vitest"; +import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; +import { describe, expect, vi } from "vitest"; + +import { GitCoreLive, makeGitCore } from "./GitCore.ts"; +import { GitCore, type GitCoreShape } from "../Services/GitCore.ts"; +import { GitCommandError } from "@t3tools/contracts"; +import { type ProcessRunResult, runProcess } from "../../processRunner.ts"; +import { ServerConfig } from "../../config.ts"; + +// ── Helpers ── + +const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-core-test-" }); +const GitCoreTestLayer = GitCoreLive.pipe( + Layer.provide(ServerConfigLayer), + Layer.provide(NodeServices.layer), +); +const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer); + +function makeTmpDir( + prefix = "git-test-", +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ prefix }); + }); +} + +function writeTextFile( + filePath: string, + contents: string, +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.writeFileString(filePath, contents); + }); +} + +/** Run a raw git command for test setup (not under test). */ +function git( + cwd: string, + args: ReadonlyArray, + env?: NodeJS.ProcessEnv, +): Effect.Effect { + return Effect.gen(function* () { + const gitCore = yield* GitCore; + const result = yield* gitCore.execute({ + operation: "GitCore.test.git", + cwd, + args, + ...(env ? { env } : {}), + timeoutMs: 10_000, + }); + return result.stdout.trim(); + }); +} + +function configureRemote( + cwd: string, + remoteName: string, + remotePath: string, + fetchNamespace: string, +): Effect.Effect { + return Effect.gen(function* () { + yield* git(cwd, ["config", `remote.${remoteName}.url`, remotePath]); + return yield* git(cwd, [ + "config", + "--replace-all", + `remote.${remoteName}.fetch`, + `+refs/heads/*:refs/remotes/${fetchNamespace}/*`, + ]); + }); +} + +function runShellCommand(input: { + command: string; + cwd: string; + timeoutMs?: number; + maxOutputBytes?: number; +}): Effect.Effect { + return Effect.promise(() => { + const shellPath = + process.platform === "win32" + ? (process.env.ComSpec ?? "cmd.exe") + : (process.env.SHELL ?? "/bin/sh"); + + const args = + process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command]; + + return runProcess(shellPath, args, { + cwd: input.cwd, + timeoutMs: input.timeoutMs ?? 30_000, + allowNonZeroExit: true, + maxBufferBytes: input.maxOutputBytes ?? 1_000_000, + outputMode: "truncate", + }); + }); +} + +const makeIsolatedGitCore = (executeOverride: GitCoreShape["execute"]) => + makeGitCore({ executeOverride }).pipe( + Effect.provide(Layer.provideMerge(ServerConfigLayer, NodeServices.layer)), + ); + +/** Create a repo with an initial commit so branches work. */ +function initRepoWithCommit( + cwd: string, +): Effect.Effect< + { initialBranch: string }, + GitCommandError | PlatformError.PlatformError, + GitCore | FileSystem.FileSystem +> { + return Effect.gen(function* () { + const core = yield* GitCore; + yield* core.initRepo({ cwd }); + yield* git(cwd, ["config", "user.email", "test@test.com"]); + yield* git(cwd, ["config", "user.name", "Test"]); + yield* writeTextFile(path.join(cwd, "README.md"), "# test\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "initial commit"]); + const initialBranch = yield* git(cwd, ["branch", "--show-current"]); + return { initialBranch }; + }); +} + +function commitWithDate( + cwd: string, + fileName: string, + fileContents: string, + dateIsoString: string, + message: string, +): Effect.Effect< + void, + GitCommandError | PlatformError.PlatformError, + GitCore | FileSystem.FileSystem +> { + return Effect.gen(function* () { + yield* writeTextFile(path.join(cwd, fileName), fileContents); + yield* git(cwd, ["add", fileName]); + yield* git(cwd, ["commit", "-m", message], { + ...process.env, + GIT_AUTHOR_DATE: dateIsoString, + GIT_COMMITTER_DATE: dateIsoString, + }); + }); +} + +function buildLargeText(lineCount = 20_000): string { + return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`) + .join("\n") + .concat("\n"); +} + +function splitNullSeparatedPaths(input: string): string[] { + return input + .split("\0") + .map((value) => value.trim()) + .filter((value) => value.length > 0); +} + +// ── Tests ── + +it.layer(TestLayer)("git integration", (it) => { + describe("shell process execution", () => { + it.effect("caps captured output when maxOutputBytes is exceeded", () => + Effect.gen(function* () { + const result = yield* runShellCommand({ + command: `node -e "process.stdout.write('x'.repeat(2000))"`, + cwd: process.cwd(), + timeoutMs: 10_000, + maxOutputBytes: 128, + }); + + expect(result.code).toBe(0); + expect(result.stdout.length).toBeLessThanOrEqual(128); + expect(result.stdoutTruncated || result.stderrTruncated).toBe(true); + }), + ); + }); + + // ── initGitRepo ── + + describe("initGitRepo", () => { + it.effect("creates a valid git repo", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* (yield* GitCore).initRepo({ cwd: tmp }); + expect(existsSync(path.join(tmp, ".git"))).toBe(true); + }), + ); + + it.effect("listGitBranches reports isRepo: true after init + commit", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(result.isRepo).toBe(true); + expect(result.hasOriginRemote).toBe(false); + expect(result.branches.length).toBeGreaterThanOrEqual(1); + }), + ); + }); + + describe("workspace helpers", () => { + it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () => + Effect.gen(function* () { + const cwd = "/virtual/repo"; + const relativePaths = Array.from({ length: 340 }, (_, index) => { + const prefix = index % 3 === 0 ? "ignored" : "kept"; + return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`; + }); + const expectedPaths = relativePaths.filter( + (relativePath) => !relativePath.startsWith("ignored/"), + ); + + const seenChunks: string[][] = []; + const core = yield* makeIsolatedGitCore((input) => { + if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") { + return Effect.fail( + new GitCommandError({ + operation: input.operation, + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "unexpected git command in chunking test", + }), + ); + } + + const chunkPaths = splitNullSeparatedPaths(input.stdin ?? ""); + seenChunks.push(chunkPaths); + const ignoredPaths = chunkPaths.filter((relativePath) => + relativePath.startsWith("ignored/"), + ); + + return Effect.succeed({ + code: ignoredPaths.length > 0 ? 0 : 1, + stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + }); + + const result = yield* core.filterIgnoredPaths(cwd, relativePaths); + + expect(seenChunks.length).toBeGreaterThan(1); + expect(seenChunks.flat()).toEqual(relativePaths); + expect(result).toEqual(expectedPaths); + }), + ); + }); + + // ── listGitBranches ── + + describe("listGitBranches", () => { + it.effect("returns isRepo: false for non-git directory", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(result.isRepo).toBe(false); + expect(result.hasOriginRemote).toBe(false); + expect(result.branches).toEqual([]); + }), + ); + + it.effect("returns the current branch with current: true", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + const current = result.branches.find((b) => b.current); + expect(current).toBeDefined(); + expect(current!.current).toBe(true); + }), + ); + + it.effect("does not include detached HEAD pseudo-refs as branches", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* git(tmp, ["checkout", "--detach", "HEAD"]); + + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false); + expect(result.branches.some((branch) => branch.current)).toBe(false); + }), + ); + + it.effect("keeps current branch first and sorts the remaining branches by recency", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const initialBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (branch) => branch.current, + )!.name; + + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "older-branch" }); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "older-branch" }); + yield* commitWithDate( + tmp, + "older.txt", + "older branch change\n", + "Thu, 1 Jan 2037 00:00:00 +0000", + "older branch change", + ); + + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: initialBranch }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "newer-branch" }); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "newer-branch" }); + yield* commitWithDate( + tmp, + "newer.txt", + "newer branch change\n", + "Fri, 1 Jan 2038 00:00:00 +0000", + "newer branch change", + ); + + // Switch away to show current branch is pinned, then remaining branches are recency-sorted. + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "older-branch" }); + + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(result.branches[0]!.name).toBe("older-branch"); + expect(result.branches[1]!.name).toBe("newer-branch"); + }), + ); + + it.effect("keeps default branch right after current branch", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const remote = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (branch) => branch.current, + )!.name; + + yield* git(remote, ["init", "--bare"]); + yield* git(tmp, ["remote", "add", "origin", remote]); + yield* git(tmp, ["push", "-u", "origin", defaultBranch]); + yield* git(tmp, ["remote", "set-head", "origin", defaultBranch]); + + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "current-branch" }); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "current-branch" }); + yield* commitWithDate( + tmp, + "current.txt", + "current change\n", + "Thu, 1 Jan 2037 00:00:00 +0000", + "current change", + ); + + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: defaultBranch }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "newer-branch" }); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "newer-branch" }); + yield* commitWithDate( + tmp, + "newer.txt", + "newer change\n", + "Fri, 1 Jan 2038 00:00:00 +0000", + "newer change", + ); + + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "current-branch" }); + + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(result.branches[0]!.name).toBe("current-branch"); + expect(result.branches[1]!.name).toBe(defaultBranch); + expect(result.branches[2]!.name).toBe("newer-branch"); + }), + ); + + it.effect("lists multiple branches after creating them", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" }); + + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + const names = result.branches.map((b) => b.name); + expect(names).toContain("feature-a"); + expect(names).toContain("feature-b"); + }), + ); + + it.effect("paginates branch results and returns paging metadata", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-c" }); + + const firstPage = yield* (yield* GitCore).listBranches({ cwd: tmp, limit: 2 }); + expect(firstPage.totalCount).toBe(4); + expect(firstPage.nextCursor).toBe(2); + expect(firstPage.branches.map((branch) => branch.name)).toEqual([ + initialBranch, + "feature-a", + ]); + + const secondPage = yield* (yield* GitCore).listBranches({ + cwd: tmp, + cursor: firstPage.nextCursor ?? 0, + limit: 2, + }); + expect(secondPage.totalCount).toBe(4); + expect(secondPage.nextCursor).toBeNull(); + expect(secondPage.branches.map((branch) => branch.name)).toEqual([ + "feature-b", + "feature-c", + ]); + }), + ); + + it.effect("parses separate branch names when column.ui is always enabled", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(tmp); + const createdBranchNames = [ + "go-bin", + "copilot/rewrite-cli-in-go", + "copilot/rewrite-cli-in-rust", + ] as const; + for (const branchName of createdBranchNames) { + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: branchName }); + } + yield* git(tmp, ["config", "column.ui", "always"]); + + const rawBranchOutput = yield* git(tmp, ["branch", "--no-color"], { + ...process.env, + COLUMNS: "120", + }); + expect( + rawBranchOutput + .split("\n") + .some( + (line) => + createdBranchNames.filter((branchName) => line.includes(branchName)).length >= 2, + ), + ).toBe(true); + + const realGitCore = yield* GitCore; + const core = yield* makeIsolatedGitCore((input) => + realGitCore.execute( + input.args[0] === "branch" + ? { + ...input, + env: { ...input.env, COLUMNS: "120" }, + } + : input, + ), + ); + + const result = yield* core.listBranches({ cwd: tmp }); + const localBranchNames = result.branches + .filter((branch) => !branch.isRemote) + .map((branch) => branch.name); + + expect(localBranchNames).toHaveLength(4); + expect(localBranchNames).toEqual( + expect.arrayContaining([initialBranch, ...createdBranchNames]), + ); + expect( + localBranchNames.some( + (branchName) => + createdBranchNames.filter((createdBranch) => branchName.includes(createdBranch)) + .length >= 2, + ), + ).toBe(false); + }), + ); + + it.effect("isDefault is false when no remote exists", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(result.branches.every((b) => b.isDefault === false)).toBe(true); + }), + ); + + it.effect("lists local branches first and remote branches last", () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const tmp = yield* makeTmpDir(); + + yield* git(remote, ["init", "--bare"]); + yield* initRepoWithCommit(tmp); + const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (branch) => branch.current, + )!.name; + + yield* git(tmp, ["remote", "add", "origin", remote]); + yield* git(tmp, ["push", "-u", "origin", defaultBranch]); + + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/local-only" }); + + const remoteOnlyBranch = "feature/remote-only"; + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: defaultBranch }); + yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]); + yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]); + yield* git(tmp, ["checkout", defaultBranch]); + yield* git(tmp, ["branch", "-D", remoteOnlyBranch]); + + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote); + + expect(result.hasOriginRemote).toBe(true); + expect(firstRemoteIndex).toBeGreaterThan(0); + expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe( + true, + ); + expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe( + true, + ); + expect( + result.branches.some( + (branch) => branch.name === "feature/local-only" && !branch.isRemote, + ), + ).toBe(true); + expect( + result.branches.some( + (branch) => branch.name === "origin/feature/remote-only" && branch.isRemote, + ), + ).toBe(true); + }), + ); + + it.effect("includes remoteName metadata for remotes with slash in the name", () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const tmp = yield* makeTmpDir(); + const remoteName = "my-org/upstream"; + + yield* git(remote, ["init", "--bare"]); + yield* initRepoWithCommit(tmp); + const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (branch) => branch.current, + )!.name; + + yield* git(tmp, ["remote", "add", remoteName, remote]); + yield* git(tmp, ["push", "-u", remoteName, defaultBranch]); + + const remoteOnlyBranch = "feature/remote-with-remote-name"; + yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]); + yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]); + yield* git(tmp, ["checkout", defaultBranch]); + yield* git(tmp, ["branch", "-D", remoteOnlyBranch]); + + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + const remoteBranch = result.branches.find( + (branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`, + ); + + expect(remoteBranch).toBeDefined(); + expect(remoteBranch?.isRemote).toBe(true); + expect(remoteBranch?.remoteName).toBe(remoteName); + }), + ); + + it.effect( + "filters branch queries before pagination and dedupes origin refs with local matches", + () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const tmp = yield* makeTmpDir(); + + yield* git(remote, ["init", "--bare"]); + const { initialBranch } = yield* initRepoWithCommit(tmp); + yield* git(tmp, ["remote", "add", "origin", remote]); + yield* git(tmp, ["push", "-u", "origin", initialBranch]); + + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/demo" }); + yield* git(tmp, ["push", "-u", "origin", "feature/demo"]); + + yield* git(tmp, ["checkout", "-b", "feature/remote-only"]); + yield* git(tmp, ["push", "-u", "origin", "feature/remote-only"]); + yield* git(tmp, ["checkout", initialBranch]); + yield* git(tmp, ["branch", "-D", "feature/remote-only"]); + + const result = yield* (yield* GitCore).listBranches({ + cwd: tmp, + query: "feature/", + limit: 10, + }); + + expect(result.totalCount).toBe(2); + expect(result.nextCursor).toBeNull(); + expect(result.branches.map((branch) => branch.name)).toEqual([ + "feature/demo", + "origin/feature/remote-only", + ]); + }), + ); + }); + + // ── checkoutGitBranch ── + + describe("checkoutGitBranch", () => { + it.effect("checks out an existing branch", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature" }); + + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature" }); + + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + const current = result.branches.find((b) => b.current); + expect(current!.name).toBe("feature"); + }), + ); + + it.effect("refreshes upstream behind count after checkout when remote branch advanced", () => + Effect.gen(function* () { + const services = yield* Effect.services(); + const runPromise = Effect.runPromiseWith(services); + + const remote = yield* makeTmpDir(); + const source = yield* makeTmpDir(); + const clone = yield* makeTmpDir(); + yield* git(remote, ["init", "--bare"]); + + yield* initRepoWithCommit(source); + const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( + (branch) => branch.current, + )!.name; + yield* git(source, ["remote", "add", "origin", remote]); + yield* git(source, ["push", "-u", "origin", defaultBranch]); + + const featureBranch = "feature-behind"; + yield* (yield* GitCore).createBranch({ cwd: source, branch: featureBranch }); + yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch }); + yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n"); + yield* git(source, ["add", "feature.txt"]); + yield* git(source, ["commit", "-m", "feature base"]); + yield* git(source, ["push", "-u", "origin", featureBranch]); + yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: defaultBranch }); + + yield* git(clone, ["clone", remote, "."]); + yield* git(clone, ["config", "user.email", "test@test.com"]); + yield* git(clone, ["config", "user.name", "Test"]); + yield* git(clone, ["checkout", "-b", featureBranch, "--track", `origin/${featureBranch}`]); + yield* writeTextFile(path.join(clone, "feature.txt"), "feature from remote\n"); + yield* git(clone, ["add", "feature.txt"]); + yield* git(clone, ["commit", "-m", "remote feature update"]); + yield* git(clone, ["push", "origin", featureBranch]); + + yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch }); + const core = yield* GitCore; + yield* Effect.promise(() => + vi.waitFor( + async () => { + const details = await runPromise(core.statusDetails(source)); + expect(details.branch).toBe(featureBranch); + expect(details.aheadCount).toBe(0); + expect(details.behindCount).toBe(1); + }, + { + timeout: 10_000, + interval: 100, + }, + ), + ); + }), + ); + + it.effect("statusDetails remains successful when upstream refresh fails after checkout", () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const source = yield* makeTmpDir(); + yield* git(remote, ["init", "--bare"]); + + yield* initRepoWithCommit(source); + const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( + (branch) => branch.current, + )!.name; + yield* git(source, ["remote", "add", "origin", remote]); + yield* git(source, ["push", "-u", "origin", defaultBranch]); + + const featureBranch = "feature-refresh-failure"; + yield* git(source, ["branch", featureBranch]); + yield* git(source, ["checkout", featureBranch]); + yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n"); + yield* git(source, ["add", "feature.txt"]); + yield* git(source, ["commit", "-m", "feature base"]); + yield* git(source, ["push", "-u", "origin", featureBranch]); + yield* git(source, ["checkout", defaultBranch]); + + const realGitCore = yield* GitCore; + let refreshFetchAttempts = 0; + const core = yield* makeIsolatedGitCore((input) => { + if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { + refreshFetchAttempts += 1; + return Effect.fail( + new GitCommandError({ + operation: "git.test.refreshFailure", + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "simulated fetch timeout", + }), + ); + } + return realGitCore.execute(input); + }); + yield* core.checkoutBranch({ cwd: source, branch: featureBranch }); + const status = yield* core.statusDetails(source); + expect(refreshFetchAttempts).toBe(1); + expect(status.branch).toBe(featureBranch); + expect(status.upstreamRef).toBe(`origin/${featureBranch}`); + expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch); + }), + ); + + it.effect("defers upstream refresh until statusDetails is requested", () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const source = yield* makeTmpDir(); + yield* git(remote, ["init", "--bare"]); + + yield* initRepoWithCommit(source); + const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( + (branch) => branch.current, + )!.name; + yield* git(source, ["remote", "add", "origin", remote]); + yield* git(source, ["push", "-u", "origin", defaultBranch]); + + const featureBranch = "feature/scoped-fetch"; + yield* git(source, ["checkout", "-b", featureBranch]); + yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n"); + yield* git(source, ["add", "feature.txt"]); + yield* git(source, ["commit", "-m", "feature base"]); + yield* git(source, ["push", "-u", "origin", featureBranch]); + yield* git(source, ["checkout", defaultBranch]); + + const realGitCore = yield* GitCore; + let refreshFetchAttempts = 0; + const core = yield* makeIsolatedGitCore((input) => { + if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { + refreshFetchAttempts += 1; + return Effect.succeed({ + code: 0, + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + } + return realGitCore.execute(input); + }); + yield* core.checkoutBranch({ cwd: source, branch: featureBranch }); + yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 50))); + expect(refreshFetchAttempts).toBe(0); + const status = yield* core.statusDetails(source); + expect(status.branch).toBe(featureBranch); + expect(refreshFetchAttempts).toBe(1); + }), + ); + + it.effect("shares upstream refreshes across worktrees that use the same git common dir", () => + Effect.gen(function* () { + const ok = (stdout = "") => + Effect.succeed({ + code: 0, + stdout, + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + + let fetchCount = 0; + const core = yield* makeIsolatedGitCore((input) => { + if ( + input.args[0] === "rev-parse" && + input.args[1] === "--abbrev-ref" && + input.args[2] === "--symbolic-full-name" && + input.args[3] === "@{upstream}" + ) { + return ok("origin/main\n"); + } + if (input.args[0] === "remote") { + return ok("origin\n"); + } + if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") { + return ok("/repo/.git\n"); + } + if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { + fetchCount += 1; + expect(input.cwd).toBe("/repo"); + return ok(); + } + if (input.operation === "GitCore.statusDetails.status") { + return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n"); + } + if ( + input.operation === "GitCore.statusDetails.unstagedNumstat" || + input.operation === "GitCore.statusDetails.stagedNumstat" + ) { + return ok(); + } + if (input.operation === "GitCore.statusDetails.defaultRef") { + return ok("refs/remotes/origin/main\n"); + } + return Effect.fail( + new GitCommandError({ + operation: input.operation, + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "Unexpected git command in shared refresh cache test.", + }), + ); + }); + + yield* core.statusDetails("/repo/worktrees/main"); + yield* core.statusDetails("/repo/worktrees/pr-123"); + expect(fetchCount).toBe(1); + }), + ); + + it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () => + Effect.gen(function* () { + const ok = (stdout = "") => + Effect.succeed({ + code: 0, + stdout, + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + + let fetchCount = 0; + const core = yield* makeIsolatedGitCore((input) => { + if ( + input.args[0] === "rev-parse" && + input.args[1] === "--abbrev-ref" && + input.args[2] === "--symbolic-full-name" && + input.args[3] === "@{upstream}" + ) { + return ok("origin/main\n"); + } + if (input.args[0] === "remote") { + return ok("origin\n"); + } + if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") { + return ok("/repo/.git\n"); + } + if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { + fetchCount += 1; + return Effect.fail( + new GitCommandError({ + operation: input.operation, + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "simulated fetch timeout", + }), + ); + } + if (input.operation === "GitCore.statusDetails.status") { + return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n"); + } + if ( + input.operation === "GitCore.statusDetails.unstagedNumstat" || + input.operation === "GitCore.statusDetails.stagedNumstat" + ) { + return ok(); + } + if (input.operation === "GitCore.statusDetails.defaultRef") { + return ok("refs/remotes/origin/main\n"); + } + return Effect.fail( + new GitCommandError({ + operation: input.operation, + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "Unexpected git command in refresh failure cooldown test.", + }), + ); + }); + + yield* core.statusDetails("/repo/worktrees/main"); + yield* core.statusDetails("/repo/worktrees/pr-123"); + expect(fetchCount).toBe(1); + }), + ); + + it.effect("throws when branch does not exist", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const result = yield* Effect.result( + (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "nonexistent" }), + ); + expect(result._tag).toBe("Failure"); + }), + ); + + it.effect("does not silently checkout a local branch when a remote ref no longer exists", () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const source = yield* makeTmpDir(); + yield* git(remote, ["init", "--bare"]); + + yield* initRepoWithCommit(source); + const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( + (branch) => branch.current, + )!.name; + yield* git(source, ["remote", "add", "origin", remote]); + yield* git(source, ["push", "-u", "origin", defaultBranch]); + + yield* (yield* GitCore).createBranch({ cwd: source, branch: "feature" }); + + const checkoutResult = yield* Effect.result( + (yield* GitCore).checkoutBranch({ cwd: source, branch: "origin/feature" }), + ); + expect(checkoutResult._tag).toBe("Failure"); + expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch); + }), + ); + + it.effect("checks out a remote tracking branch when remote name contains slashes", () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const prefixRemote = yield* makeTmpDir(); + const source = yield* makeTmpDir(); + const prefixFetchNamespace = "prefix-my-org"; + const prefixRemoteName = "my-org"; + const remoteName = "my-org/upstream"; + const featureBranch = "feature"; + yield* git(remote, ["init", "--bare"]); + yield* git(prefixRemote, ["init", "--bare"]); + + yield* initRepoWithCommit(source); + const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( + (branch) => branch.current, + )!.name; + yield* configureRemote(source, prefixRemoteName, prefixRemote, prefixFetchNamespace); + yield* configureRemote(source, remoteName, remote, remoteName); + yield* git(source, ["push", "-u", remoteName, defaultBranch]); + + yield* git(source, ["checkout", "-b", featureBranch]); + yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n"); + yield* git(source, ["add", "feature.txt"]); + yield* git(source, ["commit", "-m", "feature commit"]); + yield* git(source, ["push", "-u", remoteName, featureBranch]); + yield* git(source, ["checkout", defaultBranch]); + yield* git(source, ["branch", "-D", featureBranch]); + + yield* (yield* GitCore).checkoutBranch({ + cwd: source, + branch: `${remoteName}/${featureBranch}`, + }); + + expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature"); + const realGitCore = yield* GitCore; + let fetchArgs: readonly string[] | null = null; + const core = yield* makeIsolatedGitCore((input) => { + if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { + fetchArgs = [...input.args]; + return Effect.succeed({ + code: 0, + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + } + return realGitCore.execute(input); + }); + + const status = yield* core.statusDetails(source); + expect(status.branch).toBe("upstream/feature"); + expect(status.upstreamRef).toBe(`${remoteName}/${featureBranch}`); + expect(fetchArgs).toEqual([ + "--git-dir", + path.join(source, ".git"), + "fetch", + "--quiet", + "--no-tags", + remoteName, + `+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`, + ]); + }), + ); + + it.effect( + "falls back to detached checkout when --track would conflict with an existing local branch", + () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const source = yield* makeTmpDir(); + yield* git(remote, ["init", "--bare"]); + + yield* initRepoWithCommit(source); + const defaultBranch = (yield* (yield* GitCore).listBranches({ + cwd: source, + })).branches.find((branch) => branch.current)!.name; + yield* git(source, ["remote", "add", "origin", remote]); + yield* git(source, ["push", "-u", "origin", defaultBranch]); + + // Keep local branch but remove tracking so `--track origin/` + // would attempt to create an already-existing local branch. + yield* git(source, ["branch", "--unset-upstream"]); + + yield* (yield* GitCore).checkoutBranch({ + cwd: source, + branch: `origin/${defaultBranch}`, + }); + + const core = yield* GitCore; + const status = yield* core.statusDetails(source); + expect(status.branch).toBeNull(); + }), + ); + + it.effect("throws when checkout would overwrite uncommitted changes", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "other" }); + + // Create a conflicting change: modify README on current branch + yield* writeTextFile(path.join(tmp, "README.md"), "modified\n"); + yield* git(tmp, ["add", "README.md"]); + + // First, checkout other branch cleanly + yield* git(tmp, ["stash"]); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "other" }); + yield* writeTextFile(path.join(tmp, "README.md"), "other content\n"); + yield* git(tmp, ["add", "."]); + yield* git(tmp, ["commit", "-m", "other change"]); + + // Go back to default branch + const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (b) => !b.current, + )!.name; + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: defaultBranch }); + + // Make uncommitted changes to the same file + yield* writeTextFile(path.join(tmp, "README.md"), "conflicting local\n"); + + // Checkout should fail due to uncommitted changes + const result = yield* Effect.result( + (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "other" }), + ); + expect(result._tag).toBe("Failure"); + }), + ); + }); + + // ── createGitBranch ── + + describe("createGitBranch", () => { + it.effect("creates a new branch visible in listGitBranches", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "new-feature" }); + + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(result.branches.some((b) => b.name === "new-feature")).toBe(true); + }), + ); + + it.effect("throws when branch already exists", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "dupe" }); + const result = yield* Effect.result( + (yield* GitCore).createBranch({ cwd: tmp, branch: "dupe" }), + ); + expect(result._tag).toBe("Failure"); + }), + ); + }); + + // ── renameGitBranch ── + + describe("renameGitBranch", () => { + it.effect("renames the current branch", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/old-name" }); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature/old-name" }); + + const renamed = yield* (yield* GitCore).renameBranch({ + cwd: tmp, + oldBranch: "feature/old-name", + newBranch: "feature/new-name", + }); + + expect(renamed.branch).toBe("feature/new-name"); + + const branches = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(branches.branches.some((branch) => branch.name === "feature/old-name")).toBe(false); + const current = branches.branches.find((branch) => branch.current); + expect(current?.name).toBe("feature/new-name"); + }), + ); + + it.effect("returns success without git invocation when old/new names match", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const current = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (b) => b.current, + )!; + + const renamed = yield* (yield* GitCore).renameBranch({ + cwd: tmp, + oldBranch: current.name, + newBranch: current.name, + }); + + expect(renamed.branch).toBe(current.name); + }), + ); + + it.effect("appends numeric suffix when target branch already exists", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "t3code/feat/session" }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "t3code/tmp-working" }); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "t3code/tmp-working" }); + + const renamed = yield* (yield* GitCore).renameBranch({ + cwd: tmp, + oldBranch: "t3code/tmp-working", + newBranch: "t3code/feat/session", + }); + + expect(renamed.branch).toBe("t3code/feat/session-1"); + const branches = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(branches.branches.some((branch) => branch.name === "t3code/feat/session")).toBe( + true, + ); + expect(branches.branches.some((branch) => branch.name === "t3code/feat/session-1")).toBe( + true, + ); + const current = branches.branches.find((branch) => branch.current); + expect(current?.name).toBe("t3code/feat/session-1"); + }), + ); + + it.effect("increments suffix until it finds an available branch name", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "t3code/feat/session" }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "t3code/feat/session-1" }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "t3code/tmp-working" }); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "t3code/tmp-working" }); + + const renamed = yield* (yield* GitCore).renameBranch({ + cwd: tmp, + oldBranch: "t3code/tmp-working", + newBranch: "t3code/feat/session", + }); + + expect(renamed.branch).toBe("t3code/feat/session-2"); + }), + ); + + it.effect("uses '--' separator for branch rename arguments", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/old-name" }); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature/old-name" }); + + const realGitCore = yield* GitCore; + let renameArgs: ReadonlyArray | null = null; + const core = yield* makeIsolatedGitCore((input) => { + if (input.args[0] === "branch" && input.args[1] === "-m") { + renameArgs = [...input.args]; + } + return realGitCore.execute(input); + }); + + const renamed = yield* core.renameBranch({ + cwd: tmp, + oldBranch: "feature/old-name", + newBranch: "feature/new-name", + }); + + expect(renamed.branch).toBe("feature/new-name"); + expect(renameArgs).toEqual(["branch", "-m", "--", "feature/old-name", "feature/new-name"]); + }), + ); + }); + + // ── createGitWorktree + removeGitWorktree ── + + describe("createGitWorktree", () => { + it.effect("creates a worktree with a new branch from the base branch", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + + const wtPath = path.join(tmp, "worktree-out"); + const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (b) => b.current, + )!.name; + + const result = yield* (yield* GitCore).createWorktree({ + cwd: tmp, + branch: currentBranch, + newBranch: "wt-branch", + path: wtPath, + }); + + expect(result.worktree.path).toBe(wtPath); + expect(result.worktree.branch).toBe("wt-branch"); + expect(existsSync(wtPath)).toBe(true); + expect(existsSync(path.join(wtPath, "README.md"))).toBe(true); + + // Clean up worktree before tmp dir disposal + yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); + }), + ); + + it.effect("worktree has the new branch checked out", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + + const wtPath = path.join(tmp, "wt-check-dir"); + const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (b) => b.current, + )!.name; + + yield* (yield* GitCore).createWorktree({ + cwd: tmp, + branch: currentBranch, + newBranch: "wt-check", + path: wtPath, + }); + + // Verify the worktree is on the new branch + const branchOutput = yield* git(wtPath, ["branch", "--show-current"]); + expect(branchOutput).toBe("wt-check"); + + yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); + }), + ); + + it.effect("creates a worktree for an existing branch when newBranch is omitted", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/existing-worktree" }); + + const wtPath = path.join(tmp, "wt-existing"); + const result = yield* (yield* GitCore).createWorktree({ + cwd: tmp, + branch: "feature/existing-worktree", + path: wtPath, + }); + + expect(result.worktree.path).toBe(wtPath); + expect(result.worktree.branch).toBe("feature/existing-worktree"); + const branchOutput = yield* git(wtPath, ["branch", "--show-current"]); + expect(branchOutput).toBe("feature/existing-worktree"); + + yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); + }), + ); + + it.effect("throws when new branch name already exists", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "existing" }); + + const wtPath = path.join(tmp, "wt-conflict"); + const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (b) => b.current, + )!.name; + + const result = yield* Effect.result( + (yield* GitCore).createWorktree({ + cwd: tmp, + branch: currentBranch, + newBranch: "existing", + path: wtPath, + }), + ); + expect(result._tag).toBe("Failure"); + }), + ); + + it.effect("listGitBranches from worktree cwd reports worktree branch as current", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + + const wtPath = path.join(tmp, "wt-list-dir"); + const mainBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (b) => b.current, + )!.name; + + yield* (yield* GitCore).createWorktree({ + cwd: tmp, + branch: mainBranch, + newBranch: "wt-list", + path: wtPath, + }); + + // listGitBranches from the worktree should show wt-list as current + const wtBranches = yield* (yield* GitCore).listBranches({ cwd: wtPath }); + expect(wtBranches.isRepo).toBe(true); + const wtCurrent = wtBranches.branches.find((b) => b.current); + expect(wtCurrent!.name).toBe("wt-list"); + + // Main repo should still show the original branch as current + const mainBranches = yield* (yield* GitCore).listBranches({ cwd: tmp }); + const mainCurrent = mainBranches.branches.find((b) => b.current); + expect(mainCurrent!.name).toBe(mainBranch); + + yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); + }), + ); + + it.effect("removeGitWorktree cleans up the worktree", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + + const wtPath = path.join(tmp, "wt-remove-dir"); + const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (b) => b.current, + )!.name; + + yield* (yield* GitCore).createWorktree({ + cwd: tmp, + branch: currentBranch, + newBranch: "wt-remove", + path: wtPath, + }); + expect(existsSync(wtPath)).toBe(true); + + yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); + expect(existsSync(wtPath)).toBe(false); + }), + ); + + it.effect("removeGitWorktree force removes a dirty worktree", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + + const wtPath = path.join(tmp, "wt-dirty-dir"); + const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (b) => b.current, + )!.name; + + yield* (yield* GitCore).createWorktree({ + cwd: tmp, + branch: currentBranch, + newBranch: "wt-dirty", + path: wtPath, + }); + expect(existsSync(wtPath)).toBe(true); + + yield* writeTextFile(path.join(wtPath, "README.md"), "dirty change\n"); + + const failedRemove = yield* Effect.result( + (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }), + ); + expect(failedRemove._tag).toBe("Failure"); + expect(existsSync(wtPath)).toBe(true); + + yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath, force: true }); + expect(existsSync(wtPath)).toBe(false); + }), + ); + }); + + // ── Full flow: local branch checkout ── + + describe("full flow: local branch checkout", () => { + it.effect("init → commit → create branch → checkout → verify current", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-login" }); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature-login" }); + + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + const current = result.branches.find((b) => b.current); + expect(current!.name).toBe("feature-login"); + }), + ); + }); + + // ── Full flow: worktree creation from base branch ── + + describe("full flow: worktree creation", () => { + it.effect("creates worktree with new branch from current branch", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + + const currentBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (b) => b.current, + )!.name; + + const wtPath = path.join(tmp, "my-worktree"); + const result = yield* (yield* GitCore).createWorktree({ + cwd: tmp, + branch: currentBranch, + newBranch: "feature-wt", + path: wtPath, + }); + + // Worktree exists + expect(existsSync(result.worktree.path)).toBe(true); + + // Main repo still on original branch + const mainBranches = yield* (yield* GitCore).listBranches({ cwd: tmp }); + const mainCurrent = mainBranches.branches.find((b) => b.current); + expect(mainCurrent!.name).toBe(currentBranch); + + // Worktree is on the new branch + const wtBranch = yield* git(wtPath, ["branch", "--show-current"]); + expect(wtBranch).toBe("feature-wt"); + + yield* (yield* GitCore).removeWorktree({ cwd: tmp, path: wtPath }); + }), + ); + }); + + describe("fetchPullRequestBranch", () => { + it.effect("fetches a GitHub pull request ref into a local branch without checkout", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(tmp); + const remoteDir = yield* makeTmpDir("git-remote-"); + yield* git(remoteDir, ["init", "--bare"]); + yield* git(tmp, ["remote", "add", "origin", remoteDir]); + yield* git(tmp, ["push", "-u", "origin", initialBranch]); + yield* git(tmp, ["checkout", "-b", "feature/pr-fetch"]); + yield* writeTextFile(path.join(tmp, "pr-fetch.txt"), "fetch me\n"); + yield* git(tmp, ["add", "pr-fetch.txt"]); + yield* git(tmp, ["commit", "-m", "Add PR fetch branch"]); + yield* git(tmp, ["push", "-u", "origin", "feature/pr-fetch"]); + yield* git(tmp, ["push", "origin", "HEAD:refs/pull/55/head"]); + yield* git(tmp, ["checkout", initialBranch]); + + yield* (yield* GitCore).fetchPullRequestBranch({ + cwd: tmp, + prNumber: 55, + branch: "feature/pr-fetch", + }); + + const localBranches = yield* git(tmp, ["branch", "--list", "feature/pr-fetch"]); + expect(localBranches).toContain("feature/pr-fetch"); + const currentBranch = yield* git(tmp, ["branch", "--show-current"]); + expect(currentBranch).toBe(initialBranch); + }), + ); + }); + + // ── Full flow: thread switching simulation ── + + describe("full flow: thread switching (checkout toggling)", () => { + it.effect("checkout a → checkout b → checkout a → current matches", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "branch-a" }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "branch-b" }); + + // Simulate switching to thread A's branch + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "branch-a" }); + let branches = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a"); + + // Simulate switching to thread B's branch + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "branch-b" }); + branches = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(branches.branches.find((b) => b.current)!.name).toBe("branch-b"); + + // Switch back to thread A + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "branch-a" }); + branches = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a"); + }), + ); + }); + + // ── Full flow: checkout conflict ── + + describe("full flow: checkout conflict", () => { + it.effect("uncommitted changes prevent checkout to a diverged branch", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "diverged" }); + + // Make diverged branch have different file content + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "diverged" }); + yield* writeTextFile(path.join(tmp, "README.md"), "diverged content\n"); + yield* git(tmp, ["add", "."]); + yield* git(tmp, ["commit", "-m", "diverge"]); + + // Actually, let's just get back to the initial branch explicitly + const allBranches = yield* (yield* GitCore).listBranches({ cwd: tmp }); + const initialBranch = allBranches.branches.find((b) => b.name !== "diverged")!.name; + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: initialBranch }); + + // Make local uncommitted changes to the same file + yield* writeTextFile(path.join(tmp, "README.md"), "local uncommitted\n"); + + // Attempt checkout should fail + const failedCheckout = yield* Effect.result( + (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "diverged" }), + ); + expect(failedCheckout._tag).toBe("Failure"); + + // Current branch should still be the initial one + const result = yield* (yield* GitCore).listBranches({ cwd: tmp }); + expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch); + }), + ); + }); + + describe("GitCore", () => { + it.effect("supports branch lifecycle operations through the service API", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const core = yield* GitCore; + + yield* core.initRepo({ cwd: tmp }); + yield* git(tmp, ["config", "user.email", "test@test.com"]); + yield* git(tmp, ["config", "user.name", "Test"]); + yield* writeTextFile(path.join(tmp, "README.md"), "# test\n"); + yield* git(tmp, ["add", "."]); + yield* git(tmp, ["commit", "-m", "initial commit"]); + + yield* core.createBranch({ cwd: tmp, branch: "feature/service-api" }); + yield* core.checkoutBranch({ cwd: tmp, branch: "feature/service-api" }); + const branches = yield* core.listBranches({ cwd: tmp }); + + expect(branches.isRepo).toBe(true); + expect( + branches.branches.find((branch: { current: boolean; name: string }) => branch.current) + ?.name, + ).toBe("feature/service-api"); + }), + ); + + it.effect( + "reuses an existing remote when the target URL only differs by a trailing slash after .git", + () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* git(tmp, ["remote", "add", "origin", "git@github.com:pingdotgg/t3code.git"]); + + const remoteName = yield* core.ensureRemote({ + cwd: tmp, + preferredName: "origin", + url: "git@github.com:pingdotgg/t3code.git/", + }); + + expect(remoteName).toBe("origin"); + expect((yield* git(tmp, ["remote"])).split("\n").filter(Boolean)).toEqual(["origin"]); + }), + ); + + it.effect("reports status details and dirty state", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + const clean = yield* core.status({ cwd: tmp }); + expect(clean.hasWorkingTreeChanges).toBe(false); + expect(clean.branch).toBeTruthy(); + + yield* writeTextFile(path.join(tmp, "README.md"), "updated\n"); + const dirty = yield* core.statusDetails(tmp); + expect(dirty.hasWorkingTreeChanges).toBe(true); + }), + ); + + it.effect("computes ahead count against base branch when no upstream is configured", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" }); + yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" }); + yield* writeTextFile(path.join(tmp, "feature.txt"), "ahead of base\n"); + yield* git(tmp, ["add", "feature.txt"]); + yield* git(tmp, ["commit", "-m", "feature commit"]); + + const details = yield* core.statusDetails(tmp); + expect(details.branch).toBe("feature/no-upstream-ahead"); + expect(details.hasUpstream).toBe(false); + expect(details.aheadCount).toBe(1); + expect(details.behindCount).toBe(0); + }), + ); + + it.effect( + "computes ahead count against origin/default when local default branch is missing", + () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const source = yield* makeTmpDir(); + yield* git(remote, ["init", "--bare"]); + + yield* initRepoWithCommit(source); + const initialBranch = (yield* (yield* GitCore).listBranches({ + cwd: source, + })).branches.find((branch) => branch.current)!.name; + yield* git(source, ["remote", "add", "origin", remote]); + yield* git(source, ["push", "-u", "origin", initialBranch]); + yield* git(source, ["checkout", "-b", "feature/remote-base-only"]); + yield* writeTextFile( + path.join(source, "feature.txt"), + `ahead of origin/${initialBranch}\n`, + ); + yield* git(source, ["add", "feature.txt"]); + yield* git(source, ["commit", "-m", "feature commit"]); + yield* git(source, ["branch", "-D", initialBranch]); + + const core = yield* GitCore; + const details = yield* core.statusDetails(source); + expect(details.branch).toBe("feature/remote-base-only"); + expect(details.hasUpstream).toBe(false); + expect(details.aheadCount).toBe(1); + expect(details.behindCount).toBe(0); + }), + ); + + it.effect( + "computes ahead count against a non-origin remote-prefixed gh-merge-base candidate", + () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const source = yield* makeTmpDir(); + const remoteName = "fork-seed"; + yield* git(remote, ["init", "--bare"]); + + yield* initRepoWithCommit(source); + const initialBranch = (yield* (yield* GitCore).listBranches({ + cwd: source, + })).branches.find((branch) => branch.current)!.name; + yield* git(source, ["remote", "add", remoteName, remote]); + yield* git(source, ["push", "-u", remoteName, initialBranch]); + yield* git(source, ["checkout", "-b", "feature/non-origin-merge-base"]); + yield* git(source, [ + "config", + "branch.feature/non-origin-merge-base.gh-merge-base", + `${remoteName}/${initialBranch}`, + ]); + yield* writeTextFile( + path.join(source, "feature.txt"), + `ahead of ${remoteName}/${initialBranch}\n`, + ); + yield* git(source, ["add", "feature.txt"]); + yield* git(source, ["commit", "-m", "feature commit"]); + yield* git(source, ["branch", "-D", initialBranch]); + + const core = yield* GitCore; + const details = yield* core.statusDetails(source); + expect(details.branch).toBe("feature/non-origin-merge-base"); + expect(details.hasUpstream).toBe(false); + expect(details.aheadCount).toBe(1); + expect(details.behindCount).toBe(0); + }), + ); + + it.effect("skips push when no upstream is configured and branch is not ahead of base", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" }); + yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" }); + + const pushed = yield* core.pushCurrentBranch(tmp, null); + expect(pushed.status).toBe("skipped_up_to_date"); + expect(pushed.branch).toBe("feature/no-upstream-no-ahead"); + expect(pushed.setUpstream).toBeUndefined(); + }), + ); + + it.effect("pushes with upstream setup when no comparable base branch exists", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const remote = yield* makeTmpDir(); + yield* git(tmp, ["init", "--initial-branch=trunk"]); + yield* git(tmp, ["config", "user.email", "test@test.com"]); + yield* git(tmp, ["config", "user.name", "Test"]); + yield* writeTextFile(path.join(tmp, "README.md"), "hello\n"); + yield* git(tmp, ["add", "README.md"]); + yield* git(tmp, ["commit", "-m", "initial"]); + yield* git(remote, ["init", "--bare"]); + yield* git(tmp, ["remote", "add", "origin", remote]); + yield* git(tmp, ["checkout", "-b", "feature/no-base"]); + + const core = yield* GitCore; + const pushed = yield* core.pushCurrentBranch(tmp, null); + expect(pushed.status).toBe("pushed"); + expect(pushed.setUpstream).toBe(true); + expect(pushed.upstreamBranch).toBe("origin/feature/no-base"); + expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( + "origin/feature/no-base", + ); + }), + ); + + it.effect("pushes with upstream setup to the only configured non-origin remote", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const remote = yield* makeTmpDir(); + yield* git(tmp, ["init", "--initial-branch=main"]); + yield* git(tmp, ["config", "user.email", "test@test.com"]); + yield* git(tmp, ["config", "user.name", "Test"]); + yield* writeTextFile(path.join(tmp, "README.md"), "hello\n"); + yield* git(tmp, ["add", "README.md"]); + yield* git(tmp, ["commit", "-m", "initial"]); + yield* git(remote, ["init", "--bare"]); + yield* git(tmp, ["remote", "add", "fork", remote]); + yield* git(tmp, ["checkout", "-b", "feature/fork-only"]); + + const core = yield* GitCore; + const pushed = yield* core.pushCurrentBranch(tmp, null); + expect(pushed.status).toBe("pushed"); + expect(pushed.setUpstream).toBe(true); + expect(pushed.upstreamBranch).toBe("fork/feature/fork-only"); + expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( + "fork/feature/fork-only", + ); + }), + ); + + it.effect( + "pushes with upstream setup when comparable base exists but remote branch is missing", + () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const remote = yield* makeTmpDir(); + yield* git(remote, ["init", "--bare"]); + + yield* initRepoWithCommit(tmp); + const initialBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (branch) => branch.current, + )!.name; + yield* git(tmp, ["remote", "add", "origin", remote]); + yield* git(tmp, ["push", "-u", "origin", initialBranch]); + + yield* writeTextFile(path.join(tmp, "default-ahead.txt"), "ahead on default\n"); + yield* git(tmp, ["add", "default-ahead.txt"]); + yield* git(tmp, ["commit", "-m", "default ahead"]); + + const featureBranch = "feature/publish-no-upstream"; + yield* git(tmp, ["checkout", "-b", featureBranch]); + + const core = yield* GitCore; + const pushed = yield* core.pushCurrentBranch(tmp, null); + expect(pushed.status).toBe("pushed"); + expect(pushed.setUpstream).toBe(true); + expect(pushed.upstreamBranch).toBe(`origin/${featureBranch}`); + expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( + `origin/${featureBranch}`, + ); + expect(yield* git(tmp, ["ls-remote", "--heads", "origin", featureBranch])).toContain( + featureBranch, + ); + }), + ); + + it.effect("prefers branch pushRemote over origin when setting upstream", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const origin = yield* makeTmpDir(); + const fork = yield* makeTmpDir(); + yield* git(origin, ["init", "--bare"]); + yield* git(fork, ["init", "--bare"]); + + yield* initRepoWithCommit(tmp); + const initialBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find( + (branch) => branch.current, + )!.name; + yield* git(tmp, ["remote", "add", "origin", origin]); + yield* git(tmp, ["remote", "add", "fork", fork]); + yield* git(tmp, ["push", "-u", "origin", initialBranch]); + + const featureBranch = "feature/push-remote"; + yield* git(tmp, ["checkout", "-b", featureBranch]); + yield* git(tmp, ["config", `branch.${featureBranch}.pushRemote`, "fork"]); + yield* writeTextFile(path.join(tmp, "feature.txt"), "push to fork\n"); + yield* git(tmp, ["add", "feature.txt"]); + yield* git(tmp, ["commit", "-m", "feature commit"]); + + const core = yield* GitCore; + const pushed = yield* core.pushCurrentBranch(tmp, null); + expect(pushed.status).toBe("pushed"); + expect(pushed.setUpstream).toBe(true); + expect(pushed.upstreamBranch).toBe(`fork/${featureBranch}`); + expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( + `fork/${featureBranch}`, + ); + expect(yield* git(tmp, ["ls-remote", "--heads", "fork", featureBranch])).toContain( + featureBranch, + ); + }), + ); + + it.effect( + "pushes renamed PR worktree branches to their tracked upstream branch even when push.default is current", + () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const fork = yield* makeTmpDir(); + yield* git(fork, ["init", "--bare"]); + + const { initialBranch } = yield* initRepoWithCommit(tmp); + yield* git(tmp, ["remote", "add", "jasonLaster", fork]); + yield* git(tmp, ["checkout", "-b", "statemachine"]); + yield* writeTextFile(path.join(tmp, "fork.txt"), "fork branch\n"); + yield* git(tmp, ["add", "fork.txt"]); + yield* git(tmp, ["commit", "-m", "fork branch"]); + yield* git(tmp, ["push", "-u", "jasonLaster", "statemachine"]); + yield* git(tmp, ["checkout", initialBranch]); + yield* git(tmp, ["branch", "-D", "statemachine"]); + yield* git(tmp, [ + "checkout", + "-b", + "t3code/pr-488/statemachine", + "--track", + "jasonLaster/statemachine", + ]); + yield* git(tmp, ["config", "push.default", "current"]); + yield* writeTextFile(path.join(tmp, "fork.txt"), "updated fork branch\n"); + yield* git(tmp, ["add", "fork.txt"]); + yield* git(tmp, ["commit", "-m", "update reviewed PR branch"]); + + const core = yield* GitCore; + const pushed = yield* core.pushCurrentBranch(tmp, null); + + expect(pushed.status).toBe("pushed"); + expect(pushed.setUpstream).toBe(false); + expect(pushed.upstreamBranch).toBe("jasonLaster/statemachine"); + expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( + "jasonLaster/statemachine", + ); + expect( + yield* git(tmp, ["ls-remote", "--heads", "jasonLaster", "statemachine"]), + ).toContain("statemachine"); + expect( + yield* git(tmp, ["ls-remote", "--heads", "jasonLaster", "t3code/pr-488/statemachine"]), + ).toBe(""); + }), + ); + + it.effect("pushes to the tracked upstream when the remote name contains slashes", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const remote = yield* makeTmpDir(); + const prefixRemote = yield* makeTmpDir(); + const prefixFetchNamespace = "prefix-my-org"; + const prefixRemoteName = "my-org"; + const remoteName = "my-org/upstream"; + const featureBranch = "feature/slash-remote-push"; + yield* git(remote, ["init", "--bare"]); + yield* git(prefixRemote, ["init", "--bare"]); + + const { initialBranch } = yield* initRepoWithCommit(tmp); + yield* configureRemote(tmp, prefixRemoteName, prefixRemote, prefixFetchNamespace); + yield* configureRemote(tmp, remoteName, remote, remoteName); + yield* git(tmp, ["push", "-u", remoteName, initialBranch]); + + yield* git(tmp, ["checkout", "-b", featureBranch]); + yield* writeTextFile(path.join(tmp, "feature.txt"), "first revision\n"); + yield* git(tmp, ["add", "feature.txt"]); + yield* git(tmp, ["commit", "-m", "feature base"]); + yield* git(tmp, ["push", "-u", remoteName, featureBranch]); + + yield* writeTextFile(path.join(tmp, "feature.txt"), "second revision\n"); + yield* git(tmp, ["add", "feature.txt"]); + yield* git(tmp, ["commit", "-m", "feature update"]); + + const core = yield* GitCore; + const pushed = yield* core.pushCurrentBranch(tmp, null); + expect(pushed.status).toBe("pushed"); + expect(pushed.setUpstream).toBe(false); + expect(pushed.upstreamBranch).toBe(`${remoteName}/${featureBranch}`); + expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( + `${remoteName}/${featureBranch}`, + ); + expect(yield* git(tmp, ["ls-remote", "--heads", remoteName, featureBranch])).toContain( + featureBranch, + ); + }), + ); + + it.effect("includes command context when worktree removal fails", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + const missingWorktreePath = path.join(tmp, "missing-worktree"); + + const removeResult = yield* Effect.result( + core.removeWorktree({ cwd: tmp, path: missingWorktreePath }), + ); + expect(removeResult._tag).toBe("Failure"); + if (removeResult._tag !== "Failure") { + return; + } + const message = removeResult.failure.message; + expect(message).toContain("git worktree remove"); + expect(message).toContain(`cwd: ${tmp}`); + expect(message).toContain(missingWorktreePath); + }), + ); + + it.effect( + "refreshes upstream before statusDetails so behind count reflects remote updates", + () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const source = yield* makeTmpDir(); + const clone = yield* makeTmpDir(); + yield* git(remote, ["init", "--bare"]); + + yield* initRepoWithCommit(source); + const initialBranch = (yield* (yield* GitCore).listBranches({ + cwd: source, + })).branches.find((branch) => branch.current)!.name; + yield* git(source, ["remote", "add", "origin", remote]); + yield* git(source, ["push", "-u", "origin", initialBranch]); + + yield* git(clone, ["clone", remote, "."]); + yield* git(clone, ["config", "user.email", "test@test.com"]); + yield* git(clone, ["config", "user.name", "Test"]); + yield* git(clone, [ + "checkout", + "-B", + initialBranch, + "--track", + `origin/${initialBranch}`, + ]); + yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n"); + yield* git(clone, ["add", "CHANGELOG.md"]); + yield* git(clone, ["commit", "-m", "remote update"]); + yield* git(clone, ["push", "origin", initialBranch]); + + const core = yield* GitCore; + const details = yield* core.statusDetails(source); + expect(details.branch).toBe(initialBranch); + expect(details.aheadCount).toBe(0); + expect(details.behindCount).toBe(1); + }), + ); + + it.effect("prepares commit context by auto-staging and creates commit", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* writeTextFile(path.join(tmp, "README.md"), "new content\n"); + const context = yield* core.prepareCommitContext(tmp); + expect(context).not.toBeNull(); + expect(context!.stagedSummary.length).toBeGreaterThan(0); + expect(context!.stagedPatch.length).toBeGreaterThan(0); + + const created = yield* core.commit(tmp, "Add README update", "- include updated content"); + expect(created.commitSha.length).toBeGreaterThan(0); + expect(yield* git(tmp, ["log", "-1", "--pretty=%s"])).toBe("Add README update"); + }), + ); + + it.effect("prepareCommitContext stages only selected files when filePaths provided", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* writeTextFile(path.join(tmp, "a.txt"), "file a\n"); + yield* writeTextFile(path.join(tmp, "b.txt"), "file b\n"); + + const context = yield* core.prepareCommitContext(tmp, ["a.txt"]); + expect(context).not.toBeNull(); + expect(context!.stagedSummary).toContain("a.txt"); + expect(context!.stagedSummary).not.toContain("b.txt"); + + yield* core.commit(tmp, "Add only a.txt", ""); + + // b.txt should still be untracked after commit + const statusAfter = yield* git(tmp, ["status", "--porcelain"]); + expect(statusAfter).toContain("b.txt"); + expect(statusAfter).not.toContain("a.txt"); + }), + ); + + it.effect("prepareCommitContext stages everything when filePaths is undefined", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* writeTextFile(path.join(tmp, "a.txt"), "file a\n"); + yield* writeTextFile(path.join(tmp, "b.txt"), "file b\n"); + + const context = yield* core.prepareCommitContext(tmp); + expect(context).not.toBeNull(); + expect(context!.stagedSummary).toContain("a.txt"); + expect(context!.stagedSummary).toContain("b.txt"); + }), + ); + + it.effect("prepareCommitContext truncates oversized staged patches instead of failing", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText()); + + const context = yield* core.prepareCommitContext(tmp); + expect(context).not.toBeNull(); + expect(context!.stagedSummary).toContain("README.md"); + expect(context!.stagedPatch).toContain("[truncated]"); + }), + ); + + it.effect("readRangeContext truncates oversized diff patches instead of failing", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* core.createBranch({ cwd: tmp, branch: "feature/large-range-context" }); + yield* core.checkoutBranch({ cwd: tmp, branch: "feature/large-range-context" }); + yield* writeTextFile(path.join(tmp, "large.txt"), buildLargeText()); + yield* git(tmp, ["add", "large.txt"]); + yield* git(tmp, ["commit", "-m", "Add large range context"]); + + const rangeContext = yield* core.readRangeContext(tmp, initialBranch); + expect(rangeContext.commitSummary).toContain("Add large range context"); + expect(rangeContext.diffSummary).toContain("large.txt"); + expect(rangeContext.diffPatch).toContain("[truncated]"); + }), + ); + + it.effect("pushes with upstream setup and then skips when up to date", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const remote = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* git(remote, ["init", "--bare"]); + yield* git(tmp, ["remote", "add", "origin", remote]); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/core-push" }); + yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "feature/core-push" }); + + yield* writeTextFile(path.join(tmp, "feature.txt"), "push me\n"); + const core = yield* GitCore; + const context = yield* core.prepareCommitContext(tmp); + expect(context).not.toBeNull(); + yield* core.commit(tmp, "Add feature file", ""); + + const pushed = yield* core.pushCurrentBranch(tmp, null); + expect(pushed.status).toBe("pushed"); + expect(pushed.setUpstream).toBe(true); + expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( + "origin/feature/core-push", + ); + + const skipped = yield* core.pushCurrentBranch(tmp, null); + expect(skipped.status).toBe("skipped_up_to_date"); + }), + ); + + it.effect("pulls behind branch and then reports up-to-date", () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const source = yield* makeTmpDir(); + const clone = yield* makeTmpDir(); + yield* git(remote, ["init", "--bare"]); + + yield* initRepoWithCommit(source); + const initialBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( + (branch) => branch.current, + )!.name; + yield* git(source, ["remote", "add", "origin", remote]); + yield* git(source, ["push", "-u", "origin", initialBranch]); + + yield* git(clone, ["clone", remote, "."]); + yield* git(clone, ["config", "user.email", "test@test.com"]); + yield* git(clone, ["config", "user.name", "Test"]); + yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n"); + yield* git(clone, ["add", "CHANGELOG.md"]); + yield* git(clone, ["commit", "-m", "remote update"]); + yield* git(clone, ["push", "origin", initialBranch]); + + const core = yield* GitCore; + const pulled = yield* core.pullCurrentBranch(source); + expect(pulled.status).toBe("pulled"); + expect((yield* core.statusDetails(source)).behindCount).toBe(0); + + const skipped = yield* core.pullCurrentBranch(source); + expect(skipped.status).toBe("skipped_up_to_date"); + }), + ); + + it.effect("top-level pullGitBranch rejects when no upstream exists", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const result = yield* Effect.result((yield* GitCore).pullCurrentBranch(tmp)); + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(result.failure.message.toLowerCase()).toContain("no upstream"); + } + }), + ); + + it.effect("lists branches when recency lookup fails", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const realGitCore = yield* GitCore; + let didFailRecency = false; + const core = yield* makeIsolatedGitCore((input) => { + if (!didFailRecency && input.args[0] === "for-each-ref") { + didFailRecency = true; + return Effect.fail( + new GitCommandError({ + operation: "git.test.listBranchesRecency", + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "timeout", + }), + ); + } + return realGitCore.execute(input); + }); + + const result = yield* core.listBranches({ cwd: tmp }); + + expect(result.isRepo).toBe(true); + expect(result.branches.length).toBeGreaterThan(0); + expect(result.branches[0]?.current).toBe(true); + expect(didFailRecency).toBe(true); + }), + ); + + it.effect("falls back to empty remote branch data when remote lookups fail", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const remote = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + yield* git(remote, ["init", "--bare"]); + yield* git(tmp, ["remote", "add", "origin", remote]); + + const realGitCore = yield* GitCore; + let didFailRemoteBranches = false; + let didFailRemoteNames = false; + const core = yield* makeIsolatedGitCore((input) => { + if (input.args.join(" ") === "branch --no-color --no-column --remotes") { + didFailRemoteBranches = true; + return Effect.fail( + new GitCommandError({ + operation: "git.test.listBranchesRemoteBranches", + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "remote unavailable", + }), + ); + } + if (input.args.join(" ") === "remote") { + didFailRemoteNames = true; + return Effect.fail( + new GitCommandError({ + operation: "git.test.listBranchesRemoteNames", + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "remote unavailable", + }), + ); + } + return realGitCore.execute(input); + }); + + const result = yield* core.listBranches({ cwd: tmp }); + + expect(result.isRepo).toBe(true); + expect(result.branches.length).toBeGreaterThan(0); + expect(result.branches.every((branch) => !branch.isRemote)).toBe(true); + expect(didFailRemoteBranches).toBe(true); + expect(didFailRemoteNames).toBe(true); + }), + ); + }); +}); diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts new file mode 100644 index 0000000000..1178a4b67e --- /dev/null +++ b/apps/server/src/git/Layers/GitCore.ts @@ -0,0 +1,2133 @@ +import { + Cache, + Data, + Duration, + Effect, + Exit, + FileSystem, + Layer, + Option, + Path, + PlatformError, + Ref, + Result, + Schema, + Scope, + Semaphore, + Stream, +} from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { GitCommandError, type GitBranch } from "@t3tools/contracts"; +import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; +import { compactTraceAttributes } from "../../observability/Attributes.ts"; +import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../../observability/Metrics.ts"; +import { + GitCore, + type ExecuteGitProgress, + type GitCommitOptions, + type GitCoreShape, + type ExecuteGitInput, + type ExecuteGitResult, +} from "../Services/GitCore.ts"; +import { + parseRemoteNames, + parseRemoteNamesInGitOrder, + parseRemoteRefWithRemoteNames, +} from "../remoteRefs.ts"; +import { ServerConfig } from "../../config.ts"; +import { decodeJsonResult } from "@t3tools/shared/schemaJson"; + +const DEFAULT_TIMEOUT_MS = 30_000; +const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000; +const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]"; +const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000; +const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000; +const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000; +const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000; +const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; +const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; +const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15); +const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5); +const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5); +const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048; +const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const; +const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100; + +type TraceTailState = { + processedChars: number; + remainder: string; +}; + +class StatusUpstreamRefreshCacheKey extends Data.Class<{ + gitCommonDir: string; + upstreamRef: string; + remoteName: string; + upstreamBranch: string; +}> {} + +interface ExecuteGitOptions { + stdin?: string | undefined; + timeoutMs?: number | undefined; + allowNonZeroExit?: boolean | undefined; + fallbackErrorMessage?: string | undefined; + maxOutputBytes?: number | undefined; + truncateOutputAtMaxBytes?: boolean | undefined; + progress?: ExecuteGitProgress | undefined; +} + +function parseBranchAb(value: string): { ahead: number; behind: number } { + const match = value.match(/^\+(\d+)\s+-(\d+)$/); + if (!match) return { ahead: 0, behind: 0 }; + return { + ahead: Number(match[1] ?? "0"), + behind: Number(match[2] ?? "0"), + }; +} + +function parseNumstatEntries( + stdout: string, +): Array<{ path: string; insertions: number; deletions: number }> { + const entries: Array<{ path: string; insertions: number; deletions: number }> = []; + for (const line of stdout.split(/\r?\n/g)) { + if (line.trim().length === 0) continue; + const [addedRaw, deletedRaw, ...pathParts] = line.split("\t"); + const rawPath = + pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim(); + if (rawPath.length === 0) continue; + const added = Number.parseInt(addedRaw ?? "0", 10); + const deleted = Number.parseInt(deletedRaw ?? "0", 10); + const renameArrowIndex = rawPath.indexOf(" => "); + const normalizedPath = + renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath; + entries.push({ + path: normalizedPath.length > 0 ? normalizedPath : rawPath, + insertions: Number.isFinite(added) ? added : 0, + deletions: Number.isFinite(deleted) ? deleted : 0, + }); + } + return entries; +} + +function splitNullSeparatedPaths(input: string, truncated: boolean): string[] { + const parts = input.split("\0"); + if (parts.length === 0) return []; + + if (truncated && parts[parts.length - 1]?.length) { + parts.pop(); + } + + return parts.filter((value) => value.length > 0); +} + +function chunkPathsForGitCheckIgnore(relativePaths: readonly string[]): string[][] { + const chunks: string[][] = []; + let chunk: string[] = []; + let chunkBytes = 0; + + for (const relativePath of relativePaths) { + const relativePathBytes = Buffer.byteLength(relativePath) + 1; + if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) { + chunks.push(chunk); + chunk = []; + chunkBytes = 0; + } + + chunk.push(relativePath); + chunkBytes += relativePathBytes; + + if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) { + chunks.push(chunk); + chunk = []; + chunkBytes = 0; + } + } + + if (chunk.length > 0) { + chunks.push(chunk); + } + + return chunks; +} + +function parsePorcelainPath(line: string): string | null { + if (line.startsWith("? ") || line.startsWith("! ")) { + const simple = line.slice(2).trim(); + return simple.length > 0 ? simple : null; + } + + if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) { + return null; + } + + const tabIndex = line.indexOf("\t"); + if (tabIndex >= 0) { + const fromTab = line.slice(tabIndex + 1); + const [filePath] = fromTab.split("\t"); + return filePath?.trim().length ? filePath.trim() : null; + } + + const parts = line.trim().split(/\s+/g); + const filePath = parts.at(-1) ?? ""; + return filePath.length > 0 ? filePath : null; +} + +function parseBranchLine(line: string): { name: string; current: boolean } | null { + const trimmed = line.trim(); + if (trimmed.length === 0) return null; + + const name = trimmed.replace(/^[*+]\s+/, ""); + // Exclude symbolic refs like: "origin/HEAD -> origin/main". + // Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)". + if (name.includes(" -> ") || name.startsWith("(")) return null; + + return { + name, + current: trimmed.startsWith("* "), + }; +} + +function filterBranchesForListQuery( + branches: ReadonlyArray, + query?: string, +): ReadonlyArray { + if (!query) { + return branches; + } + + const normalizedQuery = query.toLowerCase(); + return branches.filter((branch) => branch.name.toLowerCase().includes(normalizedQuery)); +} + +function paginateBranches(input: { + branches: ReadonlyArray; + cursor?: number | undefined; + limit?: number | undefined; +}): { + branches: ReadonlyArray; + nextCursor: number | null; + totalCount: number; +} { + const cursor = input.cursor ?? 0; + const limit = input.limit ?? GIT_LIST_BRANCHES_DEFAULT_LIMIT; + const totalCount = input.branches.length; + const branches = input.branches.slice(cursor, cursor + limit); + const nextCursor = cursor + branches.length < totalCount ? cursor + branches.length : null; + + return { + branches, + nextCursor, + totalCount, + }; +} + +function sanitizeRemoteName(value: string): string { + const sanitized = value + .trim() + .replace(/[^A-Za-z0-9._-]+/g, "-") + .replace(/^-+|-+$/g, ""); + return sanitized.length > 0 ? sanitized : "fork"; +} + +function normalizeRemoteUrl(value: string): string { + return value + .trim() + .replace(/\/+$/g, "") + .replace(/\.git$/i, "") + .toLowerCase(); +} + +function parseRemoteFetchUrls(stdout: string): Map { + const remotes = new Map(); + for (const line of stdout.split("\n")) { + const trimmed = line.trim(); + if (trimmed.length === 0) continue; + const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed); + if (!match) continue; + const [, remoteName = "", remoteUrl = "", direction = ""] = match; + if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) { + continue; + } + remotes.set(remoteName, remoteUrl); + } + return remotes; +} + +function parseUpstreamRefWithRemoteNames( + upstreamRef: string, + remoteNames: ReadonlyArray, +): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null { + const parsed = parseRemoteRefWithRemoteNames(upstreamRef, remoteNames); + if (!parsed) { + return null; + } + + return { + upstreamRef, + remoteName: parsed.remoteName, + upstreamBranch: parsed.branchName, + }; +} + +function parseUpstreamRefByFirstSeparator( + upstreamRef: string, +): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null { + const separatorIndex = upstreamRef.indexOf("/"); + if (separatorIndex <= 0 || separatorIndex === upstreamRef.length - 1) { + return null; + } + + const remoteName = upstreamRef.slice(0, separatorIndex).trim(); + const upstreamBranch = upstreamRef.slice(separatorIndex + 1).trim(); + if (remoteName.length === 0 || upstreamBranch.length === 0) { + return null; + } + + return { + upstreamRef, + remoteName, + upstreamBranch, + }; +} + +function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null { + for (const line of stdout.split("\n")) { + const trimmedLine = line.trim(); + if (trimmedLine.length === 0) { + continue; + } + const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t"); + const branchName = branchNameRaw?.trim() ?? ""; + const upstreamBranch = upstreamBranchRaw.trim(); + if (branchName.length === 0 || upstreamBranch.length === 0) { + continue; + } + if (upstreamBranch === upstreamRef) { + return branchName; + } + } + + return null; +} + +function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null { + const separatorIndex = branchName.indexOf("/"); + if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) { + return null; + } + const localBranch = branchName.slice(separatorIndex + 1).trim(); + return localBranch.length > 0 ? localBranch : null; +} + +function commandLabel(args: readonly string[]): string { + return `git ${args.join(" ")}`; +} + +function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null { + const trimmed = value.trim(); + const prefix = `refs/remotes/${remoteName}/`; + if (!trimmed.startsWith(prefix)) { + return null; + } + const branch = trimmed.slice(prefix.length).trim(); + return branch.length > 0 ? branch : null; +} + +function createGitCommandError( + operation: string, + cwd: string, + args: readonly string[], + detail: string, + cause?: unknown, +): GitCommandError { + return new GitCommandError({ + operation, + command: commandLabel(args), + cwd, + detail, + ...(cause !== undefined ? { cause } : {}), + }); +} + +function quoteGitCommand(args: ReadonlyArray): string { + return `git ${args.join(" ")}`; +} + +function toGitCommandError( + input: Pick, + detail: string, +) { + return (cause: unknown) => + Schema.is(GitCommandError)(cause) + ? cause + : new GitCommandError({ + operation: input.operation, + command: quoteGitCommand(input.args), + cwd: input.cwd, + detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`, + ...(cause !== undefined ? { cause } : {}), + }); +} + +interface Trace2Monitor { + readonly env: NodeJS.ProcessEnv; + readonly flush: Effect.Effect; +} + +const nowUnixNano = (): bigint => BigInt(Date.now()) * 1_000_000n; + +const addCurrentSpanEvent = (name: string, attributes: Record) => + Effect.currentSpan.pipe( + Effect.tap((span) => + Effect.sync(() => { + span.event(name, nowUnixNano(), compactTraceAttributes(attributes)); + }), + ), + Effect.catch(() => Effect.void), + ); + +function trace2ChildKey(record: Record): string | null { + const childId = record.child_id; + if (typeof childId === "number" || typeof childId === "string") { + return String(childId); + } + const hookName = record.hook_name; + return typeof hookName === "string" && hookName.trim().length > 0 ? hookName.trim() : null; +} + +const Trace2Record = Schema.Record(Schema.String, Schema.Unknown); + +const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( + input: Pick, + progress: ExecuteGitProgress | undefined, +): Effect.fn.Return< + Trace2Monitor, + PlatformError.PlatformError, + Scope.Scope | FileSystem.FileSystem | Path.Path +> { + if (!progress?.onHookStarted && !progress?.onHookFinished) { + return { + env: {}, + flush: Effect.void, + }; + } + + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const traceFilePath = yield* fs.makeTempFileScoped({ + prefix: `t3code-git-trace2-${process.pid}-`, + suffix: ".json", + }); + const hookStartByChildKey = new Map(); + const traceTailState = yield* Ref.make({ + processedChars: 0, + remainder: "", + }); + + const handleTraceLine = Effect.fn("handleTraceLine")(function* (line: string) { + const trimmedLine = line.trim(); + if (trimmedLine.length === 0) { + return; + } + + const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine); + if (Result.isFailure(traceRecord)) { + yield* Effect.logDebug( + `GitCore.trace2: failed to parse trace line for ${quoteGitCommand(input.args)} in ${input.cwd}`, + traceRecord.failure, + ); + return; + } + + if (traceRecord.success.child_class !== "hook") { + return; + } + + const event = traceRecord.success.event; + const childKey = trace2ChildKey(traceRecord.success); + if (childKey === null) { + return; + } + const started = hookStartByChildKey.get(childKey); + const hookNameFromEvent = + typeof traceRecord.success.hook_name === "string" ? traceRecord.success.hook_name.trim() : ""; + const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? ""); + if (hookName.length === 0) { + return; + } + + if (event === "child_start") { + hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() }); + yield* addCurrentSpanEvent("git.hook.started", { + hookName, + }); + if (progress.onHookStarted) { + yield* progress.onHookStarted(hookName); + } + return; + } + + if (event === "child_exit") { + hookStartByChildKey.delete(childKey); + const code = traceRecord.success.code; + const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null; + const durationMs = started ? Math.max(0, Date.now() - started.startedAtMs) : null; + yield* addCurrentSpanEvent("git.hook.finished", { + hookName: started?.hookName ?? hookName, + exitCode, + durationMs, + }); + if (progress.onHookFinished) { + yield* progress.onHookFinished({ + hookName: started?.hookName ?? hookName, + exitCode, + durationMs, + }); + } + } + }); + + const deltaMutex = yield* Semaphore.make(1); + const readTraceDelta = deltaMutex.withPermit( + fs.readFileString(traceFilePath).pipe( + Effect.flatMap((contents) => + Effect.uninterruptible( + Ref.modify(traceTailState, ({ processedChars, remainder }) => { + if (contents.length <= processedChars) { + return [[], { processedChars, remainder }]; + } + + const appended = contents.slice(processedChars); + const combined = remainder + appended; + const lines = combined.split("\n"); + const nextRemainder = lines.pop() ?? ""; + + return [ + lines.map((line) => line.replace(/\r$/, "")), + { + processedChars: contents.length, + remainder: nextRemainder, + }, + ]; + }).pipe( + Effect.flatMap((lines) => Effect.forEach(lines, handleTraceLine, { discard: true })), + ), + ), + ), + Effect.ignore({ log: true }), + ), + ); + const traceFileName = path.basename(traceFilePath); + yield* Stream.runForEach(fs.watch(traceFilePath), (event) => { + const eventPath = event.path; + const isTargetTraceEvent = + eventPath === traceFilePath || + eventPath === traceFileName || + path.basename(eventPath) === traceFileName; + if (!isTargetTraceEvent) return Effect.void; + return readTraceDelta; + }).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped); + + const finalizeTrace2Monitor = Effect.fn("finalizeTrace2Monitor")(function* () { + yield* readTraceDelta; + const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [ + remainder.trim(), + { + processedChars, + remainder: "", + }, + ]); + if (finalLine.length > 0) { + yield* handleTraceLine(finalLine); + } + }); + + yield* Effect.addFinalizer(finalizeTrace2Monitor); + + return { + env: { + GIT_TRACE2_EVENT: traceFilePath, + }, + flush: readTraceDelta, + }; +}); + +const collectOutput = Effect.fn("collectOutput")(function* ( + input: Pick, + stream: Stream.Stream, + maxOutputBytes: number, + truncateOutputAtMaxBytes: boolean, + onLine: ((line: string) => Effect.Effect) | undefined, +): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> { + const decoder = new TextDecoder(); + let bytes = 0; + let text = ""; + let lineBuffer = ""; + let truncated = false; + + const emitCompleteLines = Effect.fn("emitCompleteLines")(function* (flush: boolean) { + let newlineIndex = lineBuffer.indexOf("\n"); + while (newlineIndex >= 0) { + const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, ""); + lineBuffer = lineBuffer.slice(newlineIndex + 1); + if (line.length > 0 && onLine) { + yield* onLine(line); + } + newlineIndex = lineBuffer.indexOf("\n"); + } + + if (flush) { + const trailing = lineBuffer.replace(/\r$/, ""); + lineBuffer = ""; + if (trailing.length > 0 && onLine) { + yield* onLine(trailing); + } + } + }); + + const processChunk = Effect.fn("processChunk")(function* (chunk: Uint8Array) { + if (truncateOutputAtMaxBytes && truncated) { + return; + } + const nextBytes = bytes + chunk.byteLength; + if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) { + return yield* new GitCommandError({ + operation: input.operation, + command: quoteGitCommand(input.args), + cwd: input.cwd, + detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`, + }); + } + + const chunkToDecode = + truncateOutputAtMaxBytes && nextBytes > maxOutputBytes + ? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes)) + : chunk; + bytes += chunkToDecode.byteLength; + truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes; + + const decoded = decoder.decode(chunkToDecode, { stream: !truncated }); + text += decoded; + lineBuffer += decoded; + yield* emitCompleteLines(false); + }); + + yield* Stream.runForEach(stream, processChunk).pipe( + Effect.mapError(toGitCommandError(input, "output stream failed.")), + ); + + const remainder = truncated ? "" : decoder.decode(); + text += remainder; + lineBuffer += remainder; + yield* emitCompleteLines(true); + return { + text, + truncated, + }; +}); + +export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { + executeOverride?: GitCoreShape["execute"]; +}) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { worktreesDir } = yield* ServerConfig; + + let executeRaw: GitCoreShape["execute"]; + + if (options?.executeOverride) { + executeRaw = options.executeOverride; + } else { + const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + executeRaw = Effect.fnUntraced(function* (input) { + const commandInput = { + ...input, + args: [...input.args], + } as const; + const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; + const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false; + + const runGitCommand = Effect.fn("runGitCommand")(function* () { + const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe( + Effect.provideService(Path.Path, path), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.mapError(toGitCommandError(commandInput, "failed to create trace2 monitor.")), + ); + const child = yield* commandSpawner + .spawn( + ChildProcess.make("git", commandInput.args, { + cwd: commandInput.cwd, + env: { + ...process.env, + ...input.env, + ...trace2Monitor.env, + }, + }), + ) + .pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn."))); + + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectOutput( + commandInput, + child.stdout, + maxOutputBytes, + truncateOutputAtMaxBytes, + input.progress?.onStdoutLine, + ), + collectOutput( + commandInput, + child.stderr, + maxOutputBytes, + truncateOutputAtMaxBytes, + input.progress?.onStderrLine, + ), + child.exitCode.pipe( + Effect.map((value) => Number(value)), + Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")), + ), + input.stdin === undefined + ? Effect.void + : Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe( + Effect.mapError(toGitCommandError(commandInput, "failed to write stdin.")), + ), + ], + { concurrency: "unbounded" }, + ).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const)); + yield* trace2Monitor.flush; + + if (!input.allowNonZeroExit && exitCode !== 0) { + const trimmedStderr = stderr.text.trim(); + return yield* new GitCommandError({ + operation: commandInput.operation, + command: quoteGitCommand(commandInput.args), + cwd: commandInput.cwd, + detail: + trimmedStderr.length > 0 + ? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}` + : `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`, + }); + } + + return { + code: exitCode, + stdout: stdout.text, + stderr: stderr.text, + stdoutTruncated: stdout.truncated, + stderrTruncated: stderr.truncated, + } satisfies ExecuteGitResult; + }); + + return yield* runGitCommand().pipe( + Effect.scoped, + Effect.timeoutOption(timeoutMs), + Effect.flatMap((result) => + Option.match(result, { + onNone: () => + Effect.fail( + new GitCommandError({ + operation: commandInput.operation, + command: quoteGitCommand(commandInput.args), + cwd: commandInput.cwd, + detail: `${quoteGitCommand(commandInput.args)} timed out.`, + }), + ), + onSome: Effect.succeed, + }), + ), + ); + }); + } + + const execute: GitCoreShape["execute"] = (input) => + executeRaw(input).pipe( + withMetrics({ + counter: gitCommandsTotal, + timer: gitCommandDuration, + attributes: { + operation: input.operation, + }, + }), + Effect.withSpan(input.operation, { + kind: "client", + attributes: { + "git.operation": input.operation, + "git.cwd": input.cwd, + "git.args_count": input.args.length, + }, + }), + ); + + const executeGit = ( + operation: string, + cwd: string, + args: readonly string[], + options: ExecuteGitOptions = {}, + ): Effect.Effect => + execute({ + operation, + cwd, + args, + ...(options.stdin !== undefined ? { stdin: options.stdin } : {}), + allowNonZeroExit: true, + ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), + ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), + ...(options.truncateOutputAtMaxBytes !== undefined + ? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes } + : {}), + ...(options.progress ? { progress: options.progress } : {}), + }).pipe( + Effect.flatMap((result) => { + if (options.allowNonZeroExit || result.code === 0) { + return Effect.succeed(result); + } + const stderr = result.stderr.trim(); + if (stderr.length > 0) { + return Effect.fail(createGitCommandError(operation, cwd, args, stderr)); + } + if (options.fallbackErrorMessage) { + return Effect.fail( + createGitCommandError(operation, cwd, args, options.fallbackErrorMessage), + ); + } + return Effect.fail( + createGitCommandError( + operation, + cwd, + args, + `${commandLabel(args)} failed: code=${result.code ?? "null"}`, + ), + ); + }), + ); + + const runGit = ( + operation: string, + cwd: string, + args: readonly string[], + allowNonZeroExit = false, + ): Effect.Effect => + executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid); + + const runGitStdout = ( + operation: string, + cwd: string, + args: readonly string[], + allowNonZeroExit = false, + ): Effect.Effect => + executeGit(operation, cwd, args, { allowNonZeroExit }).pipe( + Effect.map((result) => result.stdout), + ); + + const runGitStdoutWithOptions = ( + operation: string, + cwd: string, + args: readonly string[], + options: ExecuteGitOptions = {}, + ): Effect.Effect => + executeGit(operation, cwd, args, options).pipe( + Effect.map((result) => + result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout, + ), + ); + + const branchExists = (cwd: string, branch: string): Effect.Effect => + executeGit( + "GitCore.branchExists", + cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], + { + allowNonZeroExit: true, + timeoutMs: 5_000, + }, + ).pipe(Effect.map((result) => result.code === 0)); + + const resolveAvailableBranchName = Effect.fn("resolveAvailableBranchName")(function* ( + cwd: string, + desiredBranch: string, + ) { + const isDesiredTaken = yield* branchExists(cwd, desiredBranch); + if (!isDesiredTaken) { + return desiredBranch; + } + + for (let suffix = 1; suffix <= 100; suffix += 1) { + const candidate = `${desiredBranch}-${suffix}`; + const isCandidateTaken = yield* branchExists(cwd, candidate); + if (!isCandidateTaken) { + return candidate; + } + } + + return yield* createGitCommandError( + "GitCore.renameBranch", + cwd, + ["branch", "-m", "--", desiredBranch], + `Could not find an available branch name for '${desiredBranch}'.`, + ); + }); + + const resolveCurrentUpstream = Effect.fn("resolveCurrentUpstream")(function* (cwd: string) { + const upstreamRef = yield* runGitStdout( + "GitCore.resolveCurrentUpstream", + cwd, + ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + + if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { + return null; + } + + const remoteNames = yield* runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe( + Effect.map(parseRemoteNames), + Effect.catch(() => Effect.succeed>([])), + ); + return ( + parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ?? + parseUpstreamRefByFirstSeparator(upstreamRef) + ); + }); + + const fetchUpstreamRefForStatus = ( + gitCommonDir: string, + upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, + ): Effect.Effect => { + const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; + const fetchCwd = + path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; + return executeGit( + "GitCore.fetchUpstreamRefForStatus", + fetchCwd, + ["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], + { + allowNonZeroExit: true, + timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT), + }, + ).pipe(Effect.asVoid); + }; + + const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) { + const gitCommonDir = yield* runGitStdout("GitCore.resolveGitCommonDir", cwd, [ + "rev-parse", + "--git-common-dir", + ]).pipe(Effect.map((stdout) => stdout.trim())); + return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir); + }); + + const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* ( + cacheKey: StatusUpstreamRefreshCacheKey, + ) { + yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, { + upstreamRef: cacheKey.upstreamRef, + remoteName: cacheKey.remoteName, + upstreamBranch: cacheKey.upstreamBranch, + }); + return true as const; + }); + + const statusUpstreamRefreshCache = yield* Cache.makeWith({ + capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY, + lookup: refreshStatusUpstreamCacheEntry, + // Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms. + timeToLive: (exit) => + Exit.isSuccess(exit) + ? STATUS_UPSTREAM_REFRESH_INTERVAL + : STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN, + }); + + const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( + cwd: string, + ) { + const upstream = yield* resolveCurrentUpstream(cwd); + if (!upstream) return; + const gitCommonDir = yield* resolveGitCommonDir(cwd); + yield* Cache.get( + statusUpstreamRefreshCache, + new StatusUpstreamRefreshCacheKey({ + gitCommonDir, + upstreamRef: upstream.upstreamRef, + remoteName: upstream.remoteName, + upstreamBranch: upstream.upstreamBranch, + }), + ); + }); + + const resolveDefaultBranchName = ( + cwd: string, + remoteName: string, + ): Effect.Effect => + executeGit( + "GitCore.resolveDefaultBranchName", + cwd, + ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`], + { allowNonZeroExit: true }, + ).pipe( + Effect.map((result) => { + if (result.code !== 0) { + return null; + } + return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName); + }), + ); + + const remoteBranchExists = ( + cwd: string, + remoteName: string, + branch: string, + ): Effect.Effect => + executeGit( + "GitCore.remoteBranchExists", + cwd, + ["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`], + { + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)); + + const originRemoteExists = (cwd: string): Effect.Effect => + executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], { + allowNonZeroExit: true, + }).pipe(Effect.map((result) => result.code === 0)); + + const listRemoteNames = (cwd: string): Effect.Effect, GitCommandError> => + runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe( + Effect.map(parseRemoteNamesInGitOrder), + ); + + const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) { + if (yield* originRemoteExists(cwd)) { + return "origin"; + } + const remotes = yield* listRemoteNames(cwd); + const [firstRemote] = remotes; + if (firstRemote) { + return firstRemote; + } + return yield* createGitCommandError( + "GitCore.resolvePrimaryRemoteName", + cwd, + ["remote"], + "No git remote is configured for this repository.", + ); + }); + + const resolvePushRemoteName = Effect.fn("resolvePushRemoteName")(function* ( + cwd: string, + branch: string, + ) { + const branchPushRemote = yield* runGitStdout( + "GitCore.resolvePushRemoteName.branchPushRemote", + cwd, + ["config", "--get", `branch.${branch}.pushRemote`], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + if (branchPushRemote.length > 0) { + return branchPushRemote; + } + + const pushDefaultRemote = yield* runGitStdout( + "GitCore.resolvePushRemoteName.remotePushDefault", + cwd, + ["config", "--get", "remote.pushDefault"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + if (pushDefaultRemote.length > 0) { + return pushDefaultRemote; + } + + return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null))); + }); + + const ensureRemote: GitCoreShape["ensureRemote"] = Effect.fn("ensureRemote")(function* (input) { + const preferredName = sanitizeRemoteName(input.preferredName); + const normalizedTargetUrl = normalizeRemoteUrl(input.url); + const remoteFetchUrls = yield* runGitStdout("GitCore.ensureRemote.listRemoteUrls", input.cwd, [ + "remote", + "-v", + ]).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout))); + + for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) { + if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) { + return remoteName; + } + } + + let remoteName = preferredName; + let suffix = 1; + while (remoteFetchUrls.has(remoteName)) { + remoteName = `${preferredName}-${suffix}`; + suffix += 1; + } + + yield* runGit("GitCore.ensureRemote.add", input.cwd, ["remote", "add", remoteName, input.url]); + return remoteName; + }); + + const resolveBaseBranchForNoUpstream = Effect.fn("resolveBaseBranchForNoUpstream")(function* ( + cwd: string, + branch: string, + ) { + const configuredBaseBranch = yield* runGitStdout( + "GitCore.resolveBaseBranchForNoUpstream.config", + cwd, + ["config", "--get", `branch.${branch}.gh-merge-base`], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + + const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + const defaultBranch = + primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName); + const candidates = [ + configuredBaseBranch.length > 0 ? configuredBaseBranch : null, + defaultBranch, + ...DEFAULT_BASE_BRANCH_CANDIDATES, + ]; + + for (const candidate of candidates) { + if (!candidate) { + continue; + } + + const remotePrefix = + primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null; + const normalizedCandidate = candidate.startsWith("origin/") + ? candidate.slice("origin/".length) + : remotePrefix && candidate.startsWith(remotePrefix) + ? candidate.slice(remotePrefix.length) + : candidate; + if (normalizedCandidate.length === 0 || normalizedCandidate === branch) { + continue; + } + + if (yield* branchExists(cwd, normalizedCandidate)) { + return normalizedCandidate; + } + + if ( + primaryRemoteName && + (yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate)) + ) { + return `${primaryRemoteName}/${normalizedCandidate}`; + } + } + + return null; + }); + + const computeAheadCountAgainstBase = Effect.fn("computeAheadCountAgainstBase")(function* ( + cwd: string, + branch: string, + ) { + const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch); + if (!baseBranch) { + return 0; + } + + const result = yield* executeGit( + "GitCore.computeAheadCountAgainstBase", + cwd, + ["rev-list", "--count", `${baseBranch}..HEAD`], + { allowNonZeroExit: true }, + ); + if (result.code !== 0) { + return 0; + } + + const parsed = Number.parseInt(result.stdout.trim(), 10); + return Number.isFinite(parsed) ? Math.max(0, parsed) : 0; + }); + + const readBranchRecency = Effect.fn("readBranchRecency")(function* (cwd: string) { + const branchRecency = yield* executeGit( + "GitCore.readBranchRecency", + cwd, + [ + "for-each-ref", + "--format=%(refname:short)%09%(committerdate:unix)", + "refs/heads", + "refs/remotes", + ], + { + timeoutMs: 15_000, + allowNonZeroExit: true, + }, + ); + + const branchLastCommit = new Map(); + if (branchRecency.code !== 0) { + return branchLastCommit; + } + + for (const line of branchRecency.stdout.split("\n")) { + if (line.length === 0) { + continue; + } + const [name, lastCommitRaw] = line.split("\t"); + if (!name) { + continue; + } + const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10); + branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0); + } + + return branchLastCommit; + }); + + const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) { + yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true })); + + const statusResult = yield* executeGit( + "GitCore.statusDetails.status", + cwd, + ["status", "--porcelain=2", "--branch"], + { + allowNonZeroExit: true, + }, + ); + + if (statusResult.code !== 0) { + const stderr = statusResult.stderr.trim(); + return yield* createGitCommandError( + "GitCore.statusDetails.status", + cwd, + ["status", "--porcelain=2", "--branch"], + stderr || "git status failed", + ); + } + + const [unstagedNumstatStdout, stagedNumstatStdout, defaultRefResult, hasOriginRemote] = + yield* Effect.all( + [ + runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]), + runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [ + "diff", + "--cached", + "--numstat", + ]), + executeGit( + "GitCore.statusDetails.defaultRef", + cwd, + ["symbolic-ref", "refs/remotes/origin/HEAD"], + { + allowNonZeroExit: true, + }, + ), + originRemoteExists(cwd).pipe(Effect.catch(() => Effect.succeed(false))), + ], + { concurrency: "unbounded" }, + ); + const statusStdout = statusResult.stdout; + const defaultBranch = + defaultRefResult.code === 0 + ? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "") + : null; + + let branch: string | null = null; + let upstreamRef: string | null = null; + let aheadCount = 0; + let behindCount = 0; + let hasWorkingTreeChanges = false; + const changedFilesWithoutNumstat = new Set(); + + for (const line of statusStdout.split(/\r?\n/g)) { + if (line.startsWith("# branch.head ")) { + const value = line.slice("# branch.head ".length).trim(); + branch = value.startsWith("(") ? null : value; + continue; + } + if (line.startsWith("# branch.upstream ")) { + const value = line.slice("# branch.upstream ".length).trim(); + upstreamRef = value.length > 0 ? value : null; + continue; + } + if (line.startsWith("# branch.ab ")) { + const value = line.slice("# branch.ab ".length).trim(); + const parsed = parseBranchAb(value); + aheadCount = parsed.ahead; + behindCount = parsed.behind; + continue; + } + if (line.trim().length > 0 && !line.startsWith("#")) { + hasWorkingTreeChanges = true; + const pathValue = parsePorcelainPath(line); + if (pathValue) changedFilesWithoutNumstat.add(pathValue); + } + } + + if (!upstreamRef && branch) { + aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe( + Effect.catch(() => Effect.succeed(0)), + ); + behindCount = 0; + } + + const stagedEntries = parseNumstatEntries(stagedNumstatStdout); + const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout); + const fileStatMap = new Map(); + for (const entry of [...stagedEntries, ...unstagedEntries]) { + const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 }; + existing.insertions += entry.insertions; + existing.deletions += entry.deletions; + fileStatMap.set(entry.path, existing); + } + + let insertions = 0; + let deletions = 0; + const files = Array.from(fileStatMap.entries()) + .map(([filePath, stat]) => { + insertions += stat.insertions; + deletions += stat.deletions; + return { path: filePath, insertions: stat.insertions, deletions: stat.deletions }; + }) + .toSorted((a, b) => a.path.localeCompare(b.path)); + + for (const filePath of changedFilesWithoutNumstat) { + if (fileStatMap.has(filePath)) continue; + files.push({ path: filePath, insertions: 0, deletions: 0 }); + } + files.sort((a, b) => a.path.localeCompare(b.path)); + + return { + isRepo: true, + hasOriginRemote, + isDefaultBranch: + branch !== null && + (branch === defaultBranch || + (defaultBranch === null && (branch === "main" || branch === "master"))), + branch, + upstreamRef, + hasWorkingTreeChanges, + workingTree: { + files, + insertions, + deletions, + }, + hasUpstream: upstreamRef !== null, + aheadCount, + behindCount, + }; + }); + + const status: GitCoreShape["status"] = (input) => + statusDetails(input.cwd).pipe( + Effect.map((details) => ({ + isRepo: details.isRepo, + hasOriginRemote: details.hasOriginRemote, + isDefaultBranch: details.isDefaultBranch, + branch: details.branch, + hasWorkingTreeChanges: details.hasWorkingTreeChanges, + workingTree: details.workingTree, + hasUpstream: details.hasUpstream, + aheadCount: details.aheadCount, + behindCount: details.behindCount, + pr: null, + })), + ); + + const prepareCommitContext: GitCoreShape["prepareCommitContext"] = Effect.fn( + "prepareCommitContext", + )(function* (cwd, filePaths) { + if (filePaths && filePaths.length > 0) { + yield* runGit("GitCore.prepareCommitContext.reset", cwd, ["reset"]).pipe( + Effect.catch(() => Effect.void), + ); + yield* runGit("GitCore.prepareCommitContext.addSelected", cwd, [ + "add", + "-A", + "--", + ...filePaths, + ]); + } else { + yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]); + } + + const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [ + "diff", + "--cached", + "--name-status", + ]).pipe(Effect.map((stdout) => stdout.trim())); + if (stagedSummary.length === 0) { + return null; + } + + const stagedPatch = yield* runGitStdoutWithOptions( + "GitCore.prepareCommitContext.stagedPatch", + cwd, + ["diff", "--cached", "--patch", "--minimal"], + { + maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ); + + return { + stagedSummary, + stagedPatch, + }; + }); + + const commit: GitCoreShape["commit"] = Effect.fn("commit")(function* ( + cwd, + subject, + body, + options?: GitCommitOptions, + ) { + const args = ["commit", "-m", subject]; + const trimmedBody = body.trim(); + if (trimmedBody.length > 0) { + args.push("-m", trimmedBody); + } + const progress = + options?.progress?.onOutputLine === undefined + ? options?.progress + : { + ...options.progress, + onStdoutLine: (line: string) => + options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ?? Effect.void, + onStderrLine: (line: string) => + options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ?? Effect.void, + }; + yield* executeGit("GitCore.commit.commit", cwd, args, { + ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), + ...(progress ? { progress } : {}), + }).pipe(Effect.asVoid); + const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [ + "rev-parse", + "HEAD", + ]).pipe(Effect.map((stdout) => stdout.trim())); + + return { commitSha }; + }); + + const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = Effect.fn("pushCurrentBranch")( + function* (cwd, fallbackBranch) { + const details = yield* statusDetails(cwd); + const branch = details.branch ?? fallbackBranch; + if (!branch) { + return yield* createGitCommandError( + "GitCore.pushCurrentBranch", + cwd, + ["push"], + "Cannot push from detached HEAD.", + ); + } + + const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0; + if (hasNoLocalDelta) { + if (details.hasUpstream) { + return { + status: "skipped_up_to_date" as const, + branch, + ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), + }; + } + + const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + if (comparableBaseBranch) { + const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + if (!publishRemoteName) { + return { + status: "skipped_up_to_date" as const, + branch, + }; + } + + const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe( + Effect.catch(() => Effect.succeed(false)), + ); + if (hasRemoteBranch) { + return { + status: "skipped_up_to_date" as const, + branch, + }; + } + } + } + + if (!details.hasUpstream) { + const publishRemoteName = yield* resolvePushRemoteName(cwd, branch); + if (!publishRemoteName) { + return yield* createGitCommandError( + "GitCore.pushCurrentBranch", + cwd, + ["push"], + "Cannot push because no git remote is configured for this repository.", + ); + } + yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [ + "push", + "-u", + publishRemoteName, + `HEAD:refs/heads/${branch}`, + ]); + return { + status: "pushed" as const, + branch, + upstreamBranch: `${publishRemoteName}/${branch}`, + setUpstream: true, + }; + } + + const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + if (currentUpstream) { + yield* runGit("GitCore.pushCurrentBranch.pushUpstream", cwd, [ + "push", + currentUpstream.remoteName, + `HEAD:${currentUpstream.upstreamBranch}`, + ]); + return { + status: "pushed" as const, + branch, + upstreamBranch: currentUpstream.upstreamRef, + setUpstream: false, + }; + } + + yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]); + return { + status: "pushed" as const, + branch, + ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), + setUpstream: false, + }; + }, + ); + + const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = Effect.fn("pullCurrentBranch")( + function* (cwd) { + const details = yield* statusDetails(cwd); + const branch = details.branch; + if (!branch) { + return yield* createGitCommandError( + "GitCore.pullCurrentBranch", + cwd, + ["pull", "--ff-only"], + "Cannot pull from detached HEAD.", + ); + } + if (!details.hasUpstream) { + return yield* createGitCommandError( + "GitCore.pullCurrentBranch", + cwd, + ["pull", "--ff-only"], + "Current branch has no upstream configured. Push with upstream first.", + ); + } + const beforeSha = yield* runGitStdout( + "GitCore.pullCurrentBranch.beforeSha", + cwd, + ["rev-parse", "HEAD"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], { + timeoutMs: 30_000, + fallbackErrorMessage: "git pull failed", + }); + const afterSha = yield* runGitStdout( + "GitCore.pullCurrentBranch.afterSha", + cwd, + ["rev-parse", "HEAD"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + + const refreshed = yield* statusDetails(cwd); + return { + status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled", + branch, + upstreamBranch: refreshed.upstreamRef, + }; + }, + ); + + const readRangeContext: GitCoreShape["readRangeContext"] = Effect.fn("readRangeContext")( + function* (cwd, baseBranch) { + const range = `${baseBranch}..HEAD`; + const [commitSummary, diffSummary, diffPatch] = yield* Effect.all( + [ + runGitStdoutWithOptions( + "GitCore.readRangeContext.log", + cwd, + ["log", "--oneline", range], + { + maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + runGitStdoutWithOptions( + "GitCore.readRangeContext.diffStat", + cwd, + ["diff", "--stat", range], + { + maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + runGitStdoutWithOptions( + "GitCore.readRangeContext.diffPatch", + cwd, + ["diff", "--patch", "--minimal", range], + { + maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + ], + { concurrency: "unbounded" }, + ); + + return { + commitSummary, + diffSummary, + diffPatch, + }; + }, + ); + + const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) => + runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe( + Effect.map((stdout) => stdout.trim()), + Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), + ); + + const isInsideWorkTree: GitCoreShape["isInsideWorkTree"] = (cwd) => + executeGit("GitCore.isInsideWorkTree", cwd, ["rev-parse", "--is-inside-work-tree"], { + allowNonZeroExit: true, + timeoutMs: 5_000, + maxOutputBytes: 4_096, + }).pipe(Effect.map((result) => result.code === 0 && result.stdout.trim() === "true")); + + const listWorkspaceFiles: GitCoreShape["listWorkspaceFiles"] = (cwd) => + executeGit( + "GitCore.listWorkspaceFiles", + cwd, + ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], + { + allowNonZeroExit: true, + timeoutMs: 20_000, + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ).pipe( + Effect.flatMap((result) => + result.code === 0 + ? Effect.succeed({ + paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated), + truncated: result.stdoutTruncated, + }) + : Effect.fail( + createGitCommandError( + "GitCore.listWorkspaceFiles", + cwd, + ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], + result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed", + ), + ), + ), + ); + + const filterIgnoredPaths: GitCoreShape["filterIgnoredPaths"] = (cwd, relativePaths) => + Effect.gen(function* () { + if (relativePaths.length === 0) { + return relativePaths; + } + + const ignoredPaths = new Set(); + const chunks = chunkPathsForGitCheckIgnore(relativePaths); + + for (const chunk of chunks) { + const result = yield* executeGit( + "GitCore.filterIgnoredPaths", + cwd, + ["check-ignore", "--no-index", "-z", "--stdin"], + { + stdin: `${chunk.join("\0")}\0`, + allowNonZeroExit: true, + timeoutMs: 20_000, + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ); + + if (result.code !== 0 && result.code !== 1) { + return yield* createGitCommandError( + "GitCore.filterIgnoredPaths", + cwd, + ["check-ignore", "--no-index", "-z", "--stdin"], + result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed", + ); + } + + for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) { + ignoredPaths.add(ignoredPath); + } + } + + if (ignoredPaths.size === 0) { + return relativePaths; + } + + return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath)); + }); + + const listBranches: GitCoreShape["listBranches"] = Effect.fn("listBranches")(function* (input) { + const branchRecencyPromise = readBranchRecency(input.cwd).pipe( + Effect.catch(() => Effect.succeed(new Map())), + ); + const localBranchResult = yield* executeGit( + "GitCore.listBranches.branchNoColor", + input.cwd, + ["branch", "--no-color", "--no-column"], + { + timeoutMs: 10_000, + allowNonZeroExit: true, + }, + ); + + if (localBranchResult.code !== 0) { + const stderr = localBranchResult.stderr.trim(); + if (stderr.toLowerCase().includes("not a git repository")) { + return { + branches: [], + isRepo: false, + hasOriginRemote: false, + nextCursor: null, + totalCount: 0, + }; + } + return yield* createGitCommandError( + "GitCore.listBranches", + input.cwd, + ["branch", "--no-color", "--no-column"], + stderr || "git branch failed", + ); + } + + const remoteBranchResultEffect = executeGit( + "GitCore.listBranches.remoteBranches", + input.cwd, + ["branch", "--no-color", "--no-column", "--remotes"], + { + timeoutMs: 10_000, + allowNonZeroExit: true, + }, + ).pipe( + Effect.catch((error) => + Effect.logWarning( + `GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`, + ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), + ), + ); + + const remoteNamesResultEffect = executeGit( + "GitCore.listBranches.remoteNames", + input.cwd, + ["remote"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe( + Effect.catch((error) => + Effect.logWarning( + `GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`, + ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), + ), + ); + + const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] = + yield* Effect.all( + [ + executeGit( + "GitCore.listBranches.defaultRef", + input.cwd, + ["symbolic-ref", "refs/remotes/origin/HEAD"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ), + executeGit( + "GitCore.listBranches.worktreeList", + input.cwd, + ["worktree", "list", "--porcelain"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ), + remoteBranchResultEffect, + remoteNamesResultEffect, + branchRecencyPromise, + ], + { concurrency: "unbounded" }, + ); + + const remoteNames = + remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : []; + if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) { + yield* Effect.logWarning( + `GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`, + ); + } + if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) { + yield* Effect.logWarning( + `GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`, + ); + } + + const defaultBranch = + defaultRef.code === 0 + ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") + : null; + + const worktreeMap = new Map(); + if (worktreeList.code === 0) { + let currentPath: string | null = null; + for (const line of worktreeList.stdout.split("\n")) { + if (line.startsWith("worktree ")) { + const candidatePath = line.slice("worktree ".length); + const exists = yield* fileSystem.stat(candidatePath).pipe( + Effect.map(() => true), + Effect.catch(() => Effect.succeed(false)), + ); + currentPath = exists ? candidatePath : null; + } else if (line.startsWith("branch refs/heads/") && currentPath) { + worktreeMap.set(line.slice("branch refs/heads/".length), currentPath); + } else if (line === "") { + currentPath = null; + } + } + } + + const localBranches = localBranchResult.stdout + .split("\n") + .map(parseBranchLine) + .filter((branch): branch is { name: string; current: boolean } => branch !== null) + .map((branch) => ({ + name: branch.name, + current: branch.current, + isRemote: false, + isDefault: branch.name === defaultBranch, + worktreePath: worktreeMap.get(branch.name) ?? null, + })) + .toSorted((a, b) => { + const aPriority = a.current ? 0 : a.isDefault ? 1 : 2; + const bPriority = b.current ? 0 : b.isDefault ? 1 : 2; + if (aPriority !== bPriority) return aPriority - bPriority; + + const aLastCommit = branchLastCommit.get(a.name) ?? 0; + const bLastCommit = branchLastCommit.get(b.name) ?? 0; + if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; + return a.name.localeCompare(b.name); + }); + + const remoteBranches = + remoteBranchResult.code === 0 + ? remoteBranchResult.stdout + .split("\n") + .map(parseBranchLine) + .filter((branch): branch is { name: string; current: boolean } => branch !== null) + .map((branch) => { + const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames); + const remoteBranch: { + name: string; + current: boolean; + isRemote: boolean; + remoteName?: string; + isDefault: boolean; + worktreePath: string | null; + } = { + name: branch.name, + current: false, + isRemote: true, + isDefault: false, + worktreePath: null, + }; + if (parsedRemoteRef) { + remoteBranch.remoteName = parsedRemoteRef.remoteName; + } + return remoteBranch; + }) + .toSorted((a, b) => { + const aLastCommit = branchLastCommit.get(a.name) ?? 0; + const bLastCommit = branchLastCommit.get(b.name) ?? 0; + if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; + return a.name.localeCompare(b.name); + }) + : []; + + const branches = paginateBranches({ + branches: filterBranchesForListQuery( + dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]), + input.query, + ), + cursor: input.cursor, + limit: input.limit, + }); + + return { + branches: [...branches.branches], + isRepo: true, + hasOriginRemote: remoteNames.includes("origin"), + nextCursor: branches.nextCursor, + totalCount: branches.totalCount, + }; + }); + + const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")( + function* (input) { + const targetBranch = input.newBranch ?? input.branch; + const sanitizedBranch = targetBranch.replace(/\//g, "-"); + const repoName = path.basename(input.cwd); + const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch); + const args = input.newBranch + ? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch] + : ["worktree", "add", worktreePath, input.branch]; + + yield* executeGit("GitCore.createWorktree", input.cwd, args, { + fallbackErrorMessage: "git worktree add failed", + }); + + return { + worktree: { + path: worktreePath, + branch: targetBranch, + }, + }; + }, + ); + + const fetchPullRequestBranch: GitCoreShape["fetchPullRequestBranch"] = Effect.fn( + "fetchPullRequestBranch", + )(function* (input) { + const remoteName = yield* resolvePrimaryRemoteName(input.cwd); + yield* executeGit( + "GitCore.fetchPullRequestBranch", + input.cwd, + [ + "fetch", + "--quiet", + "--no-tags", + remoteName, + `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`, + ], + { + fallbackErrorMessage: "git fetch pull request branch failed", + }, + ); + }); + + const fetchRemoteBranch: GitCoreShape["fetchRemoteBranch"] = Effect.fn("fetchRemoteBranch")( + function* (input) { + yield* runGit("GitCore.fetchRemoteBranch.fetch", input.cwd, [ + "fetch", + "--quiet", + "--no-tags", + input.remoteName, + `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, + ]); + + const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch); + const targetRef = `${input.remoteName}/${input.remoteBranch}`; + yield* runGit( + "GitCore.fetchRemoteBranch.materialize", + input.cwd, + localBranchAlreadyExists + ? ["branch", "--force", input.localBranch, targetRef] + : ["branch", input.localBranch, targetRef], + ); + }, + ); + + const setBranchUpstream: GitCoreShape["setBranchUpstream"] = (input) => + runGit("GitCore.setBranchUpstream", input.cwd, [ + "branch", + "--set-upstream-to", + `${input.remoteName}/${input.remoteBranch}`, + input.branch, + ]); + + const removeWorktree: GitCoreShape["removeWorktree"] = Effect.fn("removeWorktree")( + function* (input) { + const args = ["worktree", "remove"]; + if (input.force) { + args.push("--force"); + } + args.push(input.path); + yield* executeGit("GitCore.removeWorktree", input.cwd, args, { + timeoutMs: 15_000, + fallbackErrorMessage: "git worktree remove failed", + }).pipe( + Effect.mapError((error) => + createGitCommandError( + "GitCore.removeWorktree", + input.cwd, + args, + `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`, + error, + ), + ), + ); + }, + ); + + const renameBranch: GitCoreShape["renameBranch"] = Effect.fn("renameBranch")(function* (input) { + if (input.oldBranch === input.newBranch) { + return { branch: input.newBranch }; + } + const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch); + + yield* executeGit( + "GitCore.renameBranch", + input.cwd, + ["branch", "-m", "--", input.oldBranch, targetBranch], + { + timeoutMs: 10_000, + fallbackErrorMessage: "git branch rename failed", + }, + ); + + return { branch: targetBranch }; + }); + + const createBranch: GitCoreShape["createBranch"] = (input) => + executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], { + timeoutMs: 10_000, + fallbackErrorMessage: "git branch create failed", + }).pipe(Effect.asVoid); + + const checkoutBranch: GitCoreShape["checkoutBranch"] = Effect.fn("checkoutBranch")( + function* (input) { + const [localInputExists, remoteExists] = yield* Effect.all( + [ + executeGit( + "GitCore.checkoutBranch.localInputExists", + input.cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)), + executeGit( + "GitCore.checkoutBranch.remoteExists", + input.cwd, + ["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)), + ], + { concurrency: "unbounded" }, + ); + + const localTrackingBranch = remoteExists + ? yield* executeGit( + "GitCore.checkoutBranch.localTrackingBranch", + input.cwd, + ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe( + Effect.map((result) => + result.code === 0 + ? parseTrackingBranchByUpstreamRef(result.stdout, input.branch) + : null, + ), + ) + : null; + + const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch); + const localTrackedBranchTargetExists = + remoteExists && localTrackedBranchCandidate + ? yield* executeGit( + "GitCore.checkoutBranch.localTrackedBranchTargetExists", + input.cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)) + : false; + + const checkoutArgs = localInputExists + ? ["checkout", input.branch] + : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists + ? ["checkout", input.branch] + : remoteExists && !localTrackingBranch + ? ["checkout", "--track", input.branch] + : remoteExists && localTrackingBranch + ? ["checkout", localTrackingBranch] + : ["checkout", input.branch]; + + yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, { + timeoutMs: 10_000, + fallbackErrorMessage: "git checkout failed", + }); + }, + ); + + const initRepo: GitCoreShape["initRepo"] = (input) => + executeGit("GitCore.initRepo", input.cwd, ["init"], { + timeoutMs: 10_000, + fallbackErrorMessage: "git init failed", + }).pipe(Effect.asVoid); + + const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) => + runGitStdout("GitCore.listLocalBranchNames", cwd, [ + "branch", + "--list", + "--no-column", + "--format=%(refname:short)", + ]).pipe( + Effect.map((stdout) => + stdout + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0), + ), + ); + + return { + execute, + status, + statusDetails, + prepareCommitContext, + commit, + pushCurrentBranch, + pullCurrentBranch, + readRangeContext, + readConfigValue, + isInsideWorkTree, + listWorkspaceFiles, + filterIgnoredPaths, + listBranches, + createWorktree, + fetchPullRequestBranch, + ensureRemote, + fetchRemoteBranch, + setBranchUpstream, + removeWorktree, + renameBranch, + createBranch, + checkoutBranch, + initRepo, + listLocalBranchNames, + } satisfies GitCoreShape; +}); + +export const GitCoreLive = Layer.effect(GitCore, makeGitCore()); diff --git a/apps/server/src/git/Layers/GitHubCli.test.ts b/apps/server/src/git/Layers/GitHubCli.test.ts new file mode 100644 index 0000000000..aafc796db3 --- /dev/null +++ b/apps/server/src/git/Layers/GitHubCli.test.ts @@ -0,0 +1,128 @@ +import { assert, it } from "@effect/vitest"; +import { Effect } from "effect"; +import { afterEach, expect, vi } from "vitest"; + +vi.mock("../../processRunner", () => ({ + runProcess: vi.fn(), +})); + +import { runProcess } from "../../processRunner"; +import { GitHubCli } from "../Services/GitHubCli.ts"; +import { GitHubCliLive } from "./GitHubCli.ts"; + +const mockedRunProcess = vi.mocked(runProcess); +const layer = it.layer(GitHubCliLive); + +afterEach(() => { + mockedRunProcess.mockReset(); +}); + +layer("GitHubCliLive", (it) => { + it.effect("parses pull request view output", () => + Effect.gen(function* () { + mockedRunProcess.mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 42, + title: "Add PR thread creation", + url: "https://github.com/pingdotgg/codething-mvp/pull/42", + baseRefName: "main", + headRefName: "feature/pr-threads", + state: "OPEN", + mergedAt: null, + isCrossRepository: true, + headRepository: { + nameWithOwner: "octocat/codething-mvp", + }, + headRepositoryOwner: { + login: "octocat", + }, + }), + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + + const result = yield* Effect.gen(function* () { + const gh = yield* GitHubCli; + return yield* gh.getPullRequest({ + cwd: "/repo", + reference: "#42", + }); + }); + + assert.deepStrictEqual(result, { + number: 42, + title: "Add PR thread creation", + url: "https://github.com/pingdotgg/codething-mvp/pull/42", + baseRefName: "main", + headRefName: "feature/pr-threads", + state: "open", + isCrossRepository: true, + headRepositoryNameWithOwner: "octocat/codething-mvp", + headRepositoryOwnerLogin: "octocat", + }); + expect(mockedRunProcess).toHaveBeenCalledWith( + "gh", + [ + "pr", + "view", + "#42", + "--json", + "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner", + ], + expect.objectContaining({ cwd: "/repo" }), + ); + }), + ); + + it.effect("reads repository clone URLs", () => + Effect.gen(function* () { + mockedRunProcess.mockResolvedValueOnce({ + stdout: JSON.stringify({ + nameWithOwner: "octocat/codething-mvp", + url: "https://github.com/octocat/codething-mvp", + sshUrl: "git@github.com:octocat/codething-mvp.git", + }), + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + + const result = yield* Effect.gen(function* () { + const gh = yield* GitHubCli; + return yield* gh.getRepositoryCloneUrls({ + cwd: "/repo", + repository: "octocat/codething-mvp", + }); + }); + + assert.deepStrictEqual(result, { + nameWithOwner: "octocat/codething-mvp", + url: "https://github.com/octocat/codething-mvp", + sshUrl: "git@github.com:octocat/codething-mvp.git", + }); + }), + ); + + it.effect("surfaces a friendly error when the pull request is not found", () => + Effect.gen(function* () { + mockedRunProcess.mockRejectedValueOnce( + new Error( + "GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)", + ), + ); + + const error = yield* Effect.gen(function* () { + const gh = yield* GitHubCli; + return yield* gh.getPullRequest({ + cwd: "/repo", + reference: "4888", + }); + }).pipe(Effect.flip); + + assert.equal(error.message.includes("Pull request not found"), true); + }), + ); +}); diff --git a/apps/server/src/git/Layers/GitHubCli.ts b/apps/server/src/git/Layers/GitHubCli.ts new file mode 100644 index 0000000000..280679e337 --- /dev/null +++ b/apps/server/src/git/Layers/GitHubCli.ts @@ -0,0 +1,280 @@ +import { Effect, Layer, Schema } from "effect"; +import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts"; + +import { runProcess } from "../../processRunner"; +import { GitHubCliError } from "@t3tools/contracts"; +import { + GitHubCli, + type GitHubRepositoryCloneUrls, + type GitHubCliShape, + type GitHubPullRequestSummary, +} from "../Services/GitHubCli.ts"; + +const DEFAULT_TIMEOUT_MS = 30_000; + +function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError { + if (error instanceof Error) { + if (error.message.includes("Command not found: gh")) { + return new GitHubCliError({ + operation, + detail: "GitHub CLI (`gh`) is required but not available on PATH.", + cause: error, + }); + } + + const lower = error.message.toLowerCase(); + if ( + lower.includes("authentication failed") || + lower.includes("not logged in") || + lower.includes("gh auth login") || + lower.includes("no oauth token") + ) { + return new GitHubCliError({ + operation, + detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.", + cause: error, + }); + } + + if ( + lower.includes("could not resolve to a pullrequest") || + lower.includes("repository.pullrequest") || + lower.includes("no pull requests found for branch") || + lower.includes("pull request not found") + ) { + return new GitHubCliError({ + operation, + detail: "Pull request not found. Check the PR number or URL and try again.", + cause: error, + }); + } + + return new GitHubCliError({ + operation, + detail: `GitHub CLI command failed: ${error.message}`, + cause: error, + }); + } + + return new GitHubCliError({ + operation, + detail: "GitHub CLI command failed.", + cause: error, + }); +} + +function normalizePullRequestState(input: { + state?: string | null | undefined; + mergedAt?: string | null | undefined; +}): "open" | "closed" | "merged" { + const mergedAt = input.mergedAt; + const state = input.state; + if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") { + return "merged"; + } + if (state === "CLOSED") { + return "closed"; + } + return "open"; +} + +const RawGitHubPullRequestSchema = Schema.Struct({ + number: PositiveInt, + title: TrimmedNonEmptyString, + url: TrimmedNonEmptyString, + baseRefName: TrimmedNonEmptyString, + headRefName: TrimmedNonEmptyString, + state: Schema.optional(Schema.NullOr(Schema.String)), + mergedAt: Schema.optional(Schema.NullOr(Schema.String)), + isCrossRepository: Schema.optional(Schema.Boolean), + headRepository: Schema.optional( + Schema.NullOr( + Schema.Struct({ + nameWithOwner: Schema.String, + }), + ), + ), + headRepositoryOwner: Schema.optional( + Schema.NullOr( + Schema.Struct({ + login: Schema.String, + }), + ), + ), +}); + +const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({ + nameWithOwner: TrimmedNonEmptyString, + url: TrimmedNonEmptyString, + sshUrl: TrimmedNonEmptyString, +}); + +function normalizePullRequestSummary( + raw: Schema.Schema.Type, +): GitHubPullRequestSummary { + const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null; + const headRepositoryOwnerLogin = + raw.headRepositoryOwner?.login ?? + (typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/") + ? (headRepositoryNameWithOwner.split("/")[0] ?? null) + : null); + return { + number: raw.number, + title: raw.title, + url: raw.url, + baseRefName: raw.baseRefName, + headRefName: raw.headRefName, + state: normalizePullRequestState(raw), + ...(typeof raw.isCrossRepository === "boolean" + ? { isCrossRepository: raw.isCrossRepository } + : {}), + ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + }; +} + +function normalizeRepositoryCloneUrls( + raw: Schema.Schema.Type, +): GitHubRepositoryCloneUrls { + return { + nameWithOwner: raw.nameWithOwner, + url: raw.url, + sshUrl: raw.sshUrl, + }; +} + +function decodeGitHubJson( + raw: string, + schema: S, + operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls", + invalidDetail: string, +): Effect.Effect { + return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe( + Effect.mapError( + (error) => + new GitHubCliError({ + operation, + detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail, + cause: error, + }), + ), + ); +} + +const makeGitHubCli = Effect.sync(() => { + const execute: GitHubCliShape["execute"] = (input) => + Effect.tryPromise({ + try: () => + runProcess("gh", input.args, { + cwd: input.cwd, + timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS, + }), + catch: (error) => normalizeGitHubCliError("execute", error), + }); + + const service = { + execute, + listOpenPullRequests: (input) => + execute({ + cwd: input.cwd, + args: [ + "pr", + "list", + "--head", + input.headSelector, + "--state", + "open", + "--limit", + String(input.limit ?? 1), + "--json", + "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner", + ], + }).pipe( + Effect.map((result) => result.stdout.trim()), + Effect.flatMap((raw) => + raw.length === 0 + ? Effect.succeed([]) + : decodeGitHubJson( + raw, + Schema.Array(RawGitHubPullRequestSchema), + "listOpenPullRequests", + "GitHub CLI returned invalid PR list JSON.", + ), + ), + Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)), + ), + getPullRequest: (input) => + execute({ + cwd: input.cwd, + args: [ + "pr", + "view", + input.reference, + "--json", + "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner", + ], + }).pipe( + Effect.map((result) => result.stdout.trim()), + Effect.flatMap((raw) => + decodeGitHubJson( + raw, + RawGitHubPullRequestSchema, + "getPullRequest", + "GitHub CLI returned invalid pull request JSON.", + ), + ), + Effect.map(normalizePullRequestSummary), + ), + getRepositoryCloneUrls: (input) => + execute({ + cwd: input.cwd, + args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"], + }).pipe( + Effect.map((result) => result.stdout.trim()), + Effect.flatMap((raw) => + decodeGitHubJson( + raw, + RawGitHubRepositoryCloneUrlsSchema, + "getRepositoryCloneUrls", + "GitHub CLI returned invalid repository JSON.", + ), + ), + Effect.map(normalizeRepositoryCloneUrls), + ), + createPullRequest: (input) => + execute({ + cwd: input.cwd, + args: [ + "pr", + "create", + "--base", + input.baseBranch, + "--head", + input.headSelector, + "--title", + input.title, + "--body-file", + input.bodyFile, + ], + }).pipe(Effect.asVoid), + getDefaultBranch: (input) => + execute({ + cwd: input.cwd, + args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"], + }).pipe( + Effect.map((value) => { + const trimmed = value.stdout.trim(); + return trimmed.length > 0 ? trimmed : null; + }), + ), + checkoutPullRequest: (input) => + execute({ + cwd: input.cwd, + args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])], + }).pipe(Effect.asVoid), + } satisfies GitHubCliShape; + + return service; +}); + +export const GitHubCliLive = Layer.effect(GitHubCli, makeGitHubCli); diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.ts new file mode 100644 index 0000000000..005bdb5bc6 --- /dev/null +++ b/apps/server/src/git/Layers/GitManager.test.ts @@ -0,0 +1,2912 @@ +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it } from "@effect/vitest"; +import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; +import { expect } from "vitest"; +import type { + GitActionProgressEvent, + GitPreparePullRequestThreadInput, + ModelSelection, + ThreadId, +} from "@t3tools/contracts"; + +import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts"; +import { type GitManagerShape } from "../Services/GitManager.ts"; +import { + type GitHubCliShape, + type GitHubPullRequestSummary, + GitHubCli, +} from "../Services/GitHubCli.ts"; +import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts"; +import { GitCoreLive } from "./GitCore.ts"; +import { GitCore } from "../Services/GitCore.ts"; +import { makeGitManager } from "./GitManager.ts"; +import { ServerConfig } from "../../config.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import { + ProjectSetupScriptRunner, + type ProjectSetupScriptRunnerInput, + type ProjectSetupScriptRunnerShape, +} from "../../project/Services/ProjectSetupScriptRunner.ts"; + +interface FakeGhScenario { + prListSequence?: string[]; + prListByHeadSelector?: Record; + prListSequenceByHeadSelector?: Record; + createdPrUrl?: string; + defaultBranch?: string; + pullRequest?: { + number: number; + title: string; + url: string; + baseRefName: string; + headRefName: string; + state?: "open" | "closed" | "merged"; + isCrossRepository?: boolean; + headRepositoryNameWithOwner?: string | null; + headRepositoryOwnerLogin?: string | null; + }; + repositoryCloneUrls?: Record; + failWith?: GitHubCliError; +} + +interface FakeGitTextGeneration { + generateCommitMessage: (input: { + cwd: string; + branch: string | null; + stagedSummary: string; + stagedPatch: string; + includeBranch?: boolean; + modelSelection: ModelSelection; + }) => Effect.Effect< + { subject: string; body: string; branch?: string | undefined }, + TextGenerationError + >; + generatePrContent: (input: { + cwd: string; + baseBranch: string; + headBranch: string; + commitSummary: string; + diffSummary: string; + diffPatch: string; + modelSelection: ModelSelection; + }) => Effect.Effect<{ title: string; body: string }, TextGenerationError>; + generateBranchName: (input: { + cwd: string; + message: string; + modelSelection: ModelSelection; + }) => Effect.Effect<{ branch: string }, TextGenerationError>; + generateThreadTitle: (input: { + cwd: string; + message: string; + modelSelection: ModelSelection; + }) => Effect.Effect<{ title: string }, TextGenerationError>; +} + +type FakePullRequest = NonNullable; + +function normalizeFakePullRequestSummary(raw: unknown): GitHubPullRequestSummary | null { + if (!raw || typeof raw !== "object") { + return null; + } + + const record = raw as Record; + const number = record.number; + const title = record.title; + const url = record.url; + const baseRefName = record.baseRefName; + const headRefName = record.headRefName; + const headRepository = + typeof record.headRepository === "object" && record.headRepository !== null + ? (record.headRepository as Record) + : null; + const headRepositoryOwner = + typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null + ? (record.headRepositoryOwner as Record) + : null; + + if ( + typeof number !== "number" || + typeof title !== "string" || + typeof url !== "string" || + typeof baseRefName !== "string" || + typeof headRefName !== "string" + ) { + return null; + } + + const state = + typeof record.state === "string" + ? record.state === "OPEN" || record.state === "open" + ? "open" + : record.state === "CLOSED" || record.state === "closed" + ? "closed" + : "merged" + : undefined; + const isCrossRepository = + typeof record.isCrossRepository === "boolean" ? record.isCrossRepository : undefined; + const headRepositoryNameWithOwner = + typeof record.headRepositoryNameWithOwner === "string" + ? record.headRepositoryNameWithOwner + : typeof headRepository?.nameWithOwner === "string" + ? headRepository.nameWithOwner + : undefined; + const headRepositoryOwnerLogin = + typeof record.headRepositoryOwnerLogin === "string" + ? record.headRepositoryOwnerLogin + : typeof headRepositoryOwner?.login === "string" + ? headRepositoryOwner.login + : undefined; + + return { + number, + title, + url, + baseRefName, + headRefName, + ...(state ? { state } : {}), + ...(isCrossRepository !== undefined ? { isCrossRepository } : {}), + ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + }; +} + +function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void { + const result = spawnSync("git", args, { + cwd, + encoding: "utf8", + }); + if (result.status === 0) { + return; + } + throw new GitHubCliError({ + operation: "execute", + detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`, + }); +} + +function isGitHubCliError(error: unknown): error is GitHubCliError { + return ( + typeof error === "object" && + error !== null && + "_tag" in error && + (error as { _tag?: unknown })._tag === "GitHubCliError" + ); +} + +function makeTempDir( + prefix: string, +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ prefix }); + }); +} + +function runGit( + cwd: string, + args: readonly string[], + allowNonZeroExit = false, +): Effect.Effect< + { readonly code: number; readonly stdout: string; readonly stderr: string }, + GitCommandError, + GitCore +> { + return Effect.gen(function* () { + const gitCore = yield* GitCore; + return yield* gitCore.execute({ + operation: "GitManager.test.runGit", + cwd, + args, + allowNonZeroExit, + }); + }); +} + +function initRepo( + cwd: string, +): Effect.Effect< + void, + PlatformError.PlatformError | GitCommandError, + FileSystem.FileSystem | Scope.Scope | GitCore +> { + return Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* runGit(cwd, ["init", "--initial-branch=main"]); + yield* runGit(cwd, ["config", "user.email", "test@example.com"]); + yield* runGit(cwd, ["config", "user.name", "Test User"]); + yield* fs.writeFileString(path.join(cwd, "README.md"), "hello\n"); + yield* runGit(cwd, ["add", "README.md"]); + yield* runGit(cwd, ["commit", "-m", "Initial commit"]); + }); +} + +function createBareRemote(): Effect.Effect< + string, + PlatformError.PlatformError | GitCommandError, + FileSystem.FileSystem | Scope.Scope | GitCore +> { + return Effect.gen(function* () { + const remoteDir = yield* makeTempDir("t3code-git-remote-"); + yield* runGit(remoteDir, ["init", "--bare"]); + return remoteDir; + }); +} + +function configureRemote( + cwd: string, + remoteName: string, + remotePath: string, + fetchNamespace: string, +): Effect.Effect { + return Effect.gen(function* () { + yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]); + yield* runGit(cwd, [ + "config", + "--replace-all", + `remote.${remoteName}.fetch`, + `+refs/heads/*:refs/remotes/${fetchNamespace}/*`, + ]); + }); +} + +function createTextGeneration(overrides: Partial = {}): TextGenerationShape { + const implementation: FakeGitTextGeneration = { + generateCommitMessage: (input) => + Effect.succeed({ + subject: "Implement stacked git actions", + body: "", + ...(input.includeBranch ? { branch: "feature/implement-stacked-git-actions" } : {}), + }), + generatePrContent: () => + Effect.succeed({ + title: "Add stacked git actions", + body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run", + }), + generateBranchName: () => + Effect.succeed({ + branch: "update-workflow", + }), + generateThreadTitle: () => + Effect.succeed({ + title: "Update workflow", + }), + ...overrides, + }; + + return { + generateCommitMessage: (input) => + implementation.generateCommitMessage(input).pipe( + Effect.mapError( + (cause) => + new TextGenerationError({ + operation: "generateCommitMessage", + detail: "fake text generation failed", + ...(cause !== undefined ? { cause } : {}), + }), + ), + ), + generatePrContent: (input) => + implementation.generatePrContent(input).pipe( + Effect.mapError( + (cause) => + new TextGenerationError({ + operation: "generatePrContent", + detail: "fake text generation failed", + ...(cause !== undefined ? { cause } : {}), + }), + ), + ), + generateBranchName: (input) => + implementation.generateBranchName(input).pipe( + Effect.mapError( + (cause) => + new TextGenerationError({ + operation: "generateBranchName", + detail: "fake text generation failed", + ...(cause !== undefined ? { cause } : {}), + }), + ), + ), + generateThreadTitle: (input) => + implementation.generateThreadTitle(input).pipe( + Effect.mapError( + (cause) => + new TextGenerationError({ + operation: "generateThreadTitle", + detail: "fake text generation failed", + ...(cause !== undefined ? { cause } : {}), + }), + ), + ), + }; +} + +function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): { + service: GitHubCliShape; + ghCalls: string[]; +} { + const prListQueue = [...(scenario.prListSequence ?? [])]; + const prListQueueByHeadSelector = new Map( + Object.entries(scenario.prListSequenceByHeadSelector ?? {}).map(([headSelector, values]) => [ + headSelector, + [...values], + ]), + ); + const ghCalls: string[] = []; + + const execute: GitHubCliShape["execute"] = (input) => { + const args = [...input.args]; + ghCalls.push(args.join(" ")); + + if (scenario.failWith) { + return Effect.fail(scenario.failWith); + } + + if (args[0] === "pr" && args[1] === "list") { + const headSelectorIndex = args.findIndex((value) => value === "--head"); + const headSelector = + headSelectorIndex >= 0 && headSelectorIndex < args.length - 1 + ? args[headSelectorIndex + 1] + : undefined; + const mappedQueue = + typeof headSelector === "string" + ? prListQueueByHeadSelector.get(headSelector)?.shift() + : undefined; + const mappedStdout = + typeof headSelector === "string" + ? scenario.prListByHeadSelector?.[headSelector] + : undefined; + const stdout = (mappedQueue ?? mappedStdout ?? prListQueue.shift() ?? "[]") + "\n"; + return Effect.succeed({ + stdout, + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + } + + if (args[0] === "pr" && args[1] === "create") { + return Effect.succeed({ + stdout: + (scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n", + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + } + + if (args[0] === "pr" && args[1] === "view") { + const pullRequest: FakePullRequest = scenario.pullRequest ?? { + number: 101, + title: "Pull request", + url: "https://github.com/pingdotgg/codething-mvp/pull/101", + baseRefName: "main", + headRefName: "feature/pull-request", + state: "open", + }; + return Effect.succeed({ + stdout: + JSON.stringify({ + ...pullRequest, + ...(pullRequest.headRepositoryNameWithOwner + ? { + headRepository: { + nameWithOwner: pullRequest.headRepositoryNameWithOwner, + }, + } + : {}), + ...(pullRequest.headRepositoryOwnerLogin + ? { + headRepositoryOwner: { + login: pullRequest.headRepositoryOwnerLogin, + }, + } + : {}), + }) + "\n", + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + } + + if (args[0] === "pr" && args[1] === "checkout") { + return Effect.try({ + try: () => { + const headBranch = scenario.pullRequest?.headRefName; + if (headBranch) { + const existingBranch = spawnSync( + "git", + ["show-ref", "--verify", "--quiet", `refs/heads/${headBranch}`], + { + cwd: input.cwd, + encoding: "utf8", + }, + ); + if (existingBranch.status === 0) { + runGitSyncForFakeGh(input.cwd, ["checkout", headBranch]); + } else { + runGitSyncForFakeGh(input.cwd, ["checkout", "-b", headBranch]); + } + } + return { + stdout: "", + stderr: "", + code: 0, + signal: null, + timedOut: false, + }; + }, + catch: (error) => + isGitHubCliError(error) + ? error + : new GitHubCliError({ + operation: "execute", + detail: + error instanceof Error + ? `Failed to simulate gh checkout: ${error.message}` + : "Failed to simulate gh checkout.", + }), + }); + } + + if (args[0] === "repo" && args[1] === "view") { + const repository = args[2]; + if (typeof repository === "string" && args.includes("nameWithOwner,url,sshUrl")) { + const cloneUrls = scenario.repositoryCloneUrls?.[repository]; + if (!cloneUrls) { + return Effect.fail( + new GitHubCliError({ + operation: "execute", + detail: `Unexpected repository lookup: ${repository}`, + }), + ); + } + return Effect.succeed({ + stdout: + JSON.stringify({ + nameWithOwner: repository, + url: cloneUrls.url, + sshUrl: cloneUrls.sshUrl, + }) + "\n", + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + } + return Effect.succeed({ + stdout: `${scenario.defaultBranch ?? "main"}\n`, + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + } + + return Effect.fail( + new GitHubCliError({ + operation: "execute", + detail: `Unexpected gh command: ${args.join(" ")}`, + }), + ); + }; + + return { + service: { + execute, + listOpenPullRequests: (input) => + execute({ + cwd: input.cwd, + args: [ + "pr", + "list", + "--head", + input.headSelector, + "--state", + "open", + "--limit", + String(input.limit ?? 1), + "--json", + "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner", + ], + }).pipe( + Effect.map((result) => JSON.parse(result.stdout) as unknown[]), + Effect.map((raw) => + raw + .map((entry) => normalizeFakePullRequestSummary(entry)) + .filter((entry): entry is GitHubPullRequestSummary => entry !== null), + ), + ), + createPullRequest: (input) => + execute({ + cwd: input.cwd, + args: [ + "pr", + "create", + "--base", + input.baseBranch, + "--head", + input.headSelector, + "--title", + input.title, + "--body-file", + input.bodyFile, + ], + }).pipe(Effect.asVoid), + getDefaultBranch: (input) => + execute({ + cwd: input.cwd, + args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"], + }).pipe( + Effect.map((result) => { + const value = result.stdout.trim(); + return value.length > 0 ? value : null; + }), + ), + getPullRequest: (input) => + execute({ + cwd: input.cwd, + args: [ + "pr", + "view", + input.reference, + "--json", + "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner", + ], + }).pipe(Effect.map((result) => JSON.parse(result.stdout) as GitHubPullRequestSummary)), + getRepositoryCloneUrls: (input) => + execute({ + cwd: input.cwd, + args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"], + }).pipe(Effect.map((result) => JSON.parse(result.stdout))), + checkoutPullRequest: (input) => + execute({ + cwd: input.cwd, + args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])], + }).pipe(Effect.asVoid), + }, + ghCalls, + }; +} + +function runStackedAction( + manager: GitManagerShape, + input: { + cwd: string; + action: "commit" | "push" | "create_pr" | "commit_push" | "commit_push_pr"; + actionId?: string; + commitMessage?: string; + featureBranch?: boolean; + filePaths?: readonly string[]; + }, + options?: Parameters[1], +) { + return manager.runStackedAction( + { + ...input, + actionId: input.actionId ?? "test-action-id", + }, + options, + ); +} + +function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) { + return manager.resolvePullRequest(input); +} + +function preparePullRequestThread( + manager: GitManagerShape, + input: GitPreparePullRequestThreadInput, +) { + return manager.preparePullRequestThread(input); +} + +function makeManager(input?: { + ghScenario?: FakeGhScenario; + textGeneration?: Partial; + setupScriptRunner?: ProjectSetupScriptRunnerShape; +}) { + const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario); + const textGeneration = createTextGeneration(input?.textGeneration); + const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-git-manager-test-", + }); + + const serverSettingsLayer = ServerSettingsService.layerTest(); + + const gitCoreLayer = GitCoreLive.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(ServerConfigLayer), + ); + + const managerLayer = Layer.mergeAll( + Layer.succeed(GitHubCli, gitHubCli), + Layer.succeed(TextGeneration, textGeneration), + Layer.succeed( + ProjectSetupScriptRunner, + input?.setupScriptRunner ?? { + runForThread: () => Effect.succeed({ status: "no-script" as const }), + }, + ), + gitCoreLayer, + serverSettingsLayer, + ).pipe(Layer.provideMerge(NodeServices.layer)); + + return makeGitManager().pipe( + Effect.provide(managerLayer), + Effect.map((manager) => ({ manager, ghCalls })), + ); +} + +const asThreadId = (threadId: string) => threadId as ThreadId; + +const GitManagerTestLayer = GitCoreLive.pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })), + Layer.provideMerge(NodeServices.layer), +); + +it.layer(GitManagerTestLayer)("GitManager", (it) => { + it.effect("status includes PR metadata when branch already has an open PR", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 13, + title: "Existing PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/13", + baseRefName: "main", + headRefName: "feature/status-open-pr", + }, + ]), + ], + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.isRepo).toBe(true); + expect(status.hasOriginRemote).toBe(true); + expect(status.isDefaultBranch).toBe(false); + expect(status.branch).toBe("feature/status-open-pr"); + expect(status.pr).toEqual({ + number: 13, + title: "Existing PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/13", + baseBranch: "main", + headBranch: "feature/status-open-pr", + state: "open", + }); + }), + ); + + it.effect("status returns an explicit non-repo result for non-git directories", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir("t3code-git-manager-non-repo-"); + const { manager } = yield* makeManager(); + + const status = yield* manager.status({ cwd }); + + expect(status).toEqual({ + isRepo: false, + hasOriginRemote: false, + isDefaultBranch: false, + branch: null, + hasWorkingTreeChanges: false, + workingTree: { + files: [], + insertions: 0, + deletions: 0, + }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + pr: null, + }); + }), + ); + + it.effect("status briefly caches repeated lookups for the same cwd", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-cache"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-cache"]); + + const existingPr = { + number: 113, + title: "Cached PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/113", + baseRefName: "main", + headRefName: "feature/status-cache", + }; + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [JSON.stringify([existingPr]), JSON.stringify([existingPr])], + }, + }); + + const first = yield* manager.status({ cwd: repoDir }); + const second = yield* manager.status({ cwd: repoDir }); + + expect(first.pr?.number).toBe(113); + expect(second.pr?.number).toBe(113); + expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(1); + }), + ); + + it.effect( + "status ignores unrelated fork PRs when the current branch tracks the same repository", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 1661, + title: "Fork PR from main", + url: "https://github.com/pingdotgg/t3code/pull/1661", + baseRefName: "main", + headRefName: "main", + state: "OPEN", + updatedAt: "2026-04-01T15:00:00Z", + isCrossRepository: true, + headRepository: { + nameWithOwner: "lnieuwenhuis/t3code", + }, + headRepositoryOwner: { + login: "lnieuwenhuis", + }, + }, + ]), + ], + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.branch).toBe("main"); + expect(status.pr).toBeNull(); + }), + ); + + it.effect( + "status detects cross-repo PRs from the upstream remote URL owner", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["checkout", "-b", "statemachine"]); + fs.writeFileSync(path.join(repoDir, "fork-pr.txt"), "fork pr\n"); + yield* runGit(repoDir, ["add", "fork-pr.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Fork PR branch"]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]); + yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-488/statemachine"]); + yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]); + yield* runGit(repoDir, [ + "config", + "remote.fork-seed.url", + "git@github.com:jasonLaster/codething-mvp.git", + ]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([]), + JSON.stringify([]), + JSON.stringify([ + { + number: 488, + title: "Rebase this PR on latest main", + url: "https://github.com/pingdotgg/codething-mvp/pull/488", + baseRefName: "main", + headRefName: "statemachine", + state: "OPEN", + updatedAt: "2026-03-10T07:00:00Z", + isCrossRepository: true, + headRepository: { + nameWithOwner: "jasonLaster/codething-mvp", + }, + headRepositoryOwner: { + login: "jasonLaster", + }, + }, + ]), + ], + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.branch).toBe("t3code/pr-488/statemachine"); + expect(status.pr).toEqual({ + number: 488, + title: "Rebase this PR on latest main", + url: "https://github.com/pingdotgg/codething-mvp/pull/488", + baseBranch: "main", + headBranch: "statemachine", + state: "open", + }); + expect(ghCalls).toContain( + "pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner", + ); + }), + 12_000, + ); + + it.effect( + "status ignores synthetic local branch aliases when the upstream remote name contains slashes", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const upstreamDir = yield* createBareRemote(); + yield* configureRemote(repoDir, "origin", originDir, "origin"); + yield* configureRemote(repoDir, "my-org/upstream", upstreamDir, "my-org/upstream"); + + yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]); + yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]); + yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]); + yield* runGit(repoDir, [ + "config", + "remote.origin.url", + "git@github.com:pingdotgg/codething-mvp.git", + ]); + yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]); + yield* runGit(repoDir, [ + "config", + "remote.my-org/upstream.url", + "git@github.com:pingdotgg/codething-mvp.git", + ]); + yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]); + yield* runGit(repoDir, ["checkout", "main"]); + yield* runGit(repoDir, ["branch", "-D", "effect-atom"]); + yield* runGit(repoDir, ["checkout", "--track", "my-org/upstream/effect-atom"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListByHeadSelector: { + "effect-atom": JSON.stringify([ + { + number: 1618, + title: "Correct PR", + url: "https://github.com/pingdotgg/t3code/pull/1618", + baseRefName: "main", + headRefName: "effect-atom", + state: "OPEN", + updatedAt: "2026-03-01T10:00:00Z", + }, + ]), + "upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + state: "OPEN", + updatedAt: "2026-04-01T10:00:00Z", + }, + ]), + "pingdotgg:effect-atom": JSON.stringify([]), + "my-org/upstream:effect-atom": JSON.stringify([]), + "pingdotgg:upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + state: "OPEN", + updatedAt: "2026-04-01T10:00:00Z", + }, + ]), + "my-org/upstream:upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + state: "OPEN", + updatedAt: "2026-04-01T10:00:00Z", + }, + ]), + }, + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.branch).toBe("upstream/effect-atom"); + expect(status.pr).toEqual({ + number: 1618, + title: "Correct PR", + url: "https://github.com/pingdotgg/t3code/pull/1618", + baseBranch: "main", + headBranch: "effect-atom", + state: "open", + }); + expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe( + false, + ); + expect( + ghCalls.some((call) => call.includes("pr list --head pingdotgg:upstream/effect-atom ")), + ).toBe(false); + expect( + ghCalls.some((call) => + call.includes("pr list --head my-org/upstream:upstream/effect-atom "), + ), + ).toBe(false); + }), + 12_000, + ); + + it.effect("status returns merged PR state when latest PR was merged", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 22, + title: "Merged PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/22", + baseRefName: "main", + headRefName: "feature/status-merged-pr", + state: "MERGED", + mergedAt: "2026-01-30T10:00:00Z", + updatedAt: "2026-01-30T10:00:00Z", + }, + ]), + ], + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.branch).toBe("feature/status-merged-pr"); + expect(status.pr).toEqual({ + number: 22, + title: "Merged PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/22", + baseBranch: "main", + headBranch: "feature/status-merged-pr", + state: "merged", + }); + }), + ); + + it.effect("status prefers open PR when merged PR has newer updatedAt", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 45, + title: "Merged PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/45", + baseRefName: "main", + headRefName: "feature/status-open-over-merged", + state: "MERGED", + mergedAt: "2026-01-31T10:00:00Z", + updatedAt: "2026-02-01T10:00:00Z", + }, + { + number: 46, + title: "Open PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/46", + baseRefName: "main", + headRefName: "feature/status-open-over-merged", + state: "OPEN", + updatedAt: "2026-01-30T10:00:00Z", + }, + ]), + ], + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.branch).toBe("feature/status-open-over-merged"); + expect(status.pr).toEqual({ + number: 46, + title: "Open PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/46", + baseBranch: "main", + headBranch: "feature/status-open-over-merged", + state: "open", + }); + }), + ); + + it.effect("status is resilient to gh lookup failures and returns pr null", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]); + + const { manager } = yield* makeManager({ + ghScenario: { + failWith: new GitHubCliError({ + operation: "execute", + detail: "GitHub CLI (`gh`) is required but not available on PATH.", + }), + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.branch).toBe("feature/status-no-gh"); + expect(status.pr).toBeNull(); + }), + ); + + it.effect("creates a commit when working tree is dirty", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n"); + + const { manager } = yield* makeManager(); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + }); + + expect(result.branch.status).toBe("skipped_not_requested"); + expect(result.commit.status).toBe("created"); + expect(result.push.status).toBe("skipped_not_requested"); + expect(result.pr.status).toBe("skipped_not_requested"); + expect(result.toast).toMatchObject({ + description: "Implement stacked git actions", + cta: { + kind: "run_action", + label: "Push", + action: { + kind: "push", + }, + }, + }); + expect(result.toast.title).toMatch(/^Committed [0-9a-f]{7}$/); + expect( + yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe( + Effect.map((result) => result.stdout.trim()), + ), + ).toBe("Implement stacked git actions"); + }), + ); + + it.effect("uses custom commit message when provided", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n"); + let generatedCount = 0; + + const { manager } = yield* makeManager({ + textGeneration: { + generateCommitMessage: (input) => + Effect.sync(() => { + generatedCount += 1; + return { + subject: "this should not be used", + body: "", + ...(input.includeBranch ? { branch: "feature/unused" } : {}), + }; + }), + }, + }); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + commitMessage: "feat: custom summary line\n\n- details from user", + }); + + expect(result.branch.status).toBe("skipped_not_requested"); + expect(result.commit.status).toBe("created"); + expect(result.commit.subject).toBe("feat: custom summary line"); + expect(generatedCount).toBe(0); + expect( + yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe( + Effect.map((result) => result.stdout.trim()), + ), + ).toBe("feat: custom summary line"); + expect( + yield* runGit(repoDir, ["log", "-1", "--pretty=%b"]).pipe( + Effect.map((result) => result.stdout.trim()), + ), + ).toContain("- details from user"); + }), + ); + + it.effect("commits only selected files when filePaths is provided", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + fs.writeFileSync(path.join(repoDir, "a.txt"), "file a\n"); + fs.writeFileSync(path.join(repoDir, "b.txt"), "file b\n"); + + const { manager } = yield* makeManager(); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + filePaths: ["a.txt"], + }); + + expect(result.commit.status).toBe("created"); + + // b.txt should remain in the working tree + const statusStdout = yield* runGit(repoDir, ["status", "--porcelain"]).pipe( + Effect.map((r) => r.stdout), + ); + expect(statusStdout).toContain("b.txt"); + expect(statusStdout).not.toContain("a.txt"); + }), + ); + + it.effect("creates feature branch, commits, and pushes with featureBranch option", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nfeature-branch\n"); + let generatedCount = 0; + + const { manager } = yield* makeManager({ + textGeneration: { + generateCommitMessage: (input) => + Effect.sync(() => { + generatedCount += 1; + return { + subject: "Implement stacked git actions", + body: "", + ...(input.includeBranch ? { branch: "feature/implement-stacked-git-actions" } : {}), + }; + }), + }, + }); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push", + featureBranch: true, + }); + + expect(result.branch.status).toBe("created"); + expect(result.branch.name).toBe("feature/implement-stacked-git-actions"); + expect(result.commit.status).toBe("created"); + expect(result.push.status).toBe("pushed"); + expect(result.toast).toMatchObject({ + description: "Implement stacked git actions", + cta: { + kind: "run_action", + label: "Create PR", + action: { + kind: "create_pr", + }, + }, + }); + expect(result.toast.title).toMatch( + /^Pushed [0-9a-f]{7} to origin\/feature\/implement-stacked-git-actions$/, + ); + expect( + yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe( + Effect.map((result) => result.stdout.trim()), + ), + ).toBe("feature/implement-stacked-git-actions"); + + const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe( + Effect.map((r) => r.stdout.trim()), + ); + const mergeBase = yield* runGit(repoDir, ["merge-base", "main", "HEAD"]).pipe( + Effect.map((r) => r.stdout.trim()), + ); + expect(mergeBase).toBe(mainSha); + expect(generatedCount).toBe(1); + }), + ); + + it.effect("featureBranch uses custom commit message and derives branch name", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom-feature\n"); + let generatedCount = 0; + + const { manager } = yield* makeManager({ + textGeneration: { + generateCommitMessage: (input) => + Effect.sync(() => { + generatedCount += 1; + return { + subject: "unused", + body: "", + ...(input.includeBranch ? { branch: "feature/unused" } : {}), + }; + }), + }, + }); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + featureBranch: true, + commitMessage: "feat: custom summary line\n\n- details from user", + }); + + expect(result.branch.status).toBe("created"); + expect(result.branch.name).toBe("feature/feat-custom-summary-line"); + expect(result.commit.status).toBe("created"); + expect(result.commit.subject).toBe("feat: custom summary line"); + expect(generatedCount).toBe(0); + + const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe( + Effect.map((r) => r.stdout.trim()), + ); + const mergeBase = yield* runGit(repoDir, ["merge-base", "main", result.branch.name!]).pipe( + Effect.map((r) => r.stdout.trim()), + ); + expect(mergeBase).toBe(mainSha); + }), + ); + + it.effect("skips commit when there are no uncommitted changes", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + + const { manager } = yield* makeManager(); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + }); + + expect(result.branch.status).toBe("skipped_not_requested"); + expect(result.commit.status).toBe("skipped_no_changes"); + expect(result.push.status).toBe("skipped_not_requested"); + expect(result.pr.status).toBe("skipped_not_requested"); + }), + ); + + it.effect("featureBranch returns error when worktree is clean", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + + const { manager } = yield* makeManager(); + const errorMessage = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + featureBranch: true, + }).pipe( + Effect.flip, + Effect.map((error) => error.message), + ); + + expect(errorMessage).toContain("no changes to commit"); + }), + ); + + it.effect("commits and pushes with upstream auto-setup when needed", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n"); + + const { manager } = yield* makeManager(); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push", + }); + + expect(result.branch.status).toBe("skipped_not_requested"); + expect(result.commit.status).toBe("created"); + expect(result.push.status).toBe("pushed"); + expect(result.push.setUpstream).toBe(true); + expect( + yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe( + Effect.map((result) => result.stdout.trim()), + ), + ).toBe("origin/feature/stacked-flow"); + }), + ); + + it.effect( + "pushes and creates PR from a no-upstream branch when local commits are ahead of base", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n"); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [ + "[]", + JSON.stringify([ + { + number: 77, + title: "Add no-upstream PR flow", + url: "https://github.com/pingdotgg/codething-mvp/pull/77", + baseRefName: "main", + headRefName: "feature/no-upstream-pr", + }, + ]), + ], + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.branch.status).toBe("skipped_not_requested"); + expect(result.commit.status).toBe("created"); + expect(result.push.status).toBe("pushed"); + expect(result.push.setUpstream).toBe(true); + expect(result.pr.status).toBe("created"); + expect( + yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe( + Effect.map((result) => result.stdout.trim()), + ), + ).toBe("origin/feature/no-upstream-pr"); + expect( + ghCalls.some((call) => + call.includes("pr create --base main --head feature/no-upstream-pr"), + ), + ).toBe(true); + }), + ); + + it.effect("skips push when branch is already up to date", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]); + + const { manager } = yield* makeManager(); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push", + }); + + expect(result.branch.status).toBe("skipped_not_requested"); + expect(result.commit.status).toBe("skipped_no_changes"); + expect(result.push.status).toBe("skipped_up_to_date"); + }), + ); + + it.effect("pushes existing clean commits without rerunning commit logic", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/push-only"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "push-only.txt"), "push only\n"); + yield* runGit(repoDir, ["add", "push-only.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Push only branch"]); + + const { manager } = yield* makeManager(); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "push", + }); + + expect(result.commit.status).toBe("skipped_not_requested"); + expect(result.push.status).toBe("pushed"); + expect(result.pr.status).toBe("skipped_not_requested"); + expect( + yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe( + Effect.map((output) => output.stdout.trim()), + ), + ).toBe("origin/feature/push-only"); + }), + ); + + it.effect("create_pr pushes a clean branch before creating the PR when needed", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/create-pr-only"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "create-pr-only.txt"), "create pr\n"); + yield* runGit(repoDir, ["add", "create-pr-only.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Create PR only branch"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [ + "[]", + JSON.stringify([ + { + number: 303, + title: "Create PR only branch", + url: "https://github.com/pingdotgg/codething-mvp/pull/303", + baseRefName: "main", + headRefName: "feature/create-pr-only", + }, + ]), + ], + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "create_pr", + }); + + expect(result.commit.status).toBe("skipped_not_requested"); + expect(result.push.status).toBe("pushed"); + expect(result.push.setUpstream).toBe(true); + expect(result.pr.status).toBe("created"); + expect(result.pr.number).toBe(303); + expect( + ghCalls.some((call) => + call.includes("pr create --base main --head feature/create-pr-only"), + ), + ).toBe(true); + }), + ); + + it.effect("returns existing PR metadata for commit/push/pr action", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 42, + title: "Existing PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/42", + baseRefName: "main", + headRefName: "feature/existing-pr", + }, + ]), + ], + }, + }); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.branch.status).toBe("skipped_not_requested"); + expect(result.pr.status).toBe("opened_existing"); + expect(result.pr.number).toBe(42); + expect(result.toast).toEqual({ + title: "Opened PR #42", + description: "Existing PR", + cta: { + kind: "open_pr", + label: "View PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/42", + }, + }); + expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false); + }), + ); + + it.effect( + "returns existing cross-repo PR metadata using the fork owner selector", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "statemachine"]); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]); + yield* runGit(repoDir, [ + "config", + "remote.fork-seed.url", + "git@github.com:octocat/codething-mvp.git", + ]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([]), + JSON.stringify([ + { + number: 142, + title: "Existing fork PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/142", + baseRefName: "main", + headRefName: "statemachine", + state: "OPEN", + isCrossRepository: true, + headRepository: { + nameWithOwner: "octocat/codething-mvp", + }, + headRepositoryOwner: { + login: "octocat", + }, + }, + ]), + ], + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.pr.status).toBe("opened_existing"); + expect(result.pr.number).toBe(142); + expect( + ghCalls.some((call) => + call.includes("pr list --head octocat:statemachine --state open --limit 1"), + ), + ).toBe(true); + expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(false); + }), + 12_000, + ); + + it.effect( + "returns the correct existing PR when a slash remote checks out to a synthetic local alias", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const upstreamDir = yield* createBareRemote(); + yield* configureRemote(repoDir, "origin", originDir, "origin"); + yield* configureRemote(repoDir, "my-org/upstream", upstreamDir, "my-org/upstream"); + + yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]); + yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]); + yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]); + yield* runGit(repoDir, [ + "config", + "remote.origin.url", + "git@github.com:pingdotgg/codething-mvp.git", + ]); + yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]); + yield* runGit(repoDir, [ + "config", + "remote.my-org/upstream.url", + "git@github.com:pingdotgg/codething-mvp.git", + ]); + yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]); + yield* runGit(repoDir, ["checkout", "main"]); + yield* runGit(repoDir, ["branch", "-D", "effect-atom"]); + yield* runGit(repoDir, ["checkout", "--track", "my-org/upstream/effect-atom"]); + fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n"); + yield* runGit(repoDir, ["add", "changes.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Feature commit"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListByHeadSelector: { + "effect-atom": JSON.stringify([ + { + number: 1618, + title: "Correct PR", + url: "https://github.com/pingdotgg/t3code/pull/1618", + baseRefName: "main", + headRefName: "effect-atom", + }, + ]), + "upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + }, + ]), + "pingdotgg:effect-atom": JSON.stringify([]), + "my-org/upstream:effect-atom": JSON.stringify([]), + "pingdotgg:upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + }, + ]), + "my-org/upstream:upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + }, + ]), + }, + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.pr.status).toBe("opened_existing"); + expect(result.pr.number).toBe(1618); + expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe( + false, + ); + }), + 12_000, + ); + + it.effect( + "prefers owner-qualified selectors before bare branch names for cross-repo PRs", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "statemachine"]); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]); + yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-142/statemachine"]); + yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]); + yield* runGit(repoDir, [ + "config", + "remote.fork-seed.url", + "git@github.com:octocat/codething-mvp.git", + ]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListByHeadSelector: { + "t3code/pr-142/statemachine": JSON.stringify([]), + statemachine: JSON.stringify([ + { + number: 41, + title: "Unrelated same-repo PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/41", + baseRefName: "main", + headRefName: "statemachine", + }, + ]), + "octocat:statemachine": JSON.stringify([ + { + number: 142, + title: "Existing fork PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/142", + baseRefName: "main", + headRefName: "statemachine", + state: "OPEN", + isCrossRepository: true, + headRepository: { + nameWithOwner: "octocat/codething-mvp", + }, + headRepositoryOwner: { + login: "octocat", + }, + }, + ]), + "fork-seed:statemachine": JSON.stringify([]), + }, + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.pr.status).toBe("opened_existing"); + expect(result.pr.number).toBe(142); + + const ownerSelectorCallIndex = ghCalls.findIndex((call) => + call.includes("pr list --head octocat:statemachine --state open --limit 1"), + ); + expect(ownerSelectorCallIndex).toBeGreaterThanOrEqual(0); + expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(false); + }), + 12_000, + ); + + it.effect( + "stops probing head selectors after finding an existing PR", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "statemachine"]); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]); + yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-142/statemachine"]); + yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]); + yield* runGit(repoDir, [ + "config", + "remote.fork-seed.url", + "git@github.com:octocat/codething-mvp.git", + ]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListByHeadSelector: { + "octocat:statemachine": JSON.stringify([ + { + number: 142, + title: "Existing fork PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/142", + baseRefName: "main", + headRefName: "statemachine", + state: "OPEN", + isCrossRepository: true, + headRepository: { + nameWithOwner: "octocat/codething-mvp", + }, + headRepositoryOwner: { + login: "octocat", + }, + }, + ]), + "fork-seed:statemachine": JSON.stringify([]), + "t3code/pr-142/statemachine": JSON.stringify([]), + statemachine: JSON.stringify([]), + }, + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.pr.status).toBe("opened_existing"); + expect(result.pr.number).toBe(142); + + const openLookupCalls = ghCalls.filter((call) => call.includes("--state open --limit 1")); + expect(openLookupCalls).toHaveLength(1); + expect(openLookupCalls[0]).toContain( + "pr list --head octocat:statemachine --state open --limit 1", + ); + }), + 12_000, + ); + + it.effect("creates PR when one does not already exist", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature-create-pr"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n"); + yield* runGit(repoDir, ["add", "changes.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Feature commit"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]); + yield* runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [ + "[]", + JSON.stringify([ + { + number: 88, + title: "Add stacked git actions", + url: "https://github.com/pingdotgg/codething-mvp/pull/88", + baseRefName: "main", + headRefName: "feature-create-pr", + }, + ]), + ], + }, + }); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.branch.status).toBe("skipped_not_requested"); + expect(result.pr.status).toBe("created"); + expect(result.pr.number).toBe(88); + expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(2); + expect( + ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")), + ).toBe(true); + expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false); + }), + ); + + it.effect( + "creates a new PR instead of reusing an unrelated fork PR with the same head branch", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/no-fork-match"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n"); + yield* runGit(repoDir, ["add", "changes.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Feature commit"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 1661, + title: "Fork PR with same branch name", + url: "https://github.com/pingdotgg/t3code/pull/1661", + baseRefName: "main", + headRefName: "feature/no-fork-match", + state: "OPEN", + isCrossRepository: true, + headRepository: { + nameWithOwner: "lnieuwenhuis/t3code", + }, + headRepositoryOwner: { + login: "lnieuwenhuis", + }, + }, + ]), + JSON.stringify([ + { + number: 188, + title: "Add stacked git actions", + url: "https://github.com/pingdotgg/codething-mvp/pull/188", + baseRefName: "main", + headRefName: "feature/no-fork-match", + state: "OPEN", + isCrossRepository: false, + }, + ]), + ], + }, + }); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.pr.status).toBe("created"); + expect(result.pr.number).toBe(188); + expect(result.toast).toEqual({ + title: "Created PR #188", + description: "Add stacked git actions", + cta: { + kind: "open_pr", + label: "View PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/188", + }, + }); + expect( + ghCalls.some((call) => + call.includes("pr create --base main --head feature/no-fork-match"), + ), + ).toBe(true); + }), + ); + + it.effect("creates cross-repo PRs with the fork owner selector and default base branch", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["checkout", "-b", "statemachine"]); + fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n"); + yield* runGit(repoDir, ["add", "changes.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Feature commit"]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]); + yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-91/statemachine"]); + yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]); + yield* runGit(repoDir, [ + "config", + "remote.fork-seed.url", + "git@github.com:octocat/codething-mvp.git", + ]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequenceByHeadSelector: { + "octocat:statemachine": [ + JSON.stringify([]), + JSON.stringify([ + { + number: 188, + title: "Add stacked git actions", + url: "https://github.com/pingdotgg/codething-mvp/pull/188", + baseRefName: "main", + headRefName: "statemachine", + state: "OPEN", + isCrossRepository: true, + headRepository: { + nameWithOwner: "octocat/codething-mvp", + }, + headRepositoryOwner: { + login: "octocat", + }, + }, + ]), + ], + "fork-seed:statemachine": [JSON.stringify([])], + statemachine: [JSON.stringify([])], + }, + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.pr.status).toBe("created"); + expect(result.pr.number).toBe(188); + expect( + ghCalls.some((call) => call.includes("pr create --base main --head octocat:statemachine")), + ).toBe(true); + expect( + ghCalls.some((call) => + call.includes("pr create --base statemachine --head octocat:statemachine"), + ), + ).toBe(false); + }), + ); + + it.effect("rejects push/pr actions from detached HEAD", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "--detach", "HEAD"]); + + const { manager } = yield* makeManager(); + const errorMessage = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push", + }).pipe( + Effect.flip, + Effect.map((error) => error.message), + ); + expect(errorMessage).toContain("detached HEAD"); + }), + ); + + it.effect("surfaces missing gh binary errors", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]); + + const { manager } = yield* makeManager({ + ghScenario: { + failWith: new GitHubCliError({ + operation: "execute", + detail: "GitHub CLI (`gh`) is required but not available on PATH.", + }), + }, + }); + + const errorMessage = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }).pipe( + Effect.flip, + Effect.map((error) => error.message), + ); + expect(errorMessage).toContain("GitHub CLI (`gh`) is required"); + }), + ); + + it.effect("surfaces gh auth errors with guidance", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]); + + const { manager } = yield* makeManager({ + ghScenario: { + failWith: new GitHubCliError({ + operation: "execute", + detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.", + }), + }, + }); + + const errorMessage = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }).pipe( + Effect.flip, + Effect.map((error) => error.message), + ); + expect(errorMessage).toContain("gh auth login"); + }), + ); + + it.effect("resolves pull requests from #number references", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 42, + title: "Resolve PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/42", + baseRefName: "main", + headRefName: "feature/resolve-pr", + state: "open", + }, + }, + }); + + const result = yield* resolvePullRequest(manager, { + cwd: repoDir, + reference: "#42", + }); + + expect(result.pullRequest).toEqual({ + number: 42, + title: "Resolve PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/42", + baseBranch: "main", + headBranch: "feature/resolve-pr", + state: "open", + }); + expect(ghCalls.some((call) => call.startsWith("pr view 42 "))).toBe(true); + }), + ); + + it.effect("prepares pull request threads in local mode by checking out the PR branch", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local"]); + fs.writeFileSync(path.join(repoDir, "local.txt"), "local\n"); + yield* runGit(repoDir, ["add", "local.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Local PR branch"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 64, + title: "Local PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/64", + baseRefName: "main", + headRefName: "feature/pr-local", + state: "open", + }, + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "#64", + mode: "local", + }); + + expect(result.branch).toBe("feature/pr-local"); + expect(result.worktreePath).toBeNull(); + const branch = (yield* runGit(repoDir, ["branch", "--show-current"])).stdout.trim(); + expect(branch).toBe("feature/pr-local"); + expect(ghCalls).toContain("pr checkout 64 --force"); + }), + ); + + it.effect("prepares pull request threads in worktree mode on the PR head branch", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-worktree"]); + fs.writeFileSync(path.join(repoDir, "worktree.txt"), "worktree\n"); + yield* runGit(repoDir, ["add", "worktree.txt"]); + yield* runGit(repoDir, ["commit", "-m", "PR worktree branch"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-worktree"]); + yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/77/head"]); + yield* runGit(repoDir, ["checkout", "main"]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 77, + title: "Worktree PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/77", + baseRefName: "main", + headRefName: "feature/pr-worktree", + state: "open", + }, + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "77", + mode: "worktree", + }); + + expect(result.branch).toBe("feature/pr-worktree"); + expect(result.worktreePath).not.toBeNull(); + expect(fs.existsSync(result.worktreePath as string)).toBe(true); + const worktreeBranch = (yield* runGit(result.worktreePath as string, [ + "branch", + "--show-current", + ])).stdout.trim(); + expect(worktreeBranch).toBe("feature/pr-worktree"); + }), + ); + + it.effect("launches setup only when creating a new PR worktree", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-worktree-setup"]); + fs.writeFileSync(path.join(repoDir, "setup.txt"), "setup\n"); + yield* runGit(repoDir, ["add", "setup.txt"]); + yield* runGit(repoDir, ["commit", "-m", "PR worktree setup branch"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-worktree-setup"]); + yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/177/head"]); + yield* runGit(repoDir, ["checkout", "main"]); + + const setupCalls: ProjectSetupScriptRunnerInput[] = []; + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 177, + title: "Worktree setup PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/177", + baseRefName: "main", + headRefName: "feature/pr-worktree-setup", + state: "open", + }, + }, + setupScriptRunner: { + runForThread: (setupInput) => + Effect.sync(() => { + setupCalls.push(setupInput); + return { status: "no-script" as const }; + }), + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "177", + mode: "worktree", + threadId: asThreadId("thread-pr-setup"), + }); + + expect(result.worktreePath).not.toBeNull(); + expect(setupCalls).toHaveLength(1); + expect(setupCalls[0]).toEqual({ + threadId: "thread-pr-setup", + projectCwd: repoDir, + worktreePath: result.worktreePath as string, + }); + }), + ); + + it.effect("preserves fork upstream tracking when preparing a worktree PR thread", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-fork"]); + fs.writeFileSync(path.join(repoDir, "fork.txt"), "fork\n"); + yield* runGit(repoDir, ["add", "fork.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Fork PR branch"]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-fork"]); + yield* runGit(repoDir, ["checkout", "main"]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 81, + title: "Fork PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/81", + baseRefName: "main", + headRefName: "feature/pr-fork", + state: "open", + isCrossRepository: true, + headRepositoryNameWithOwner: "octocat/codething-mvp", + headRepositoryOwnerLogin: "octocat", + }, + repositoryCloneUrls: { + "octocat/codething-mvp": { + url: forkDir, + sshUrl: forkDir, + }, + }, + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "81", + mode: "worktree", + }); + + expect(result.worktreePath).not.toBeNull(); + const upstreamRef = (yield* runGit(result.worktreePath as string, [ + "rev-parse", + "--abbrev-ref", + "@{upstream}", + ])).stdout.trim(); + expect(upstreamRef).toBe("fork-seed/feature/pr-fork"); + expect(upstreamRef.startsWith("origin/")).toBe(false); + expect( + (yield* runGit(result.worktreePath as string, [ + "config", + "--get", + "remote.fork-seed.url", + ])).stdout.trim(), + ).toBe(forkDir); + }), + ); + + it.effect("preserves fork upstream tracking when preparing a local PR thread", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-fork"]); + fs.writeFileSync(path.join(repoDir, "local-fork.txt"), "local fork\n"); + yield* runGit(repoDir, ["add", "local-fork.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Local fork PR branch"]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-local-fork"]); + yield* runGit(repoDir, ["checkout", "main"]); + yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-fork"]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 82, + title: "Local Fork PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/82", + baseRefName: "main", + headRefName: "feature/pr-local-fork", + state: "open", + isCrossRepository: true, + headRepositoryNameWithOwner: "octocat/codething-mvp", + headRepositoryOwnerLogin: "octocat", + }, + repositoryCloneUrls: { + "octocat/codething-mvp": { + url: forkDir, + sshUrl: forkDir, + }, + }, + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "82", + mode: "local", + }); + + expect(result.worktreePath).toBeNull(); + expect(result.branch).toBe("feature/pr-local-fork"); + expect( + (yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(), + ).toBe("fork-seed/feature/pr-local-fork"); + }), + ); + + it.effect("derives fork repository identity from PR URL when GitHub omits nameWithOwner", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["remote", "add", "binbandit-seed", forkDir]); + yield* runGit(repoDir, ["checkout", "-b", "fix/git-action-default-without-origin"]); + fs.writeFileSync(path.join(repoDir, "derived-fork.txt"), "derived fork\n"); + yield* runGit(repoDir, ["add", "derived-fork.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Derived fork PR branch"]); + yield* runGit(repoDir, [ + "push", + "-u", + "binbandit-seed", + "fix/git-action-default-without-origin", + ]); + yield* runGit(repoDir, ["checkout", "main"]); + yield* runGit(repoDir, ["branch", "-D", "fix/git-action-default-without-origin"]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 642, + title: "fix: use commit as the default git action without origin", + url: "https://github.com/pingdotgg/t3code/pull/642", + baseRefName: "main", + headRefName: "fix/git-action-default-without-origin", + state: "open", + isCrossRepository: true, + headRepositoryOwnerLogin: "binbandit", + }, + repositoryCloneUrls: { + "binbandit/t3code": { + url: forkDir, + sshUrl: forkDir, + }, + }, + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "642", + mode: "local", + }); + + expect(result.branch).toBe("fix/git-action-default-without-origin"); + expect(result.worktreePath).toBeNull(); + expect( + (yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(), + ).toBe("binbandit-seed/fix/git-action-default-without-origin"); + }), + ); + + it.effect("reuses an existing dedicated worktree for the PR head branch", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-existing-worktree"]); + fs.writeFileSync(path.join(repoDir, "existing.txt"), "existing\n"); + yield* runGit(repoDir, ["add", "existing.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Existing worktree branch"]); + yield* runGit(repoDir, ["checkout", "main"]); + const worktreePath = path.join(repoDir, "..", `pr-existing-${Date.now()}`); + yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]); + + const setupCalls: ProjectSetupScriptRunnerInput[] = []; + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 78, + title: "Existing worktree PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/78", + baseRefName: "main", + headRefName: "feature/pr-existing-worktree", + state: "open", + }, + }, + setupScriptRunner: { + runForThread: (setupInput) => + Effect.sync(() => { + setupCalls.push(setupInput); + return { status: "no-script" as const }; + }), + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "78", + mode: "worktree", + threadId: asThreadId("thread-pr-existing-worktree"), + }); + + expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe( + fs.realpathSync.native(worktreePath), + ); + expect(result.branch).toBe("feature/pr-existing-worktree"); + expect(setupCalls).toHaveLength(0); + }), + ); + + it.effect( + "does not block fork PR worktree prep when the fork head branch collides with root main", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]); + fs.writeFileSync(path.join(repoDir, "fork-main.txt"), "fork main\n"); + yield* runGit(repoDir, ["add", "fork-main.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Fork main branch"]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]); + yield* runGit(repoDir, ["checkout", "main"]); + const mainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim(); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 91, + title: "Fork main PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/91", + baseRefName: "main", + headRefName: "main", + state: "open", + isCrossRepository: true, + headRepositoryNameWithOwner: "octocat/codething-mvp", + headRepositoryOwnerLogin: "octocat", + }, + repositoryCloneUrls: { + "octocat/codething-mvp": { + url: forkDir, + sshUrl: forkDir, + }, + }, + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "91", + mode: "worktree", + }); + + expect(result.branch).toBe("t3code/pr-91/main"); + expect(result.worktreePath).not.toBeNull(); + expect((yield* runGit(repoDir, ["branch", "--show-current"])).stdout.trim()).toBe("main"); + expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(mainBefore); + expect( + (yield* runGit(result.worktreePath as string, [ + "branch", + "--show-current", + ])).stdout.trim(), + ).toBe("t3code/pr-91/main"); + }), + ); + + it.effect( + "does not overwrite an existing local main branch when preparing a fork PR worktree", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]); + fs.writeFileSync(path.join(repoDir, "fork-main-second.txt"), "fork main second\n"); + yield* runGit(repoDir, ["add", "fork-main-second.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]); + yield* runGit(repoDir, ["checkout", "main"]); + const localMainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim(); + yield* runGit(repoDir, ["checkout", "-b", "feature/root-branch"]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 92, + title: "Fork main overwrite PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/92", + baseRefName: "main", + headRefName: "main", + state: "open", + isCrossRepository: true, + headRepositoryNameWithOwner: "octocat/codething-mvp", + headRepositoryOwnerLogin: "octocat", + }, + repositoryCloneUrls: { + "octocat/codething-mvp": { + url: forkDir, + sshUrl: forkDir, + }, + }, + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "92", + mode: "worktree", + }); + + expect(result.branch).toBe("t3code/pr-92/main"); + expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(localMainBefore); + expect( + (yield* runGit(result.worktreePath as string, [ + "rev-parse", + "--abbrev-ref", + "@{upstream}", + ])).stdout.trim(), + ).toBe("fork-seed/main"); + }), + ); + + it.effect("reuses an existing PR worktree and restores fork upstream tracking", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-reused-fork"]); + fs.writeFileSync(path.join(repoDir, "reused-fork.txt"), "reused fork\n"); + yield* runGit(repoDir, ["add", "reused-fork.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Reused fork PR branch"]); + yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-reused-fork"]); + yield* runGit(repoDir, ["checkout", "main"]); + const worktreePath = path.join(repoDir, "..", `pr-reused-fork-${Date.now()}`); + yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-fork"]); + yield* runGit(worktreePath, ["branch", "--unset-upstream"], true); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 83, + title: "Reused Fork PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/83", + baseRefName: "main", + headRefName: "feature/pr-reused-fork", + state: "open", + isCrossRepository: true, + headRepositoryNameWithOwner: "octocat/codething-mvp", + headRepositoryOwnerLogin: "octocat", + }, + repositoryCloneUrls: { + "octocat/codething-mvp": { + url: forkDir, + sshUrl: forkDir, + }, + }, + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "83", + mode: "worktree", + }); + + expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe( + fs.realpathSync.native(worktreePath), + ); + expect( + (yield* runGit(worktreePath, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(), + ).toBe("fork-seed/feature/pr-reused-fork"); + }), + ); + + it.effect("does not fail PR worktree prep when setup terminal startup fails", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-setup-failure"]); + fs.writeFileSync(path.join(repoDir, "setup-failure.txt"), "setup failure\n"); + yield* runGit(repoDir, ["add", "setup-failure.txt"]); + yield* runGit(repoDir, ["commit", "-m", "PR setup failure branch"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-setup-failure"]); + yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/184/head"]); + yield* runGit(repoDir, ["checkout", "main"]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 184, + title: "Setup failure PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/184", + baseRefName: "main", + headRefName: "feature/pr-setup-failure", + state: "open", + }, + }, + setupScriptRunner: { + runForThread: () => Effect.fail(new Error("terminal start failed")), + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "184", + mode: "worktree", + threadId: asThreadId("thread-pr-setup-failure"), + }); + + expect(result.branch).toBe("feature/pr-setup-failure"); + expect(result.worktreePath).not.toBeNull(); + expect(fs.existsSync(result.worktreePath as string)).toBe(true); + }), + ); + + it.effect("rejects worktree prep when the PR head branch is checked out in the main repo", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-root-only"]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 79, + title: "Root-only PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/79", + baseRefName: "main", + headRefName: "feature/pr-root-only", + state: "open", + }, + }, + }); + + const errorMessage = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "79", + mode: "worktree", + }).pipe( + Effect.flip, + Effect.map((error) => error.message), + ); + + expect(errorMessage).toContain("already checked out in the main repo"); + }), + ); + + it.effect("emits ordered progress events for commit hooks", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + fs.writeFileSync(path.join(repoDir, "hooked.txt"), "hooked\n"); + fs.writeFileSync( + path.join(repoDir, ".git", "hooks", "pre-commit"), + '#!/bin/sh\necho "hook: start" >&2\nsleep 1\necho "hook: end" >&2\n', + { mode: 0o755 }, + ); + + const { manager } = yield* makeManager(); + const events: GitActionProgressEvent[] = []; + + const result = yield* runStackedAction( + manager, + { + cwd: repoDir, + action: "commit", + }, + { + actionId: "action-1", + progressReporter: { + publish: (event) => + Effect.sync(() => { + events.push(event); + }), + }, + }, + ); + + expect(result.commit.status).toBe("created"); + expect(events.map((event) => event.kind)).toContain("action_started"); + expect(events).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "phase_started", + phase: "commit", + }), + expect.objectContaining({ + kind: "hook_started", + hookName: "pre-commit", + }), + expect.objectContaining({ + kind: "hook_output", + text: "hook: start", + }), + expect.objectContaining({ + kind: "hook_output", + text: "hook: end", + }), + expect.objectContaining({ + kind: "hook_finished", + hookName: "pre-commit", + }), + expect.objectContaining({ + kind: "action_finished", + }), + ]), + ); + }), + ); + + it.effect("emits action_failed when a commit hook rejects", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + fs.writeFileSync(path.join(repoDir, "hook-failure.txt"), "broken\n"); + fs.writeFileSync( + path.join(repoDir, ".git", "hooks", "pre-commit"), + '#!/bin/sh\necho "hook: fail" >&2\nexit 1\n', + { mode: 0o755 }, + ); + + const { manager } = yield* makeManager(); + const events: GitActionProgressEvent[] = []; + + const errorMessage = yield* runStackedAction( + manager, + { + cwd: repoDir, + action: "commit", + }, + { + actionId: "action-2", + progressReporter: { + publish: (event) => + Effect.sync(() => { + events.push(event); + }), + }, + }, + ).pipe( + Effect.flip, + Effect.map((error) => error.message), + ); + + expect(errorMessage).toContain("hook: fail"); + expect(events).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "hook_started", + hookName: "pre-commit", + }), + expect.objectContaining({ + kind: "action_failed", + phase: "commit", + }), + ]), + ); + }), + ); + + it.effect("create_pr emits only the PR phase when the branch is already pushed", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-only-follow-up"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "pr-only.txt"), "pr only\n"); + yield* runGit(repoDir, ["add", "pr-only.txt"]); + yield* runGit(repoDir, ["commit", "-m", "PR only branch"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-only-follow-up"]); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([]), + JSON.stringify([ + { + number: 201, + title: "PR only branch", + url: "https://github.com/pingdotgg/codething-mvp/pull/201", + baseRefName: "main", + headRefName: "feature/pr-only-follow-up", + state: "OPEN", + isCrossRepository: false, + }, + ]), + ], + }, + }); + const events: GitActionProgressEvent[] = []; + + const result = yield* runStackedAction( + manager, + { + cwd: repoDir, + action: "create_pr", + }, + { + actionId: "action-pr-only", + progressReporter: { + publish: (event) => + Effect.sync(() => { + events.push(event); + }), + }, + }, + ); + + expect(result.commit.status).toBe("skipped_not_requested"); + expect(result.push.status).toBe("skipped_not_requested"); + expect(result.pr.status).toBe("created"); + expect( + events.filter( + (event): event is Extract => + event.kind === "phase_started", + ), + ).toEqual([ + expect.objectContaining({ + kind: "phase_started", + phase: "pr", + label: "Preparing PR...", + }), + expect.objectContaining({ + kind: "phase_started", + phase: "pr", + label: "Generating PR content...", + }), + expect.objectContaining({ + kind: "phase_started", + phase: "pr", + label: "Creating GitHub pull request...", + }), + ]); + }), + ); +}); diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.ts new file mode 100644 index 0000000000..7fedb15714 --- /dev/null +++ b/apps/server/src/git/Layers/GitManager.ts @@ -0,0 +1,1717 @@ +import { randomUUID } from "node:crypto"; +import { realpathSync } from "node:fs"; + +import { Cache, Duration, Effect, Exit, FileSystem, Layer, Option, Path, Ref } from "effect"; +import { + GitActionProgressEvent, + GitActionProgressPhase, + GitCommandError, + GitRunStackedActionResult, + GitStackedAction, + ModelSelection, +} from "@t3tools/contracts"; +import { + resolveAutoFeatureBranchName, + sanitizeBranchFragment, + sanitizeFeatureBranchName, +} from "@t3tools/shared/git"; + +import { GitManagerError } from "@t3tools/contracts"; +import { + GitManager, + type GitActionProgressReporter, + type GitManagerShape, + type GitRunStackedActionOptions, +} from "../Services/GitManager.ts"; +import { GitCore, GitStatusDetails } from "../Services/GitCore.ts"; +import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts"; +import { TextGeneration } from "../Services/TextGeneration.ts"; +import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts"; +import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import type { GitManagerServiceError } from "@t3tools/contracts"; + +const COMMIT_TIMEOUT_MS = 10 * 60_000; +const MAX_PROGRESS_TEXT_LENGTH = 500; +const SHORT_SHA_LENGTH = 7; +const TOAST_DESCRIPTION_MAX = 72; +const STATUS_RESULT_CACHE_TTL = Duration.seconds(1); +const STATUS_RESULT_CACHE_CAPACITY = 2_048; +type StripProgressContext = T extends any ? Omit : never; +type GitActionProgressPayload = StripProgressContext; +type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect; + +function isNotGitRepositoryError(error: GitCommandError): boolean { + return error.message.toLowerCase().includes("not a git repository"); +} + +interface OpenPrInfo { + number: number; + title: string; + url: string; + baseRefName: string; + headRefName: string; +} + +interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo { + state: "open" | "closed" | "merged"; + updatedAt: string | null; +} + +interface ResolvedPullRequest { + number: number; + title: string; + url: string; + baseBranch: string; + headBranch: string; + state: "open" | "closed" | "merged"; +} + +interface PullRequestHeadRemoteInfo { + isCrossRepository?: boolean; + headRepositoryNameWithOwner?: string | null; + headRepositoryOwnerLogin?: string | null; +} + +interface BranchHeadContext { + localBranch: string; + headBranch: string; + headSelectors: ReadonlyArray; + preferredHeadSelector: string; + remoteName: string | null; + headRepositoryNameWithOwner: string | null; + headRepositoryOwnerLogin: string | null; + isCrossRepository: boolean; +} + +function parseRepositoryNameFromPullRequestUrl(url: string): string | null { + const trimmed = url.trim(); + const match = /^https:\/\/github\.com\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed); + const repositoryName = match?.[1]?.trim() ?? ""; + return repositoryName.length > 0 ? repositoryName : null; +} + +function resolveHeadRepositoryNameWithOwner( + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, +): string | null { + const explicitRepository = pullRequest.headRepositoryNameWithOwner?.trim() ?? ""; + if (explicitRepository.length > 0) { + return explicitRepository; + } + + if (!pullRequest.isCrossRepository) { + return null; + } + + const ownerLogin = pullRequest.headRepositoryOwnerLogin?.trim() ?? ""; + const repositoryName = parseRepositoryNameFromPullRequestUrl(pullRequest.url); + if (ownerLogin.length === 0 || !repositoryName) { + return null; + } + + return `${ownerLogin}/${repositoryName}`; +} + +function resolvePullRequestWorktreeLocalBranchName( + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, +): string { + if (!pullRequest.isCrossRepository) { + return pullRequest.headBranch; + } + + const sanitizedHeadBranch = sanitizeBranchFragment(pullRequest.headBranch).trim(); + const suffix = sanitizedHeadBranch.length > 0 ? sanitizedHeadBranch : "head"; + return `t3code/pr-${pullRequest.number}/${suffix}`; +} + +function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null { + const trimmed = url?.trim() ?? ""; + if (trimmed.length === 0) { + return null; + } + + const match = + /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec( + trimmed, + ); + const repositoryNameWithOwner = match?.[1]?.trim() ?? ""; + return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null; +} + +function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null { + const trimmed = nameWithOwner?.trim() ?? ""; + if (trimmed.length === 0) { + return null; + } + const [ownerLogin] = trimmed.split("/"); + const normalizedOwnerLogin = ownerLogin?.trim() ?? ""; + return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null; +} + +function normalizeOptionalString(value: string | null | undefined): string | null { + const trimmed = value?.trim() ?? ""; + return trimmed.length > 0 ? trimmed : null; +} + +function normalizeOptionalRepositoryNameWithOwner(value: string | null | undefined): string | null { + const normalized = normalizeOptionalString(value); + return normalized ? normalized.toLowerCase() : null; +} + +function normalizeOptionalOwnerLogin(value: string | null | undefined): string | null { + const normalized = normalizeOptionalString(value); + return normalized ? normalized.toLowerCase() : null; +} + +function resolvePullRequestHeadRepositoryNameWithOwner( + pr: PullRequestHeadRemoteInfo & { url: string }, +) { + const explicitRepository = normalizeOptionalString(pr.headRepositoryNameWithOwner); + if (explicitRepository) { + return explicitRepository; + } + + if (!pr.isCrossRepository) { + return null; + } + + const ownerLogin = normalizeOptionalString(pr.headRepositoryOwnerLogin); + const repositoryName = parseRepositoryNameFromPullRequestUrl(pr.url); + if (!ownerLogin || !repositoryName) { + return null; + } + + return `${ownerLogin}/${repositoryName}`; +} + +function matchesBranchHeadContext( + pr: PullRequestInfo, + headContext: Pick< + BranchHeadContext, + "headBranch" | "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin" | "isCrossRepository" + >, +): boolean { + if (pr.headRefName !== headContext.headBranch) { + return false; + } + + const expectedHeadRepository = normalizeOptionalRepositoryNameWithOwner( + headContext.headRepositoryNameWithOwner, + ); + const expectedHeadOwner = + normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ?? + parseRepositoryOwnerLogin(expectedHeadRepository); + const prHeadRepository = normalizeOptionalRepositoryNameWithOwner( + resolvePullRequestHeadRepositoryNameWithOwner(pr), + ); + const prHeadOwner = + normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ?? + parseRepositoryOwnerLogin(prHeadRepository); + + if (headContext.isCrossRepository) { + if (pr.isCrossRepository === false) { + return false; + } + if ((expectedHeadRepository || expectedHeadOwner) && !prHeadRepository && !prHeadOwner) { + return false; + } + if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) { + return false; + } + if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) { + return false; + } + return true; + } + + if (pr.isCrossRepository === true) { + return false; + } + if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) { + return false; + } + if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) { + return false; + } + return true; +} + +function parsePullRequestList(raw: unknown): PullRequestInfo[] { + if (!Array.isArray(raw)) return []; + + const parsed: PullRequestInfo[] = []; + for (const entry of raw) { + if (!entry || typeof entry !== "object") continue; + const record = entry as Record; + const number = record.number; + const title = record.title; + const url = record.url; + const baseRefName = record.baseRefName; + const headRefName = record.headRefName; + const state = record.state; + const mergedAt = record.mergedAt; + const updatedAt = record.updatedAt; + const isCrossRepository = record.isCrossRepository; + const headRepositoryRecord = + typeof record.headRepository === "object" && record.headRepository !== null + ? (record.headRepository as Record) + : null; + const headRepositoryOwnerRecord = + typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null + ? (record.headRepositoryOwner as Record) + : null; + const headRepositoryNameWithOwner = + typeof record.headRepositoryNameWithOwner === "string" + ? record.headRepositoryNameWithOwner + : typeof headRepositoryRecord?.nameWithOwner === "string" + ? headRepositoryRecord.nameWithOwner + : null; + const headRepositoryOwnerLogin = + typeof record.headRepositoryOwnerLogin === "string" + ? record.headRepositoryOwnerLogin + : typeof headRepositoryOwnerRecord?.login === "string" + ? headRepositoryOwnerRecord.login + : null; + if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) { + continue; + } + if ( + typeof title !== "string" || + typeof url !== "string" || + typeof baseRefName !== "string" || + typeof headRefName !== "string" + ) { + continue; + } + + let normalizedState: "open" | "closed" | "merged"; + if ( + (typeof mergedAt === "string" && mergedAt.trim().length > 0) || + state === "MERGED" || + state === "merged" + ) { + normalizedState = "merged"; + } else if (state === "OPEN" || state === "open" || state === undefined || state === null) { + normalizedState = "open"; + } else if (state === "CLOSED" || state === "closed") { + normalizedState = "closed"; + } else { + continue; + } + + parsed.push({ + number, + title, + url, + baseRefName, + headRefName, + state: normalizedState, + updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null, + ...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}), + ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + }); + } + return parsed; +} + +function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo { + return { + number: summary.number, + title: summary.title, + url: summary.url, + baseRefName: summary.baseRefName, + headRefName: summary.headRefName, + state: summary.state ?? "open", + updatedAt: null, + ...(summary.isCrossRepository !== undefined + ? { isCrossRepository: summary.isCrossRepository } + : {}), + ...(summary.headRepositoryNameWithOwner !== undefined + ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner } + : {}), + ...(summary.headRepositoryOwnerLogin !== undefined + ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin } + : {}), + }; +} + +function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError { + return new GitManagerError({ + operation, + detail, + ...(cause !== undefined ? { cause } : {}), + }); +} + +function limitContext(value: string, maxChars: number): string { + if (value.length <= maxChars) return value; + return `${value.slice(0, maxChars)}\n\n[truncated]`; +} + +function shortenSha(sha: string | undefined): string | null { + if (!sha) return null; + return sha.slice(0, SHORT_SHA_LENGTH); +} + +function truncateText( + value: string | undefined, + maxLength = TOAST_DESCRIPTION_MAX, +): string | undefined { + if (!value) return undefined; + if (value.length <= maxLength) return value; + if (maxLength <= 3) return "...".slice(0, maxLength); + return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`; +} + +function withDescription(title: string, description: string | undefined) { + return description ? { title, description } : { title }; +} + +function summarizeGitActionResult( + result: Pick, +): { + title: string; + description?: string; +} { + if (result.pr.status === "created" || result.pr.status === "opened_existing") { + const prNumber = result.pr.number ? ` #${result.pr.number}` : ""; + const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`; + return withDescription(title, truncateText(result.pr.title)); + } + + if (result.push.status === "pushed") { + const shortSha = shortenSha(result.commit.commitSha); + const branch = result.push.upstreamBranch ?? result.push.branch; + const pushedCommitPart = shortSha ? ` ${shortSha}` : ""; + const branchPart = branch ? ` to ${branch}` : ""; + return withDescription( + `Pushed${pushedCommitPart}${branchPart}`, + truncateText(result.commit.subject), + ); + } + + if (result.commit.status === "created") { + const shortSha = shortenSha(result.commit.commitSha); + const title = shortSha ? `Committed ${shortSha}` : "Committed changes"; + return withDescription(title, truncateText(result.commit.subject)); + } + + return { title: "Done" }; +} + +function sanitizeCommitMessage(generated: { + subject: string; + body: string; + branch?: string | undefined; +}): { + subject: string; + body: string; + branch?: string | undefined; +} { + const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? ""; + const subject = rawSubject.replace(/[.]+$/g, "").trim(); + const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files"; + return { + subject: safeSubject, + body: generated.body.trim(), + ...(generated.branch !== undefined ? { branch: generated.branch } : {}), + }; +} + +function sanitizeProgressText(value: string): string | null { + const trimmed = value.trim(); + if (trimmed.length === 0) { + return null; + } + if (trimmed.length <= MAX_PROGRESS_TEXT_LENGTH) { + return trimmed; + } + return trimmed.slice(0, MAX_PROGRESS_TEXT_LENGTH).trimEnd(); +} + +interface CommitAndBranchSuggestion { + subject: string; + body: string; + branch?: string | undefined; + commitMessage: string; +} + +function isCommitAction( + action: GitStackedAction, +): action is "commit" | "commit_push" | "commit_push_pr" { + return action === "commit" || action === "commit_push" || action === "commit_push_pr"; +} + +function formatCommitMessage(subject: string, body: string): string { + const trimmedBody = body.trim(); + if (trimmedBody.length === 0) { + return subject; + } + return `${subject}\n\n${trimmedBody}`; +} + +function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null { + const normalized = raw.replace(/\r\n/g, "\n").trim(); + if (normalized.length === 0) { + return null; + } + + const [firstLine, ...rest] = normalized.split("\n"); + const subject = firstLine?.trim() ?? ""; + if (subject.length === 0) { + return null; + } + + return { + subject, + body: rest.join("\n").trim(), + }; +} + +function appendUnique(values: string[], next: string | null | undefined): void { + const trimmed = next?.trim() ?? ""; + if (trimmed.length === 0 || values.includes(trimmed)) { + return; + } + values.push(trimmed); +} + +function toStatusPr(pr: PullRequestInfo): { + number: number; + title: string; + url: string; + baseBranch: string; + headBranch: string; + state: "open" | "closed" | "merged"; +} { + return { + number: pr.number, + title: pr.title, + url: pr.url, + baseBranch: pr.baseRefName, + headBranch: pr.headRefName, + state: pr.state, + }; +} + +function normalizePullRequestReference(reference: string): string { + const trimmed = reference.trim(); + const hashNumber = /^#(\d+)$/.exec(trimmed); + return hashNumber?.[1] ?? trimmed; +} + +function canonicalizeExistingPath(value: string): string { + try { + return realpathSync.native(value); + } catch { + return value; + } +} + +function toResolvedPullRequest(pr: { + number: number; + title: string; + url: string; + baseRefName: string; + headRefName: string; + state?: "open" | "closed" | "merged"; +}): ResolvedPullRequest { + return { + number: pr.number, + title: pr.title, + url: pr.url, + baseBranch: pr.baseRefName, + headBranch: pr.headRefName, + state: pr.state ?? "open", + }; +} + +function shouldPreferSshRemote(url: string | null): boolean { + if (!url) return false; + const trimmed = url.trim(); + return trimmed.startsWith("git@") || trimmed.startsWith("ssh://"); +} + +function toPullRequestHeadRemoteInfo(pr: { + isCrossRepository?: boolean; + headRepositoryNameWithOwner?: string | null; + headRepositoryOwnerLogin?: string | null; +}): PullRequestHeadRemoteInfo { + return { + ...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}), + ...(pr.headRepositoryNameWithOwner !== undefined + ? { headRepositoryNameWithOwner: pr.headRepositoryNameWithOwner } + : {}), + ...(pr.headRepositoryOwnerLogin !== undefined + ? { headRepositoryOwnerLogin: pr.headRepositoryOwnerLogin } + : {}), + }; +} + +export const makeGitManager = Effect.fn("makeGitManager")(function* () { + const gitCore = yield* GitCore; + const gitHubCli = yield* GitHubCli; + const textGeneration = yield* TextGeneration; + const projectSetupScriptRunner = yield* ProjectSetupScriptRunner; + const serverSettingsService = yield* ServerSettingsService; + + const createProgressEmitter = ( + input: { cwd: string; action: GitStackedAction }, + options?: GitRunStackedActionOptions, + ) => { + const actionId = options?.actionId ?? randomUUID(); + const reporter = options?.progressReporter; + + const emit = (event: GitActionProgressPayload) => + reporter + ? reporter.publish({ + actionId, + cwd: input.cwd, + action: input.action, + ...event, + } as GitActionProgressEvent) + : Effect.void; + + return { + actionId, + emit, + }; + }; + + const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")( + function* ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) { + const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? ""; + if (repositoryNameWithOwner.length === 0) { + return; + } + + const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({ + cwd, + repository: repositoryNameWithOwner, + }); + const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url"); + const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url; + const preferredRemoteName = + pullRequest.headRepositoryOwnerLogin?.trim() || + repositoryNameWithOwner.split("/")[0]?.trim() || + "fork"; + const remoteName = yield* gitCore.ensureRemote({ + cwd, + preferredName: preferredRemoteName, + url: remoteUrl, + }); + + yield* gitCore.setBranchUpstream({ + cwd, + branch: localBranch, + remoteName, + remoteBranch: pullRequest.headBranch, + }); + }, + ); + + const configurePullRequestHeadUpstream = ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) => + configurePullRequestHeadUpstreamBase(cwd, pullRequest, localBranch).pipe( + Effect.catch((error) => + Effect.logWarning( + `GitManager.configurePullRequestHeadUpstream: failed to configure upstream for ${localBranch} -> ${pullRequest.headBranch} in ${cwd}: ${error.message}`, + ).pipe(Effect.asVoid), + ), + ); + + const materializePullRequestHeadBranchBase = Effect.fn("materializePullRequestHeadBranch")( + function* ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) { + const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? ""; + + if (repositoryNameWithOwner.length === 0) { + yield* gitCore.fetchPullRequestBranch({ + cwd, + prNumber: pullRequest.number, + branch: localBranch, + }); + return; + } + + const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({ + cwd, + repository: repositoryNameWithOwner, + }); + const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url"); + const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url; + const preferredRemoteName = + pullRequest.headRepositoryOwnerLogin?.trim() || + repositoryNameWithOwner.split("/")[0]?.trim() || + "fork"; + const remoteName = yield* gitCore.ensureRemote({ + cwd, + preferredName: preferredRemoteName, + url: remoteUrl, + }); + + yield* gitCore.fetchRemoteBranch({ + cwd, + remoteName, + remoteBranch: pullRequest.headBranch, + localBranch, + }); + yield* gitCore.setBranchUpstream({ + cwd, + branch: localBranch, + remoteName, + remoteBranch: pullRequest.headBranch, + }); + }, + ); + + const materializePullRequestHeadBranch = ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) => + materializePullRequestHeadBranchBase(cwd, pullRequest, localBranch).pipe( + Effect.catch(() => + gitCore.fetchPullRequestBranch({ + cwd, + prNumber: pullRequest.number, + branch: localBranch, + }), + ), + ); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp"; + const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd); + const readStatus = Effect.fn("readStatus")(function* (cwd: string) { + const details = yield* gitCore.statusDetails(cwd).pipe( + Effect.catchIf(isNotGitRepositoryError, () => + Effect.succeed({ + isRepo: false, + hasOriginRemote: false, + isDefaultBranch: false, + branch: null, + upstreamRef: null, + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + } satisfies GitStatusDetails), + ), + ); + + const pr = + details.isRepo && details.branch !== null + ? yield* findLatestPr(cwd, { + branch: details.branch, + upstreamRef: details.upstreamRef, + }).pipe( + Effect.map((latest) => (latest ? toStatusPr(latest) : null)), + Effect.catch(() => Effect.succeed(null)), + ) + : null; + + return { + isRepo: details.isRepo, + hasOriginRemote: details.hasOriginRemote, + isDefaultBranch: details.isDefaultBranch, + branch: details.branch, + hasWorkingTreeChanges: details.hasWorkingTreeChanges, + workingTree: details.workingTree, + hasUpstream: details.hasUpstream, + aheadCount: details.aheadCount, + behindCount: details.behindCount, + pr, + }; + }); + const statusResultCache = yield* Cache.makeWith({ + capacity: STATUS_RESULT_CACHE_CAPACITY, + lookup: readStatus, + timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero), + }); + const invalidateStatusResultCache = (cwd: string) => + Cache.invalidate(statusResultCache, normalizeStatusCacheKey(cwd)); + + const readConfigValueNullable = (cwd: string, key: string) => + gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null))); + + const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* ( + cwd: string, + remoteName: string | null, + ) { + if (!remoteName) { + return { + repositoryNameWithOwner: null, + ownerLogin: null, + }; + } + + const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`); + const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl); + return { + repositoryNameWithOwner, + ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner), + }; + }); + + const resolveBranchHeadContext = Effect.fn("resolveBranchHeadContext")(function* ( + cwd: string, + details: { branch: string; upstreamRef: string | null }, + ) { + const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`); + const headBranchFromUpstream = details.upstreamRef + ? extractBranchNameFromRemoteRef(details.upstreamRef, { remoteName }) + : ""; + const headBranch = headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch; + const shouldProbeLocalBranchSelector = + headBranchFromUpstream.length === 0 || headBranch === details.branch; + + const [remoteRepository, originRepository] = yield* Effect.all( + [ + resolveRemoteRepositoryContext(cwd, remoteName), + resolveRemoteRepositoryContext(cwd, "origin"), + ], + { concurrency: "unbounded" }, + ); + + const isCrossRepository = + remoteRepository.repositoryNameWithOwner !== null && + originRepository.repositoryNameWithOwner !== null + ? remoteRepository.repositoryNameWithOwner.toLowerCase() !== + originRepository.repositoryNameWithOwner.toLowerCase() + : remoteName !== null && + remoteName !== "origin" && + remoteRepository.repositoryNameWithOwner !== null; + + const ownerHeadSelector = + remoteRepository.ownerLogin && headBranch.length > 0 + ? `${remoteRepository.ownerLogin}:${headBranch}` + : null; + const remoteAliasHeadSelector = + remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null; + const shouldProbeRemoteOwnedSelectors = + isCrossRepository || (remoteName !== null && remoteName !== "origin"); + + const headSelectors: string[] = []; + if (isCrossRepository && shouldProbeRemoteOwnedSelectors) { + appendUnique(headSelectors, ownerHeadSelector); + appendUnique( + headSelectors, + remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, + ); + } + if (shouldProbeLocalBranchSelector) { + appendUnique(headSelectors, details.branch); + } + appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null); + if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) { + appendUnique(headSelectors, ownerHeadSelector); + appendUnique( + headSelectors, + remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, + ); + } + + return { + localBranch: details.branch, + headBranch, + headSelectors, + preferredHeadSelector: + ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch, + remoteName, + headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner, + headRepositoryOwnerLogin: remoteRepository.ownerLogin, + isCrossRepository, + } satisfies BranchHeadContext; + }); + + const findOpenPr = Effect.fn("findOpenPr")(function* ( + cwd: string, + headContext: Pick< + BranchHeadContext, + | "headBranch" + | "headSelectors" + | "headRepositoryNameWithOwner" + | "headRepositoryOwnerLogin" + | "isCrossRepository" + >, + ) { + for (const headSelector of headContext.headSelectors) { + const pullRequests = yield* gitHubCli.listOpenPullRequests({ + cwd, + headSelector, + limit: 1, + }); + const normalizedPullRequests = pullRequests.map(toPullRequestInfo); + + const firstPullRequest = normalizedPullRequests.find((pullRequest) => + matchesBranchHeadContext(pullRequest, headContext), + ); + if (firstPullRequest) { + return { + number: firstPullRequest.number, + title: firstPullRequest.title, + url: firstPullRequest.url, + baseRefName: firstPullRequest.baseRefName, + headRefName: firstPullRequest.headRefName, + state: "open", + updatedAt: null, + } satisfies PullRequestInfo; + } + } + + return null; + }); + + const findLatestPr = Effect.fn("findLatestPr")(function* ( + cwd: string, + details: { branch: string; upstreamRef: string | null }, + ) { + const headContext = yield* resolveBranchHeadContext(cwd, details); + const parsedByNumber = new Map(); + + for (const headSelector of headContext.headSelectors) { + const stdout = yield* gitHubCli + .execute({ + cwd, + args: [ + "pr", + "list", + "--head", + headSelector, + "--state", + "all", + "--limit", + "20", + "--json", + "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner", + ], + }) + .pipe(Effect.map((result) => result.stdout)); + + const raw = stdout.trim(); + if (raw.length === 0) { + continue; + } + + const parsedJson = yield* Effect.try({ + try: () => JSON.parse(raw) as unknown, + catch: (cause) => + gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause), + }); + + for (const pr of parsePullRequestList(parsedJson)) { + if (!matchesBranchHeadContext(pr, headContext)) { + continue; + } + parsedByNumber.set(pr.number, pr); + } + } + + const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => { + const left = a.updatedAt ? Date.parse(a.updatedAt) : 0; + const right = b.updatedAt ? Date.parse(b.updatedAt) : 0; + return right - left; + }); + + const latestOpenPr = parsed.find((pr) => pr.state === "open"); + if (latestOpenPr) { + return latestOpenPr; + } + return parsed[0] ?? null; + }); + + const buildCompletionToast = Effect.fn("buildCompletionToast")(function* ( + cwd: string, + result: Pick, + ) { + const summary = summarizeGitActionResult(result); + let latestOpenPr: PullRequestInfo | null = null; + let currentBranchIsDefault = false; + let finalBranchContext: { + branch: string; + upstreamRef: string | null; + hasUpstream: boolean; + } | null = null; + + if (result.action !== "commit") { + const finalStatus = yield* gitCore.statusDetails(cwd); + if (finalStatus.branch) { + finalBranchContext = { + branch: finalStatus.branch, + upstreamRef: finalStatus.upstreamRef, + hasUpstream: finalStatus.hasUpstream, + }; + currentBranchIsDefault = finalStatus.isDefaultBranch; + } + } + + const explicitResultPr = + (result.pr.status === "created" || result.pr.status === "opened_existing") && result.pr.url + ? { + url: result.pr.url, + state: "open" as const, + } + : null; + const shouldLookupExistingOpenPr = + (result.action === "commit_push" || result.action === "push") && + result.push.status === "pushed" && + result.branch.status !== "created" && + !currentBranchIsDefault && + explicitResultPr === null && + finalBranchContext?.hasUpstream === true; + + if (shouldLookupExistingOpenPr && finalBranchContext) { + latestOpenPr = yield* resolveBranchHeadContext(cwd, { + branch: finalBranchContext.branch, + upstreamRef: finalBranchContext.upstreamRef, + }).pipe( + Effect.flatMap((headContext) => findOpenPr(cwd, headContext)), + Effect.catch(() => Effect.succeed(null)), + ); + } + + const openPr = latestOpenPr ?? explicitResultPr; + + const cta = + result.action === "commit" && result.commit.status === "created" + ? { + kind: "run_action" as const, + label: "Push", + action: { kind: "push" as const }, + } + : (result.action === "push" || + result.action === "create_pr" || + result.action === "commit_push" || + result.action === "commit_push_pr") && + openPr?.url && + (!currentBranchIsDefault || + result.pr.status === "created" || + result.pr.status === "opened_existing") + ? { + kind: "open_pr" as const, + label: "View PR", + url: openPr.url, + } + : (result.action === "push" || result.action === "commit_push") && + result.push.status === "pushed" && + !currentBranchIsDefault + ? { + kind: "run_action" as const, + label: "Create PR", + action: { kind: "create_pr" as const }, + } + : { + kind: "none" as const, + }; + + return { + ...summary, + cta, + }; + }); + + const resolveBaseBranch = Effect.fn("resolveBaseBranch")(function* ( + cwd: string, + branch: string, + upstreamRef: string | null, + headContext: Pick, + ) { + const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`); + if (configured) return configured; + + if (upstreamRef && !headContext.isCrossRepository) { + const upstreamBranch = extractBranchNameFromRemoteRef(upstreamRef, { + remoteName: headContext.remoteName, + }); + if (upstreamBranch.length > 0 && upstreamBranch !== branch) { + return upstreamBranch; + } + } + + const defaultFromGh = yield* gitHubCli + .getDefaultBranch({ cwd }) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (defaultFromGh) { + return defaultFromGh; + } + + return "main"; + }); + + const resolveCommitAndBranchSuggestion = Effect.fn("resolveCommitAndBranchSuggestion")( + function* (input: { + cwd: string; + branch: string | null; + commitMessage?: string; + /** When true, also produce a semantic feature branch name. */ + includeBranch?: boolean; + filePaths?: readonly string[]; + modelSelection: ModelSelection; + }) { + const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths); + if (!context) { + return null; + } + + const customCommit = parseCustomCommitMessage(input.commitMessage ?? ""); + if (customCommit) { + return { + subject: customCommit.subject, + body: customCommit.body, + ...(input.includeBranch + ? { branch: sanitizeFeatureBranchName(customCommit.subject) } + : {}), + commitMessage: formatCommitMessage(customCommit.subject, customCommit.body), + }; + } + + const generated = yield* textGeneration + .generateCommitMessage({ + cwd: input.cwd, + branch: input.branch, + stagedSummary: limitContext(context.stagedSummary, 8_000), + stagedPatch: limitContext(context.stagedPatch, 50_000), + ...(input.includeBranch ? { includeBranch: true } : {}), + modelSelection: input.modelSelection, + }) + .pipe(Effect.map((result) => sanitizeCommitMessage(result))); + + return { + subject: generated.subject, + body: generated.body, + ...(generated.branch !== undefined ? { branch: generated.branch } : {}), + commitMessage: formatCommitMessage(generated.subject, generated.body), + }; + }, + ); + + const runCommitStep = Effect.fn("runCommitStep")(function* ( + modelSelection: ModelSelection, + cwd: string, + action: "commit" | "commit_push" | "commit_push_pr", + branch: string | null, + commitMessage?: string, + preResolvedSuggestion?: CommitAndBranchSuggestion, + filePaths?: readonly string[], + progressReporter?: GitActionProgressReporter, + actionId?: string, + ) { + const emit = (event: GitActionProgressPayload) => + progressReporter && actionId + ? progressReporter.publish({ + actionId, + cwd, + action, + ...event, + } as GitActionProgressEvent) + : Effect.void; + + let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion; + if (!suggestion) { + const needsGeneration = !commitMessage?.trim(); + if (needsGeneration) { + yield* emit({ + kind: "phase_started", + phase: "commit", + label: "Generating commit message...", + }); + } + suggestion = yield* resolveCommitAndBranchSuggestion({ + cwd, + branch, + ...(commitMessage ? { commitMessage } : {}), + ...(filePaths ? { filePaths } : {}), + modelSelection, + }); + } + if (!suggestion) { + return { status: "skipped_no_changes" as const }; + } + + yield* emit({ + kind: "phase_started", + phase: "commit", + label: "Committing...", + }); + + let currentHookName: string | null = null; + const commitProgress = + progressReporter && actionId + ? { + onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => { + const sanitized = sanitizeProgressText(text); + if (!sanitized) { + return Effect.void; + } + return emit({ + kind: "hook_output", + hookName: currentHookName, + stream, + text: sanitized, + }); + }, + onHookStarted: (hookName: string) => { + currentHookName = hookName; + return emit({ + kind: "hook_started", + hookName, + }); + }, + onHookFinished: ({ + hookName, + exitCode, + durationMs, + }: { + hookName: string; + exitCode: number | null; + durationMs: number | null; + }) => { + if (currentHookName === hookName) { + currentHookName = null; + } + return emit({ + kind: "hook_finished", + hookName, + exitCode, + durationMs, + }); + }, + } + : null; + const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, { + timeoutMs: COMMIT_TIMEOUT_MS, + ...(commitProgress ? { progress: commitProgress } : {}), + }); + if (currentHookName !== null) { + yield* emit({ + kind: "hook_finished", + hookName: currentHookName, + exitCode: 0, + durationMs: null, + }); + currentHookName = null; + } + return { + status: "created" as const, + commitSha, + subject: suggestion.subject, + }; + }); + + const runPrStep = Effect.fn("runPrStep")(function* ( + modelSelection: ModelSelection, + cwd: string, + fallbackBranch: string | null, + emit: GitActionProgressEmitter, + ) { + const details = yield* gitCore.statusDetails(cwd); + const branch = details.branch ?? fallbackBranch; + if (!branch) { + return yield* gitManagerError( + "runPrStep", + "Cannot create a pull request from detached HEAD.", + ); + } + if (!details.hasUpstream) { + return yield* gitManagerError( + "runPrStep", + "Current branch has not been pushed. Push before creating a PR.", + ); + } + + const headContext = yield* resolveBranchHeadContext(cwd, { + branch, + upstreamRef: details.upstreamRef, + }); + + const existing = yield* findOpenPr(cwd, headContext); + if (existing) { + return { + status: "opened_existing" as const, + url: existing.url, + number: existing.number, + baseBranch: existing.baseRefName, + headBranch: existing.headRefName, + title: existing.title, + }; + } + + const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext); + yield* emit({ + kind: "phase_started", + phase: "pr", + label: "Generating PR content...", + }); + const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch); + + const generated = yield* textGeneration.generatePrContent({ + cwd, + baseBranch, + headBranch: headContext.headBranch, + commitSummary: limitContext(rangeContext.commitSummary, 20_000), + diffSummary: limitContext(rangeContext.diffSummary, 20_000), + diffPatch: limitContext(rangeContext.diffPatch, 60_000), + modelSelection, + }); + + const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`); + yield* fileSystem + .writeFileString(bodyFile, generated.body) + .pipe( + Effect.mapError((cause) => + gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause), + ), + ); + yield* emit({ + kind: "phase_started", + phase: "pr", + label: "Creating GitHub pull request...", + }); + yield* gitHubCli + .createPullRequest({ + cwd, + baseBranch, + headSelector: headContext.preferredHeadSelector, + title: generated.title, + bodyFile, + }) + .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void)))); + + const created = yield* findOpenPr(cwd, headContext); + if (!created) { + return { + status: "created" as const, + baseBranch, + headBranch: headContext.headBranch, + title: generated.title, + }; + } + + return { + status: "created" as const, + url: created.url, + number: created.number, + baseBranch: created.baseRefName, + headBranch: created.headRefName, + title: created.title, + }; + }); + + const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) { + return yield* Cache.get(statusResultCache, normalizeStatusCacheKey(input.cwd)); + }); + + const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")( + function* (input) { + const pullRequest = yield* gitHubCli + .getPullRequest({ + cwd: input.cwd, + reference: normalizePullRequestReference(input.reference), + }) + .pipe(Effect.map((resolved) => toResolvedPullRequest(resolved))); + + return { pullRequest }; + }, + ); + + const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fn( + "preparePullRequestThread", + )(function* (input) { + const maybeRunSetupScript = (worktreePath: string) => { + if (!input.threadId) { + return Effect.void; + } + return projectSetupScriptRunner + .runForThread({ + threadId: input.threadId, + projectCwd: input.cwd, + worktreePath, + }) + .pipe( + Effect.catch((error) => + Effect.logWarning( + `GitManager.preparePullRequestThread: failed to launch worktree setup script for thread ${input.threadId} in ${worktreePath}: ${error.message}`, + ).pipe(Effect.asVoid), + ), + ); + }; + return yield* Effect.gen(function* () { + const normalizedReference = normalizePullRequestReference(input.reference); + const rootWorktreePath = canonicalizeExistingPath(input.cwd); + const pullRequestSummary = yield* gitHubCli.getPullRequest({ + cwd: input.cwd, + reference: normalizedReference, + }); + const pullRequest = toResolvedPullRequest(pullRequestSummary); + + if (input.mode === "local") { + yield* gitHubCli.checkoutPullRequest({ + cwd: input.cwd, + reference: normalizedReference, + force: true, + }); + const details = yield* gitCore.statusDetails(input.cwd); + yield* configurePullRequestHeadUpstream( + input.cwd, + { + ...pullRequest, + ...toPullRequestHeadRemoteInfo(pullRequestSummary), + }, + details.branch ?? pullRequest.headBranch, + ); + return { + pullRequest, + branch: details.branch ?? pullRequest.headBranch, + worktreePath: null, + }; + } + + const ensureExistingWorktreeUpstream = Effect.fn("ensureExistingWorktreeUpstream")(function* ( + worktreePath: string, + ) { + const details = yield* gitCore.statusDetails(worktreePath); + yield* configurePullRequestHeadUpstream( + worktreePath, + { + ...pullRequest, + ...toPullRequestHeadRemoteInfo(pullRequestSummary), + }, + details.branch ?? pullRequest.headBranch, + ); + }); + + const pullRequestWithRemoteInfo = { + ...pullRequest, + ...toPullRequestHeadRemoteInfo(pullRequestSummary), + } as const; + const localPullRequestBranch = + resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo); + + const findLocalHeadBranch = (cwd: string) => + gitCore.listBranches({ cwd }).pipe( + Effect.map((result) => { + const localBranch = result.branches.find( + (branch) => !branch.isRemote && branch.name === localPullRequestBranch, + ); + if (localBranch) { + return localBranch; + } + if (localPullRequestBranch === pullRequest.headBranch) { + return null; + } + return ( + result.branches.find( + (branch) => + !branch.isRemote && + branch.name === pullRequest.headBranch && + branch.worktreePath !== null && + canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath, + ) ?? null + ); + }), + ); + + const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd); + const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath + ? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath) + : null; + if ( + existingBranchBeforeFetch?.worktreePath && + existingBranchBeforeFetchPath !== rootWorktreePath + ) { + yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath); + return { + pullRequest, + branch: localPullRequestBranch, + worktreePath: existingBranchBeforeFetch.worktreePath, + }; + } + if (existingBranchBeforeFetchPath === rootWorktreePath) { + return yield* gitManagerError( + "preparePullRequestThread", + "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", + ); + } + + yield* materializePullRequestHeadBranch( + input.cwd, + pullRequestWithRemoteInfo, + localPullRequestBranch, + ); + + const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd); + const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath + ? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath) + : null; + if ( + existingBranchAfterFetch?.worktreePath && + existingBranchAfterFetchPath !== rootWorktreePath + ) { + yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath); + return { + pullRequest, + branch: localPullRequestBranch, + worktreePath: existingBranchAfterFetch.worktreePath, + }; + } + if (existingBranchAfterFetchPath === rootWorktreePath) { + return yield* gitManagerError( + "preparePullRequestThread", + "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", + ); + } + + const worktree = yield* gitCore.createWorktree({ + cwd: input.cwd, + branch: localPullRequestBranch, + path: null, + }); + yield* ensureExistingWorktreeUpstream(worktree.worktree.path); + yield* maybeRunSetupScript(worktree.worktree.path); + + return { + pullRequest, + branch: worktree.worktree.branch, + worktreePath: worktree.worktree.path, + }; + }).pipe(Effect.ensuring(invalidateStatusResultCache(input.cwd))); + }); + + const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* ( + modelSelection: ModelSelection, + cwd: string, + branch: string | null, + commitMessage?: string, + filePaths?: readonly string[], + ) { + const suggestion = yield* resolveCommitAndBranchSuggestion({ + cwd, + branch, + ...(commitMessage ? { commitMessage } : {}), + ...(filePaths ? { filePaths } : {}), + includeBranch: true, + modelSelection, + }); + if (!suggestion) { + return yield* gitManagerError( + "runFeatureBranchStep", + "Cannot create a feature branch because there are no changes to commit.", + ); + } + + const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject); + const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd); + const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch); + + yield* gitCore.createBranch({ cwd, branch: resolvedBranch }); + yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch })); + + return { + branchStep: { status: "created" as const, name: resolvedBranch }, + resolvedCommitMessage: suggestion.commitMessage, + resolvedCommitSuggestion: suggestion, + }; + }); + + const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")( + function* (input, options) { + const progress = createProgressEmitter(input, options); + const currentPhase = yield* Ref.make>(Option.none()); + + const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return< + GitRunStackedActionResult, + GitManagerServiceError + > { + const initialStatus = yield* gitCore.statusDetails(input.cwd); + const wantsCommit = isCommitAction(input.action); + const wantsPush = + input.action === "push" || + input.action === "commit_push" || + input.action === "commit_push_pr" || + (input.action === "create_pr" && + (!initialStatus.hasUpstream || initialStatus.aheadCount > 0)); + const wantsPr = input.action === "create_pr" || input.action === "commit_push_pr"; + + if (input.featureBranch && !wantsCommit) { + return yield* gitManagerError( + "runStackedAction", + "Feature-branch checkout is only supported for commit actions.", + ); + } + if (input.action === "push" && initialStatus.hasWorkingTreeChanges) { + return yield* gitManagerError( + "runStackedAction", + "Commit or stash local changes before pushing.", + ); + } + if (input.action === "create_pr" && initialStatus.hasWorkingTreeChanges) { + return yield* gitManagerError( + "runStackedAction", + "Commit local changes before creating a PR.", + ); + } + + const phases: GitActionProgressPhase[] = [ + ...(input.featureBranch ? (["branch"] as const) : []), + ...(wantsCommit ? (["commit"] as const) : []), + ...(wantsPush ? (["push"] as const) : []), + ...(wantsPr ? (["pr"] as const) : []), + ]; + + yield* progress.emit({ + kind: "action_started", + phases, + }); + + if (!input.featureBranch && wantsPush && !initialStatus.branch) { + return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD."); + } + if (!input.featureBranch && wantsPr && !initialStatus.branch) { + return yield* gitManagerError( + "runStackedAction", + "Cannot create a pull request from detached HEAD.", + ); + } + + let branchStep: { status: "created" | "skipped_not_requested"; name?: string }; + let commitMessageForStep = input.commitMessage; + let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined; + + const modelSelection = yield* serverSettingsService.getSettings.pipe( + Effect.map((settings) => settings.textGenerationModelSelection), + Effect.mapError((cause) => + gitManagerError("runStackedAction", "Failed to get server settings.", cause), + ), + ); + + if (input.featureBranch) { + yield* Ref.set(currentPhase, Option.some("branch")); + yield* progress.emit({ + kind: "phase_started", + phase: "branch", + label: "Preparing feature branch...", + }); + const result = yield* runFeatureBranchStep( + modelSelection, + input.cwd, + initialStatus.branch, + input.commitMessage, + input.filePaths, + ); + branchStep = result.branchStep; + commitMessageForStep = result.resolvedCommitMessage; + preResolvedCommitSuggestion = result.resolvedCommitSuggestion; + } else { + branchStep = { status: "skipped_not_requested" as const }; + } + + const currentBranch = branchStep.name ?? initialStatus.branch; + const commitAction = isCommitAction(input.action) ? input.action : null; + + const commit = commitAction + ? yield* Ref.set(currentPhase, Option.some("commit")).pipe( + Effect.flatMap(() => + runCommitStep( + modelSelection, + input.cwd, + commitAction, + currentBranch, + commitMessageForStep, + preResolvedCommitSuggestion, + input.filePaths, + options?.progressReporter, + progress.actionId, + ), + ), + ) + : { status: "skipped_not_requested" as const }; + + const push = wantsPush + ? yield* progress + .emit({ + kind: "phase_started", + phase: "push", + label: "Pushing...", + }) + .pipe( + Effect.tap(() => Ref.set(currentPhase, Option.some("push"))), + Effect.flatMap(() => gitCore.pushCurrentBranch(input.cwd, currentBranch)), + ) + : { status: "skipped_not_requested" as const }; + + const pr = wantsPr + ? yield* progress + .emit({ + kind: "phase_started", + phase: "pr", + label: "Preparing PR...", + }) + .pipe( + Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))), + Effect.flatMap(() => + runPrStep(modelSelection, input.cwd, currentBranch, progress.emit), + ), + ) + : { status: "skipped_not_requested" as const }; + + const toast = yield* buildCompletionToast(input.cwd, { + action: input.action, + branch: branchStep, + commit, + push, + pr, + }); + + const result = { + action: input.action, + branch: branchStep, + commit, + push, + pr, + toast, + }; + yield* progress.emit({ + kind: "action_finished", + result, + }); + return result; + }); + + return yield* runAction().pipe( + Effect.ensuring(invalidateStatusResultCache(input.cwd)), + Effect.tapError((error) => + Effect.flatMap(Ref.get(currentPhase), (phase) => + progress.emit({ + kind: "action_failed", + phase: Option.getOrNull(phase), + message: error.message, + }), + ), + ), + ); + }, + ); + + return { + status, + resolvePullRequest, + preparePullRequestThread, + runStackedAction, + } satisfies GitManagerShape; +}); + +export const GitManagerLive = Layer.effect(GitManager, makeGitManager()); diff --git a/apps/server/src/git/Layers/RoutingTextGeneration.ts b/apps/server/src/git/Layers/RoutingTextGeneration.ts new file mode 100644 index 0000000000..dee12a3e0e --- /dev/null +++ b/apps/server/src/git/Layers/RoutingTextGeneration.ts @@ -0,0 +1,73 @@ +/** + * RoutingTextGeneration – Dispatches text generation requests to either the + * Codex CLI or Claude CLI implementation based on the provider in each + * request input. + * + * When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to + * the Claude layer; for any other value (including the default `undefined`) it + * falls through to the Codex layer. + * + * @module RoutingTextGeneration + */ +import { Effect, Layer, ServiceMap } from "effect"; + +import { + TextGeneration, + type TextGenerationProvider, + type TextGenerationShape, +} from "../Services/TextGeneration.ts"; +import { CodexTextGenerationLive } from "./CodexTextGeneration.ts"; +import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; + +// --------------------------------------------------------------------------- +// Internal service tags so both concrete layers can coexist. +// --------------------------------------------------------------------------- + +class CodexTextGen extends ServiceMap.Service()( + "t3/git/Layers/RoutingTextGeneration/CodexTextGen", +) {} + +class ClaudeTextGen extends ServiceMap.Service()( + "t3/git/Layers/RoutingTextGeneration/ClaudeTextGen", +) {} + +// --------------------------------------------------------------------------- +// Routing implementation +// --------------------------------------------------------------------------- + +const makeRoutingTextGeneration = Effect.gen(function* () { + const codex = yield* CodexTextGen; + const claude = yield* ClaudeTextGen; + + const route = (provider?: TextGenerationProvider): TextGenerationShape => + provider === "claudeAgent" ? claude : codex; + + return { + generateCommitMessage: (input) => + route(input.modelSelection.provider).generateCommitMessage(input), + generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input), + generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input), + generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input), + } satisfies TextGenerationShape; +}); + +const InternalCodexLayer = Layer.effect( + CodexTextGen, + Effect.gen(function* () { + const svc = yield* TextGeneration; + return svc; + }), +).pipe(Layer.provide(CodexTextGenerationLive)); + +const InternalClaudeLayer = Layer.effect( + ClaudeTextGen, + Effect.gen(function* () { + const svc = yield* TextGeneration; + return svc; + }), +).pipe(Layer.provide(ClaudeTextGenerationLive)); + +export const RoutingTextGenerationLive = Layer.effect( + TextGeneration, + makeRoutingTextGeneration, +).pipe(Layer.provide(InternalCodexLayer), Layer.provide(InternalClaudeLayer)); diff --git a/apps/server/src/git/Prompts.test.ts b/apps/server/src/git/Prompts.test.ts new file mode 100644 index 0000000000..d8d079c0cf --- /dev/null +++ b/apps/server/src/git/Prompts.test.ts @@ -0,0 +1,193 @@ +import { describe, expect, it } from "vitest"; + +import { + buildBranchNamePrompt, + buildCommitMessagePrompt, + buildPrContentPrompt, + buildThreadTitlePrompt, +} from "./Prompts.ts"; +import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts"; +import { TextGenerationError } from "@t3tools/contracts"; + +describe("buildCommitMessagePrompt", () => { + it("includes staged patch and summary in the prompt", () => { + const result = buildCommitMessagePrompt({ + branch: "main", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md\n+hello", + includeBranch: false, + }); + + expect(result.prompt).toContain("Staged files:"); + expect(result.prompt).toContain("M README.md"); + expect(result.prompt).toContain("Staged patch:"); + expect(result.prompt).toContain("diff --git a/README.md b/README.md"); + expect(result.prompt).toContain("Branch: main"); + // Should NOT include the branch generation instruction + expect(result.prompt).not.toContain("branch must be a short semantic git branch fragment"); + }); + + it("includes branch generation instruction when includeBranch is true", () => { + const result = buildCommitMessagePrompt({ + branch: "feature/foo", + stagedSummary: "M README.md", + stagedPatch: "diff", + includeBranch: true, + }); + + expect(result.prompt).toContain("branch must be a short semantic git branch fragment"); + expect(result.prompt).toContain("Return a JSON object with keys: subject, body, branch."); + }); + + it("shows (detached) when branch is null", () => { + const result = buildCommitMessagePrompt({ + branch: null, + stagedSummary: "M a.ts", + stagedPatch: "diff", + includeBranch: false, + }); + + expect(result.prompt).toContain("Branch: (detached)"); + }); +}); + +describe("buildPrContentPrompt", () => { + it("includes branch names, commits, and diff in the prompt", () => { + const result = buildPrContentPrompt({ + baseBranch: "main", + headBranch: "feature/auth", + commitSummary: "feat: add login page", + diffSummary: "3 files changed", + diffPatch: "diff --git a/auth.ts b/auth.ts\n+export function login()", + }); + + expect(result.prompt).toContain("Base branch: main"); + expect(result.prompt).toContain("Head branch: feature/auth"); + expect(result.prompt).toContain("Commits:"); + expect(result.prompt).toContain("feat: add login page"); + expect(result.prompt).toContain("Diff stat:"); + expect(result.prompt).toContain("3 files changed"); + expect(result.prompt).toContain("Diff patch:"); + expect(result.prompt).toContain("export function login()"); + }); +}); + +describe("buildBranchNamePrompt", () => { + it("includes the user message in the prompt", () => { + const result = buildBranchNamePrompt({ + message: "Fix the login timeout bug", + }); + + expect(result.prompt).toContain("User message:"); + expect(result.prompt).toContain("Fix the login timeout bug"); + expect(result.prompt).not.toContain("Attachment metadata:"); + }); + + it("includes attachment metadata when attachments are provided", () => { + const result = buildBranchNamePrompt({ + message: "Fix the layout from screenshot", + attachments: [ + { + type: "image" as const, + id: "att-123", + name: "screenshot.png", + mimeType: "image/png", + sizeBytes: 12345, + }, + ], + }); + + expect(result.prompt).toContain("Attachment metadata:"); + expect(result.prompt).toContain("screenshot.png"); + expect(result.prompt).toContain("image/png"); + expect(result.prompt).toContain("12345 bytes"); + }); +}); + +describe("buildThreadTitlePrompt", () => { + it("includes the user message in the prompt", () => { + const result = buildThreadTitlePrompt({ + message: "Investigate reconnect regressions after session restore", + }); + + expect(result.prompt).toContain("User message:"); + expect(result.prompt).toContain("Investigate reconnect regressions after session restore"); + expect(result.prompt).not.toContain("Attachment metadata:"); + }); + + it("includes attachment metadata when attachments are provided", () => { + const result = buildThreadTitlePrompt({ + message: "Name this thread from the screenshot", + attachments: [ + { + type: "image" as const, + id: "att-456", + name: "thread.png", + mimeType: "image/png", + sizeBytes: 67890, + }, + ], + }); + + expect(result.prompt).toContain("Attachment metadata:"); + expect(result.prompt).toContain("thread.png"); + expect(result.prompt).toContain("image/png"); + expect(result.prompt).toContain("67890 bytes"); + }); +}); + +describe("sanitizeThreadTitle", () => { + it("truncates long titles with the shared sidebar-safe limit", () => { + expect( + sanitizeThreadTitle( + ' "Reconnect failures after restart because the session state does not recover" ', + ), + ).toBe("Reconnect failures after restart because the se..."); + }); +}); + +describe("normalizeCliError", () => { + it("detects 'Command not found' and includes CLI name in the message", () => { + const error = normalizeCliError( + "claude", + "generateCommitMessage", + new Error("Command not found: claude"), + "Something went wrong", + ); + + expect(error).toBeInstanceOf(TextGenerationError); + expect(error.detail).toContain("Claude CLI"); + expect(error.detail).toContain("not available on PATH"); + }); + + it("uses the CLI name from the first argument for codex", () => { + const error = normalizeCliError( + "codex", + "generateBranchName", + new Error("Command not found: codex"), + "Something went wrong", + ); + + expect(error).toBeInstanceOf(TextGenerationError); + expect(error.detail).toContain("Codex CLI"); + expect(error.detail).toContain("not available on PATH"); + }); + + it("returns the error as-is if it is already a TextGenerationError", () => { + const existing = new TextGenerationError({ + operation: "generatePrContent", + detail: "Already wrapped", + }); + + const result = normalizeCliError("claude", "generatePrContent", existing, "fallback"); + + expect(result).toBe(existing); + }); + + it("wraps unknown non-Error values with the fallback message", () => { + const result = normalizeCliError("codex", "generateCommitMessage", "string error", "fallback"); + + expect(result).toBeInstanceOf(TextGenerationError); + expect(result.detail).toBe("fallback"); + }); +}); diff --git a/apps/server/src/git/Prompts.ts b/apps/server/src/git/Prompts.ts new file mode 100644 index 0000000000..4092358825 --- /dev/null +++ b/apps/server/src/git/Prompts.ts @@ -0,0 +1,202 @@ +/** + * Shared prompt builders for text generation providers. + * + * Extracts the prompt construction logic that is identical across + * Codex, Claude, and any future CLI-based text generation backends. + * + * @module textGenerationPrompts + */ +import { Schema } from "effect"; +import type { ChatAttachment } from "@t3tools/contracts"; + +import { limitSection } from "./Utils.ts"; + +// --------------------------------------------------------------------------- +// Commit message +// --------------------------------------------------------------------------- + +export interface CommitMessagePromptInput { + branch: string | null; + stagedSummary: string; + stagedPatch: string; + includeBranch: boolean; +} + +export function buildCommitMessagePrompt(input: CommitMessagePromptInput) { + const wantsBranch = input.includeBranch; + + const prompt = [ + "You write concise git commit messages.", + wantsBranch + ? "Return a JSON object with keys: subject, body, branch." + : "Return a JSON object with keys: subject, body.", + "Rules:", + "- subject must be imperative, <= 72 chars, and no trailing period", + "- body can be empty string or short bullet points", + ...(wantsBranch + ? ["- branch must be a short semantic git branch fragment for this change"] + : []), + "- capture the primary user-visible or developer-visible change", + "", + `Branch: ${input.branch ?? "(detached)"}`, + "", + "Staged files:", + limitSection(input.stagedSummary, 6_000), + "", + "Staged patch:", + limitSection(input.stagedPatch, 40_000), + ].join("\n"); + + if (wantsBranch) { + return { + prompt, + outputSchema: Schema.Struct({ + subject: Schema.String, + body: Schema.String, + branch: Schema.String, + }), + }; + } + + return { + prompt, + outputSchema: Schema.Struct({ + subject: Schema.String, + body: Schema.String, + }), + }; +} + +// --------------------------------------------------------------------------- +// PR content +// --------------------------------------------------------------------------- + +export interface PrContentPromptInput { + baseBranch: string; + headBranch: string; + commitSummary: string; + diffSummary: string; + diffPatch: string; +} + +export function buildPrContentPrompt(input: PrContentPromptInput) { + const prompt = [ + "You write GitHub pull request content.", + "Return a JSON object with keys: title, body.", + "Rules:", + "- title should be concise and specific", + "- body must be markdown and include headings '## Summary' and '## Testing'", + "- under Summary, provide short bullet points", + "- under Testing, include bullet points with concrete checks or 'Not run' where appropriate", + "", + `Base branch: ${input.baseBranch}`, + `Head branch: ${input.headBranch}`, + "", + "Commits:", + limitSection(input.commitSummary, 12_000), + "", + "Diff stat:", + limitSection(input.diffSummary, 12_000), + "", + "Diff patch:", + limitSection(input.diffPatch, 40_000), + ].join("\n"); + + const outputSchema = Schema.Struct({ + title: Schema.String, + body: Schema.String, + }); + + return { prompt, outputSchema }; +} + +// --------------------------------------------------------------------------- +// Branch name +// --------------------------------------------------------------------------- + +export interface BranchNamePromptInput { + message: string; + attachments?: ReadonlyArray | undefined; +} + +interface PromptFromMessageInput { + instruction: string; + responseShape: string; + rules: ReadonlyArray; + message: string; + attachments?: ReadonlyArray | undefined; +} + +function buildPromptFromMessage(input: PromptFromMessageInput): string { + const attachmentLines = (input.attachments ?? []).map( + (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`, + ); + + const promptSections = [ + input.instruction, + input.responseShape, + "Rules:", + ...input.rules.map((rule) => `- ${rule}`), + "", + "User message:", + limitSection(input.message, 8_000), + ]; + if (attachmentLines.length > 0) { + promptSections.push( + "", + "Attachment metadata:", + limitSection(attachmentLines.join("\n"), 4_000), + ); + } + + return promptSections.join("\n"); +} + +export function buildBranchNamePrompt(input: BranchNamePromptInput) { + const prompt = buildPromptFromMessage({ + instruction: "You generate concise git branch names.", + responseShape: "Return a JSON object with key: branch.", + rules: [ + "Branch should describe the requested work from the user message.", + "Keep it short and specific (2-6 words).", + "Use plain words only, no issue prefixes and no punctuation-heavy text.", + "If images are attached, use them as primary context for visual/UI issues.", + ], + message: input.message, + attachments: input.attachments, + }); + const outputSchema = Schema.Struct({ + branch: Schema.String, + }); + + return { prompt, outputSchema }; +} + +// --------------------------------------------------------------------------- +// Thread title +// --------------------------------------------------------------------------- + +export interface ThreadTitlePromptInput { + message: string; + attachments?: ReadonlyArray | undefined; +} + +export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) { + const prompt = buildPromptFromMessage({ + instruction: "You write concise thread titles for coding conversations.", + responseShape: "Return a JSON object with key: title.", + rules: [ + "Title should summarize the user's request, not restate it verbatim.", + "Keep it short and specific (3-8 words).", + "Avoid quotes, filler, prefixes, and trailing punctuation.", + "If images are attached, use them as primary context for visual/UI issues.", + ], + message: input.message, + attachments: input.attachments, + }); + const outputSchema = Schema.Struct({ + title: Schema.String, + }); + + return { prompt, outputSchema }; +} diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.ts new file mode 100644 index 0000000000..d7a28d1763 --- /dev/null +++ b/apps/server/src/git/Services/GitCore.ts @@ -0,0 +1,306 @@ +/** + * GitCore - Effect service contract for low-level Git operations. + * + * Wraps core repository primitives used by higher-level orchestration + * services and WebSocket routes. + * + * @module GitCore + */ +import { ServiceMap } from "effect"; +import type { Effect, Scope } from "effect"; +import type { + GitCheckoutInput, + GitCreateBranchInput, + GitCreateWorktreeInput, + GitCreateWorktreeResult, + GitInitInput, + GitListBranchesInput, + GitListBranchesResult, + GitPullResult, + GitRemoveWorktreeInput, + GitStatusInput, + GitStatusResult, +} from "@t3tools/contracts"; + +import type { GitCommandError } from "@t3tools/contracts"; + +export interface ExecuteGitInput { + readonly operation: string; + readonly cwd: string; + readonly args: ReadonlyArray; + readonly stdin?: string; + readonly env?: NodeJS.ProcessEnv; + readonly allowNonZeroExit?: boolean; + readonly timeoutMs?: number; + readonly maxOutputBytes?: number; + readonly truncateOutputAtMaxBytes?: boolean; + readonly progress?: ExecuteGitProgress; +} + +export interface ExecuteGitResult { + readonly code: number; + readonly stdout: string; + readonly stderr: string; + readonly stdoutTruncated: boolean; + readonly stderrTruncated: boolean; +} + +export interface GitStatusDetails extends Omit { + upstreamRef: string | null; +} + +export interface GitPreparedCommitContext { + stagedSummary: string; + stagedPatch: string; +} + +export interface ExecuteGitProgress { + readonly onStdoutLine?: (line: string) => Effect.Effect; + readonly onStderrLine?: (line: string) => Effect.Effect; + readonly onHookStarted?: (hookName: string) => Effect.Effect; + readonly onHookFinished?: (input: { + hookName: string; + exitCode: number | null; + durationMs: number | null; + }) => Effect.Effect; +} + +export interface GitCommitProgress { + readonly onOutputLine?: (input: { + stream: "stdout" | "stderr"; + text: string; + }) => Effect.Effect; + readonly onHookStarted?: (hookName: string) => Effect.Effect; + readonly onHookFinished?: (input: { + hookName: string; + exitCode: number | null; + durationMs: number | null; + }) => Effect.Effect; +} + +export interface GitCommitOptions { + readonly timeoutMs?: number; + readonly progress?: GitCommitProgress; +} + +export interface GitPushResult { + status: "pushed" | "skipped_up_to_date"; + branch: string; + upstreamBranch?: string | undefined; + setUpstream?: boolean | undefined; +} + +export interface GitRangeContext { + commitSummary: string; + diffSummary: string; + diffPatch: string; +} + +export interface GitListWorkspaceFilesResult { + readonly paths: ReadonlyArray; + readonly truncated: boolean; +} + +export interface GitRenameBranchInput { + cwd: string; + oldBranch: string; + newBranch: string; +} + +export interface GitRenameBranchResult { + branch: string; +} + +export interface GitFetchPullRequestBranchInput { + cwd: string; + prNumber: number; + branch: string; +} + +export interface GitEnsureRemoteInput { + cwd: string; + preferredName: string; + url: string; +} + +export interface GitFetchRemoteBranchInput { + cwd: string; + remoteName: string; + remoteBranch: string; + localBranch: string; +} + +export interface GitSetBranchUpstreamInput { + cwd: string; + branch: string; + remoteName: string; + remoteBranch: string; +} + +/** + * GitCoreShape - Service API for low-level Git repository interactions. + */ +export interface GitCoreShape { + /** + * Execute a raw Git command. + */ + readonly execute: (input: ExecuteGitInput) => Effect.Effect; + + /** + * Read Git status for a repository. + */ + readonly status: (input: GitStatusInput) => Effect.Effect; + + /** + * Read detailed working tree / branch status for a repository. + */ + readonly statusDetails: (cwd: string) => Effect.Effect; + + /** + * Build staged change context for commit generation. + */ + readonly prepareCommitContext: ( + cwd: string, + filePaths?: readonly string[], + ) => Effect.Effect; + + /** + * Create a commit with provided subject/body. + */ + readonly commit: ( + cwd: string, + subject: string, + body: string, + options?: GitCommitOptions, + ) => Effect.Effect<{ commitSha: string }, GitCommandError>; + + /** + * Push current branch, setting upstream if needed. + */ + readonly pushCurrentBranch: ( + cwd: string, + fallbackBranch: string | null, + ) => Effect.Effect; + + /** + * Collect commit/diff context between base branch and current HEAD. + */ + readonly readRangeContext: ( + cwd: string, + baseBranch: string, + ) => Effect.Effect; + + /** + * Read a Git config value from the local repository. + */ + readonly readConfigValue: ( + cwd: string, + key: string, + ) => Effect.Effect; + + /** + * Determine whether the provided cwd is inside a git work tree. + */ + readonly isInsideWorkTree: (cwd: string) => Effect.Effect; + + /** + * List tracked and untracked workspace file paths relative to cwd. + */ + readonly listWorkspaceFiles: ( + cwd: string, + ) => Effect.Effect; + + /** + * Remove gitignored paths from a relative path list. + */ + readonly filterIgnoredPaths: ( + cwd: string, + relativePaths: ReadonlyArray, + ) => Effect.Effect, GitCommandError>; + + /** + * List local + remote branches and branch metadata. + */ + readonly listBranches: ( + input: GitListBranchesInput, + ) => Effect.Effect; + + /** + * Pull current branch from upstream using fast-forward only. + */ + readonly pullCurrentBranch: (cwd: string) => Effect.Effect; + + /** + * Create a worktree and branch from a base branch. + */ + readonly createWorktree: ( + input: GitCreateWorktreeInput, + ) => Effect.Effect; + + /** + * Materialize a GitHub pull request head as a local branch without switching checkout. + */ + readonly fetchPullRequestBranch: ( + input: GitFetchPullRequestBranchInput, + ) => Effect.Effect; + + /** + * Ensure a named remote exists for the provided URL, returning the reused or created remote name. + */ + readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect; + + /** + * Fetch a remote branch into a local branch without checkout. + */ + readonly fetchRemoteBranch: ( + input: GitFetchRemoteBranchInput, + ) => Effect.Effect; + + /** + * Set the upstream tracking branch for a local branch. + */ + readonly setBranchUpstream: ( + input: GitSetBranchUpstreamInput, + ) => Effect.Effect; + + /** + * Remove an existing worktree. + */ + readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect; + + /** + * Rename an existing local branch. + */ + readonly renameBranch: ( + input: GitRenameBranchInput, + ) => Effect.Effect; + + /** + * Create a local branch. + */ + readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect; + + /** + * Checkout an existing branch and refresh its upstream metadata in background. + */ + readonly checkoutBranch: ( + input: GitCheckoutInput, + ) => Effect.Effect; + + /** + * Initialize a repository in the provided directory. + */ + readonly initRepo: (input: GitInitInput) => Effect.Effect; + + /** + * List local branch names (short format). + */ + readonly listLocalBranchNames: (cwd: string) => Effect.Effect; +} + +/** + * GitCore - Service tag for low-level Git repository operations. + */ +export class GitCore extends ServiceMap.Service()( + "t3/git/Services/GitCore", +) {} diff --git a/apps/server/src/git/Services/GitHubCli.ts b/apps/server/src/git/Services/GitHubCli.ts new file mode 100644 index 0000000000..38afdd5f92 --- /dev/null +++ b/apps/server/src/git/Services/GitHubCli.ts @@ -0,0 +1,103 @@ +/** + * GitHubCli - Effect service contract for `gh` process interactions. + * + * Provides thin command execution helpers used by Git workflow orchestration. + * + * @module GitHubCli + */ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProcessRunResult } from "../../processRunner"; +import type { GitHubCliError } from "@t3tools/contracts"; + +export interface GitHubPullRequestSummary { + readonly number: number; + readonly title: string; + readonly url: string; + readonly baseRefName: string; + readonly headRefName: string; + readonly state?: "open" | "closed" | "merged"; + readonly isCrossRepository?: boolean; + readonly headRepositoryNameWithOwner?: string | null; + readonly headRepositoryOwnerLogin?: string | null; +} + +export interface GitHubRepositoryCloneUrls { + readonly nameWithOwner: string; + readonly url: string; + readonly sshUrl: string; +} + +/** + * GitHubCliShape - Service API for executing GitHub CLI commands. + */ +export interface GitHubCliShape { + /** + * Execute a GitHub CLI command and return full process output. + */ + readonly execute: (input: { + readonly cwd: string; + readonly args: ReadonlyArray; + readonly timeoutMs?: number; + }) => Effect.Effect; + + /** + * List open pull requests for a head branch. + */ + readonly listOpenPullRequests: (input: { + readonly cwd: string; + readonly headSelector: string; + readonly limit?: number; + }) => Effect.Effect, GitHubCliError>; + + /** + * Resolve a pull request by URL, number, or branch-ish identifier. + */ + readonly getPullRequest: (input: { + readonly cwd: string; + readonly reference: string; + }) => Effect.Effect; + + /** + * Resolve clone URLs for a GitHub repository. + */ + readonly getRepositoryCloneUrls: (input: { + readonly cwd: string; + readonly repository: string; + }) => Effect.Effect; + + /** + * Create a pull request from branch context and body file. + */ + readonly createPullRequest: (input: { + readonly cwd: string; + readonly baseBranch: string; + readonly headSelector: string; + readonly title: string; + readonly bodyFile: string; + }) => Effect.Effect; + + /** + * Resolve repository default branch through GitHub metadata. + */ + readonly getDefaultBranch: (input: { + readonly cwd: string; + }) => Effect.Effect; + + /** + * Checkout a pull request into the current repository worktree. + */ + readonly checkoutPullRequest: (input: { + readonly cwd: string; + readonly reference: string; + readonly force?: boolean; + }) => Effect.Effect; +} + +/** + * GitHubCli - Service tag for GitHub CLI process execution. + */ +export class GitHubCli extends ServiceMap.Service()( + "t3/git/Services/GitHubCli", +) {} diff --git a/apps/server/src/git/Services/GitManager.ts b/apps/server/src/git/Services/GitManager.ts new file mode 100644 index 0000000000..86842257b4 --- /dev/null +++ b/apps/server/src/git/Services/GitManager.ts @@ -0,0 +1,73 @@ +/** + * GitManager - Effect service contract for stacked Git workflows. + * + * Orchestrates status inspection and commit/push/PR flows by composing + * lower-level Git and external tool services. + * + * @module GitManager + */ +import { + GitActionProgressEvent, + GitPreparePullRequestThreadInput, + GitPreparePullRequestThreadResult, + GitPullRequestRefInput, + GitResolvePullRequestResult, + GitRunStackedActionInput, + GitRunStackedActionResult, + GitStatusInput, + GitStatusResult, +} from "@t3tools/contracts"; +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; +import type { GitManagerServiceError } from "@t3tools/contracts"; + +export interface GitActionProgressReporter { + readonly publish: (event: GitActionProgressEvent) => Effect.Effect; +} + +export interface GitRunStackedActionOptions { + readonly actionId?: string; + readonly progressReporter?: GitActionProgressReporter; +} + +/** + * GitManagerShape - Service API for high-level Git workflow actions. + */ +export interface GitManagerShape { + /** + * Read current repository Git status plus open PR metadata when available. + */ + readonly status: ( + input: GitStatusInput, + ) => Effect.Effect; + + /** + * Resolve a pull request by URL/number against the current repository. + */ + readonly resolvePullRequest: ( + input: GitPullRequestRefInput, + ) => Effect.Effect; + + /** + * Prepare a new thread workspace from a pull request in local or worktree mode. + */ + readonly preparePullRequestThread: ( + input: GitPreparePullRequestThreadInput, + ) => Effect.Effect; + + /** + * Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`). + * When `featureBranch` is set, creates and checks out a feature branch first. + */ + readonly runStackedAction: ( + input: GitRunStackedActionInput, + options?: GitRunStackedActionOptions, + ) => Effect.Effect; +} + +/** + * GitManager - Service tag for stacked Git workflow orchestration. + */ +export class GitManager extends ServiceMap.Service()( + "t3/git/Services/GitManager", +) {} diff --git a/apps/server/src/git/Services/TextGeneration.ts b/apps/server/src/git/Services/TextGeneration.ts new file mode 100644 index 0000000000..f4354c7a99 --- /dev/null +++ b/apps/server/src/git/Services/TextGeneration.ts @@ -0,0 +1,123 @@ +/** + * TextGeneration - Effect service contract for AI-generated Git content. + * + * Generates commit messages and pull request titles/bodies from repository + * context prepared by Git services. + * + * @module TextGeneration + */ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; +import type { ChatAttachment, ModelSelection } from "@t3tools/contracts"; + +import type { TextGenerationError } from "@t3tools/contracts"; + +/** Providers that support git text generation (commit messages, PR content, branch names). */ +export type TextGenerationProvider = "codex" | "claudeAgent"; + +export interface CommitMessageGenerationInput { + cwd: string; + branch: string | null; + stagedSummary: string; + stagedPatch: string; + /** When true, the model also returns a semantic branch name for the change. */ + includeBranch?: boolean; + /** What model and provider to use for generation. */ + modelSelection: ModelSelection; +} + +export interface CommitMessageGenerationResult { + subject: string; + body: string; + /** Only present when `includeBranch` was set on the input. */ + branch?: string | undefined; +} + +export interface PrContentGenerationInput { + cwd: string; + baseBranch: string; + headBranch: string; + commitSummary: string; + diffSummary: string; + diffPatch: string; + /** What model and provider to use for generation. */ + modelSelection: ModelSelection; +} + +export interface PrContentGenerationResult { + title: string; + body: string; +} + +export interface BranchNameGenerationInput { + cwd: string; + message: string; + attachments?: ReadonlyArray | undefined; + /** What model and provider to use for generation. */ + modelSelection: ModelSelection; +} + +export interface BranchNameGenerationResult { + branch: string; +} + +export interface ThreadTitleGenerationInput { + cwd: string; + message: string; + attachments?: ReadonlyArray | undefined; + /** What model and provider to use for generation. */ + modelSelection: ModelSelection; +} + +export interface ThreadTitleGenerationResult { + title: string; +} + +export interface TextGenerationService { + generateCommitMessage( + input: CommitMessageGenerationInput, + ): Promise; + generatePrContent(input: PrContentGenerationInput): Promise; + generateBranchName(input: BranchNameGenerationInput): Promise; + generateThreadTitle(input: ThreadTitleGenerationInput): Promise; +} + +/** + * TextGenerationShape - Service API for commit/PR text generation. + */ +export interface TextGenerationShape { + /** + * Generate a commit message from staged change context. + */ + readonly generateCommitMessage: ( + input: CommitMessageGenerationInput, + ) => Effect.Effect; + + /** + * Generate pull request title/body from branch and diff context. + */ + readonly generatePrContent: ( + input: PrContentGenerationInput, + ) => Effect.Effect; + + /** + * Generate a concise branch name from a user message. + */ + readonly generateBranchName: ( + input: BranchNameGenerationInput, + ) => Effect.Effect; + + /** + * Generate a concise thread title from a user's first message. + */ + readonly generateThreadTitle: ( + input: ThreadTitleGenerationInput, + ) => Effect.Effect; +} + +/** + * TextGeneration - Service tag for commit and PR text generation. + */ +export class TextGeneration extends ServiceMap.Service()( + "t3/git/Services/TextGeneration", +) {} diff --git a/apps/server/src/git/Utils.ts b/apps/server/src/git/Utils.ts new file mode 100644 index 0000000000..4a7931c74b --- /dev/null +++ b/apps/server/src/git/Utils.ts @@ -0,0 +1,123 @@ +/** + * Shared utilities for text generation layers (Codex, Claude, etc.). + * + * @module textGenerationUtils + */ +import { Schema } from "effect"; + +import { TextGenerationError } from "@t3tools/contracts"; + +import { existsSync } from "node:fs"; +import { join } from "node:path"; + +export function isGitRepository(cwd: string): boolean { + return existsSync(join(cwd, ".git")); +} + +/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */ +export function toJsonSchemaObject(schema: Schema.Top): unknown { + const document = Schema.toJsonSchemaDocument(schema); + if (document.definitions && Object.keys(document.definitions).length > 0) { + return { ...document.schema, $defs: document.definitions }; + } + return document.schema; +} + +/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */ +export function limitSection(value: string, maxChars: number): string { + if (value.length <= maxChars) return value; + const truncated = value.slice(0, maxChars); + return `${truncated}\n\n[truncated]`; +} + +/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */ +export function sanitizeCommitSubject(raw: string): string { + const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? ""; + const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim(); + if (withoutTrailingPeriod.length === 0) { + return "Update project files"; + } + + if (withoutTrailingPeriod.length <= 72) { + return withoutTrailingPeriod; + } + return withoutTrailingPeriod.slice(0, 72).trimEnd(); +} + +/** Normalise a raw PR title to a single line with a sensible fallback. */ +export function sanitizePrTitle(raw: string): string { + const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? ""; + if (singleLine.length > 0) { + return singleLine; + } + return "Update project changes"; +} + +/** Normalise a raw thread title to a compact single-line sidebar-safe label. */ +export function sanitizeThreadTitle(raw: string): string { + const normalized = raw + .trim() + .split(/\r?\n/g)[0] + ?.trim() + .replace(/^['"`]+|['"`]+$/g, "") + .trim() + .replace(/\s+/g, " "); + + if (!normalized || normalized.trim().length === 0) { + return "New thread"; + } + + if (normalized.length <= 50) { + return normalized; + } + + return `${normalized.slice(0, 47).trimEnd()}...`; +} + +/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */ +function cliLabel(cliName: string): string { + const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1); + return `${capitalized} CLI (\`${cliName}\`)`; +} + +/** + * Normalize an unknown error from a CLI text generation process into a + * typed `TextGenerationError`. Parameterized by CLI name so both Codex + * and Claude (and future providers) can share the same logic. + */ +export function normalizeCliError( + cliName: string, + operation: string, + error: unknown, + fallback: string, +): TextGenerationError { + if (Schema.is(TextGenerationError)(error)) { + return error; + } + + if (error instanceof Error) { + const lower = error.message.toLowerCase(); + if ( + error.message.includes(`Command not found: ${cliName}`) || + lower.includes(`spawn ${cliName}`) || + lower.includes("enoent") + ) { + return new TextGenerationError({ + operation, + detail: `${cliLabel(cliName)} is required but not available on PATH.`, + cause: error, + }); + } + return new TextGenerationError({ + operation, + detail: `${fallback}: ${error.message}`, + cause: error, + }); + } + + return new TextGenerationError({ + operation, + detail: fallback, + cause: error, + }); +} diff --git a/apps/server/src/git/remoteRefs.ts b/apps/server/src/git/remoteRefs.ts new file mode 100644 index 0000000000..b5dfc87bd0 --- /dev/null +++ b/apps/server/src/git/remoteRefs.ts @@ -0,0 +1,67 @@ +export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray { + return stdout + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0); +} + +export function parseRemoteNames(stdout: string): ReadonlyArray { + return parseRemoteNamesInGitOrder(stdout).toSorted((a, b) => b.length - a.length); +} + +export function parseRemoteRefWithRemoteNames( + ref: string, + remoteNames: ReadonlyArray, +): { remoteRef: string; remoteName: string; branchName: string } | null { + const trimmedRef = ref.trim(); + if (trimmedRef.length === 0) { + return null; + } + + for (const remoteName of remoteNames) { + const remotePrefix = `${remoteName}/`; + if (!trimmedRef.startsWith(remotePrefix)) { + continue; + } + const branchName = trimmedRef.slice(remotePrefix.length).trim(); + if (branchName.length === 0) { + return null; + } + return { + remoteRef: trimmedRef, + remoteName, + branchName, + }; + } + + return null; +} + +export function extractBranchNameFromRemoteRef( + ref: string, + options?: { + remoteName?: string | null; + remoteNames?: ReadonlyArray; + }, +): string { + const normalized = ref.trim(); + if (normalized.length === 0) { + return ""; + } + + if (normalized.startsWith("refs/remotes/")) { + return extractBranchNameFromRemoteRef(normalized.slice("refs/remotes/".length), options); + } + + const remoteNames = options?.remoteName ? [options.remoteName] : (options?.remoteNames ?? []); + const parsedRemoteRef = parseRemoteRefWithRemoteNames(normalized, remoteNames); + if (parsedRemoteRef) { + return parsedRemoteRef.branchName; + } + + const firstSlash = normalized.indexOf("/"); + if (firstSlash === -1) { + return normalized; + } + return normalized.slice(firstSlash + 1).trim(); +} diff --git a/apps/server/src/gitManager.test.ts b/apps/server/src/gitManager.test.ts deleted file mode 100644 index f2d399c8b8..0000000000 --- a/apps/server/src/gitManager.test.ts +++ /dev/null @@ -1,482 +0,0 @@ -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { afterEach, describe, expect, it } from "vitest"; - -import { GitManager } from "./gitManager"; -import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner"; - -interface FakeGhScenario { - prListSequence?: string[]; - createdPrUrl?: string; - defaultBranch?: string; - failWith?: Error; -} - -interface FakeGitTextGenerator { - generateCommitMessage: (input: { - cwd: string; - branch: string | null; - stagedSummary: string; - stagedPatch: string; - }) => Promise<{ subject: string; body: string }>; - generatePrContent: (input: { - cwd: string; - baseBranch: string; - headBranch: string; - commitSummary: string; - diffSummary: string; - diffPatch: string; - }) => Promise<{ title: string; body: string }>; -} - -const tempDirs: string[] = []; - -function makeTempDir(prefix: string): string { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); - tempDirs.push(dir); - return dir; -} - -async function runGit( - cwd: string, - args: readonly string[], - allowNonZeroExit = false, -): Promise { - return runProcess("git", args, { cwd, allowNonZeroExit }); -} - -async function runGitStdout(cwd: string, args: readonly string[]): Promise { - const result = await runGit(cwd, args); - return result.stdout.trim(); -} - -async function initRepo(cwd: string): Promise { - await runGit(cwd, ["init", "--initial-branch=main"]); - await runGit(cwd, ["config", "user.email", "test@example.com"]); - await runGit(cwd, ["config", "user.name", "Test User"]); - fs.writeFileSync(path.join(cwd, "README.md"), "hello\n"); - await runGit(cwd, ["add", "README.md"]); - await runGit(cwd, ["commit", "-m", "Initial commit"]); -} - -async function createBareRemote(): Promise { - const remoteDir = makeTempDir("t3code-git-remote-"); - await runProcess("git", ["init", "--bare"], { cwd: remoteDir }); - return remoteDir; -} - -function createTextGenerator(overrides: Partial = {}): FakeGitTextGenerator { - return { - generateCommitMessage: async () => ({ - subject: "Implement stacked git actions", - body: "", - }), - generatePrContent: async () => ({ - title: "Add stacked git actions", - body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run", - }), - ...overrides, - }; -} - -function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): { - runner: ( - command: string, - args: readonly string[], - options?: ProcessRunOptions, - ) => Promise; - ghCalls: string[]; -} { - const prListQueue = [...(scenario.prListSequence ?? [])]; - const ghCalls: string[] = []; - - const runner = async ( - command: string, - args: readonly string[], - options?: ProcessRunOptions, - ): Promise => { - if (command !== "gh") { - return runProcess(command, args, options); - } - - ghCalls.push(args.join(" ")); - if (scenario.failWith) { - throw scenario.failWith; - } - - if (args[0] === "pr" && args[1] === "list") { - const stdout = (prListQueue.shift() ?? "[]") + "\n"; - return { - stdout, - stderr: "", - code: 0, - signal: null, - timedOut: false, - }; - } - - if (args[0] === "pr" && args[1] === "create") { - return { - stdout: - (scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n", - stderr: "", - code: 0, - signal: null, - timedOut: false, - }; - } - - if (args[0] === "pr" && args[1] === "view") { - return { - stdout: "", - stderr: "", - code: 0, - signal: null, - timedOut: false, - }; - } - - if (args[0] === "repo" && args[1] === "view") { - return { - stdout: `${scenario.defaultBranch ?? "main"}\n`, - stderr: "", - code: 0, - signal: null, - timedOut: false, - }; - } - - throw new Error(`Unexpected gh command: ${args.join(" ")}`); - }; - - return { runner, ghCalls }; -} - -afterEach(() => { - for (const dir of tempDirs.splice(0, tempDirs.length)) { - fs.rmSync(dir, { recursive: true, force: true }); - } -}); - -describe("GitManager", () => { - it("status includes open PR metadata when branch already has an open PR", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - await runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]); - const remoteDir = await createBareRemote(); - await runGit(repoDir, ["remote", "add", "origin", remoteDir]); - await runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]); - - const { runner } = createRunnerWithFakeGh({ - prListSequence: [ - JSON.stringify([ - { - number: 13, - title: "Existing PR", - url: "https://github.com/pingdotgg/codething-mvp/pull/13", - baseRefName: "main", - headRefName: "feature/status-open-pr", - }, - ]), - ], - }); - - const manager = new GitManager({ - runProcess: runner, - textGenerator: createTextGenerator(), - }); - - const status = await manager.status({ cwd: repoDir }); - expect(status.branch).toBe("feature/status-open-pr"); - expect(status.openPr).toEqual({ - number: 13, - title: "Existing PR", - url: "https://github.com/pingdotgg/codething-mvp/pull/13", - baseBranch: "main", - headBranch: "feature/status-open-pr", - }); - }); - - it("status is resilient to gh lookup failures and returns openPr null", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - await runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]); - const remoteDir = await createBareRemote(); - await runGit(repoDir, ["remote", "add", "origin", remoteDir]); - await runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]); - - const { runner } = createRunnerWithFakeGh({ - failWith: new Error("Command not found: gh"), - }); - const manager = new GitManager({ - runProcess: runner, - textGenerator: createTextGenerator(), - }); - - const status = await manager.status({ cwd: repoDir }); - expect(status.branch).toBe("feature/status-no-gh"); - expect(status.openPr).toBeNull(); - }); - - it("creates a commit when working tree is dirty", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n"); - - const manager = new GitManager({ - textGenerator: createTextGenerator(), - }); - const result = await manager.runStackedAction({ - cwd: repoDir, - action: "commit", - }); - - expect(result.commit.status).toBe("created"); - expect(result.push.status).toBe("skipped_not_requested"); - expect(result.pr.status).toBe("skipped_not_requested"); - expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe( - "Implement stacked git actions", - ); - }); - - it("uses custom commit message when provided", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n"); - let generatedCount = 0; - - const manager = new GitManager({ - textGenerator: createTextGenerator({ - generateCommitMessage: async () => { - generatedCount += 1; - return { - subject: "this should not be used", - body: "", - }; - }, - }), - }); - const result = await manager.runStackedAction({ - cwd: repoDir, - action: "commit", - commitMessage: "feat: custom summary line\n\n- details from user", - }); - - expect(result.commit.status).toBe("created"); - expect(result.commit.subject).toBe("feat: custom summary line"); - expect(generatedCount).toBe(0); - expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe( - "feat: custom summary line", - ); - expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%b"])).toContain( - "- details from user", - ); - }); - - it("skips commit when there are no uncommitted changes", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - - const manager = new GitManager({ - textGenerator: createTextGenerator(), - }); - const result = await manager.runStackedAction({ - cwd: repoDir, - action: "commit", - }); - - expect(result.commit.status).toBe("skipped_no_changes"); - expect(result.push.status).toBe("skipped_not_requested"); - expect(result.pr.status).toBe("skipped_not_requested"); - }); - - it("commits and pushes with upstream auto-setup when needed", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - await runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]); - const remoteDir = await createBareRemote(); - await runGit(repoDir, ["remote", "add", "origin", remoteDir]); - fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n"); - - const manager = new GitManager({ - textGenerator: createTextGenerator(), - }); - const result = await manager.runStackedAction({ - cwd: repoDir, - action: "commit_push", - }); - - expect(result.commit.status).toBe("created"); - expect(result.push.status).toBe("pushed"); - expect(result.push.setUpstream).toBe(true); - expect(await runGitStdout(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( - "origin/feature/stacked-flow", - ); - }); - - it("skips push when branch is already up to date", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - await runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]); - const remoteDir = await createBareRemote(); - await runGit(repoDir, ["remote", "add", "origin", remoteDir]); - await runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]); - - const manager = new GitManager({ - textGenerator: createTextGenerator(), - }); - const result = await manager.runStackedAction({ - cwd: repoDir, - action: "commit_push", - }); - - expect(result.commit.status).toBe("skipped_no_changes"); - expect(result.push.status).toBe("skipped_up_to_date"); - }); - - it("returns existing PR metadata for commit/push/pr action", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - await runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]); - const remoteDir = await createBareRemote(); - await runGit(repoDir, ["remote", "add", "origin", remoteDir]); - await runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]); - - const { runner, ghCalls } = createRunnerWithFakeGh({ - prListSequence: [ - JSON.stringify([ - { - number: 42, - title: "Existing PR", - url: "https://github.com/pingdotgg/codething-mvp/pull/42", - baseRefName: "main", - headRefName: "feature/existing-pr", - }, - ]), - ], - }); - - const manager = new GitManager({ - runProcess: runner, - textGenerator: createTextGenerator(), - }); - const result = await manager.runStackedAction({ - cwd: repoDir, - action: "commit_push_pr", - }); - - expect(result.pr.status).toBe("opened_existing"); - expect(result.pr.number).toBe(42); - expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false); - }); - - it("creates PR when one does not already exist", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - await runGit(repoDir, ["checkout", "-b", "feature-create-pr"]); - const remoteDir = await createBareRemote(); - await runGit(repoDir, ["remote", "add", "origin", remoteDir]); - fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n"); - await runGit(repoDir, ["add", "changes.txt"]); - await runGit(repoDir, ["commit", "-m", "Feature commit"]); - await runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]); - await runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]); - - const { runner, ghCalls } = createRunnerWithFakeGh({ - prListSequence: [ - "[]", - JSON.stringify([ - { - number: 88, - title: "Add stacked git actions", - url: "https://github.com/pingdotgg/codething-mvp/pull/88", - baseRefName: "main", - headRefName: "feature-create-pr", - }, - ]), - ], - }); - - const manager = new GitManager({ - runProcess: runner, - textGenerator: createTextGenerator(), - }); - const result = await manager.runStackedAction({ - cwd: repoDir, - action: "commit_push_pr", - }); - - expect(result.pr.status).toBe("created"); - expect(result.pr.number).toBe(88); - expect( - ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")), - ).toBe(true); - expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false); - }); - - it("rejects push/pr actions from detached HEAD", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - await runGit(repoDir, ["checkout", "--detach", "HEAD"]); - - const manager = new GitManager({ - textGenerator: createTextGenerator(), - }); - await expect( - manager.runStackedAction({ - cwd: repoDir, - action: "commit_push", - }), - ).rejects.toThrow("detached HEAD"); - }); - - it("surfaces missing gh binary errors", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - await runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]); - const remoteDir = await createBareRemote(); - await runGit(repoDir, ["remote", "add", "origin", remoteDir]); - await runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]); - - const { runner } = createRunnerWithFakeGh({ - failWith: new Error("Command not found: gh"), - }); - const manager = new GitManager({ - runProcess: runner, - textGenerator: createTextGenerator(), - }); - - await expect( - manager.runStackedAction({ - cwd: repoDir, - action: "commit_push_pr", - }), - ).rejects.toThrow("GitHub CLI (`gh`) is required"); - }); - - it("surfaces gh auth errors with guidance", async () => { - const repoDir = makeTempDir("t3code-git-manager-"); - await initRepo(repoDir); - await runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]); - const remoteDir = await createBareRemote(); - await runGit(repoDir, ["remote", "add", "origin", remoteDir]); - await runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]); - - const { runner } = createRunnerWithFakeGh({ - failWith: new Error("authentication failed"), - }); - const manager = new GitManager({ - runProcess: runner, - textGenerator: createTextGenerator(), - }); - - await expect( - manager.runStackedAction({ - cwd: repoDir, - action: "commit_push_pr", - }), - ).rejects.toThrow("gh auth login"); - }); -}); diff --git a/apps/server/src/gitManager.ts b/apps/server/src/gitManager.ts deleted file mode 100644 index a9d7689513..0000000000 --- a/apps/server/src/gitManager.ts +++ /dev/null @@ -1,467 +0,0 @@ -import { randomUUID } from "node:crypto"; -import fs from "node:fs/promises"; -import os from "node:os"; -import path from "node:path"; - -import { - gitRunStackedActionInputSchema, - gitRunStackedActionResultSchema, - gitStatusInputSchema, - type GitRunStackedActionInput, - type GitRunStackedActionResult, - type GitStatusInput, - type GitStatusResult, -} from "@t3tools/contracts"; - -import type { - CommitMessageGenerationResult, - PrContentGenerationResult, - TextGenerationService, -} from "./coreServices"; -import { CodexTextGenerator } from "./codexTextGenerator"; -import { GitCoreService } from "./git"; -import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner"; - -const GH_CLI_TIMEOUT_MS = 30_000; - -interface GitManagerDeps { - runProcess?: ( - command: string, - args: readonly string[], - options?: ProcessRunOptions, - ) => Promise; - textGenerator?: TextGenerationService; - gitCore?: GitCoreService; -} - -interface OpenPrInfo { - number: number; - title: string; - url: string; - baseRefName: string; - headRefName: string; -} - -function parseOpenPrList(raw: unknown): OpenPrInfo[] { - if (!Array.isArray(raw)) return []; - - const parsed: OpenPrInfo[] = []; - for (const entry of raw) { - if (!entry || typeof entry !== "object") continue; - const record = entry as Record; - const number = record.number; - const title = record.title; - const url = record.url; - const baseRefName = record.baseRefName; - const headRefName = record.headRefName; - if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) { - continue; - } - if ( - typeof title !== "string" || - typeof url !== "string" || - typeof baseRefName !== "string" || - typeof headRefName !== "string" - ) { - continue; - } - parsed.push({ - number, - title, - url, - baseRefName, - headRefName, - }); - } - return parsed; -} - -function trimStdout(value: string): string { - return value.trim(); -} - -function limitContext(value: string, maxChars: number): string { - if (value.length <= maxChars) return value; - return `${value.slice(0, maxChars)}\n\n[truncated]`; -} - -function sanitizeCommitMessage( - generated: CommitMessageGenerationResult, -): CommitMessageGenerationResult { - const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? ""; - const subject = rawSubject.replace(/[.]+$/g, "").trim(); - const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files"; - return { - subject: safeSubject, - body: generated.body.trim(), - }; -} - -function parseCustomCommitMessage(raw: string): CommitMessageGenerationResult | null { - const normalized = raw.replace(/\r\n/g, "\n").trim(); - if (normalized.length === 0) { - return null; - } - - const [firstLine, ...rest] = normalized.split("\n"); - const subject = firstLine?.trim() ?? ""; - if (subject.length === 0) { - return null; - } - - return { - subject, - body: rest.join("\n").trim(), - }; -} - -function extractBranchFromRef(ref: string): string { - const normalized = ref.trim(); - - if (normalized.startsWith("refs/remotes/")) { - const withoutPrefix = normalized.slice("refs/remotes/".length); - const firstSlash = withoutPrefix.indexOf("/"); - if (firstSlash === -1) { - return withoutPrefix.trim(); - } - return withoutPrefix.slice(firstSlash + 1).trim(); - } - - const firstSlash = normalized.indexOf("/"); - if (firstSlash === -1) { - return normalized; - } - return normalized.slice(firstSlash + 1).trim(); -} - -function asCommandNotFound(command: string, error: unknown): Error | undefined { - if (!(error instanceof Error)) return undefined; - if (!error.message.includes(`Command not found: ${command}`)) return undefined; - if (command === "gh") { - return new Error("GitHub CLI (`gh`) is required but not available on PATH."); - } - if (command === "codex") { - return new Error("Codex CLI (`codex`) is required but not available on PATH."); - } - return new Error(`${command} is required but not available on PATH.`); -} - -function normalizeGitHubAuthError(error: unknown): Error | undefined { - if (!(error instanceof Error)) return undefined; - const lower = error.message.toLowerCase(); - if ( - lower.includes("authentication failed") || - lower.includes("not logged in") || - lower.includes("gh auth login") || - lower.includes("no oauth token") - ) { - return new Error("GitHub CLI is not authenticated. Run `gh auth login` and retry."); - } - return undefined; -} - -function toStatusOpenPr(pr: OpenPrInfo): { - number: number; - title: string; - url: string; - baseBranch: string; - headBranch: string; -} { - return { - number: pr.number, - title: pr.title, - url: pr.url, - baseBranch: pr.baseRefName, - headBranch: pr.headRefName, - }; -} - -export class GitManager { - private readonly run: NonNullable; - private readonly textGenerator: TextGenerationService; - private readonly gitCore: GitCoreService; - - constructor(deps: GitManagerDeps = {}) { - this.run = deps.runProcess ?? runProcess; - this.textGenerator = deps.textGenerator ?? new CodexTextGenerator(); - this.gitCore = deps.gitCore ?? new GitCoreService(); - } - - async status(raw: GitStatusInput): Promise { - const input = gitStatusInputSchema.parse(raw); - const details = await this.gitCore.statusDetails(input.cwd); - - let openPr: ReturnType | null = null; - if (details.branch && details.hasUpstream) { - try { - const existing = await this.findOpenPr(input.cwd, details.branch); - if (existing) { - openPr = toStatusOpenPr(existing); - } - } catch { - // PR lookup is best-effort for status rendering. - } - } - - return { - branch: details.branch, - hasWorkingTreeChanges: details.hasWorkingTreeChanges, - workingTree: details.workingTree, - hasUpstream: details.hasUpstream, - aheadCount: details.aheadCount, - behindCount: details.behindCount, - openPr, - }; - } - - async runStackedAction(raw: GitRunStackedActionInput): Promise { - const input = gitRunStackedActionInputSchema.parse(raw); - const wantsPush = input.action !== "commit"; - const wantsPr = input.action === "commit_push_pr"; - - const initialStatus = await this.gitCore.statusDetails(input.cwd); - if (wantsPush && !initialStatus.branch) { - throw new Error("Cannot push from detached HEAD."); - } - if (wantsPr && !initialStatus.branch) { - throw new Error("Cannot create a pull request from detached HEAD."); - } - - const commit = await this.runCommitStep(input.cwd, initialStatus.branch, input.commitMessage); - - const push = wantsPush - ? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch) - : { status: "skipped_not_requested" as const }; - - const pr = wantsPr - ? await this.runPrStep(input.cwd, initialStatus.branch) - : { status: "skipped_not_requested" as const }; - - return gitRunStackedActionResultSchema.parse({ - action: input.action, - commit, - push, - pr, - }); - } - - private async runCommitStep( - cwd: string, - branch: string | null, - commitMessage?: string, - ): Promise<{ - status: "created" | "skipped_no_changes"; - commitSha?: string | undefined; - subject?: string | undefined; - }> { - const context = await this.gitCore.prepareCommitContext(cwd); - if (!context) { - return { status: "skipped_no_changes" }; - } - - let generated: CommitMessageGenerationResult | null = parseCustomCommitMessage( - commitMessage ?? "", - ); - - if (!generated) { - try { - generated = sanitizeCommitMessage( - await this.textGenerator.generateCommitMessage({ - cwd, - branch, - stagedSummary: limitContext(context.stagedSummary, 8_000), - stagedPatch: limitContext(context.stagedPatch, 50_000), - }), - ); - } catch (error) { - throw asCommandNotFound("codex", error) ?? error; - } - } - - const { commitSha } = await this.gitCore.commit(cwd, generated.subject, generated.body); - return { - status: "created", - commitSha, - subject: generated.subject, - }; - } - - private async runPrStep( - cwd: string, - fallbackBranch: string | null, - ): Promise<{ - status: "created" | "opened_existing" | "skipped_not_requested"; - url?: string | undefined; - number?: number | undefined; - baseBranch?: string | undefined; - headBranch?: string | undefined; - title?: string | undefined; - }> { - const details = await this.gitCore.statusDetails(cwd); - const branch = details.branch ?? fallbackBranch; - if (!branch) { - throw new Error("Cannot create a pull request from detached HEAD."); - } - if (!details.hasUpstream) { - throw new Error("Current branch has not been pushed. Push before creating a PR."); - } - - const existing = await this.findOpenPr(cwd, branch); - if (existing) { - return { - status: "opened_existing", - url: existing.url, - number: existing.number, - baseBranch: existing.baseRefName, - headBranch: existing.headRefName, - title: existing.title, - }; - } - - const baseBranch = await this.resolveBaseBranch(cwd, branch, details.upstreamRef); - const rangeContext = await this.gitCore.readRangeContext(cwd, baseBranch); - - let generated: PrContentGenerationResult; - try { - generated = await this.textGenerator.generatePrContent({ - cwd, - baseBranch, - headBranch: branch, - commitSummary: limitContext(rangeContext.commitSummary, 20_000), - diffSummary: limitContext(rangeContext.diffSummary, 20_000), - diffPatch: limitContext(rangeContext.diffPatch, 60_000), - }); - } catch (error) { - throw asCommandNotFound("codex", error) ?? error; - } - - const bodyFile = path.join(os.tmpdir(), `t3code-pr-body-${process.pid}-${randomUUID()}.md`); - await fs.writeFile(bodyFile, generated.body, "utf8"); - - try { - await this.runGh(cwd, [ - "pr", - "create", - "--base", - baseBranch, - "--head", - branch, - "--title", - generated.title, - "--body-file", - bodyFile, - ]); - } finally { - try { - await fs.unlink(bodyFile); - } catch { - // Best-effort cleanup. - } - } - - const created = await this.findOpenPr(cwd, branch); - - if (!created) { - return { - status: "created", - baseBranch, - headBranch: branch, - title: generated.title, - }; - } - - return { - status: "created", - url: created.url, - number: created.number, - baseBranch: created.baseRefName, - headBranch: created.headRefName, - title: created.title, - }; - } - - private async findOpenPr(cwd: string, branch: string): Promise { - const stdout = await this.runGhStdout(cwd, [ - "pr", - "list", - "--head", - branch, - "--state", - "open", - "--limit", - "1", - "--json", - "number,title,url,baseRefName,headRefName", - ]); - - const raw = trimStdout(stdout); - if (raw.length === 0) return null; - - let parsedJson: unknown; - try { - parsedJson = JSON.parse(raw); - } catch { - throw new Error("GitHub CLI returned invalid PR list JSON."); - } - - const parsed = parseOpenPrList(parsedJson); - return parsed[0] ?? null; - } - - private async resolveBaseBranch( - cwd: string, - branch: string, - upstreamRef: string | null, - ): Promise { - const configured = await this.gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`); - if (configured) return configured; - - if (upstreamRef) { - const upstreamBranch = extractBranchFromRef(upstreamRef); - if (upstreamBranch.length > 0 && upstreamBranch !== branch) { - return upstreamBranch; - } - } - - try { - const ghDefault = await this.runGhStdout(cwd, [ - "repo", - "view", - "--json", - "defaultBranchRef", - "--jq", - ".defaultBranchRef.name", - ]); - const defaultBranch = trimStdout(ghDefault); - if (defaultBranch.length > 0) return defaultBranch; - } catch { - // Fall through to deterministic fallback. - } - - return "main"; - } - - private async runGh(cwd: string, args: readonly string[]): Promise { - await this.runGhCommand(cwd, args); - } - - private async runGhStdout(cwd: string, args: readonly string[]): Promise { - const result = await this.runGhCommand(cwd, args); - return result.stdout; - } - - private async runGhCommand(cwd: string, args: readonly string[]): Promise { - try { - return await this.run("gh", args, { - cwd, - timeoutMs: GH_CLI_TIMEOUT_MS, - }); - } catch (error) { - throw ( - asCommandNotFound("gh", error) ?? - normalizeGitHubAuthError(error) ?? - (error instanceof Error ? error : new Error("GitHub CLI command failed.")) - ); - } - } -} diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts new file mode 100644 index 0000000000..cee08b4f98 --- /dev/null +++ b/apps/server/src/http.ts @@ -0,0 +1,197 @@ +import Mime from "@effect/platform-node/Mime"; +import { Effect, FileSystem, Option, Path } from "effect"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; + +import { + ATTACHMENTS_ROUTE_PREFIX, + normalizeAttachmentRelativePath, + resolveAttachmentRelativePath, +} from "./attachmentPaths"; +import { resolveAttachmentPathById } from "./attachmentStore"; +import { ServerConfig } from "./config"; +import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver"; + +const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600"; +const FALLBACK_PROJECT_FAVICON_SVG = ``; + +export const attachmentsRouteLayer = HttpRouter.add( + "GET", + `${ATTACHMENTS_ROUTE_PREFIX}/*`, + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) { + return HttpServerResponse.text("Bad Request", { status: 400 }); + } + + const config = yield* ServerConfig; + const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length); + const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath); + if (!normalizedRelativePath) { + return HttpServerResponse.text("Invalid attachment path", { status: 400 }); + } + + const isIdLookup = + !normalizedRelativePath.includes("/") && !normalizedRelativePath.includes("."); + const filePath = isIdLookup + ? resolveAttachmentPathById({ + attachmentsDir: config.attachmentsDir, + attachmentId: normalizedRelativePath, + }) + : resolveAttachmentRelativePath({ + attachmentsDir: config.attachmentsDir, + relativePath: normalizedRelativePath, + }); + if (!filePath) { + return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", { + status: isIdLookup ? 404 : 400, + }); + } + + const fileSystem = yield* FileSystem.FileSystem; + const fileInfo = yield* fileSystem + .stat(filePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!fileInfo || fileInfo.type !== "File") { + return HttpServerResponse.text("Not Found", { status: 404 }); + } + + return yield* HttpServerResponse.file(filePath, { + status: 200, + headers: { + "Cache-Control": "public, max-age=31536000, immutable", + }, + }).pipe( + Effect.catch(() => + Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })), + ), + ); + }), +); + +export const projectFaviconRouteLayer = HttpRouter.add( + "GET", + "/api/project-favicon", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) { + return HttpServerResponse.text("Bad Request", { status: 400 }); + } + + const projectCwd = url.value.searchParams.get("cwd"); + if (!projectCwd) { + return HttpServerResponse.text("Missing cwd parameter", { status: 400 }); + } + + const faviconResolver = yield* ProjectFaviconResolver; + const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd); + if (!faviconFilePath) { + return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, { + status: 200, + contentType: "image/svg+xml", + headers: { + "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL, + }, + }); + } + + return yield* HttpServerResponse.file(faviconFilePath, { + status: 200, + headers: { + "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL, + }, + }).pipe( + Effect.catch(() => + Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })), + ), + ); + }), +); + +export const staticAndDevRouteLayer = HttpRouter.add( + "GET", + "*", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) { + return HttpServerResponse.text("Bad Request", { status: 400 }); + } + + const config = yield* ServerConfig; + if (config.devUrl) { + return HttpServerResponse.redirect(config.devUrl.href, { status: 302 }); + } + + if (!config.staticDir) { + return HttpServerResponse.text("No static directory configured and no dev URL set.", { + status: 503, + }); + } + + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const staticRoot = path.resolve(config.staticDir); + const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname; + const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, ""); + const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith(".."); + const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, ""); + const hasPathTraversalSegment = staticRelativePath.startsWith(".."); + if ( + staticRelativePath.length === 0 || + hasRawLeadingParentSegment || + hasPathTraversalSegment || + staticRelativePath.includes("\0") + ) { + return HttpServerResponse.text("Invalid static file path", { status: 400 }); + } + + const isWithinStaticRoot = (candidate: string) => + candidate === staticRoot || + candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`); + + let filePath = path.resolve(staticRoot, staticRelativePath); + if (!isWithinStaticRoot(filePath)) { + return HttpServerResponse.text("Invalid static file path", { status: 400 }); + } + + const ext = path.extname(filePath); + if (!ext) { + filePath = path.resolve(filePath, "index.html"); + if (!isWithinStaticRoot(filePath)) { + return HttpServerResponse.text("Invalid static file path", { status: 400 }); + } + } + + const fileInfo = yield* fileSystem + .stat(filePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!fileInfo || fileInfo.type !== "File") { + const indexPath = path.resolve(staticRoot, "index.html"); + const indexData = yield* fileSystem + .readFile(indexPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!indexData) { + return HttpServerResponse.text("Not Found", { status: 404 }); + } + return HttpServerResponse.uint8Array(indexData, { + status: 200, + contentType: "text/html; charset=utf-8", + }); + } + + const contentType = Mime.getType(filePath) ?? "application/octet-stream"; + const data = yield* fileSystem + .readFile(filePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!data) { + return HttpServerResponse.text("Internal Server Error", { status: 500 }); + } + + return HttpServerResponse.uint8Array(data, { + status: 200, + contentType, + }); + }), +); diff --git a/apps/server/src/imageMime.test.ts b/apps/server/src/imageMime.test.ts new file mode 100644 index 0000000000..ceec282794 --- /dev/null +++ b/apps/server/src/imageMime.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; + +import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts"; + +describe("imageMime", () => { + it("parses base64 data URL with mime type", () => { + expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({ + mimeType: "image/png", + base64: "SGVsbG8=", + }); + }); + + it("parses base64 data URL with mime parameters", () => { + expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({ + mimeType: "image/png", + base64: "SGVsbG8=", + }); + }); + + it("rejects non-base64 data URL", () => { + expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull(); + }); + + it("rejects missing mime type", () => { + expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull(); + }); + + it("parses base64 data URL with spaces in payload", () => { + expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({ + mimeType: "image/png", + base64: "SGVsbG8=", + }); + }); + + it("does not read inherited keys from mime extension map", () => { + expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin"); + }); +}); diff --git a/apps/server/src/imageMime.ts b/apps/server/src/imageMime.ts new file mode 100644 index 0000000000..814abbb32c --- /dev/null +++ b/apps/server/src/imageMime.ts @@ -0,0 +1,79 @@ +import Mime from "@effect/platform-node/Mime"; + +export const IMAGE_EXTENSION_BY_MIME_TYPE: Record = { + "image/avif": ".avif", + "image/bmp": ".bmp", + "image/gif": ".gif", + "image/heic": ".heic", + "image/heif": ".heif", + "image/jpeg": ".jpg", + "image/jpg": ".jpg", + "image/png": ".png", + "image/svg+xml": ".svg", + "image/tiff": ".tiff", + "image/webp": ".webp", +}; + +export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([ + ".avif", + ".bmp", + ".gif", + ".heic", + ".heif", + ".ico", + ".jpeg", + ".jpg", + ".png", + ".svg", + ".tiff", + ".webp", +]); + +export function parseBase64DataUrl( + dataUrl: string, +): { readonly mimeType: string; readonly base64: string } | null { + const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim()); + if (!match) return null; + + const headerParts = (match[1] ?? "") + .split(";") + .map((part) => part.trim()) + .filter((part) => part.length > 0); + if (headerParts.length < 2) { + return null; + } + const trailingToken = headerParts.at(-1)?.toLowerCase(); + if (trailingToken !== "base64") { + return null; + } + + const mimeType = headerParts[0]?.toLowerCase(); + const base64 = match[2]?.replace(/\s+/g, ""); + if (!mimeType || !base64) return null; + + return { mimeType, base64 }; +} + +export function inferImageExtension(input: { mimeType: string; fileName?: string }): string { + const key = input.mimeType.toLowerCase(); + const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key) + ? IMAGE_EXTENSION_BY_MIME_TYPE[key] + : undefined; + if (fromMime) { + return fromMime; + } + + const fromMimeExtension = Mime.getExtension(input.mimeType); + if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) { + return fromMimeExtension; + } + + const fileName = input.fileName?.trim() ?? ""; + const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName); + const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : ""; + if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) { + return fileNameExtension; + } + + return ".bin"; +} diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts deleted file mode 100644 index d340657608..0000000000 --- a/apps/server/src/index.ts +++ /dev/null @@ -1,176 +0,0 @@ -import fs from "node:fs"; -import net from "node:net"; -import os from "node:os"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -import { fixPath } from "./fixPath"; -import { createLogger } from "./logger"; -import { ProjectRegistry } from "./projectRegistry"; -import { createServer } from "./wsServer"; - -fixPath(); - -const DEFAULT_PORT = 3773; -const cwd = process.cwd(); -const logger = createLogger("server"); - -type RuntimeMode = "web" | "desktop"; - -function parseBooleanEnv(value: string | undefined): boolean | undefined { - if (value === undefined) return undefined; - const normalized = value.trim().toLowerCase(); - if (["1", "true", "yes", "on"].includes(normalized)) return true; - if (["0", "false", "no", "off"].includes(normalized)) return false; - return undefined; -} - -function parsePort(value: string | undefined): number | undefined { - if (!value) return undefined; - const parsed = Number(value); - if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) { - throw new Error(`Invalid T3CODE_PORT: ${value}`); - } - return parsed; -} - -function expandHomePath(input: string): string { - if (input === "~") return os.homedir(); - if (input.startsWith("~/")) { - return path.join(os.homedir(), input.slice(2)); - } - return input; -} - -function resolveStateDir(raw: string | undefined): string { - if (!raw || raw.trim().length === 0) { - return path.join(os.homedir(), ".t3", "userdata"); - } - return path.resolve(expandHomePath(raw.trim())); -} - -async function findAvailablePort(preferred: number): Promise { - return new Promise((resolve, reject) => { - const server = net.createServer(); - server.listen(preferred, () => { - server.close(() => resolve(preferred)); - }); - server.on("error", () => { - // Preferred port busy — let the OS pick one - const fallback = net.createServer(); - fallback.listen(0, () => { - const addr = fallback.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - fallback.close(() => { - if (port > 0) resolve(port); - else reject(new Error("Could not find an available port.")); - }); - }); - fallback.on("error", reject); - }); - }); -} - -function resolveStaticDir(): string | undefined { - const __dirname = path.dirname(fileURLToPath(import.meta.url)); - - // Check for bundled client (npm publish / npx scenario): - // dist/client/ lives alongside dist/index.js - const bundledClient = path.resolve(__dirname, "client"); - try { - const stat = fs.statSync(path.join(bundledClient, "index.html")); - if (stat.isFile()) return bundledClient; - } catch { - // Not bundled — check monorepo layout - } - - // Monorepo layout: apps/server/dist/index.js → apps/web/dist/ - const monorepoClient = path.resolve(__dirname, "../../web/dist"); - try { - const stat = fs.statSync(path.join(monorepoClient, "index.html")); - if (stat.isFile()) return monorepoClient; - } catch { - // Not found — probably dev mode, Vite will serve - } - - return undefined; -} - -async function main() { - const mode: RuntimeMode = process.env.T3CODE_MODE === "desktop" ? "desktop" : "web"; - const requestedPort = parsePort(process.env.T3CODE_PORT); - const port = - requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT)); - const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR); - const projectRegistry = new ProjectRegistry(stateDir); - const devUrl = process.env.VITE_DEV_SERVER_URL; - const noBrowser = parseBooleanEnv(process.env.T3CODE_NO_BROWSER) ?? mode === "desktop"; - const authToken = process.env.T3CODE_AUTH_TOKEN; - const staticDir = devUrl ? undefined : resolveStaticDir(); - - if (!devUrl && !staticDir) { - logger.warn("web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable", { - hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.", - }); - } - - const server = createServer({ - port, - host: mode === "desktop" ? "127.0.0.1" : undefined, - cwd, - staticDir, - devUrl, - projectRegistry, - authToken, - }); - await server.start(); - - const url = `http://localhost:${port}`; - logger.info("T3 Code running", { - url, - cwd, - mode, - stateDir, - authEnabled: Boolean(authToken), - }); - - // Open browser (dynamic import because `open` is ESM-only) - if (!noBrowser) { - try { - const open = await import("open"); - const target = devUrl ?? url; - await open.default(target); - } catch { - logger.info("browser auto-open unavailable", { - hint: `Open ${devUrl ?? url} in your browser.`, - }); - } - } - - // Graceful shutdown - let shuttingDown = false; - async function shutdown() { - if (shuttingDown) return; - shuttingDown = true; - logger.info("shutting down"); - try { - await server.stop(); - process.exit(0); - } catch (error) { - logger.error("failed to stop server cleanly", { error }); - process.exit(1); - } - } - - process.on("SIGINT", () => { - void shutdown(); - }); - process.on("SIGTERM", () => { - void shutdown(); - }); -} - -main().catch((err) => { - logger.error("failed to start T3 Code", { error: err }); - process.exit(1); -}); diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index d761588e93..8eda0ca85d 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -1,69 +1,503 @@ -import { assert, describe, it } from "vitest"; +import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/contracts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { assertFailure } from "@effect/vitest/utils"; +import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect"; +import { ServerConfig } from "./config"; -import { compileResolvedKeybindingRule, parseKeybindingShortcut } from "./keybindings"; +import { + DEFAULT_KEYBINDINGS, + Keybindings, + KeybindingsLive, + ResolvedKeybindingFromConfig, + compileResolvedKeybindingRule, + compileResolvedKeybindingsConfig, + parseKeybindingShortcut, +} from "./keybindings"; +import { KeybindingsConfigError } from "@t3tools/contracts"; -describe("server keybindings", () => { - it("parses shortcuts including plus key", () => { - assert.deepEqual(parseKeybindingShortcut("mod+j"), { - key: "j", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }); - assert.deepEqual(parseKeybindingShortcut("mod++"), { - key: "+", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }); +const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig); +const makeKeybindingsLayer = () => { + return KeybindingsLive.pipe( + Layer.provideMerge( + Layer.fresh( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3code-keybindings-test-", + }), + ), + ), + ); +}; + +const toDetailResult = (effect: Effect.Effect) => + effect.pipe( + Effect.mapError((error) => error.detail), + Effect.result, + ); + +const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules); + yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true }); + yield* fileSystem.writeFileString(configPath, encoded); }); - it("compiles valid rule with parsed when AST", () => { - const compiled = compileResolvedKeybindingRule({ - key: "mod+d", - command: "terminal.split", - when: "terminalOpen && !terminalFocus", - }); +const readKeybindingsConfig = (configPath: string) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const rawConfig = yield* fileSystem.readFileString(configPath); + return yield* Schema.decodeUnknownEffect(KeybindingsConfigJson)(rawConfig); + }); - assert.deepEqual(compiled, { - command: "terminal.split", - shortcut: { - key: "d", +it.layer(NodeServices.layer)("keybindings", (it) => { + it.effect("parses shortcuts including plus key", () => + Effect.sync(() => { + assert.deepEqual(parseKeybindingShortcut("mod+j"), { + key: "j", metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, modKey: true, - }, - whenAst: { - type: "and", - left: { type: "identifier", name: "terminalOpen" }, - right: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - }); - }); + }); + assert.deepEqual(parseKeybindingShortcut("mod++"), { + key: "+", + metaKey: false, + ctrlKey: false, + shiftKey: false, + altKey: false, + modKey: true, + }); + }), + ); - it("rejects invalid rules", () => { - assert.isNull( - compileResolvedKeybindingRule({ - key: "mod+shift+d+o", - command: "terminal.new", - }), - ); - - assert.isNull( - compileResolvedKeybindingRule({ + it.effect("compiles valid rule with parsed when AST", () => + Effect.sync(() => { + const compiled = compileResolvedKeybindingRule({ key: "mod+d", command: "terminal.split", - when: "terminalFocus && (", - }), + when: "terminalOpen && !terminalFocus", + }); + + assert.deepEqual(compiled, { + command: "terminal.split", + shortcut: { + key: "d", + metaKey: false, + ctrlKey: false, + shiftKey: false, + altKey: false, + modKey: true, + }, + whenAst: { + type: "and", + left: { type: "identifier", name: "terminalOpen" }, + right: { + type: "not", + node: { type: "identifier", name: "terminalFocus" }, + }, + }, + }); + }), + ); + + it.effect("encodes resolved plus-key shortcuts", () => + Effect.gen(function* () { + const encoded = yield* Schema.encodeEffect(ResolvedKeybindingFromConfig)({ + command: "terminal.toggle", + shortcut: { + key: "+", + metaKey: false, + ctrlKey: false, + shiftKey: false, + altKey: false, + modKey: true, + }, + }); + + assert.equal(encoded.key, "mod++"); + assert.equal(encoded.command, "terminal.toggle"); + }), + ); + + it.effect("rejects invalid rules", () => + Effect.sync(() => { + assert.isNull( + compileResolvedKeybindingRule({ + key: "mod+shift+d+o", + command: "terminal.new", + }), + ); + + assert.isNull( + compileResolvedKeybindingRule({ + key: "mod+d", + command: "terminal.split", + when: "terminalFocus && (", + }), + ); + + assert.isNull( + compileResolvedKeybindingRule({ + key: "mod+d", + command: "terminal.split", + when: `${"!".repeat(300)}terminalFocus`, + }), + ); + }), + ); + + it.effect("bootstraps default keybindings when config file is missing", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { keybindingsConfigPath } = yield* ServerConfig; + assert.isFalse(yield* fs.exists(keybindingsConfigPath)); + + yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + yield* keybindings.syncDefaultKeybindingsOnStartup; + }); + + const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); + assert.deepEqual(persisted, DEFAULT_KEYBINDINGS); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("ships configurable thread navigation defaults", () => + Effect.sync(() => { + const defaultsByCommand = new Map( + DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const), + ); + + assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+["); + assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]"); + assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1"); + assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9"); + }), + ); + + it.effect("uses defaults in runtime when config is malformed without overriding file", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { keybindingsConfigPath } = yield* ServerConfig; + yield* fs.writeFileString(keybindingsConfigPath, "{ not-json"); + + const configState = yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + return yield* keybindings.loadConfigState; + }); + + assert.deepEqual( + configState.keybindings, + compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS), + ); + assert.deepEqual(configState.issues, [ + { + kind: "keybindings.malformed-config", + message: configState.issues[0]?.message ?? "", + }, + ]); + assert.equal(yield* fs.readFileString(keybindingsConfigPath), "{ not-json"); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("ignores invalid entries in runtime and reports them as issues", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { keybindingsConfigPath } = yield* ServerConfig; + yield* fs.writeFileString( + keybindingsConfigPath, + JSON.stringify([ + { key: "mod+j", command: "terminal.toggle" }, + { key: "mod+shift+d+o", command: "terminal.new" }, + { key: "mod+x", command: "invalid.command" }, + ]), + ); + + const configState = yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + return yield* keybindings.loadConfigState; + }); + + assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle")); + assert.isFalse( + configState.keybindings.some((entry) => String(entry.command) === "invalid.command"), + ); + assert.deepEqual(configState.issues, [ + { + kind: "keybindings.invalid-entry", + index: 1, + message: configState.issues[0]?.message ?? "", + }, + { + kind: "keybindings.invalid-entry", + index: 2, + message: configState.issues[1]?.message ?? "", + }, + ]); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect( + "upserts missing default keybindings on startup without overriding existing command rules", + () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, [ + { key: "mod+shift+t", command: "terminal.toggle" }, + { key: "mod+shift+r", command: "script.run-tests.run" }, + ]); + + yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + yield* keybindings.syncDefaultKeybindingsOnStartup; + }); + + const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); + const byCommand = new Map(persisted.map((entry) => [entry.command, entry])); + + const persistedToggle = byCommand.get("terminal.toggle"); + assert.isNotNull(persistedToggle); + assert.equal(persistedToggle?.key, "mod+shift+t"); + assert.isFalse( + persisted.some((entry) => entry.command === "terminal.toggle" && entry.key === "mod+j"), + ); + + for (const defaultRule of DEFAULT_KEYBINDINGS) { + assert.isTrue(byCommand.has(defaultRule.command), `expected ${defaultRule.command}`); + } + assert.isTrue(byCommand.has("script.run-tests.run")); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("skips conflicting default keybindings on startup and logs a detailed warning", () => { + const messages: string[] = []; + const logger = Logger.make(({ message }) => { + messages.push(String(message)); + }); + + return Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, [ + { key: "mod+j", command: "script.custom-action.run" }, + ]); + + yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + yield* keybindings.syncDefaultKeybindingsOnStartup; + }); + + const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); + assert.isFalse(persisted.some((entry) => entry.command === "terminal.toggle")); + assert.isTrue(persisted.some((entry) => entry.command === "script.custom-action.run")); + + assert.isTrue( + messages.some((message) => + message.includes("skipping default keybinding due to shortcut conflict"), + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + makeKeybindingsLayer(), + Logger.layer([logger], { mergeWithExisting: false }), + ), + ), ); }); + + it.effect("upserts custom keybindings to configured path", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, [ + { key: "mod+j", command: "terminal.toggle" }, + ]); + + const resolved = yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + return yield* keybindings.upsertKeybindingRule({ + key: "mod+shift+r", + command: "script.run-tests.run", + }); + }); + + const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); + const persistedView = persisted.map(({ key, command }) => ({ key, command })); + + assert.deepEqual(persistedView, [ + { key: "mod+j", command: "terminal.toggle" }, + { key: "mod+shift+r", command: "script.run-tests.run" }, + ]); + assert.isTrue(resolved.some((entry) => entry.command === "script.run-tests.run")); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("replaces existing custom keybinding for the same command", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, [ + { key: "mod+r", command: "script.run-tests.run" }, + ]); + yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + return yield* keybindings.upsertKeybindingRule({ + key: "mod+shift+r", + command: "script.run-tests.run", + }); + }); + + const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); + const persistedView = persisted.map(({ key, command }) => ({ key, command })); + assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("refuses to overwrite malformed keybindings config", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { keybindingsConfigPath } = yield* ServerConfig; + yield* fs.writeFileString(keybindingsConfigPath, "{ not-json"); + + const result = yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + return yield* keybindings.upsertKeybindingRule({ + key: "mod+shift+r", + command: "script.run-tests.run", + }); + }).pipe(toDetailResult); + assertFailure(result, "expected JSON array"); + + const persistedRaw = yield* fs.readFileString(keybindingsConfigPath); + assert.equal(persistedRaw, "{ not-json"); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("reports non-array config parse errors without duplicate prefix", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { keybindingsConfigPath } = yield* ServerConfig; + yield* fs.writeFileString( + keybindingsConfigPath, + '{"key":"mod+j","command":"terminal.toggle"}', + ); + + const firstResult = yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + return yield* keybindings.upsertKeybindingRule({ + key: "mod+shift+r", + command: "script.run-tests.run", + }); + }).pipe(toDetailResult); + assertFailure(firstResult, "expected JSON array"); + + const secondResult = yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + return yield* keybindings.upsertKeybindingRule({ + key: "mod+shift+r", + command: "script.run-tests.run", + }); + }).pipe(toDetailResult); + assertFailure(secondResult, "expected JSON array"); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("fails when config directory is not writable", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { keybindingsConfigPath } = yield* ServerConfig; + const { dirname } = yield* Path.Path; + yield* writeKeybindingsConfig(keybindingsConfigPath, [ + { key: "mod+j", command: "terminal.toggle" }, + ]); + yield* fs.chmod(dirname(keybindingsConfigPath), 0o500); + + const result = yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + return yield* keybindings.upsertKeybindingRule({ + key: "mod+shift+r", + command: "script.run-tests.run", + }); + }).pipe(toDetailResult); + assertFailure(result, "failed to write keybindings config"); + + yield* fs.chmod(dirname(keybindingsConfigPath), 0o700); + + const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); + const persistedView = persisted.map(({ key, command }) => ({ key, command })); + assert.deepEqual(persistedView, [{ key: "mod+j", command: "terminal.toggle" }]); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("caches loaded resolved config across repeated reads", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, [ + { key: "mod+j", command: "terminal.toggle" }, + ]); + + const [first, second] = yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + const firstLoad = (yield* keybindings.loadConfigState).keybindings; + const secondLoad = (yield* keybindings.loadConfigState).keybindings; + return [firstLoad, secondLoad] as const; + }); + + assert.deepEqual(first, second); + assert.isTrue(second.some((entry) => entry.command === "terminal.toggle")); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("updates cached resolved config after upsert", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, [ + { key: "mod+j", command: "terminal.toggle" }, + ]); + + const loadedAfterUpsert = yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + yield* keybindings.loadConfigState; + yield* keybindings.upsertKeybindingRule({ + key: "mod+shift+r", + command: "script.run-tests.run", + }); + return (yield* keybindings.loadConfigState).keybindings; + }); + + assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "script.run-tests.run")); + assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "terminal.toggle")); + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); + + it.effect("serializes concurrent upserts to avoid lost updates", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, []); + + const commands = Array.from( + { length: 20 }, + (_, index): KeybindingCommand => `script.concurrent-${index}.run`, + ); + yield* Effect.gen(function* () { + const keybindings = yield* Keybindings; + yield* Effect.all( + commands.map((command, index) => + keybindings.upsertKeybindingRule({ + key: `mod+${String.fromCharCode(97 + index)}`, + command, + }), + ), + { concurrency: "unbounded", discard: true }, + ); + }); + + const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); + const persistedCommands = new Set(persisted.map((entry) => entry.command)); + for (const command of commands) { + assert.isTrue(persistedCommands.has(command), `expected persisted command ${command}`); + } + }).pipe(Effect.provide(makeKeybindingsLayer())), + ); }); diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 97e2de438f..086d795c0c 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -1,20 +1,51 @@ -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import type { +/** + * Keybindings - Keybinding configuration service definitions. + * + * Owns parsing, validation, merge, and persistence of user keybinding + * configuration consumed by the server runtime. + * + * @module Keybindings + */ +import { KeybindingRule, KeybindingsConfig, + KeybindingsConfigError, KeybindingShortcut, KeybindingWhenNode, + MAX_KEYBINDINGS_COUNT, + MAX_WHEN_EXPRESSION_DEPTH, ResolvedKeybindingRule, ResolvedKeybindingsConfig, + THREAD_JUMP_KEYBINDING_COMMANDS, + type ServerConfigIssue, } from "@t3tools/contracts"; -import { keybindingRuleSchema } from "@t3tools/contracts"; - -interface KeybindingsLogger { - warn(message: string, context?: Record): void; -} +import { Mutable } from "effect/Types"; +import { + Array, + Cache, + Cause, + Deferred, + Duration, + Effect, + Exit, + FileSystem, + Path, + Layer, + Option, + Predicate, + PubSub, + Schema, + SchemaGetter, + SchemaIssue, + SchemaTransformation, + Ref, + ServiceMap, + Scope, + Stream, +} from "effect"; +import * as Semaphore from "effect/Semaphore"; +import { ServerConfig } from "./config"; +import { fromLenientJson } from "@t3tools/shared/schemaJson"; type WhenToken = | { type: "identifier"; value: string } @@ -29,10 +60,17 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+d", command: "terminal.split", when: "terminalFocus" }, { key: "mod+n", command: "terminal.new", when: "terminalFocus" }, { key: "mod+w", command: "terminal.close", when: "terminalFocus" }, + { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" }, { key: "mod+n", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" }, { key: "mod+o", command: "editor.openFavorite" }, + { key: "mod+shift+[", command: "thread.previous" }, + { key: "mod+shift+]", command: "thread.next" }, + ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({ + key: `mod+${index + 1}`, + command, + })), ]; function normalizeKeyToken(token: string): string { @@ -41,6 +79,7 @@ function normalizeKeyToken(token: string): string { return token; } +/** @internal - Exported for testing */ export function parseKeybindingShortcut(value: string): KeybindingShortcut | null { const rawTokens = value .toLowerCase() @@ -154,12 +193,15 @@ function tokenizeWhenExpression(expression: string): WhenToken[] | null { return tokens; } -export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null { +function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null { const tokens = tokenizeWhenExpression(expression); if (!tokens || tokens.length === 0) return null; let index = 0; - const parsePrimary = (): KeybindingWhenNode | null => { + const parsePrimary = (depth: number): KeybindingWhenNode | null => { + if (depth > MAX_WHEN_EXPRESSION_DEPTH) { + return null; + } const token = tokens[index]; if (!token) return null; @@ -170,7 +212,7 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe if (token.type === "lparen") { index += 1; - const expressionNode = parseOr(); + const expressionNode = parseOr(depth + 1); const closeToken = tokens[index]; if (!expressionNode || !closeToken || closeToken.type !== "rparen") { return null; @@ -182,24 +224,34 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe return null; }; - const parseUnary = (): KeybindingWhenNode | null => { - const token = tokens[index]; - if (token?.type === "not") { + const parseUnary = (depth: number): KeybindingWhenNode | null => { + let notCount = 0; + while (tokens[index]?.type === "not") { index += 1; - const node = parseUnary(); - if (!node) return null; - return { type: "not", node }; + notCount += 1; + if (notCount > MAX_WHEN_EXPRESSION_DEPTH) { + return null; + } } - return parsePrimary(); + + let node = parsePrimary(depth); + if (!node) return null; + + while (notCount > 0) { + node = { type: "not", node }; + notCount -= 1; + } + + return node; }; - const parseAnd = (): KeybindingWhenNode | null => { - let left = parseUnary(); + const parseAnd = (depth: number): KeybindingWhenNode | null => { + let left = parseUnary(depth); if (!left) return null; while (tokens[index]?.type === "and") { index += 1; - const right = parseUnary(); + const right = parseUnary(depth); if (!right) return null; left = { type: "and", left, right }; } @@ -207,13 +259,13 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe return left; }; - const parseOr = (): KeybindingWhenNode | null => { - let left = parseAnd(); + const parseOr = (depth: number): KeybindingWhenNode | null => { + let left = parseAnd(depth); if (!left) return null; while (tokens[index]?.type === "or") { index += 1; - const right = parseAnd(); + const right = parseAnd(depth); if (!right) return null; left = { type: "or", left, right }; } @@ -221,20 +273,18 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe return left; }; - const ast = parseOr(); + const ast = parseOr(0); if (!ast || index !== tokens.length) return null; return ast; } +/** @internal - Exported for testing */ export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null { - const key = rule.key.trim(); - if (key.length === 0) return null; - const shortcut = parseKeybindingShortcut(key); + const shortcut = parseKeybindingShortcut(rule.key); if (!shortcut) return null; - const when = rule.when?.trim(); - if (when && when.length > 0) { - const whenAst = parseKeybindingWhenExpression(when); + if (rule.when !== undefined) { + const whenAst = parseKeybindingWhenExpression(rule.when); if (!whenAst) return null; return { command: rule.command, @@ -252,28 +302,150 @@ export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKey export function compileResolvedKeybindingsConfig( config: KeybindingsConfig, ): ResolvedKeybindingsConfig { - const compiled: ResolvedKeybindingsConfig = []; + const compiled: Mutable = []; for (const rule of config) { - const resolved = compileResolvedKeybindingRule(rule); - if (!resolved) continue; - compiled.push(resolved); + const result = Schema.decodeExit(ResolvedKeybindingFromConfig)(rule); + if (result._tag === "Success") { + compiled.push(result.value); + } } return compiled; } -function compileDefaultKeybindings(): ResolvedKeybindingsConfig { - const resolved: ResolvedKeybindingsConfig = []; - for (const rule of DEFAULT_KEYBINDINGS) { - const compiled = compileResolvedKeybindingRule(rule); - if (!compiled) { - throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`); - } - resolved.push(compiled); - } - return resolved; +export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( + Schema.decodeTo( + Schema.toType(ResolvedKeybindingRule), + SchemaTransformation.transformOrFail({ + decode: (rule) => + Effect.succeed(compileResolvedKeybindingRule(rule)).pipe( + Effect.filterOrFail( + Predicate.isNotNull, + () => + new SchemaIssue.InvalidValue(Option.some(rule), { + title: "Invalid keybinding rule", + }), + ), + Effect.map((resolved) => resolved), + ), + + encode: (resolved) => + Effect.gen(function* () { + const key = encodeShortcut(resolved.shortcut); + if (!key) { + return yield* Effect.fail( + new SchemaIssue.InvalidValue(Option.some(resolved), { + title: "Resolved shortcut cannot be encoded to key string", + }), + ); + } + + const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined; + return { + key, + command: resolved.command, + when, + }; + }), + }), + ), +); + +export const ResolvedKeybindingsFromConfig = Schema.Array(ResolvedKeybindingFromConfig).check( + Schema.isMaxLength(MAX_KEYBINDINGS_COUNT), +); + +function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean { + return ( + left.command === right.command && + left.key === right.key && + (left.when ?? undefined) === (right.when ?? undefined) + ); } -const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings(); +function keybindingShortcutContext(rule: KeybindingRule): string | null { + const parsed = parseKeybindingShortcut(rule.key); + if (!parsed) return null; + const encoded = encodeShortcut(parsed); + if (!encoded) return null; + return `${encoded}\u0000${rule.when ?? ""}`; +} + +function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): boolean { + const leftContext = keybindingShortcutContext(left); + const rightContext = keybindingShortcutContext(right); + if (!leftContext || !rightContext) return false; + return leftContext === rightContext; +} + +function encodeShortcut(shortcut: KeybindingShortcut): string | null { + const modifiers: string[] = []; + if (shortcut.modKey) modifiers.push("mod"); + if (shortcut.metaKey) modifiers.push("meta"); + if (shortcut.ctrlKey) modifiers.push("ctrl"); + if (shortcut.altKey) modifiers.push("alt"); + if (shortcut.shiftKey) modifiers.push("shift"); + if (!shortcut.key) return null; + if (shortcut.key !== "+" && shortcut.key.includes("+")) return null; + const key = shortcut.key === " " ? "space" : shortcut.key; + return [...modifiers, key].join("+"); +} + +function encodeWhenAst(node: KeybindingWhenNode): string { + switch (node.type) { + case "identifier": + return node.name; + case "not": + return `!(${encodeWhenAst(node.node)})`; + case "and": + return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`; + case "or": + return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`; + } +} + +const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS); + +const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown)); +const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig); +const PrettyJsonString = SchemaGetter.parseJson().compose( + SchemaGetter.stringifyJson({ space: 2 }), +); +const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe( + Schema.encode({ + decode: PrettyJsonString, + encode: PrettyJsonString, + }), +); + +export interface KeybindingsConfigState { + readonly keybindings: ResolvedKeybindingsConfig; + readonly issues: readonly ServerConfigIssue[]; +} + +export interface KeybindingsChangeEvent { + readonly keybindings: ResolvedKeybindingsConfig; + readonly issues: readonly ServerConfigIssue[]; +} + +function trimIssueMessage(message: string): string { + const trimmed = message.trim(); + return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration."; +} + +function malformedConfigIssue(detail: string): ServerConfigIssue { + return { + kind: "keybindings.malformed-config", + message: trimIssueMessage(detail), + }; +} + +function invalidEntryIssue(index: number, detail: string): ServerConfigIssue { + return { + kind: "keybindings.invalid-entry", + index, + message: trimIssueMessage(detail), + }; +} function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig { if (custom.length === 0) { @@ -286,70 +458,450 @@ function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): Resolve ); const merged = [...retainedDefaults, ...custom]; - if (merged.length <= 256) { + if (merged.length <= MAX_KEYBINDINGS_COUNT) { return merged; } // Keep the latest rules when the config exceeds max size; later rules have higher precedence. - return merged.slice(-256); + return merged.slice(-MAX_KEYBINDINGS_COUNT); } -export function loadResolvedKeybindingsConfig( - logger: KeybindingsLogger, -): ResolvedKeybindingsConfig { - const configPath = path.join(os.homedir(), ".t3", "keybindings.json"); - try { - const raw = fs.readFileSync(configPath, "utf8"); - const parsed = JSON.parse(raw) as unknown; - if (!Array.isArray(parsed)) { - logger.warn("ignoring keybindings config with unsupported format; expected array", { - path: configPath, - }); - return [...DEFAULT_RESOLVED_KEYBINDINGS]; +/** + * KeybindingsShape - Service API for keybinding configuration operations. + */ +export interface KeybindingsShape { + /** + * Start the keybindings runtime and attach file watching. + * + * Safe to call multiple times. The first successful call establishes the + * runtime; later calls await the same startup. + */ + readonly start: Effect.Effect; + + /** + * Await keybindings runtime readiness. + * + * Readiness means the config directory exists, the watcher is attached, the + * startup sync has completed, and the current snapshot has been loaded. + */ + readonly ready: Effect.Effect; + + /** + * Ensure the on-disk keybindings file exists and includes all default + * commands so newly-added defaults are backfilled on startup. + */ + readonly syncDefaultKeybindingsOnStartup: Effect.Effect; + + /** + * Load runtime keybindings state along with non-fatal configuration issues. + */ + readonly loadConfigState: Effect.Effect; + + /** + * Read the latest keybindings snapshot from cache/disk. + */ + readonly getSnapshot: Effect.Effect; + + /** + * Stream of keybindings config change events. + */ + readonly streamChanges: Stream.Stream; + + /** + * Upsert a keybinding rule and persist the resulting configuration. + * + * Writes config atomically and enforces the max rule count by truncating + * oldest entries when needed. + */ + readonly upsertKeybindingRule: ( + rule: KeybindingRule, + ) => Effect.Effect; +} + +/** + * Keybindings - Service tag for keybinding configuration operations. + */ +export class Keybindings extends ServiceMap.Service()( + "t3/keybindings", +) {} + +const makeKeybindings = Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const upsertSemaphore = yield* Semaphore.make(1); + const resolvedConfigCacheKey = "resolved" as const; + const changesPubSub = yield* PubSub.unbounded(); + const startedRef = yield* Ref.make(false); + const startedDeferred = yield* Deferred.make(); + const watcherScope = yield* Scope.make("sequential"); + yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void)); + const emitChange = (configState: KeybindingsConfigState) => + PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid); + + const readConfigExists = fs.exists(keybindingsConfigPath).pipe( + Effect.mapError( + (cause) => + new KeybindingsConfigError({ + configPath: keybindingsConfigPath, + detail: "failed to access keybindings config", + cause, + }), + ), + ); + + const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe( + Effect.mapError( + (cause) => + new KeybindingsConfigError({ + configPath: keybindingsConfigPath, + detail: "failed to read keybindings config", + cause, + }), + ), + ); + + const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return< + readonly KeybindingRule[], + KeybindingsConfigError + > { + if (!(yield* readConfigExists)) { + return []; } - const sanitized: ResolvedKeybindingsConfig = []; - let invalidEntries = 0; - for (const entry of parsed) { - const result = keybindingRuleSchema.safeParse(entry); - if (result.success) { - const compiled = compileResolvedKeybindingRule(result.data); - if (!compiled) { - invalidEntries += 1; - continue; + const rawConfig = yield* readRawConfig.pipe( + Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)), + Effect.mapError( + (cause) => + new KeybindingsConfigError({ + configPath: keybindingsConfigPath, + detail: "expected JSON array", + cause, + }), + ), + ); + + return yield* Effect.forEach(rawConfig, (entry) => + Effect.gen(function* () { + const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry); + if (decodedRule._tag === "Failure") { + yield* Effect.logWarning("ignoring invalid keybinding entry", { + path: keybindingsConfigPath, + entry, + error: Cause.pretty(decodedRule.cause), + }); + return null; } - sanitized.push(compiled); + const resolved = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value); + if (resolved._tag === "Failure") { + yield* Effect.logWarning("ignoring invalid keybinding entry", { + path: keybindingsConfigPath, + entry, + error: Cause.pretty(resolved.cause), + }); + return null; + } + return decodedRule.value; + }), + ).pipe(Effect.map(Array.filter(Predicate.isNotNull))); + }); + + const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return< + { + readonly keybindings: readonly KeybindingRule[]; + readonly issues: readonly ServerConfigIssue[]; + }, + KeybindingsConfigError + > { + if (!(yield* readConfigExists)) { + return { keybindings: [], issues: [] }; + } + + const rawConfig = yield* readRawConfig; + const decodedEntries = Schema.decodeUnknownExit(RawKeybindingsEntries)(rawConfig); + if (decodedEntries._tag === "Failure") { + const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`; + return { + keybindings: [], + issues: [malformedConfigIssue(detail)], + }; + } + + const keybindings: KeybindingRule[] = []; + const issues: ServerConfigIssue[] = []; + for (const [index, entry] of decodedEntries.value.entries()) { + const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry); + if (decodedRule._tag === "Failure") { + const detail = Cause.pretty(decodedRule.cause); + issues.push(invalidEntryIssue(index, detail)); + yield* Effect.logWarning("ignoring invalid keybinding entry", { + path: keybindingsConfigPath, + index, + entry, + error: detail, + }); continue; } - invalidEntries += 1; + + const resolvedRule = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value); + if (resolvedRule._tag === "Failure") { + const detail = Cause.pretty(resolvedRule.cause); + issues.push(invalidEntryIssue(index, detail)); + yield* Effect.logWarning("ignoring invalid keybinding entry", { + path: keybindingsConfigPath, + index, + entry, + error: detail, + }); + continue; + } + keybindings.push(decodedRule.value); } - if (invalidEntries > 0) { - logger.warn("ignoring invalid keybinding entries", { - path: configPath, - invalidEntries, - totalEntries: parsed.length, - }); + + return { keybindings, issues }; + }); + + const writeConfigAtomically = (rules: readonly KeybindingRule[]) => { + const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`; + + return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe( + Effect.map((encoded) => `${encoded}\n`), + Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })), + Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)), + Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)), + Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))), + Effect.mapError( + (cause) => + new KeybindingsConfigError({ + configPath: keybindingsConfigPath, + detail: "failed to write keybindings config", + cause, + }), + ), + ); + }; + + const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe( + Effect.map(({ keybindings, issues }) => ({ + keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)), + issues, + })), + ); + + const resolvedConfigCache = yield* Cache.make< + typeof resolvedConfigCacheKey, + KeybindingsConfigState, + KeybindingsConfigError + >({ + capacity: 1, + lookup: () => loadConfigStateFromDisk, + }); + + const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey); + + const revalidateAndEmit = upsertSemaphore.withPermits(1)( + Effect.gen(function* () { + yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); + const configState = yield* loadConfigStateFromCacheOrDisk; + yield* emitChange(configState); + }), + ); + + const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)( + Effect.gen(function* () { + const configExists = yield* readConfigExists; + if (!configExists) { + yield* writeConfigAtomically(DEFAULT_KEYBINDINGS); + yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); + return; + } + + const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig(); + if (runtimeConfig.issues.length > 0) { + yield* Effect.logWarning( + "skipping startup keybindings default sync because config has issues", + { + path: keybindingsConfigPath, + issues: runtimeConfig.issues, + }, + ); + yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); + return; + } + const customConfig = runtimeConfig.keybindings; + const existingCommands = new Set(customConfig.map((entry) => entry.command)); + const missingDefaults: KeybindingRule[] = []; + const shortcutConflictWarnings: Array<{ + defaultCommand: KeybindingRule["command"]; + conflictingCommand: KeybindingRule["command"]; + key: string; + when: string | null; + }> = []; + for (const defaultRule of DEFAULT_KEYBINDINGS) { + if (existingCommands.has(defaultRule.command)) { + continue; + } + const conflictingEntry = customConfig.find((entry) => + hasSameShortcutContext(entry, defaultRule), + ); + if (conflictingEntry) { + shortcutConflictWarnings.push({ + defaultCommand: defaultRule.command, + conflictingCommand: conflictingEntry.command, + key: defaultRule.key, + when: defaultRule.when ?? null, + }); + continue; + } + missingDefaults.push(defaultRule); + } + for (const conflict of shortcutConflictWarnings) { + yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", { + path: keybindingsConfigPath, + defaultCommand: conflict.defaultCommand, + conflictingCommand: conflict.conflictingCommand, + key: conflict.key, + when: conflict.when, + reason: "shortcut context already used by existing rule", + }); + } + if (missingDefaults.length === 0) { + yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); + return; + } + + const matchingDefaults = DEFAULT_KEYBINDINGS.filter((defaultRule) => + customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)), + ).map((rule) => rule.command); + if (matchingDefaults.length > 0) { + yield* Effect.logWarning("default keybinding rule already defined in user config", { + path: keybindingsConfigPath, + commands: matchingDefaults, + }); + } + + const nextConfig = [...customConfig, ...missingDefaults]; + const cappedConfig = + nextConfig.length > MAX_KEYBINDINGS_COUNT + ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT) + : nextConfig; + if (nextConfig.length > MAX_KEYBINDINGS_COUNT) { + yield* Effect.logWarning("truncating keybindings config to max entries", { + path: keybindingsConfigPath, + maxEntries: MAX_KEYBINDINGS_COUNT, + }); + } + + yield* writeConfigAtomically(cappedConfig); + yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); + }), + ); + + const startWatcher = Effect.gen(function* () { + const keybindingsConfigDir = path.dirname(keybindingsConfigPath); + const keybindingsConfigFile = path.basename(keybindingsConfigPath); + const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath); + + yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe( + Effect.mapError( + (cause) => + new KeybindingsConfigError({ + configPath: keybindingsConfigPath, + detail: "failed to prepare keybindings config directory", + cause, + }), + ), + ); + + const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true })); + + // Debounce watch events so the file is fully written before we read it. + // Editors emit multiple events per save (truncate, write, rename) and + // `fs.watch` can fire before the content has been flushed to disk. + const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe( + Stream.filter((event) => { + return ( + event.path === keybindingsConfigFile || + event.path === keybindingsConfigPath || + path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved + ); + }), + Stream.debounce(Duration.millis(100)), + ); + + yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe( + Effect.ignoreCause({ log: true }), + Effect.forkIn(watcherScope), + Effect.asVoid, + ); + }); + + const start = Effect.gen(function* () { + const alreadyStarted = yield* Ref.get(startedRef); + if (alreadyStarted) { + return yield* Deferred.await(startedDeferred); } - const overriddenCommands = new Set(sanitized.map((entry) => entry.command)); - const mergedBeforeCapLength = - DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command)) - .length + sanitized.length; - const merged = mergeWithDefaultKeybindings(sanitized); - if (mergedBeforeCapLength > 256) { - logger.warn("truncating merged keybindings config to max entries", { - path: configPath, - maxEntries: 256, - }); - } - return merged; - } catch (error) { - if ((error as NodeJS.ErrnoException)?.code === "ENOENT") { - return [...DEFAULT_RESOLVED_KEYBINDINGS]; - } - logger.warn("ignoring malformed keybindings config", { - path: configPath, - error: error instanceof Error ? error.message : String(error), + + yield* Ref.set(startedRef, true); + const startup = Effect.gen(function* () { + yield* startWatcher; + yield* syncDefaultKeybindingsOnStartup; + yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); + yield* loadConfigStateFromCacheOrDisk; }); - } - return [...DEFAULT_RESOLVED_KEYBINDINGS]; -} + + const startupExit = yield* Effect.exit(startup); + if (startupExit._tag === "Failure") { + yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie); + return yield* Effect.failCause(startupExit.cause); + } + + yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie); + }); + + return { + start, + ready: Deferred.await(startedDeferred), + syncDefaultKeybindingsOnStartup, + loadConfigState: loadConfigStateFromCacheOrDisk, + getSnapshot: loadConfigStateFromCacheOrDisk, + get streamChanges() { + return Stream.fromPubSub(changesPubSub); + }, + upsertKeybindingRule: (rule) => + upsertSemaphore.withPermits(1)( + Effect.gen(function* () { + const customConfig = yield* loadWritableCustomKeybindingsConfig(); + const nextConfig = [ + ...customConfig.filter((entry) => entry.command !== rule.command), + rule, + ]; + const cappedConfig = + nextConfig.length > MAX_KEYBINDINGS_COUNT + ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT) + : nextConfig; + if (nextConfig.length > MAX_KEYBINDINGS_COUNT) { + yield* Effect.logWarning("truncating keybindings config to max entries", { + path: keybindingsConfigPath, + maxEntries: MAX_KEYBINDINGS_COUNT, + }); + } + yield* writeConfigAtomically(cappedConfig); + const nextResolved = mergeWithDefaultKeybindings( + compileResolvedKeybindingsConfig(cappedConfig), + ); + yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, { + keybindings: nextResolved, + issues: [], + }); + yield* emitChange({ + keybindings: nextResolved, + issues: [], + }); + return nextResolved; + }), + ), + } satisfies KeybindingsShape; +}); + +export const KeybindingsLive = Layer.effect(Keybindings, makeKeybindings); diff --git a/apps/server/src/logger.ts b/apps/server/src/logger.ts deleted file mode 100644 index b9d18569cc..0000000000 --- a/apps/server/src/logger.ts +++ /dev/null @@ -1,103 +0,0 @@ -import util from "node:util"; - -type LogLevel = "info" | "warn" | "error" | "event"; - -type LogContext = Record; - -const ANSI = { - reset: "\u001b[0m", - dim: "\u001b[2m", - cyan: "\u001b[36m", - yellow: "\u001b[33m", - red: "\u001b[31m", - magenta: "\u001b[35m", -} as const; - -const LEVEL_LABEL: Record = { - info: "INFO", - warn: "WARN", - error: "ERROR", - event: "EVENT", -}; - -const LEVEL_COLOR: Record = { - info: ANSI.cyan, - warn: ANSI.yellow, - error: ANSI.red, - event: ANSI.magenta, -}; - -function useColors() { - return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined; -} - -function colorize(value: string, color: string, enabled: boolean) { - return enabled ? `${color}${value}${ANSI.reset}` : value; -} - -function timeStamp() { - return new Date().toISOString().slice(11, 23); -} - -function formatValue(value: unknown) { - if (typeof value === "string") { - return JSON.stringify(value); - } - if ( - typeof value === "number" || - typeof value === "boolean" || - value === null || - value === undefined - ) { - return String(value); - } - return util.inspect(value, { - depth: 4, - breakLength: Infinity, - compact: true, - maxArrayLength: 25, - maxStringLength: 320, - }); -} - -function formatContext(context: LogContext | undefined) { - if (!context) return ""; - const entries = Object.entries(context).filter(([, value]) => value !== undefined); - if (entries.length === 0) return ""; - return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" "); -} - -function write(level: LogLevel, scope: string, message: string, context?: LogContext) { - const colorEnabled = useColors(); - const ts = colorize(timeStamp(), ANSI.dim, colorEnabled); - const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled); - const contextText = formatContext(context); - const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`; - - if (level === "warn") { - console.warn(line); - return; - } - if (level === "error") { - console.error(line); - return; - } - console.log(line); -} - -export function createLogger(scope: string) { - return { - info(message: string, context?: LogContext) { - write("info", scope, message, context); - }, - warn(message: string, context?: LogContext) { - write("warn", scope, message, context); - }, - error(message: string, context?: LogContext) { - write("error", scope, message, context); - }, - event(message: string, context?: LogContext) { - write("event", scope, message, context); - }, - }; -} diff --git a/apps/server/src/observability/Attributes.test.ts b/apps/server/src/observability/Attributes.test.ts new file mode 100644 index 0000000000..4b495598ea --- /dev/null +++ b/apps/server/src/observability/Attributes.test.ts @@ -0,0 +1,46 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { compactTraceAttributes, normalizeModelMetricLabel } from "./Attributes.ts"; + +describe("Attributes", () => { + it("normalizes circular arrays, maps, and sets without recursing forever", () => { + const array: Array = ["alpha"]; + array.push(array); + + const map = new Map(); + map.set("self", map); + + const set = new Set(); + set.add(set); + + assert.deepStrictEqual( + compactTraceAttributes({ + array, + map, + set, + }), + { + array: ["alpha", "[Circular]"], + map: { self: "[Circular]" }, + set: ["[Circular]"], + }, + ); + }); + + it("normalizes invalid dates without throwing", () => { + assert.deepStrictEqual( + compactTraceAttributes({ + invalidDate: new Date("not-a-real-date"), + }), + { + invalidDate: "Invalid Date", + }, + ); + }); + + it("groups GPT-family models under a shared metric label", () => { + assert.strictEqual(normalizeModelMetricLabel("gpt-4o"), "gpt"); + assert.strictEqual(normalizeModelMetricLabel("gpt-5.4"), "gpt"); + assert.strictEqual(normalizeModelMetricLabel("claude-sonnet-4"), "claude"); + }); +}); diff --git a/apps/server/src/observability/Attributes.ts b/apps/server/src/observability/Attributes.ts new file mode 100644 index 0000000000..2251fcfea6 --- /dev/null +++ b/apps/server/src/observability/Attributes.ts @@ -0,0 +1,128 @@ +import { Cause, Exit } from "effect"; + +export type MetricAttributeValue = string; +export type MetricAttributes = Readonly>; +export type TraceAttributes = Readonly>; +export type ObservabilityOutcome = "success" | "failure" | "interrupt"; + +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function markSeen(value: object, seen: WeakSet): boolean { + if (seen.has(value)) { + return true; + } + seen.add(value); + return false; +} + +function normalizeJsonValue(value: unknown, seen: WeakSet = new WeakSet()): unknown { + if ( + value === null || + value === undefined || + typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" + ) { + return value ?? null; + } + if (typeof value === "bigint") { + return value.toString(); + } + if (value instanceof Date) { + return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString(); + } + if (value instanceof Error) { + return { + name: value.name, + message: value.message, + ...(value.stack ? { stack: value.stack } : {}), + }; + } + if (Array.isArray(value)) { + if (markSeen(value, seen)) { + return "[Circular]"; + } + return value.map((entry) => normalizeJsonValue(entry, seen)); + } + if (value instanceof Map) { + if (markSeen(value, seen)) { + return "[Circular]"; + } + return Object.fromEntries( + Array.from(value.entries(), ([key, entryValue]) => [ + String(key), + normalizeJsonValue(entryValue, seen), + ]), + ); + } + if (value instanceof Set) { + if (markSeen(value, seen)) { + return "[Circular]"; + } + return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen)); + } + if (!isPlainObject(value)) { + return String(value); + } + if (markSeen(value, seen)) { + return "[Circular]"; + } + return Object.fromEntries( + Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]), + ); +} + +export function compactTraceAttributes( + attributes: Readonly>, +): TraceAttributes { + return Object.fromEntries( + Object.entries(attributes) + .filter(([, value]) => value !== undefined) + .map(([key, value]) => [key, normalizeJsonValue(value)]), + ); +} + +export function compactMetricAttributes( + attributes: Readonly>, +): MetricAttributes { + return Object.fromEntries( + Object.entries(attributes).flatMap(([key, value]) => { + if (value === undefined || value === null) { + return []; + } + if (typeof value === "string") { + return [[key, value]]; + } + if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") { + return [[key, String(value)]]; + } + return []; + }), + ); +} + +export function outcomeFromExit(exit: Exit.Exit): ObservabilityOutcome { + if (Exit.isSuccess(exit)) { + return "success"; + } + return Cause.hasInterruptsOnly(exit.cause) ? "interrupt" : "failure"; +} + +export function normalizeModelMetricLabel(model: string | null | undefined): string | undefined { + const normalized = model?.trim().toLowerCase(); + if (!normalized) { + return undefined; + } + if (normalized.includes("gpt")) { + return "gpt"; + } + if (normalized.includes("claude")) { + return "claude"; + } + if (normalized.includes("gemini")) { + return "gemini"; + } + return "other"; +} diff --git a/apps/server/src/observability/Layers/Observability.ts b/apps/server/src/observability/Layers/Observability.ts new file mode 100644 index 0000000000..29b9d7eac5 --- /dev/null +++ b/apps/server/src/observability/Layers/Observability.ts @@ -0,0 +1,64 @@ +import { Effect, Layer, References, Tracer } from "effect"; +import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; + +import { ServerConfig } from "../../config.ts"; +import { ServerLoggerLive } from "../../serverLogger.ts"; +import { makeLocalFileTracer } from "../LocalFileTracer.ts"; + +const otlpSerializationLayer = OtlpSerialization.layerJson; + +export const ObservabilityLive = Layer.unwrap( + Effect.gen(function* () { + const config = yield* ServerConfig; + + const traceReferencesLayer = Layer.mergeAll( + Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel), + Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled), + ); + + const tracerLayer = Layer.effect( + Tracer.Tracer, + Effect.gen(function* () { + const delegate = + config.otlpTracesUrl === undefined + ? undefined + : yield* OtlpTracer.make({ + url: config.otlpTracesUrl, + exportInterval: `${config.otlpExportIntervalMs} millis`, + resource: { + serviceName: config.otlpServiceName, + attributes: { + "service.runtime": "t3-server", + "service.mode": config.mode, + }, + }, + }); + + return yield* makeLocalFileTracer({ + filePath: config.serverTracePath, + maxBytes: config.traceMaxBytes, + maxFiles: config.traceMaxFiles, + batchWindowMs: config.traceBatchWindowMs, + ...(delegate ? { delegate } : {}), + }); + }), + ).pipe(Layer.provideMerge(otlpSerializationLayer)); + + const metricsLayer = + config.otlpMetricsUrl === undefined + ? Layer.empty + : OtlpMetrics.layer({ + url: config.otlpMetricsUrl, + exportInterval: `${config.otlpExportIntervalMs} millis`, + resource: { + serviceName: config.otlpServiceName, + attributes: { + "service.runtime": "t3-server", + "service.mode": config.mode, + }, + }, + }).pipe(Layer.provideMerge(otlpSerializationLayer)); + + return Layer.mergeAll(ServerLoggerLive, traceReferencesLayer, tracerLayer, metricsLayer); + }), +); diff --git a/apps/server/src/observability/LocalFileTracer.test.ts b/apps/server/src/observability/LocalFileTracer.test.ts new file mode 100644 index 0000000000..1bc5a34305 --- /dev/null +++ b/apps/server/src/observability/LocalFileTracer.test.ts @@ -0,0 +1,117 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Layer, Logger, References, Tracer } from "effect"; + +import type { TraceRecord } from "./TraceRecord.ts"; +import { makeLocalFileTracer } from "./LocalFileTracer.ts"; + +const makeTestLayer = (tracePath: string) => + Layer.mergeAll( + Layer.effect( + Tracer.Tracer, + makeLocalFileTracer({ + filePath: tracePath, + maxBytes: 1024 * 1024, + maxFiles: 2, + batchWindowMs: 10_000, + }), + ), + Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }), + Layer.succeed(References.MinimumLogLevel, "Info"), + ); + +const readTraceRecords = (tracePath: string): Array => + fs + .readFileSync(tracePath, "utf8") + .trim() + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line) as TraceRecord); + +describe("LocalFileTracer", () => { + it.effect("writes nested spans to disk and captures log messages as span events", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + yield* Effect.scoped( + Effect.gen(function* () { + const program = Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "demo.parent": true, + }); + yield* Effect.logInfo("parent event"); + yield* Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "demo.child": true, + }); + yield* Effect.logInfo("child event"); + }).pipe(Effect.withSpan("child-span")); + }).pipe(Effect.withSpan("parent-span")); + + yield* program.pipe(Effect.provide(makeTestLayer(tracePath))); + }), + ); + + const records = readTraceRecords(tracePath); + assert.equal(records.length, 2); + + const parent = records.find((record) => record.name === "parent-span"); + const child = records.find((record) => record.name === "child-span"); + + assert.notEqual(parent, undefined); + assert.notEqual(child, undefined); + if (!parent || !child) { + return; + } + + assert.equal(child.parentSpanId, parent.spanId); + assert.equal(parent.attributes["demo.parent"], true); + assert.equal(child.attributes["demo.child"], true); + assert.equal( + parent.events.some((event) => event.name === "parent event"), + true, + ); + assert.equal( + child.events.some((event) => event.name === "child event"), + true, + ); + assert.equal( + child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"), + true, + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + + it.effect("serializes interrupted spans with an interrupted exit status", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + yield* Effect.scoped( + Effect.exit( + Effect.interrupt.pipe( + Effect.withSpan("interrupt-span"), + Effect.provide(makeTestLayer(tracePath)), + ), + ), + ); + + const records = readTraceRecords(tracePath); + assert.equal(records.length, 1); + assert.equal(records[0]?.name, "interrupt-span"); + assert.equal(records[0]?.exit._tag, "Interrupted"); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); +}); diff --git a/apps/server/src/observability/LocalFileTracer.ts b/apps/server/src/observability/LocalFileTracer.ts new file mode 100644 index 0000000000..7f75eb0bf9 --- /dev/null +++ b/apps/server/src/observability/LocalFileTracer.ts @@ -0,0 +1,104 @@ +import type * as Exit from "effect/Exit"; +import { Effect, Option, Tracer } from "effect"; + +import { spanToTraceRecord } from "./TraceRecord.ts"; +import { makeTraceSink } from "./TraceSink.ts"; + +export interface LocalFileTracerOptions { + readonly filePath: string; + readonly maxBytes: number; + readonly maxFiles: number; + readonly batchWindowMs: number; + readonly delegate?: Tracer.Tracer; +} + +class LocalFileSpan implements Tracer.Span { + readonly _tag = "Span"; + readonly name: string; + readonly spanId: string; + readonly traceId: string; + readonly parent: Option.Option; + readonly annotations: Tracer.Span["annotations"]; + readonly links: Array; + readonly sampled: boolean; + readonly kind: Tracer.SpanKind; + + status: Tracer.SpanStatus; + attributes: Map; + events: Array<[name: string, startTime: bigint, attributes: Record]>; + + constructor( + options: Parameters[0], + private readonly delegate: Tracer.Span, + private readonly push: (record: ReturnType) => void, + ) { + this.name = delegate.name; + this.spanId = delegate.spanId; + this.traceId = delegate.traceId; + this.parent = options.parent; + this.annotations = options.annotations; + this.links = [...options.links]; + this.sampled = delegate.sampled; + this.kind = delegate.kind; + this.status = { + _tag: "Started", + startTime: options.startTime, + }; + this.attributes = new Map(); + this.events = []; + } + + end(endTime: bigint, exit: Exit.Exit): void { + this.status = { + _tag: "Ended", + startTime: this.status.startTime, + endTime, + exit, + }; + this.delegate.end(endTime, exit); + + if (this.sampled) { + this.push(spanToTraceRecord(this)); + } + } + + attribute(key: string, value: unknown): void { + this.attributes.set(key, value); + this.delegate.attribute(key, value); + } + + event(name: string, startTime: bigint, attributes?: Record): void { + const nextAttributes = attributes ?? {}; + this.events.push([name, startTime, nextAttributes]); + this.delegate.event(name, startTime, nextAttributes); + } + + addLinks(links: ReadonlyArray): void { + this.links.push(...links); + this.delegate.addLinks(links); + } +} + +export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* ( + options: LocalFileTracerOptions, +) { + const sink = yield* makeTraceSink({ + filePath: options.filePath, + maxBytes: options.maxBytes, + maxFiles: options.maxFiles, + batchWindowMs: options.batchWindowMs, + }); + + const delegate = + options.delegate ?? + Tracer.make({ + span: (spanOptions) => new Tracer.NativeSpan(spanOptions), + }); + + return Tracer.make({ + span(spanOptions) { + return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push); + }, + ...(delegate.context ? { context: delegate.context } : {}), + }); +}); diff --git a/apps/server/src/observability/Metrics.test.ts b/apps/server/src/observability/Metrics.test.ts new file mode 100644 index 0000000000..4604f43b63 --- /dev/null +++ b/apps/server/src/observability/Metrics.test.ts @@ -0,0 +1,111 @@ +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Metric } from "effect"; + +import { withMetrics } from "./Metrics.ts"; + +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + +describe("withMetrics", () => { + it.effect("supports pipe-style usage", () => + Effect.gen(function* () { + const counter = Metric.counter("with_metrics_pipe_total"); + const timer = Metric.timer("with_metrics_pipe_duration"); + + const result = yield* Effect.succeed("ok").pipe( + withMetrics({ + counter, + timer, + attributes: { + operation: "pipe", + }, + }), + ); + + assert.equal(result, "ok"); + + const snapshots = yield* Metric.snapshot; + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_pipe_total", { + operation: "pipe", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_pipe_duration", { + operation: "pipe", + }), + true, + ); + }), + ); + + it.effect("supports direct invocation", () => + Effect.gen(function* () { + const counter = Metric.counter("with_metrics_direct_total"); + + yield* withMetrics(Effect.fail("boom"), { + counter, + attributes: { + operation: "direct", + }, + }).pipe(Effect.exit); + + const snapshots = yield* Metric.snapshot; + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_direct_total", { + operation: "direct", + outcome: "failure", + }), + true, + ); + }), + ); + + it.effect("evaluates attributes lazily after the wrapped effect runs", () => + Effect.gen(function* () { + const counter = Metric.counter("with_metrics_lazy_total"); + const timer = Metric.timer("with_metrics_lazy_duration"); + let provider = "unknown"; + + yield* Effect.sync(() => { + provider = "codex"; + }).pipe( + withMetrics({ + counter, + timer, + attributes: () => ({ + provider, + operation: "lazy", + }), + }), + ); + + const snapshots = yield* Metric.snapshot; + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_lazy_total", { + provider: "codex", + operation: "lazy", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", { + provider: "codex", + operation: "lazy", + }), + true, + ); + }), + ); +}); diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.ts new file mode 100644 index 0000000000..3e527c7cb4 --- /dev/null +++ b/apps/server/src/observability/Metrics.ts @@ -0,0 +1,160 @@ +import { Duration, Effect, Exit, Metric } from "effect"; +import { dual } from "effect/Function"; + +import { + compactMetricAttributes, + normalizeModelMetricLabel, + outcomeFromExit, +} from "./Attributes.ts"; + +export const rpcRequestsTotal = Metric.counter("t3_rpc_requests_total", { + description: "Total RPC requests handled by the websocket RPC server.", +}); + +export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", { + description: "RPC request handling duration.", +}); + +export const orchestrationCommandsTotal = Metric.counter("t3_orchestration_commands_total", { + description: "Total orchestration commands dispatched.", +}); + +export const orchestrationCommandDuration = Metric.timer("t3_orchestration_command_duration", { + description: "Orchestration command dispatch duration.", +}); + +export const orchestrationCommandAckDuration = Metric.timer( + "t3_orchestration_command_ack_duration", + { + description: + "Time from orchestration command dispatch to the first committed domain event emitted for that command.", + }, +); + +export const orchestrationEventsProcessedTotal = Metric.counter( + "t3_orchestration_events_processed_total", + { + description: "Total orchestration intent events processed by runtime reactors.", + }, +); + +export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", { + description: "Total provider session lifecycle operations.", +}); + +export const providerTurnsTotal = Metric.counter("t3_provider_turns_total", { + description: "Total provider turn lifecycle operations.", +}); + +export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", { + description: "Provider turn request duration.", +}); + +export const providerRuntimeEventsTotal = Metric.counter("t3_provider_runtime_events_total", { + description: "Total canonical provider runtime events processed.", +}); + +export const gitCommandsTotal = Metric.counter("t3_git_commands_total", { + description: "Total git commands executed by the server runtime.", +}); + +export const gitCommandDuration = Metric.timer("t3_git_command_duration", { + description: "Git command execution duration.", +}); + +export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", { + description: "Total terminal sessions started.", +}); + +export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total", { + description: "Total terminal restart requests handled.", +}); + +export const metricAttributes = ( + attributes: Readonly>, +): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes)); + +export const increment = ( + metric: Metric.Metric, + attributes: Readonly>, + amount = 1, +) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount); + +export interface WithMetricsOptions { + readonly counter?: Metric.Metric; + readonly timer?: Metric.Metric; + readonly attributes?: + | Readonly> + | (() => Readonly>); + readonly outcomeAttributes?: ( + outcome: ReturnType, + ) => Readonly>; +} + +const withMetricsImpl = ( + effect: Effect.Effect, + options: WithMetricsOptions, +): Effect.Effect => + Effect.gen(function* () { + const startedAt = Date.now(); + const exit = yield* Effect.exit(effect); + const duration = Duration.millis(Math.max(0, Date.now() - startedAt)); + const baseAttributes = + typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {}); + + if (options.timer) { + yield* Metric.update( + Metric.withAttributes(options.timer, metricAttributes(baseAttributes)), + duration, + ); + } + + if (options.counter) { + const outcome = outcomeFromExit(exit); + yield* Metric.update( + Metric.withAttributes( + options.counter, + metricAttributes({ + ...baseAttributes, + outcome, + ...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}), + }), + ), + 1, + ); + } + + if (Exit.isSuccess(exit)) { + return exit.value; + } + return yield* Effect.failCause(exit.cause); + }); + +export const withMetrics: { + ( + options: WithMetricsOptions, + ): (effect: Effect.Effect) => Effect.Effect; + (effect: Effect.Effect, options: WithMetricsOptions): Effect.Effect; +} = dual(2, withMetricsImpl); + +export const providerMetricAttributes = ( + provider: string, + extra?: Readonly>, +) => + compactMetricAttributes({ + provider, + ...extra, + }); + +export const providerTurnMetricAttributes = (input: { + readonly provider: string; + readonly model: string | null | undefined; + readonly extra?: Readonly>; +}) => { + const modelFamily = normalizeModelMetricLabel(input.model); + return compactMetricAttributes({ + provider: input.provider, + ...(modelFamily ? { modelFamily } : {}), + ...input.extra, + }); +}; diff --git a/apps/server/src/observability/RpcInstrumentation.test.ts b/apps/server/src/observability/RpcInstrumentation.test.ts new file mode 100644 index 0000000000..d29b05f3c2 --- /dev/null +++ b/apps/server/src/observability/RpcInstrumentation.test.ts @@ -0,0 +1,161 @@ +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Exit, Metric, Stream } from "effect"; + +import { + observeRpcEffect, + observeRpcStream, + observeRpcStreamEffect, +} from "./RpcInstrumentation.ts"; + +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + +describe("RpcInstrumentation", () => { + it.effect("records success metrics for unary RPC handlers", () => + Effect.gen(function* () { + yield* observeRpcEffect("rpc.instrumentation.success", Effect.succeed("ok"), { + "rpc.aggregate": "test", + }).pipe(Effect.withSpan("rpc.instrumentation.success.span")); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.success", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.success", + }), + true, + ); + }), + ); + + it.effect("records failure outcomes for unary RPC handlers", () => + Effect.gen(function* () { + yield* Effect.exit( + observeRpcEffect("rpc.instrumentation.failure", Effect.fail("boom"), { + "rpc.aggregate": "test", + }).pipe(Effect.withSpan("rpc.instrumentation.failure.span")), + ); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.failure", + outcome: "failure", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.failure", + }), + true, + ); + }), + ); + + it.effect("records subscription activation metrics for stream RPC handlers", () => + Effect.gen(function* () { + const events = yield* Stream.runCollect( + observeRpcStreamEffect( + "rpc.instrumentation.stream", + Effect.succeed(Stream.make("a", "b")), + { "rpc.aggregate": "test" }, + ).pipe(Stream.withSpan("rpc.instrumentation.stream.span")), + ); + + assert.deepStrictEqual(Array.from(events), ["a", "b"]); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.stream", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.stream", + }), + true, + ); + }), + ); + + it.effect("records failure outcomes for direct stream RPC handlers during consumption", () => + Effect.gen(function* () { + const exit = yield* Stream.runCollect( + observeRpcStream( + "rpc.instrumentation.stream.failure", + Stream.make("a").pipe(Stream.concat(Stream.fail("boom"))), + { "rpc.aggregate": "test" }, + ).pipe(Stream.withSpan("rpc.instrumentation.stream.failure.span")), + ).pipe(Effect.exit); + + assert.equal(Exit.isFailure(exit), true); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.stream.failure", + outcome: "failure", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.stream.failure", + }), + true, + ); + }), + ); + + it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () => + Effect.gen(function* () { + const exit = yield* Stream.runCollect( + observeRpcStreamEffect( + "rpc.instrumentation.stream.effect.failure", + Effect.succeed(Stream.fail("boom")), + { "rpc.aggregate": "test" }, + ).pipe(Stream.withSpan("rpc.instrumentation.stream.effect.failure.span")), + ).pipe(Effect.exit); + + assert.equal(Exit.isFailure(exit), true); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.stream.effect.failure", + outcome: "failure", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.stream.effect.failure", + }), + true, + ); + }), + ); +}); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts new file mode 100644 index 0000000000..a3ac29aa02 --- /dev/null +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -0,0 +1,89 @@ +import { Duration, Effect, Exit, Metric, Stream } from "effect"; + +import { outcomeFromExit } from "./Attributes.ts"; +import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts"; + +const annotateRpcSpan = ( + method: string, + traceAttributes?: Readonly>, +): Effect.Effect => + Effect.annotateCurrentSpan({ + "rpc.method": method, + ...traceAttributes, + }); + +const recordRpcStreamMetrics = ( + method: string, + startedAt: number, + exit: Exit.Exit, +): Effect.Effect => + Effect.gen(function* () { + yield* Metric.update( + Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })), + Duration.millis(Math.max(0, Date.now() - startedAt)), + ); + yield* Metric.update( + Metric.withAttributes( + rpcRequestsTotal, + metricAttributes({ + method, + outcome: outcomeFromExit(exit), + }), + ), + 1, + ); + }); + +export const observeRpcEffect = ( + method: string, + effect: Effect.Effect, + traceAttributes?: Readonly>, +): Effect.Effect => + Effect.gen(function* () { + yield* annotateRpcSpan(method, traceAttributes); + + return yield* effect.pipe( + withMetrics({ + counter: rpcRequestsTotal, + timer: rpcRequestDuration, + attributes: { + method, + }, + }), + ); + }); + +export const observeRpcStream = ( + method: string, + stream: Stream.Stream, + traceAttributes?: Readonly>, +): Stream.Stream => + Stream.unwrap( + Effect.gen(function* () { + yield* annotateRpcSpan(method, traceAttributes); + const startedAt = Date.now(); + return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit))); + }), + ); + +export const observeRpcStreamEffect = ( + method: string, + effect: Effect.Effect, EffectError, EffectContext>, + traceAttributes?: Readonly>, +): Stream.Stream => + Stream.unwrap( + Effect.gen(function* () { + yield* annotateRpcSpan(method, traceAttributes); + const startedAt = Date.now(); + const exit = yield* Effect.exit(effect); + + if (Exit.isFailure(exit)) { + yield* recordRpcStreamMetrics(method, startedAt, exit); + return yield* Effect.failCause(exit.cause); + } + + return exit.value.pipe( + Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)), + ); + }), + ); diff --git a/apps/server/src/observability/TraceRecord.ts b/apps/server/src/observability/TraceRecord.ts new file mode 100644 index 0000000000..3aee1b267c --- /dev/null +++ b/apps/server/src/observability/TraceRecord.ts @@ -0,0 +1,100 @@ +import { Cause, Exit, Option, Tracer } from "effect"; + +import { compactTraceAttributes } from "./Attributes.ts"; + +export interface TraceRecord { + readonly type: "effect-span"; + readonly name: string; + readonly traceId: string; + readonly spanId: string; + readonly parentSpanId?: string; + readonly sampled: boolean; + readonly kind: Tracer.SpanKind; + readonly startTimeUnixNano: string; + readonly endTimeUnixNano: string; + readonly durationMs: number; + readonly attributes: Readonly>; + readonly events: ReadonlyArray<{ + readonly name: string; + readonly timeUnixNano: string; + readonly attributes: Readonly>; + }>; + readonly links: ReadonlyArray<{ + readonly traceId: string; + readonly spanId: string; + readonly attributes: Readonly>; + }>; + readonly exit: + | { + readonly _tag: "Success"; + } + | { + readonly _tag: "Interrupted"; + readonly cause: string; + } + | { + readonly _tag: "Failure"; + readonly cause: string; + }; +} + +interface SerializableSpan { + readonly name: string; + readonly traceId: string; + readonly spanId: string; + readonly parent: Option.Option; + readonly status: Tracer.SpanStatus; + readonly sampled: boolean; + readonly kind: Tracer.SpanKind; + readonly attributes: ReadonlyMap; + readonly links: ReadonlyArray; + readonly events: ReadonlyArray< + readonly [name: string, startTime: bigint, attributes: Record] + >; +} + +function formatTraceExit(exit: Exit.Exit): TraceRecord["exit"] { + if (Exit.isSuccess(exit)) { + return { _tag: "Success" }; + } + if (Cause.hasInterruptsOnly(exit.cause)) { + return { + _tag: "Interrupted", + cause: Cause.pretty(exit.cause), + }; + } + return { + _tag: "Failure", + cause: Cause.pretty(exit.cause), + }; +} + +export function spanToTraceRecord(span: SerializableSpan): TraceRecord { + const status = span.status as Extract; + const parentSpanId = Option.getOrUndefined(span.parent)?.spanId; + + return { + type: "effect-span", + name: span.name, + traceId: span.traceId, + spanId: span.spanId, + ...(parentSpanId ? { parentSpanId } : {}), + sampled: span.sampled, + kind: span.kind, + startTimeUnixNano: String(status.startTime), + endTimeUnixNano: String(status.endTime), + durationMs: Number(status.endTime - status.startTime) / 1_000_000, + attributes: compactTraceAttributes(Object.fromEntries(span.attributes)), + events: span.events.map(([name, startTime, attributes]) => ({ + name, + timeUnixNano: String(startTime), + attributes: compactTraceAttributes(attributes), + })), + links: span.links.map((link) => ({ + traceId: link.span.traceId, + spanId: link.span.spanId, + attributes: compactTraceAttributes(link.attributes), + })), + exit: formatTraceExit(status.exit), + }; +} diff --git a/apps/server/src/observability/TraceSink.test.ts b/apps/server/src/observability/TraceSink.test.ts new file mode 100644 index 0000000000..f4db90516b --- /dev/null +++ b/apps/server/src/observability/TraceSink.test.ts @@ -0,0 +1,152 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { assert, describe, it } from "@effect/vitest"; +import { Effect } from "effect"; + +import type { TraceRecord } from "./TraceRecord.ts"; +import { makeTraceSink } from "./TraceSink.ts"; + +const makeRecord = (name: string, suffix = ""): TraceRecord => ({ + type: "effect-span", + name, + traceId: `trace-${name}-${suffix}`, + spanId: `span-${name}-${suffix}`, + sampled: true, + kind: "internal", + startTimeUnixNano: "1", + endTimeUnixNano: "2", + durationMs: 1, + attributes: { + payload: suffix, + }, + events: [], + links: [], + exit: { + _tag: "Success", + }, +}); + +describe("TraceSink", () => { + it.effect("flushes buffered records on close", () => + Effect.scoped( + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + const sink = yield* makeTraceSink({ + filePath: tracePath, + maxBytes: 1024, + maxFiles: 2, + batchWindowMs: 10_000, + }); + + sink.push(makeRecord("alpha")); + sink.push(makeRecord("beta")); + yield* sink.close(); + + const lines = fs + .readFileSync(tracePath, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line) as TraceRecord); + + assert.equal(lines.length, 2); + assert.equal(lines[0]?.name, "alpha"); + assert.equal(lines[1]?.name, "beta"); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ), + ); + + it.effect("rotates the trace file when the configured max size is exceeded", () => + Effect.scoped( + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + const sink = yield* makeTraceSink({ + filePath: tracePath, + maxBytes: 180, + maxFiles: 2, + batchWindowMs: 10_000, + }); + + for (let index = 0; index < 8; index += 1) { + sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`)); + yield* sink.flush; + } + yield* sink.close(); + + const matchingFiles = fs + .readdirSync(tempDir) + .filter( + (entry) => + entry === "server.trace.ndjson" || entry.startsWith("server.trace.ndjson."), + ) + .toSorted(); + + assert.equal( + matchingFiles.some((entry) => entry === "server.trace.ndjson.1"), + true, + ); + assert.equal( + matchingFiles.some((entry) => entry === "server.trace.ndjson.3"), + false, + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ), + ); + + it.effect("drops only the invalid record when serialization fails", () => + Effect.scoped( + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + const sink = yield* makeTraceSink({ + filePath: tracePath, + maxBytes: 1024, + maxFiles: 2, + batchWindowMs: 10_000, + }); + + const circular: Array = []; + circular.push(circular); + + sink.push(makeRecord("alpha")); + sink.push({ + ...makeRecord("invalid"), + attributes: { + circular, + }, + } as TraceRecord); + sink.push(makeRecord("beta")); + yield* sink.close(); + + const lines = fs + .readFileSync(tracePath, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line) as TraceRecord); + + assert.deepStrictEqual( + lines.map((line) => line.name), + ["alpha", "beta"], + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ), + ); +}); diff --git a/apps/server/src/observability/TraceSink.ts b/apps/server/src/observability/TraceSink.ts new file mode 100644 index 0000000000..1bd00b4734 --- /dev/null +++ b/apps/server/src/observability/TraceSink.ts @@ -0,0 +1,68 @@ +import { RotatingFileSink } from "@t3tools/shared/logging"; +import { Effect } from "effect"; + +import type { TraceRecord } from "./TraceRecord.ts"; + +const FLUSH_BUFFER_THRESHOLD = 32; + +export interface TraceSinkOptions { + readonly filePath: string; + readonly maxBytes: number; + readonly maxFiles: number; + readonly batchWindowMs: number; +} + +export interface TraceSink { + readonly filePath: string; + push: (record: TraceRecord) => void; + flush: Effect.Effect; + close: () => Effect.Effect; +} + +export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) { + const sink = new RotatingFileSink({ + filePath: options.filePath, + maxBytes: options.maxBytes, + maxFiles: options.maxFiles, + }); + + let buffer: Array = []; + + const flushUnsafe = () => { + if (buffer.length === 0) { + return; + } + + const chunk = buffer.join(""); + buffer = []; + + try { + sink.write(chunk); + } catch { + buffer.unshift(chunk); + } + }; + + const flush = Effect.sync(flushUnsafe).pipe(Effect.withTracerEnabled(false)); + + yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore)); + yield* Effect.forkScoped( + Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever), + ); + + return { + filePath: options.filePath, + push(record) { + try { + buffer.push(`${JSON.stringify(record)}\n`); + if (buffer.length >= FLUSH_BUFFER_THRESHOLD) { + flushUnsafe(); + } + } catch { + return; + } + }, + flush, + close: () => flush, + } satisfies TraceSink; +}); diff --git a/apps/server/src/open.test.ts b/apps/server/src/open.test.ts new file mode 100644 index 0000000000..76b14c8597 --- /dev/null +++ b/apps/server/src/open.test.ts @@ -0,0 +1,324 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { assertSuccess } from "@effect/vitest/utils"; +import { FileSystem, Path, Effect } from "effect"; + +import { + isCommandAvailable, + launchDetached, + resolveAvailableEditors, + resolveEditorLaunch, +} from "./open"; + +it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { + it.effect("returns commands for command-based editors", () => + Effect.gen(function* () { + const antigravityLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "antigravity" }, + "darwin", + ); + assert.deepEqual(antigravityLaunch, { + command: "agy", + args: ["/tmp/workspace"], + }); + + const cursorLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "cursor" }, + "darwin", + ); + assert.deepEqual(cursorLaunch, { + command: "cursor", + args: ["/tmp/workspace"], + }); + + const traeLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "trae" }, + "darwin", + ); + assert.deepEqual(traeLaunch, { + command: "trae", + args: ["/tmp/workspace"], + }); + + const vscodeLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "vscode" }, + "darwin", + ); + assert.deepEqual(vscodeLaunch, { + command: "code", + args: ["/tmp/workspace"], + }); + + const vscodeInsidersLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "vscode-insiders" }, + "darwin", + ); + assert.deepEqual(vscodeInsidersLaunch, { + command: "code-insiders", + args: ["/tmp/workspace"], + }); + + const vscodiumLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "vscodium" }, + "darwin", + ); + assert.deepEqual(vscodiumLaunch, { + command: "codium", + args: ["/tmp/workspace"], + }); + + const zedLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "zed" }, + "darwin", + ); + assert.deepEqual(zedLaunch, { + command: "zed", + args: ["/tmp/workspace"], + }); + + const ideaLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "idea" }, + "darwin", + ); + assert.deepEqual(ideaLaunch, { + command: "idea", + args: ["/tmp/workspace"], + }); + }), + ); + + it.effect("applies launch-style-specific navigation arguments", () => + Effect.gen(function* () { + const lineOnly = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" }, + "darwin", + ); + assert.deepEqual(lineOnly, { + command: "cursor", + args: ["--goto", "/tmp/workspace/AGENTS.md:48"], + }); + + const lineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" }, + "darwin", + ); + assert.deepEqual(lineAndColumn, { + command: "cursor", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + + const traeLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" }, + "darwin", + ); + assert.deepEqual(traeLineAndColumn, { + command: "trae", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + + const vscodeLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" }, + "darwin", + ); + assert.deepEqual(vscodeLineAndColumn, { + command: "code", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + + const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" }, + "darwin", + ); + assert.deepEqual(vscodeInsidersLineAndColumn, { + command: "code-insiders", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + + const vscodiumLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" }, + "darwin", + ); + assert.deepEqual(vscodiumLineAndColumn, { + command: "codium", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + + const zedLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" }, + "darwin", + ); + assert.deepEqual(zedLineAndColumn, { + command: "zed", + args: ["/tmp/workspace/src/open.ts:71:5"], + }); + + const zedLineOnly = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/AGENTS.md:48", editor: "zed" }, + "darwin", + ); + assert.deepEqual(zedLineOnly, { + command: "zed", + args: ["/tmp/workspace/AGENTS.md:48"], + }); + + const ideaLineOnly = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/AGENTS.md:48", editor: "idea" }, + "darwin", + ); + assert.deepEqual(ideaLineOnly, { + command: "idea", + args: ["--line", "48", "/tmp/workspace/AGENTS.md"], + }); + + const ideaLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" }, + "darwin", + ); + assert.deepEqual(ideaLineAndColumn, { + command: "idea", + args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"], + }); + }), + ); + + it.effect("maps file-manager editor to OS open commands", () => + Effect.gen(function* () { + const launch1 = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "file-manager" }, + "darwin", + ); + assert.deepEqual(launch1, { + command: "open", + args: ["/tmp/workspace"], + }); + + const launch2 = yield* resolveEditorLaunch( + { cwd: "C:\\workspace", editor: "file-manager" }, + "win32", + ); + assert.deepEqual(launch2, { + command: "explorer", + args: ["C:\\workspace"], + }); + + const launch3 = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "file-manager" }, + "linux", + ); + assert.deepEqual(launch3, { + command: "xdg-open", + args: ["/tmp/workspace"], + }); + }), + ); +}); + +it.layer(NodeServices.layer)("launchDetached", (it) => { + it.effect("resolves when command can be spawned", () => + Effect.gen(function* () { + const result = yield* launchDetached({ + command: process.execPath, + args: ["-e", "process.exit(0)"], + }).pipe(Effect.result); + assertSuccess(result, undefined); + }), + ); + + it.effect("rejects when command does not exist", () => + Effect.gen(function* () { + const result = yield* launchDetached({ + command: `t3code-no-such-command-${Date.now()}`, + args: [], + }).pipe(Effect.result); + assert.equal(result._tag, "Failure"); + }), + ); +}); + +it.layer(NodeServices.layer)("isCommandAvailable", (it) => { + it.effect("resolves win32 commands with PATHEXT", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n"); + const env = { + PATH: dir, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + } satisfies NodeJS.ProcessEnv; + assert.equal(isCommandAvailable("code", { platform: "win32", env }), true); + }), + ); + + it("returns false when a command is not on PATH", () => { + const env = { + PATH: "", + PATHEXT: ".COM;.EXE;.BAT;.CMD", + } satisfies NodeJS.ProcessEnv; + assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false); + }); + + it.effect("does not treat bare files without executable extension as available on win32", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n"); + const env = { + PATH: dir, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + } satisfies NodeJS.ProcessEnv; + assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false); + }), + ); + + it.effect("appends PATHEXT for commands with non-executable extensions on win32", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n"); + const env = { + PATH: dir, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + } satisfies NodeJS.ProcessEnv; + assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true); + }), + ); + + it.effect("uses platform-specific PATH delimiter for platform overrides", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n"); + yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ"); + const env = { + PATH: `${firstDir};${secondDir}`, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + } satisfies NodeJS.ProcessEnv; + assert.equal(isCommandAvailable("code", { platform: "win32", env }), true); + }), + ); +}); + +it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => { + it.effect("returns installed editors for command launches", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + + yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n"); + yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n"); + yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n"); + yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ"); + const editors = resolveAvailableEditors("win32", { + PATH: dir, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + }); + assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]); + }), + ); +}); diff --git a/apps/server/src/open.ts b/apps/server/src/open.ts new file mode 100644 index 0000000000..58074ceef2 --- /dev/null +++ b/apps/server/src/open.ts @@ -0,0 +1,312 @@ +/** + * Open - Browser/editor launch service interface. + * + * Owns process launch helpers for opening URLs in a browser and workspace + * paths in a configured editor. + * + * @module Open + */ +import { spawn } from "node:child_process"; +import { accessSync, constants, statSync } from "node:fs"; +import { extname, join } from "node:path"; + +import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts"; +import { ServiceMap, Effect, Layer } from "effect"; + +// ============================== +// Definitions +// ============================== + +export { OpenError }; + +export interface OpenInEditorInput { + readonly cwd: string; + readonly editor: EditorId; +} + +interface EditorLaunch { + readonly command: string; + readonly args: ReadonlyArray; +} + +interface CommandAvailabilityOptions { + readonly platform?: NodeJS.Platform; + readonly env?: NodeJS.ProcessEnv; +} + +const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/; + +function parseTargetPathAndPosition(target: string): { + path: string; + line: string | undefined; + column: string | undefined; +} | null { + const match = TARGET_WITH_POSITION_PATTERN.exec(target); + if (!match?.[1] || !match[2]) { + return null; + } + + return { + path: match[1], + line: match[2], + column: match[3], + }; +} + +function resolveCommandEditorArgs( + editor: (typeof EDITORS)[number], + target: string, +): ReadonlyArray { + const parsedTarget = parseTargetPathAndPosition(target); + + switch (editor.launchStyle) { + case "direct-path": + return [target]; + case "goto": + return parsedTarget ? ["--goto", target] : [target]; + case "line-column": { + if (!parsedTarget) { + return [target]; + } + + const { path, line, column } = parsedTarget; + return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path]; + } + } +} + +function fileManagerCommandForPlatform(platform: NodeJS.Platform): string { + switch (platform) { + case "darwin": + return "open"; + case "win32": + return "explorer"; + default: + return "xdg-open"; + } +} + +function stripWrappingQuotes(value: string): string { + return value.replace(/^"+|"+$/g, ""); +} + +function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string { + return env.PATH ?? env.Path ?? env.path ?? ""; +} + +function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray { + const rawValue = env.PATHEXT; + const fallback = [".COM", ".EXE", ".BAT", ".CMD"]; + if (!rawValue) return fallback; + + const parsed = rawValue + .split(";") + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0) + .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`)); + return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback; +} + +function resolveCommandCandidates( + command: string, + platform: NodeJS.Platform, + windowsPathExtensions: ReadonlyArray, +): ReadonlyArray { + if (platform !== "win32") return [command]; + const extension = extname(command); + const normalizedExtension = extension.toUpperCase(); + + if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) { + const commandWithoutExtension = command.slice(0, -extension.length); + return Array.from( + new Set([ + command, + `${commandWithoutExtension}${normalizedExtension}`, + `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`, + ]), + ); + } + + const candidates: string[] = []; + for (const extension of windowsPathExtensions) { + candidates.push(`${command}${extension}`); + candidates.push(`${command}${extension.toLowerCase()}`); + } + return Array.from(new Set(candidates)); +} + +function isExecutableFile( + filePath: string, + platform: NodeJS.Platform, + windowsPathExtensions: ReadonlyArray, +): boolean { + try { + const stat = statSync(filePath); + if (!stat.isFile()) return false; + if (platform === "win32") { + const extension = extname(filePath); + if (extension.length === 0) return false; + return windowsPathExtensions.includes(extension.toUpperCase()); + } + accessSync(filePath, constants.X_OK); + return true; + } catch { + return false; + } +} + +function resolvePathDelimiter(platform: NodeJS.Platform): string { + return platform === "win32" ? ";" : ":"; +} + +export function isCommandAvailable( + command: string, + options: CommandAvailabilityOptions = {}, +): boolean { + const platform = options.platform ?? process.platform; + const env = options.env ?? process.env; + const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : []; + const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions); + + if (command.includes("/") || command.includes("\\")) { + return commandCandidates.some((candidate) => + isExecutableFile(candidate, platform, windowsPathExtensions), + ); + } + + const pathValue = resolvePathEnvironmentVariable(env); + if (pathValue.length === 0) return false; + const pathEntries = pathValue + .split(resolvePathDelimiter(platform)) + .map((entry) => stripWrappingQuotes(entry.trim())) + .filter((entry) => entry.length > 0); + + for (const pathEntry of pathEntries) { + for (const candidate of commandCandidates) { + if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) { + return true; + } + } + } + return false; +} + +export function resolveAvailableEditors( + platform: NodeJS.Platform = process.platform, + env: NodeJS.ProcessEnv = process.env, +): ReadonlyArray { + const available: EditorId[] = []; + + for (const editor of EDITORS) { + const command = editor.command ?? fileManagerCommandForPlatform(platform); + if (isCommandAvailable(command, { platform, env })) { + available.push(editor.id); + } + } + + return available; +} + +/** + * OpenShape - Service API for browser and editor launch actions. + */ +export interface OpenShape { + /** + * Open a URL target in the default browser. + */ + readonly openBrowser: (target: string) => Effect.Effect; + + /** + * Open a workspace path in a selected editor integration. + * + * Launches the editor as a detached process so server startup is not blocked. + */ + readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect; +} + +/** + * Open - Service tag for browser/editor launch operations. + */ +export class Open extends ServiceMap.Service()("t3/open") {} + +// ============================== +// Implementations +// ============================== + +export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( + input: OpenInEditorInput, + platform: NodeJS.Platform = process.platform, +): Effect.fn.Return { + yield* Effect.annotateCurrentSpan({ + "open.editor": input.editor, + "open.cwd": input.cwd, + "open.platform": platform, + }); + const editorDef = EDITORS.find((editor) => editor.id === input.editor); + if (!editorDef) { + return yield* new OpenError({ message: `Unknown editor: ${input.editor}` }); + } + + if (editorDef.command) { + return { + command: editorDef.command, + args: resolveCommandEditorArgs(editorDef, input.cwd), + }; + } + + if (editorDef.id !== "file-manager") { + return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` }); + } + + return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] }; +}); + +export const launchDetached = (launch: EditorLaunch) => + Effect.gen(function* () { + if (!isCommandAvailable(launch.command)) { + return yield* new OpenError({ message: `Editor command not found: ${launch.command}` }); + } + + yield* Effect.callback((resume) => { + let child; + try { + child = spawn(launch.command, [...launch.args], { + detached: true, + stdio: "ignore", + shell: process.platform === "win32", + }); + } catch (error) { + return resume( + Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })), + ); + } + + const handleSpawn = () => { + child.unref(); + resume(Effect.void); + }; + + child.once("spawn", handleSpawn); + child.once("error", (cause) => + resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))), + ); + }); + }); + +const make = Effect.gen(function* () { + const open = yield* Effect.tryPromise({ + try: () => import("open"), + catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }), + }); + + return { + openBrowser: (target) => + Effect.tryPromise({ + try: () => open.default(target), + catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }), + }), + openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached), + } satisfies OpenShape; +}); + +export const OpenLive = Layer.effect(Open, make); diff --git a/apps/server/src/orchestration/Errors.ts b/apps/server/src/orchestration/Errors.ts new file mode 100644 index 0000000000..1ea038e1d1 --- /dev/null +++ b/apps/server/src/orchestration/Errors.ts @@ -0,0 +1,123 @@ +import { SchemaIssue, Schema } from "effect"; + +import type { ProjectionRepositoryError } from "../persistence/Errors.ts"; + +export class OrchestrationCommandJsonParseError extends Schema.TaggedErrorClass()( + "OrchestrationCommandJsonParseError", + { + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Invalid orchestration command JSON: ${this.detail}`; + } +} + +export class OrchestrationCommandDecodeError extends Schema.TaggedErrorClass()( + "OrchestrationCommandDecodeError", + { + issue: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Invalid orchestration command payload: ${this.issue}`; + } +} + +export class OrchestrationCommandInvariantError extends Schema.TaggedErrorClass()( + "OrchestrationCommandInvariantError", + { + commandType: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Orchestration command invariant failed (${this.commandType}): ${this.detail}`; + } +} + +export class OrchestrationCommandPreviouslyRejectedError extends Schema.TaggedErrorClass()( + "OrchestrationCommandPreviouslyRejectedError", + { + commandId: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Command previously rejected (${this.commandId}): ${this.detail}`; + } +} + +export class OrchestrationProjectorDecodeError extends Schema.TaggedErrorClass()( + "OrchestrationProjectorDecodeError", + { + eventType: Schema.String, + issue: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Projector decode failed for ${this.eventType}: ${this.issue}`; + } +} + +export class OrchestrationListenerCallbackError extends Schema.TaggedErrorClass()( + "OrchestrationListenerCallbackError", + { + listener: Schema.Literals(["read-model", "domain-event"]), + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Orchestration ${this.listener} listener failed: ${this.detail}`; + } +} + +export type OrchestrationDispatchError = + | ProjectionRepositoryError + | OrchestrationCommandInvariantError + | OrchestrationCommandPreviouslyRejectedError + | OrchestrationProjectorDecodeError + | OrchestrationListenerCallbackError; + +export type OrchestrationEngineError = + | OrchestrationDispatchError + | OrchestrationCommandJsonParseError + | OrchestrationCommandDecodeError; + +export function toOrchestrationCommandDecodeError(error: Schema.SchemaError) { + return new OrchestrationCommandDecodeError({ + issue: SchemaIssue.makeFormatterDefault()(error.issue), + cause: error, + }); +} + +export function toProjectorDecodeError(eventType: string) { + return (error: Schema.SchemaError): OrchestrationProjectorDecodeError => + new OrchestrationProjectorDecodeError({ + eventType, + issue: SchemaIssue.makeFormatterDefault()(error.issue), + cause: error, + }); +} + +export function toOrchestrationJsonParseError(cause: unknown) { + return new OrchestrationCommandJsonParseError({ + detail: `Failed to parse orchestration command JSON`, + cause, + }); +} + +export function toListenerCallbackError(listener: "read-model" | "domain-event") { + return (cause: unknown): OrchestrationListenerCallbackError => + new OrchestrationListenerCallbackError({ + listener, + detail: `Failed to invoke orchestration ${listener} listener`, + cause, + }); +} diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts new file mode 100644 index 0000000000..ab9f633e02 --- /dev/null +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -0,0 +1,1050 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; + +import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts"; +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + EventId, + MessageId, + ProjectId, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts"; +import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts"; +import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { CheckpointReactorLive } from "./CheckpointReactor.ts"; +import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; +import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; +import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts"; +import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; +import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { + OrchestrationEngineService, + type OrchestrationEngineShape, +} from "../Services/OrchestrationEngine.ts"; +import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; +import { + ProviderService, + type ProviderServiceShape, +} from "../../provider/Services/ProviderService.ts"; +import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts"; +import { ServerConfig } from "../../config.ts"; +import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts"; +import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts"; + +const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); +const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); + +type LegacyProviderRuntimeEvent = { + readonly type: string; + readonly eventId: EventId; + readonly provider: ProviderKind; + readonly createdAt: string; + readonly threadId: ThreadId; + readonly turnId?: string | undefined; + readonly itemId?: string | undefined; + readonly requestId?: string | undefined; + readonly payload?: unknown | undefined; + readonly [key: string]: unknown; +}; + +function createProviderServiceHarness( + cwd: string, + hasSession = true, + sessionCwd = cwd, + providerName: ProviderSession["provider"] = "codex", +) { + const now = new Date().toISOString(); + const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); + const rollbackConversation = vi.fn( + (_input: { readonly threadId: ThreadId; readonly numTurns: number }) => Effect.void, + ); + + const unsupported = () => + Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect; + const listSessions = () => + hasSession + ? Effect.succeed([ + { + provider: providerName, + status: "ready", + runtimeMode: "full-access", + threadId: ThreadId.makeUnsafe("thread-1"), + cwd: sessionCwd, + createdAt: now, + updatedAt: now, + }, + ] satisfies ReadonlyArray) + : Effect.succeed([] as ReadonlyArray); + const service: ProviderServiceShape = { + startSession: () => unsupported(), + sendTurn: () => unsupported(), + interruptTurn: () => unsupported(), + respondToRequest: () => unsupported(), + respondToUserInput: () => unsupported(), + stopSession: () => unsupported(), + listSessions, + getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), + rollbackConversation, + streamEvents: Stream.fromPubSub(runtimeEventPubSub), + }; + + const emit = (event: LegacyProviderRuntimeEvent): void => { + Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent)); + }; + + return { + service, + rollbackConversation, + emit, + }; +} + +async function waitForThread( + engine: OrchestrationEngineShape, + predicate: (thread: { + latestTurn: { turnId: string } | null; + checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>; + activities: ReadonlyArray<{ kind: string }>; + }) => boolean, + timeoutMs = 15_000, +) { + const deadline = Date.now() + timeoutMs; + const poll = async (): Promise<{ + latestTurn: { turnId: string } | null; + checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>; + activities: ReadonlyArray<{ kind: string }>; + }> => { + const readModel = await Effect.runPromise(engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + if (thread && predicate(thread)) { + return thread; + } + if (Date.now() >= deadline) { + throw new Error("Timed out waiting for thread state."); + } + await new Promise((resolve) => setTimeout(resolve, 10)); + return poll(); + }; + return poll(); +} + +async function waitForEvent( + engine: OrchestrationEngineShape, + predicate: (event: { type: string }) => boolean, + timeoutMs = 15_000, +) { + const deadline = Date.now() + timeoutMs; + const poll = async () => { + const events = await Effect.runPromise( + Stream.runCollect(engine.readEvents(0)).pipe(Effect.map((chunk) => Array.from(chunk))), + ); + if (events.some(predicate)) { + return events; + } + if (Date.now() >= deadline) { + throw new Error("Timed out waiting for orchestration event."); + } + await new Promise((resolve) => setTimeout(resolve, 10)); + return poll(); + }; + return poll(); +} + +function runGit(cwd: string, args: ReadonlyArray) { + return execFileSync("git", args, { + cwd, + stdio: ["ignore", "pipe", "pipe"], + encoding: "utf8", + }); +} + +function createGitRepository() { + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "t3-checkpoint-handler-")); + runGit(cwd, ["init", "--initial-branch=main"]); + runGit(cwd, ["config", "user.email", "test@example.com"]); + runGit(cwd, ["config", "user.name", "Test User"]); + fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8"); + runGit(cwd, ["add", "."]); + runGit(cwd, ["commit", "-m", "Initial"]); + return cwd; +} + +function gitRefExists(cwd: string, ref: string): boolean { + try { + runGit(cwd, ["show-ref", "--verify", "--quiet", ref]); + return true; + } catch { + return false; + } +} + +function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string { + return runGit(cwd, ["show", `${ref}:${filePath}`]); +} + +async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) { + const deadline = Date.now() + timeoutMs; + const poll = async (): Promise => { + if (gitRefExists(cwd, ref)) { + return; + } + if (Date.now() >= deadline) { + throw new Error(`Timed out waiting for git ref '${ref}'.`); + } + await new Promise((resolve) => setTimeout(resolve, 10)); + return poll(); + }; + return poll(); +} + +describe("CheckpointReactor", () => { + let runtime: ManagedRuntime.ManagedRuntime< + OrchestrationEngineService | CheckpointReactor | CheckpointStore, + unknown + > | null = null; + let scope: Scope.Closeable | null = null; + const tempDirs: string[] = []; + + afterEach(async () => { + if (scope) { + await Effect.runPromise(Scope.close(scope, Exit.void)); + } + scope = null; + if (runtime) { + await runtime.dispose(); + } + runtime = null; + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) { + fs.rmSync(dir, { recursive: true, force: true }); + } + } + }); + + async function createHarness(options?: { + readonly hasSession?: boolean; + readonly seedFilesystemCheckpoints?: boolean; + readonly projectWorkspaceRoot?: string; + readonly threadWorktreePath?: string | null; + readonly providerSessionCwd?: string; + readonly providerName?: ProviderKind; + }) { + const cwd = createGitRepository(); + tempDirs.push(cwd); + const provider = createProviderServiceHarness( + cwd, + options?.hasSession ?? true, + options?.providerSessionCwd ?? cwd, + options?.providerName ?? "codex", + ); + const orchestrationLayer = OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), + Layer.provide(OrchestrationProjectionPipelineLive), + Layer.provide(OrchestrationEventStoreLive), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(SqlitePersistenceMemory), + ); + + const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-checkpoint-reactor-test-", + }); + + const layer = CheckpointReactorLive.pipe( + Layer.provideMerge(orchestrationLayer), + Layer.provideMerge(RuntimeReceiptBusLive), + Layer.provideMerge(Layer.succeed(ProviderService, provider.service)), + Layer.provideMerge(CheckpointStoreLive), + Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + Layer.provideMerge(WorkspacePathsLive), + Layer.provideMerge(GitCoreLive), + Layer.provideMerge(ServerConfigLayer), + Layer.provideMerge(NodeServices.layer), + ); + + runtime = ManagedRuntime.make(layer); + const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); + const reactor = await runtime.runPromise(Effect.service(CheckpointReactor)); + const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore)); + scope = await Effect.runPromise(Scope.make("sequential")); + await Effect.runPromise(reactor.start().pipe(Scope.provide(scope))); + const drain = () => Effect.runPromise(reactor.drain); + + const createdAt = new Date().toISOString(); + await Effect.runPromise( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-create"), + projectId: asProjectId("project-1"), + title: "Test Project", + workspaceRoot: options?.projectWorkspaceRoot ?? cwd, + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + await Effect.runPromise( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-create"), + threadId: ThreadId.makeUnsafe("thread-1"), + projectId: asProjectId("project-1"), + title: "Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: options?.threadWorktreePath ?? cwd, + createdAt, + }), + ); + + if (options?.seedFilesystemCheckpoints ?? true) { + await runtime.runPromise( + checkpointStore.captureCheckpoint({ + cwd, + checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + }), + ); + fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8"); + await runtime.runPromise( + checkpointStore.captureCheckpoint({ + cwd, + checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1), + }), + ); + fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8"); + await runtime.runPromise( + checkpointStore.captureCheckpoint({ + cwd, + checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2), + }), + ); + } + + return { + engine, + provider, + cwd, + drain, + }; + } + + it("captures pre-turn baseline on turn.started and post-turn checkpoint on turn.completed", async () => { + const harness = await createHarness({ seedFilesystemCheckpoints: false }); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-capture"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: createdAt, + }, + createdAt, + }), + ); + + harness.provider.emit({ + type: "turn.started", + eventId: EventId.makeUnsafe("evt-turn-started-1"), + provider: "codex", + + createdAt: new Date().toISOString(), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-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-1"), + provider: "codex", + + createdAt: new Date().toISOString(), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-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-1" && entry.checkpoints.length === 1, + ); + expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1); + expect( + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)), + ).toBe(true); + expect( + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)), + ).toBe(true); + expect( + gitShowFileAtRef( + harness.cwd, + checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + "README.md", + ), + ).toBe("v1\n"); + expect( + gitShowFileAtRef( + harness.cwd, + checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1), + "README.md", + ), + ).toBe("v2\n"); + }); + + it("ignores auxiliary thread turn completion while primary turn is active", async () => { + const harness = await createHarness({ seedFilesystemCheckpoints: false }); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: asTurnId("turn-main"), + lastError: null, + updatedAt: createdAt, + }, + createdAt, + }), + ); + + harness.provider.emit({ + type: "turn.started", + eventId: EventId.makeUnsafe("evt-turn-started-main"), + provider: "codex", + + createdAt: new Date().toISOString(), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-main"), + }); + 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-aux"), + provider: "codex", + + createdAt: new Date().toISOString(), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-aux"), + payload: { state: "completed" }, + }); + + await harness.drain(); + const midReadModel = await Effect.runPromise(harness.engine.getReadModel()); + const midThread = midReadModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + expect(midThread?.checkpoints).toHaveLength(0); + + harness.provider.emit({ + type: "turn.completed", + eventId: EventId.makeUnsafe("evt-turn-completed-main"), + provider: "codex", + + createdAt: new Date().toISOString(), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-main"), + payload: { state: "completed" }, + }); + + const thread = await waitForThread( + harness.engine, + (entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1, + ); + expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1); + }); + + it("captures pre-turn and completion checkpoints for claude runtime events", async () => { + const harness = await createHarness({ + seedFilesystemCheckpoints: false, + providerName: "claudeAgent", + }); + 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: "claudeAgent", + 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: "claudeAgent", + 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: "claudeAgent", + 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(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-missing-baseline-diff"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: createdAt, + }, + createdAt, + }), + ); + + harness.provider.emit({ + type: "turn.completed", + eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"), + provider: "codex", + + createdAt: new Date().toISOString(), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-missing-baseline"), + payload: { state: "completed" }, + }); + + await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed"); + const thread = await waitForThread( + harness.engine, + (entry) => + entry.checkpoints.length === 1 && + entry.activities.some((activity) => activity.kind === "checkpoint.capture.failed"), + ); + + expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1); + expect( + thread.activities.some((activity) => activity.kind === "checkpoint.capture.failed"), + ).toBe(true); + }); + + it("captures pre-turn baseline from project workspace root when thread worktree is unset", async () => { + const harness = await createHarness({ + hasSession: false, + seedFilesystemCheckpoints: false, + threadWorktreePath: null, + }); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-for-baseline"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: MessageId.makeUnsafe("message-user-1"), + role: "user", + text: "start turn", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: new Date().toISOString(), + }), + ); + + await waitForGitRefExists( + harness.cwd, + checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + ); + expect( + gitShowFileAtRef( + harness.cwd, + checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + "README.md", + ), + ).toBe("v1\n"); + }); + + it("captures turn completion checkpoint from project workspace root when provider session cwd is unavailable", async () => { + const harness = await createHarness({ + hasSession: false, + seedFilesystemCheckpoints: false, + threadWorktreePath: null, + }); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-missing-provider-cwd"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: asTurnId("turn-missing-cwd"), + lastError: null, + updatedAt: createdAt, + }, + createdAt, + }), + ); + + fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8"); + harness.provider.emit({ + type: "turn.completed", + eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"), + provider: "codex", + + createdAt: new Date().toISOString(), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-missing-cwd"), + payload: { state: "completed" }, + }); + + await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed"); + expect( + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)), + ).toBe(true); + expect( + gitShowFileAtRef( + harness.cwd, + checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1), + "README.md", + ), + ).toBe("v2\n"); + }); + + it("ignores non-v2 checkpoint.captured runtime events", async () => { + const harness = await createHarness(); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-checkpoint-captured"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: createdAt, + }, + createdAt, + }), + ); + + harness.provider.emit({ + type: "checkpoint.captured", + eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"), + provider: "codex", + + createdAt: new Date().toISOString(), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-3"), + turnCount: 3, + status: "completed", + }); + + await harness.drain(); + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe( + false, + ); + }); + + it("continues processing runtime events after a single checkpoint runtime failure", async () => { + const nonRepositorySessionCwd = fs.mkdtempSync( + path.join(os.tmpdir(), "t3-checkpoint-runtime-non-repo-"), + ); + tempDirs.push(nonRepositorySessionCwd); + + const harness = await createHarness({ + seedFilesystemCheckpoints: false, + providerSessionCwd: nonRepositorySessionCwd, + }); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-non-repo-runtime"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: createdAt, + }, + createdAt, + }), + ); + + harness.provider.emit({ + type: "turn.completed", + eventId: EventId.makeUnsafe("evt-runtime-capture-failure"), + provider: "codex", + + createdAt: new Date().toISOString(), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-runtime-failure"), + payload: { state: "completed" }, + }); + + harness.provider.emit({ + type: "turn.started", + eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"), + provider: "codex", + + createdAt: new Date().toISOString(), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-after-runtime-failure"), + }); + + await waitForGitRefExists( + harness.cwd, + checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + ); + expect( + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)), + ).toBe(true); + }); + + it("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => { + const harness = await createHarness(); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "ready", + providerName: "codex", + 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-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-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-2"), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-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"), + threadId: ThreadId.makeUnsafe("thread-1"), + turnCount: 1, + createdAt, + }), + ); + + await waitForEvent(harness.engine, (event) => event.type === "thread.reverted"); + const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1); + + expect(thread.latestTurn?.turnId).toBe("turn-1"); + expect(thread.checkpoints).toHaveLength(1); + 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"); + expect( + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2)), + ).toBe(false); + }); + + it("executes provider revert and emits thread.reverted for claude sessions", async () => { + const harness = await createHarness({ providerName: "claudeAgent" }); + 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: "claudeAgent", + 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({ + threadId: ThreadId.makeUnsafe("thread-1"), + numTurns: 1, + }); + }); + + it("processes consecutive revert requests with deterministic rollback sequencing", async () => { + const harness = await createHarness(); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-inline-revert"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "ready", + providerName: "codex", + 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-inline-revert-diff-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-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-inline-revert-diff-2"), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-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-sequenced-revert-request-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + turnCount: 1, + createdAt, + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.checkpoint.revert", + commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-0"), + threadId: ThreadId.makeUnsafe("thread-1"), + turnCount: 0, + createdAt, + }), + ); + + await harness.drain(); + + 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, + }); + }); + + it("appends an error activity when revert is requested without an active session", async () => { + const harness = await createHarness({ hasSession: false }); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.checkpoint.revert", + commandId: CommandId.makeUnsafe("cmd-revert-no-session"), + threadId: ThreadId.makeUnsafe("thread-1"), + turnCount: 1, + createdAt, + }), + ); + + const thread = await waitForThread(harness.engine, (entry) => + entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"), + ); + + expect(thread.activities.some((activity) => activity.kind === "checkpoint.revert.failed")).toBe( + true, + ); + expect(harness.provider.rollbackConversation).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts new file mode 100644 index 0000000000..03abebaf3a --- /dev/null +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -0,0 +1,805 @@ +import { + CommandId, + EventId, + MessageId, + type ProjectId, + ThreadId, + TurnId, + type OrchestrationEvent, + type ProviderRuntimeEvent, +} from "@t3tools/contracts"; +import { Cause, Effect, Layer, Option, Stream } from "effect"; +import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; + +import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts"; +import { + checkpointRefForThreadTurn, + resolveThreadWorkspaceCwd, +} from "../../checkpointing/Utils.ts"; +import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts"; +import { ProviderService } from "../../provider/Services/ProviderService.ts"; +import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts"; +import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; +import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts"; +import { CheckpointStoreError } from "../../checkpointing/Errors.ts"; +import { OrchestrationDispatchError } from "../Errors.ts"; +import { isGitRepository } from "../../git/Utils.ts"; +import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts"; + +type ReactorInput = + | { + readonly source: "runtime"; + readonly event: ProviderRuntimeEvent; + } + | { + readonly source: "domain"; + readonly event: OrchestrationEvent; + }; + +function toTurnId(value: string | undefined): TurnId | null { + return value === undefined ? null : TurnId.makeUnsafe(String(value)); +} + +function sameId(left: string | null | undefined, right: string | null | undefined): boolean { + if (left === null || left === undefined || right === null || right === undefined) { + return false; + } + return left === right; +} + +function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" { + switch (status) { + case "failed": + return "error"; + case "cancelled": + case "interrupted": + return "missing"; + case "completed": + default: + return "ready"; + } +} + +const serverCommandId = (tag: string): CommandId => + CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`); + +const make = Effect.gen(function* () { + const orchestrationEngine = yield* OrchestrationEngineService; + const providerService = yield* ProviderService; + const checkpointStore = yield* CheckpointStore; + const receiptBus = yield* RuntimeReceiptBus; + const workspaceEntries = yield* WorkspaceEntries; + + const appendRevertFailureActivity = (input: { + readonly threadId: ThreadId; + readonly turnCount: number; + readonly detail: string; + readonly createdAt: string; + }) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: serverCommandId("checkpoint-revert-failure"), + threadId: input.threadId, + activity: { + id: EventId.makeUnsafe(crypto.randomUUID()), + tone: "error", + kind: "checkpoint.revert.failed", + summary: "Checkpoint revert failed", + payload: { + turnCount: input.turnCount, + detail: input.detail, + }, + turnId: null, + createdAt: input.createdAt, + }, + createdAt: input.createdAt, + }); + + const appendCaptureFailureActivity = (input: { + readonly threadId: ThreadId; + readonly turnId: TurnId | null; + readonly detail: string; + readonly createdAt: string; + }) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: serverCommandId("checkpoint-capture-failure"), + threadId: input.threadId, + activity: { + id: EventId.makeUnsafe(crypto.randomUUID()), + tone: "error", + kind: "checkpoint.capture.failed", + summary: "Checkpoint capture failed", + payload: { + detail: input.detail, + }, + turnId: input.turnId, + createdAt: input.createdAt, + }, + createdAt: input.createdAt, + }); + + const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* ( + threadId: ThreadId, + ): Effect.fn.Return> { + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === threadId); + + const sessions = yield* providerService.listSessions(); + + const findSessionWithCwd = ( + session: (typeof sessions)[number] | undefined, + ): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => { + if (!session?.cwd) { + return Option.none(); + } + return Option.some({ threadId: session.threadId, cwd: session.cwd }); + }; + + if (thread) { + const projectedSession = sessions.find((session) => session.threadId === thread.id); + const fromProjected = findSessionWithCwd(projectedSession); + if (Option.isSome(fromProjected)) { + return fromProjected; + } + } + + return Option.none(); + }); + + const isGitWorkspace = (cwd: string) => isGitRepository(cwd); + + // Resolves the workspace CWD for checkpoint operations, preferring the + // active provider session CWD and falling back to the thread/project config. + // Returns undefined when no CWD can be determined or the workspace is not + // a git repository. + const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: { + readonly threadId: ThreadId; + readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null }; + readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>; + readonly preferSessionRuntime: boolean; + }): Effect.fn.Return { + const fromSession = yield* resolveSessionRuntimeForThread(input.threadId); + const fromThread = resolveThreadWorkspaceCwd({ + thread: input.thread, + projects: input.projects, + }); + + const cwd = input.preferSessionRuntime + ? (Option.match(fromSession, { + onNone: () => undefined, + onSome: (runtime) => runtime.cwd, + }) ?? fromThread) + : (fromThread ?? + Option.match(fromSession, { + onNone: () => undefined, + onSome: (runtime) => runtime.cwd, + })); + + if (!cwd) { + return undefined; + } + if (!isGitWorkspace(cwd)) { + return undefined; + } + return cwd; + }); + + // Shared tail for both capture paths: creates the git checkpoint ref, diffs + // it against the previous turn, then dispatches the domain events to update + // the orchestration read model. + const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: { + readonly threadId: ThreadId; + readonly turnId: TurnId; + readonly thread: { + readonly messages: ReadonlyArray<{ + readonly id: MessageId; + readonly role: string; + readonly turnId: TurnId | null; + }>; + }; + readonly cwd: string; + readonly turnCount: number; + readonly status: "ready" | "missing" | "error"; + readonly assistantMessageId: MessageId | undefined; + readonly createdAt: string; + }) { + const fromTurnCount = Math.max(0, input.turnCount - 1); + const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, fromTurnCount); + const targetCheckpointRef = checkpointRefForThreadTurn(input.threadId, input.turnCount); + + const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({ + cwd: input.cwd, + checkpointRef: fromCheckpointRef, + }); + if (!fromCheckpointExists) { + yield* Effect.logWarning("checkpoint capture missing pre-turn baseline", { + threadId: input.threadId, + turnId: input.turnId, + fromTurnCount, + }); + } + + yield* checkpointStore.captureCheckpoint({ + cwd: input.cwd, + checkpointRef: targetCheckpointRef, + }); + + // Invalidate the workspace entry cache so the @-mention file picker + // reflects files created or deleted during this turn. + yield* workspaceEntries.invalidate(input.cwd); + + const files = yield* checkpointStore + .diffCheckpoints({ + cwd: input.cwd, + fromCheckpointRef, + toCheckpointRef: targetCheckpointRef, + fallbackFromToHead: false, + }) + .pipe( + Effect.map((diff) => + parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({ + path: file.path, + kind: "modified" as const, + additions: file.additions, + deletions: file.deletions, + })), + ), + Effect.tapError((error) => + appendCaptureFailureActivity({ + threadId: input.threadId, + turnId: input.turnId, + detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`, + createdAt: input.createdAt, + }), + ), + Effect.catch((error) => + Effect.logWarning("failed to derive checkpoint file summary", { + threadId: input.threadId, + turnId: input.turnId, + turnCount: input.turnCount, + detail: error.message, + }).pipe(Effect.as([])), + ), + ); + + const assistantMessageId = + input.assistantMessageId ?? + input.thread.messages + .toReversed() + .find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ?? + MessageId.makeUnsafe(`assistant:${input.turnId}`); + + yield* orchestrationEngine.dispatch({ + type: "thread.turn.diff.complete", + commandId: serverCommandId("checkpoint-turn-diff-complete"), + threadId: input.threadId, + turnId: input.turnId, + completedAt: input.createdAt, + checkpointRef: targetCheckpointRef, + status: input.status, + files, + assistantMessageId, + checkpointTurnCount: input.turnCount, + createdAt: input.createdAt, + }); + yield* receiptBus.publish({ + type: "checkpoint.diff.finalized", + threadId: input.threadId, + turnId: input.turnId, + checkpointTurnCount: input.turnCount, + checkpointRef: targetCheckpointRef, + status: input.status, + createdAt: input.createdAt, + }); + yield* receiptBus.publish({ + type: "turn.processing.quiesced", + threadId: input.threadId, + turnId: input.turnId, + checkpointTurnCount: input.turnCount, + createdAt: input.createdAt, + }); + + yield* orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: serverCommandId("checkpoint-captured-activity"), + threadId: input.threadId, + activity: { + id: EventId.makeUnsafe(crypto.randomUUID()), + tone: "info", + kind: "checkpoint.captured", + summary: "Checkpoint captured", + payload: { + turnCount: input.turnCount, + status: input.status, + }, + turnId: input.turnId, + createdAt: input.createdAt, + }, + createdAt: input.createdAt, + }); + }); + + // Captures a real git checkpoint when a turn completes via a runtime event. + const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")( + function* (event: Extract) { + const turnId = toTurnId(event.turnId); + if (!turnId) { + return; + } + + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === event.threadId); + if (!thread) { + return; + } + + // When a primary turn is active, only that turn may produce completion checkpoints. + if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) { + return; + } + + // Only skip if a real (non-placeholder) checkpoint already exists for this turn. + // ProviderRuntimeIngestion may insert placeholder entries with status "missing" + // before this reactor runs; those must not prevent real git capture. + if ( + thread.checkpoints.some( + (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing", + ) + ) { + return; + } + + const checkpointCwd = yield* resolveCheckpointCwd({ + threadId: thread.id, + thread, + projects: readModel.projects, + preferSessionRuntime: true, + }); + if (!checkpointCwd) { + return; + } + + // If a placeholder checkpoint exists for this turn, reuse its turn count + // instead of incrementing past it. + const existingPlaceholder = thread.checkpoints.find( + (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing", + ); + const currentTurnCount = thread.checkpoints.reduce( + (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), + 0, + ); + const nextTurnCount = existingPlaceholder + ? existingPlaceholder.checkpointTurnCount + : currentTurnCount + 1; + + yield* captureAndDispatchCheckpoint({ + threadId: thread.id, + turnId, + thread, + cwd: checkpointCwd, + turnCount: nextTurnCount, + status: checkpointStatusFromRuntime(event.payload.state), + assistantMessageId: undefined, + createdAt: event.createdAt, + }); + }, + ); + + // Captures a real git checkpoint when a placeholder checkpoint (status "missing") + // is detected via a domain event. This replaces the placeholder with a real + // git-ref-based checkpoint. + // + // ProviderRuntimeIngestion creates placeholder checkpoints on turn.diff.updated + // events from the Codex runtime. This handler fires when the corresponding + // domain event arrives, allowing the reactor to capture the actual filesystem + // state into a git ref and dispatch a replacement checkpoint. + const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* ( + event: Extract, + ) { + const { threadId, turnId, checkpointTurnCount, status } = event.payload; + + // Only replace placeholders; skip events from our own real captures. + if (status !== "missing") { + return; + } + + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === threadId); + if (!thread) { + yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", { + threadId, + }); + return; + } + + // If a real checkpoint already exists for this turn, skip. + if ( + thread.checkpoints.some( + (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing", + ) + ) { + yield* Effect.logDebug( + "checkpoint capture from placeholder skipped: real checkpoint already exists", + { threadId, turnId }, + ); + return; + } + + const checkpointCwd = yield* resolveCheckpointCwd({ + threadId, + thread, + projects: readModel.projects, + preferSessionRuntime: true, + }); + if (!checkpointCwd) { + return; + } + + yield* captureAndDispatchCheckpoint({ + threadId, + turnId, + thread, + cwd: checkpointCwd, + turnCount: checkpointTurnCount, + status: "ready", + assistantMessageId: event.payload.assistantMessageId ?? undefined, + createdAt: event.payload.completedAt, + }); + }); + + const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")( + function* (event: Extract) { + const turnId = toTurnId(event.turnId); + if (!turnId) { + return; + } + + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === event.threadId); + if (!thread) { + return; + } + + const checkpointCwd = yield* resolveCheckpointCwd({ + threadId: thread.id, + thread, + projects: readModel.projects, + preferSessionRuntime: false, + }); + if (!checkpointCwd) { + return; + } + + const currentTurnCount = thread.checkpoints.reduce( + (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), + 0, + ); + const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount); + const baselineExists = yield* checkpointStore.hasCheckpointRef({ + cwd: checkpointCwd, + checkpointRef: baselineCheckpointRef, + }); + if (baselineExists) { + return; + } + + yield* checkpointStore.captureCheckpoint({ + cwd: checkpointCwd, + checkpointRef: baselineCheckpointRef, + }); + yield* receiptBus.publish({ + type: "checkpoint.baseline.captured", + threadId: thread.id, + checkpointTurnCount: currentTurnCount, + checkpointRef: baselineCheckpointRef, + createdAt: event.createdAt, + }); + }, + ); + + const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn( + "ensurePreTurnBaselineFromDomainTurnStart", + )(function* ( + event: Extract< + OrchestrationEvent, + { type: "thread.turn-start-requested" | "thread.message-sent" } + >, + ) { + if (event.type === "thread.message-sent") { + if ( + event.payload.role !== "user" || + event.payload.streaming || + event.payload.turnId !== null + ) { + return; + } + } + + const threadId = event.payload.threadId; + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === threadId); + if (!thread) { + return; + } + + const checkpointCwd = yield* resolveCheckpointCwd({ + threadId, + thread, + projects: readModel.projects, + preferSessionRuntime: false, + }); + if (!checkpointCwd) { + return; + } + + const currentTurnCount = thread.checkpoints.reduce( + (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), + 0, + ); + const baselineCheckpointRef = checkpointRefForThreadTurn(threadId, currentTurnCount); + const baselineExists = yield* checkpointStore.hasCheckpointRef({ + cwd: checkpointCwd, + checkpointRef: baselineCheckpointRef, + }); + if (baselineExists) { + return; + } + + yield* checkpointStore.captureCheckpoint({ + cwd: checkpointCwd, + checkpointRef: baselineCheckpointRef, + }); + yield* receiptBus.publish({ + type: "checkpoint.baseline.captured", + threadId, + checkpointTurnCount: currentTurnCount, + checkpointRef: baselineCheckpointRef, + createdAt: event.occurredAt, + }); + }); + + const handleRevertRequested = Effect.fn("handleRevertRequested")(function* ( + event: Extract, + ) { + const now = new Date().toISOString(); + + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === event.payload.threadId); + if (!thread) { + yield* appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail: "Thread was not found in read model.", + createdAt: now, + }).pipe(Effect.catch(() => Effect.void)); + return; + } + + const sessionRuntime = yield* resolveSessionRuntimeForThread(event.payload.threadId); + if (Option.isNone(sessionRuntime)) { + yield* appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail: "No active provider session with workspace cwd is bound to this thread.", + createdAt: now, + }).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), + 0, + ); + + if (event.payload.turnCount > currentTurnCount) { + yield* appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail: `Checkpoint turn count ${event.payload.turnCount} exceeds current turn count ${currentTurnCount}.`, + createdAt: now, + }).pipe(Effect.catch(() => Effect.void)); + return; + } + + const targetCheckpointRef = + event.payload.turnCount === 0 + ? checkpointRefForThreadTurn(event.payload.threadId, 0) + : thread.checkpoints.find( + (checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount, + )?.checkpointRef; + + if (!targetCheckpointRef) { + yield* appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`, + createdAt: now, + }).pipe(Effect.catch(() => Effect.void)); + return; + } + + const restored = yield* checkpointStore.restoreCheckpoint({ + cwd: sessionRuntime.value.cwd, + checkpointRef: targetCheckpointRef, + fallbackToHead: event.payload.turnCount === 0, + }); + if (!restored) { + yield* appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`, + createdAt: now, + }).pipe(Effect.catch(() => Effect.void)); + return; + } + + // Invalidate the workspace entry cache so the @-mention file picker + // reflects the reverted filesystem state. + yield* workspaceEntries.invalidate(sessionRuntime.value.cwd); + + const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount); + if (rolledBackTurns > 0) { + yield* providerService.rollbackConversation({ + threadId: sessionRuntime.value.threadId, + numTurns: rolledBackTurns, + }); + } + + const staleCheckpointRefs = thread.checkpoints + .filter((checkpoint) => checkpoint.checkpointTurnCount > event.payload.turnCount) + .map((checkpoint) => checkpoint.checkpointRef); + + if (staleCheckpointRefs.length > 0) { + yield* checkpointStore.deleteCheckpointRefs({ + cwd: sessionRuntime.value.cwd, + checkpointRefs: staleCheckpointRefs, + }); + } + + yield* orchestrationEngine + .dispatch({ + type: "thread.revert.complete", + commandId: serverCommandId("checkpoint-revert-complete"), + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + createdAt: now, + }) + .pipe( + Effect.catch((error) => + appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail: error.message, + createdAt: now, + }), + ), + Effect.asVoid, + ); + }); + + const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) { + if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") { + yield* ensurePreTurnBaselineFromDomainTurnStart(event); + return; + } + + if (event.type === "thread.checkpoint-revert-requested") { + yield* handleRevertRequested(event).pipe( + Effect.catch((error) => + appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail: error.message, + createdAt: new Date().toISOString(), + }), + ), + ); + return; + } + + // When ProviderRuntimeIngestion creates a placeholder checkpoint (status "missing") + // from a turn.diff.updated runtime event, capture the real git checkpoint to + // replace it. The providerService.streamEvents PubSub does not reliably deliver + // turn.completed runtime events to this reactor (shared subscription), so + // reacting to the domain event is the reliable path. + if (event.type === "thread.turn-diff-completed") { + yield* captureCheckpointFromPlaceholder(event).pipe( + Effect.catch((error) => + appendCaptureFailureActivity({ + threadId: event.payload.threadId, + turnId: event.payload.turnId, + detail: error.message, + createdAt: new Date().toISOString(), + }).pipe(Effect.catch(() => Effect.void)), + ), + ); + } + }); + + const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* ( + event: ProviderRuntimeEvent, + ) { + if (event.type === "turn.started") { + yield* ensurePreTurnBaselineFromTurnStart(event); + return; + } + + if (event.type === "turn.completed") { + const turnId = toTurnId(event.turnId); + yield* captureCheckpointFromTurnCompletion(event).pipe( + Effect.catch((error) => + appendCaptureFailureActivity({ + threadId: event.threadId, + turnId, + detail: error.message, + createdAt: new Date().toISOString(), + }).pipe(Effect.catch(() => Effect.void)), + ), + ); + return; + } + }); + + const processInput = ( + input: ReactorInput, + ): Effect.Effect => + input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event); + + const processInputSafely = (input: ReactorInput) => + processInput(input).pipe( + Effect.catchCause((cause) => { + if (Cause.hasInterruptsOnly(cause)) { + return Effect.failCause(cause); + } + return Effect.logWarning("checkpoint reactor failed to process input", { + source: input.source, + eventType: input.event.type, + cause: Cause.pretty(cause), + }); + }), + ); + + const worker = yield* makeDrainableWorker(processInputSafely); + + const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () { + yield* Effect.forkScoped( + Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { + if ( + event.type !== "thread.turn-start-requested" && + event.type !== "thread.message-sent" && + event.type !== "thread.checkpoint-revert-requested" && + event.type !== "thread.turn-diff-completed" + ) { + return Effect.void; + } + return worker.enqueue({ source: "domain", event }); + }), + ); + + yield* Effect.forkScoped( + Stream.runForEach(providerService.streamEvents, (event) => { + if (event.type !== "turn.started" && event.type !== "turn.completed") { + return Effect.void; + } + return worker.enqueue({ source: "runtime", event }); + }), + ); + }); + + return { + start, + drain: worker.drain, + } satisfies CheckpointReactorShape; +}); + +export const CheckpointReactorLive = Layer.effect(CheckpointReactor, make); diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts new file mode 100644 index 0000000000..5a0a6113f0 --- /dev/null +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -0,0 +1,1012 @@ +import { + CheckpointRef, + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + MessageId, + ProjectId, + ThreadId, + TurnId, + type OrchestrationEvent, +} from "@t3tools/contracts"; +import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect"; +import { describe, expect, it } from "vitest"; + +import { PersistenceSqlError } from "../../persistence/Errors.ts"; +import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; +import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { + OrchestrationEventStore, + type OrchestrationEventStoreShape, +} from "../../persistence/Services/OrchestrationEventStore.ts"; +import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; +import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; +import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; +import { + OrchestrationProjectionPipeline, + type OrchestrationProjectionPipelineShape, +} from "../Services/ProjectionPipeline.ts"; +import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; +import { ServerConfig } from "../../config.ts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; + +const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); +const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); +const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); +const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value); + +async function createOrchestrationSystem() { + const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-orchestration-engine-test-", + }); + const orchestrationLayer = OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), + Layer.provide(OrchestrationProjectionPipelineLive), + Layer.provide(OrchestrationEventStoreLive), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(SqlitePersistenceMemory), + Layer.provideMerge(ServerConfigLayer), + Layer.provideMerge(NodeServices.layer), + ); + const runtime = ManagedRuntime.make(orchestrationLayer); + const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); + return { + engine, + run: (effect: Effect.Effect) => runtime.runPromise(effect), + dispose: () => runtime.dispose(), + }; +} + +function now() { + return new Date().toISOString(); +} + +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + +describe("OrchestrationEngine", () => { + it("bootstraps the in-memory read model from persisted projections", async () => { + const failOnHistoricalReplayStore: OrchestrationEventStoreShape = { + append: () => + Effect.fail( + new PersistenceSqlError({ + operation: "test.append", + detail: "append should not be called during bootstrap", + }), + ), + readFromSequence: () => Stream.empty, + readAll: () => + Stream.fail( + new PersistenceSqlError({ + operation: "test.readAll", + detail: "historical replay should not be used during bootstrap", + }), + ), + }; + + const projectionSnapshot = { + snapshotSequence: 7, + updatedAt: "2026-03-03T00:00:04.000Z", + projects: [ + { + id: asProjectId("project-bootstrap"), + title: "Bootstrap Project", + workspaceRoot: "/tmp/project-bootstrap", + defaultModelSelection: { + provider: "codex" as const, + model: "gpt-5-codex", + }, + scripts: [], + createdAt: "2026-03-03T00:00:00.000Z", + updatedAt: "2026-03-03T00:00:01.000Z", + deletedAt: null, + }, + ], + threads: [ + { + id: ThreadId.makeUnsafe("thread-bootstrap"), + projectId: asProjectId("project-bootstrap"), + title: "Bootstrap Thread", + modelSelection: { + provider: "codex" as const, + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access" as const, + branch: null, + worktreePath: null, + latestTurn: null, + createdAt: "2026-03-03T00:00:02.000Z", + updatedAt: "2026-03-03T00:00:03.000Z", + archivedAt: null, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + session: null, + }, + ], + }; + + const layer = OrchestrationEngineLive.pipe( + Layer.provide( + Layer.succeed(ProjectionSnapshotQuery, { + getSnapshot: () => Effect.succeed(projectionSnapshot), + getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }), + getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), + getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), + getThreadCheckpointContext: () => Effect.succeed(Option.none()), + }), + ), + Layer.provide( + Layer.succeed(OrchestrationProjectionPipeline, { + bootstrap: Effect.void, + projectEvent: () => Effect.void, + } satisfies OrchestrationProjectionPipelineShape), + ), + Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(SqlitePersistenceMemory), + ); + + const runtime = ManagedRuntime.make(layer); + + const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); + const readModel = await runtime.runPromise(engine.getReadModel()); + + expect(readModel.snapshotSequence).toBe(7); + expect(readModel.projects).toHaveLength(1); + expect(readModel.projects[0]?.title).toBe("Bootstrap Project"); + expect(readModel.threads).toHaveLength(1); + expect(readModel.threads[0]?.title).toBe("Bootstrap Thread"); + + await runtime.dispose(); + }); + + it("returns deterministic read models for repeated reads", async () => { + const createdAt = now(); + const system = await createOrchestrationSystem(); + const { engine } = system; + + await system.run( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-1-create"), + projectId: asProjectId("project-1"), + title: "Project 1", + workspaceRoot: "/tmp/project-1", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + await system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-1-create"), + threadId: ThreadId.makeUnsafe("thread-1"), + projectId: asProjectId("project-1"), + title: "Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + await system.run( + engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("msg-1"), + role: "user", + text: "hello", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt, + }), + ); + + const readModelA = await system.run(engine.getReadModel()); + const readModelB = await system.run(engine.getReadModel()); + expect(readModelB).toEqual(readModelA); + await system.dispose(); + }); + + it("archives and unarchives threads through orchestration commands", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await system.run( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-archive-create"), + projectId: asProjectId("project-archive"), + title: "Project Archive", + workspaceRoot: "/tmp/project-archive", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + await system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-archive-create"), + threadId: ThreadId.makeUnsafe("thread-archive"), + projectId: asProjectId("project-archive"), + title: "Archive me", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }), + ); + + await system.run( + engine.dispatch({ + type: "thread.archive", + commandId: CommandId.makeUnsafe("cmd-thread-archive"), + threadId: ThreadId.makeUnsafe("thread-archive"), + }), + ); + expect( + (await system.run(engine.getReadModel())).threads.find( + (thread) => thread.id === "thread-archive", + )?.archivedAt, + ).not.toBeNull(); + + await system.run( + engine.dispatch({ + type: "thread.unarchive", + commandId: CommandId.makeUnsafe("cmd-thread-unarchive"), + threadId: ThreadId.makeUnsafe("thread-archive"), + }), + ); + expect( + (await system.run(engine.getReadModel())).threads.find( + (thread) => thread.id === "thread-archive", + )?.archivedAt, + ).toBeNull(); + + await system.dispose(); + }); + + it("replays append-only events from sequence", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await system.run( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-replay-create"), + projectId: asProjectId("project-replay"), + title: "Replay Project", + workspaceRoot: "/tmp/project-replay", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + await system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-replay-create"), + threadId: ThreadId.makeUnsafe("thread-replay"), + projectId: asProjectId("project-replay"), + title: "replay", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + await system.run( + engine.dispatch({ + type: "thread.delete", + commandId: CommandId.makeUnsafe("cmd-thread-replay-delete"), + threadId: ThreadId.makeUnsafe("thread-replay"), + }), + ); + + const events = await system.run( + Stream.runCollect(engine.readEvents(0)).pipe( + Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)), + ), + ); + expect(events.map((event) => event.type)).toEqual([ + "project.created", + "thread.created", + "thread.deleted", + ]); + await system.dispose(); + }); + + it("streams persisted domain events in order", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await system.run( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-stream-create"), + projectId: asProjectId("project-stream"), + title: "Stream Project", + workspaceRoot: "/tmp/project-stream", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + + const eventTypes: string[] = []; + await system.run( + Effect.gen(function* () { + const eventQueue = yield* Queue.unbounded(); + yield* Effect.forkScoped( + Stream.take(engine.streamDomainEvents, 2).pipe( + Stream.runForEach((event) => Queue.offer(eventQueue, event).pipe(Effect.asVoid)), + ), + ); + yield* Effect.sleep("10 millis"); + yield* engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-stream-thread-create"), + threadId: ThreadId.makeUnsafe("thread-stream"), + projectId: asProjectId("project-stream"), + title: "domain-stream", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }); + yield* engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-stream-thread-update"), + threadId: ThreadId.makeUnsafe("thread-stream"), + title: "domain-stream-updated", + }); + eventTypes.push((yield* Queue.take(eventQueue)).type); + eventTypes.push((yield* Queue.take(eventQueue)).type); + }).pipe(Effect.scoped), + ); + + expect(eventTypes).toEqual(["thread.created", "thread.meta-updated"]); + await system.dispose(); + }); + + it("records command ack duration using the first committed event type", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await system.run( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-ack-create"), + projectId: asProjectId("project-ack"), + title: "Ack Project", + workspaceRoot: "/tmp/project-ack", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + + await system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-ack-create"), + threadId: ThreadId.makeUnsafe("thread-ack"), + projectId: asProjectId("project-ack"), + title: "Ack Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }), + ); + + const snapshots = await system.run(Metric.snapshot); + expect( + hasMetricSnapshot(snapshots, "t3_orchestration_command_ack_duration", { + commandType: "thread.create", + aggregateKind: "thread", + ackEventType: "thread.created", + }), + ).toBe(true); + + await system.dispose(); + }); + + it("records failed command dispatches as metric failures", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await expect( + system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-missing-project"), + threadId: ThreadId.makeUnsafe("thread-missing-project"), + projectId: asProjectId("project-missing"), + title: "Missing Project Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }), + ), + ).rejects.toThrow("does not exist"); + + const snapshots = await system.run(Metric.snapshot); + expect( + hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", { + commandType: "thread.create", + aggregateKind: "thread", + outcome: "failure", + }), + ).toBe(true); + + await system.dispose(); + }); + + it("stores completed checkpoint summaries even when no files changed", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await system.run( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-turn-diff-create"), + projectId: asProjectId("project-turn-diff"), + title: "Turn Diff Project", + workspaceRoot: "/tmp/project-turn-diff", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + await system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-turn-diff-create"), + threadId: ThreadId.makeUnsafe("thread-turn-diff"), + projectId: asProjectId("project-turn-diff"), + title: "Turn diff thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + await system.run( + engine.dispatch({ + type: "thread.turn.diff.complete", + commandId: CommandId.makeUnsafe("cmd-turn-diff-complete"), + threadId: ThreadId.makeUnsafe("thread-turn-diff"), + turnId: asTurnId("turn-1"), + completedAt: createdAt, + checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"), + status: "ready", + files: [], + checkpointTurnCount: 1, + createdAt, + }), + ); + + const thread = (await system.run(engine.getReadModel())).threads.find( + (entry) => entry.id === "thread-turn-diff", + ); + expect(thread?.checkpoints).toEqual([ + { + turnId: asTurnId("turn-1"), + checkpointTurnCount: 1, + checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"), + status: "ready", + files: [], + assistantMessageId: null, + completedAt: createdAt, + }, + ]); + await system.dispose(); + }); + + it("keeps processing queued commands after a storage failure", async () => { + type StoredEvent = + ReturnType extends Effect.Effect + ? A + : never; + const events: StoredEvent[] = []; + let nextSequence = 1; + let shouldFailFirstAppend = true; + + const flakyStore: OrchestrationEventStoreShape = { + append(event) { + if (shouldFailFirstAppend && event.commandId === CommandId.makeUnsafe("cmd-flaky-1")) { + shouldFailFirstAppend = false; + return Effect.fail( + new PersistenceSqlError({ + operation: "test.append", + detail: "append failed", + }), + ); + } + const savedEvent = { + ...event, + sequence: nextSequence, + } as StoredEvent; + nextSequence += 1; + events.push(savedEvent); + return Effect.succeed(savedEvent); + }, + readFromSequence(sequenceExclusive) { + return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive)); + }, + readAll() { + return Stream.fromIterable(events); + }, + }; + + const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-orchestration-engine-test-", + }); + + const runtime = ManagedRuntime.make( + OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), + Layer.provide(OrchestrationProjectionPipelineLive), + Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(SqlitePersistenceMemory), + Layer.provideMerge(ServerConfigLayer), + Layer.provideMerge(NodeServices.layer), + ), + ); + const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); + const createdAt = now(); + + await runtime.runPromise( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-flaky-create"), + projectId: asProjectId("project-flaky"), + title: "Flaky Project", + workspaceRoot: "/tmp/project-flaky", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + + await expect( + runtime.runPromise( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-flaky-1"), + threadId: ThreadId.makeUnsafe("thread-flaky-fail"), + projectId: asProjectId("project-flaky"), + title: "flaky-fail", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ), + ).rejects.toThrow("append failed"); + + const result = await runtime.runPromise( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-flaky-2"), + threadId: ThreadId.makeUnsafe("thread-flaky-ok"), + projectId: asProjectId("project-flaky"), + title: "flaky-ok", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + + expect(result.sequence).toBe(2); + expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2); + await runtime.dispose(); + }); + + it("rolls back all events for a multi-event command when projection fails mid-dispatch", async () => { + let shouldFailRequestedProjection = true; + const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = { + bootstrap: Effect.void, + projectEvent: (event) => { + if ( + shouldFailRequestedProjection && + event.commandId === CommandId.makeUnsafe("cmd-turn-start-atomic") && + event.type === "thread.turn-start-requested" + ) { + shouldFailRequestedProjection = false; + return Effect.fail( + new PersistenceSqlError({ + operation: "test.projection", + detail: "projection failed", + }), + ); + } + return Effect.void; + }, + }; + + const runtime = ManagedRuntime.make( + OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), + Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)), + Layer.provide(OrchestrationEventStoreLive), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(SqlitePersistenceMemory), + ), + ); + const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); + const createdAt = now(); + + await runtime.runPromise( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-atomic-create"), + projectId: asProjectId("project-atomic"), + title: "Atomic Project", + workspaceRoot: "/tmp/project-atomic", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + await runtime.runPromise( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-atomic-create"), + threadId: ThreadId.makeUnsafe("thread-atomic"), + projectId: asProjectId("project-atomic"), + title: "atomic", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + + const turnStartCommand = { + type: "thread.turn.start" as const, + commandId: CommandId.makeUnsafe("cmd-turn-start-atomic"), + threadId: ThreadId.makeUnsafe("thread-atomic"), + message: { + messageId: asMessageId("msg-atomic-1"), + role: "user" as const, + text: "hello", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required" as const, + createdAt, + }; + + await expect(runtime.runPromise(engine.dispatch(turnStartCommand))).rejects.toThrow( + "projection failed", + ); + + const eventsAfterFailure = await runtime.runPromise( + Stream.runCollect(engine.readEvents(0)).pipe( + Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)), + ), + ); + expect(eventsAfterFailure.map((event) => event.type)).toEqual([ + "project.created", + "thread.created", + ]); + expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2); + + const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand)); + expect(retryResult.sequence).toBe(4); + + const eventsAfterRetry = await runtime.runPromise( + Stream.runCollect(engine.readEvents(0)).pipe( + Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)), + ), + ); + expect(eventsAfterRetry.map((event) => event.type)).toEqual([ + "project.created", + "thread.created", + "thread.message-sent", + "thread.turn-start-requested", + ]); + expect( + eventsAfterRetry.filter((event) => event.commandId === turnStartCommand.commandId), + ).toHaveLength(2); + + await runtime.dispose(); + }); + + it("reconciles in-memory state when append persists but projection fails", async () => { + type StoredEvent = + ReturnType extends Effect.Effect + ? A + : never; + const events: StoredEvent[] = []; + let nextSequence = 1; + + const nonTransactionalStore: OrchestrationEventStoreShape = { + append(event) { + const savedEvent = { + ...event, + sequence: nextSequence, + } as StoredEvent; + nextSequence += 1; + events.push(savedEvent); + return Effect.succeed(savedEvent); + }, + readFromSequence(sequenceExclusive) { + return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive)); + }, + readAll() { + return Stream.fromIterable(events); + }, + }; + + let shouldFailProjection = true; + const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = { + bootstrap: Effect.void, + projectEvent: (event) => { + if ( + shouldFailProjection && + event.commandId === CommandId.makeUnsafe("cmd-thread-meta-sync-fail") + ) { + shouldFailProjection = false; + return Effect.fail( + new PersistenceSqlError({ + operation: "test.projection", + detail: "projection failed", + }), + ); + } + return Effect.void; + }, + }; + + const runtime = ManagedRuntime.make( + OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), + Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)), + Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(SqlitePersistenceMemory), + ), + ); + const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); + const createdAt = now(); + + await runtime.runPromise( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-sync-create"), + projectId: asProjectId("project-sync"), + title: "Sync Project", + workspaceRoot: "/tmp/project-sync", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + await runtime.runPromise( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-sync-create"), + threadId: ThreadId.makeUnsafe("thread-sync"), + projectId: asProjectId("project-sync"), + title: "sync-before", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + + await expect( + runtime.runPromise( + engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-meta-sync-fail"), + threadId: ThreadId.makeUnsafe("thread-sync"), + title: "sync-after-failed-projection", + }), + ), + ).rejects.toThrow("projection failed"); + + const readModelAfterFailure = await runtime.runPromise(engine.getReadModel()); + const updatedThread = readModelAfterFailure.threads.find( + (thread) => thread.id === "thread-sync", + ); + expect(readModelAfterFailure.snapshotSequence).toBe(3); + expect(updatedThread?.title).toBe("sync-after-failed-projection"); + + await runtime.dispose(); + }); + + it("fails command dispatch when command invariants are violated", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + + await expect( + system.run( + engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-invariant-missing-thread"), + threadId: ThreadId.makeUnsafe("thread-missing"), + message: { + messageId: asMessageId("msg-missing"), + role: "user", + text: "hello", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now(), + }), + ), + ).rejects.toThrow("Thread 'thread-missing' does not exist"); + + await system.dispose(); + }); + + it("rejects duplicate thread creation", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await system.run( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-duplicate-create"), + projectId: asProjectId("project-duplicate"), + title: "Duplicate Project", + workspaceRoot: "/tmp/project-duplicate", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + + await system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-duplicate-1"), + threadId: ThreadId.makeUnsafe("thread-duplicate"), + projectId: asProjectId("project-duplicate"), + title: "duplicate", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + + await expect( + system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-duplicate-2"), + threadId: ThreadId.makeUnsafe("thread-duplicate"), + projectId: asProjectId("project-duplicate"), + title: "duplicate", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ), + ).rejects.toThrow("already exists"); + + await system.dispose(); + }); +}); diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts new file mode 100644 index 0000000000..ddd1718faf --- /dev/null +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts @@ -0,0 +1,310 @@ +import type { + OrchestrationEvent, + OrchestrationReadModel, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { OrchestrationCommand } from "@t3tools/contracts"; +import { + Cause, + Deferred, + Duration, + Effect, + Exit, + Layer, + Metric, + Option, + PubSub, + Queue, + Schema, + Stream, +} from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { + metricAttributes, + orchestrationCommandAckDuration, + orchestrationCommandsTotal, + orchestrationCommandDuration, +} from "../../observability/Metrics.ts"; +import { toPersistenceSqlError } from "../../persistence/Errors.ts"; +import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts"; +import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts"; +import { + OrchestrationCommandInvariantError, + OrchestrationCommandPreviouslyRejectedError, + type OrchestrationDispatchError, +} from "../Errors.ts"; +import { decideOrchestrationCommand } from "../decider.ts"; +import { createEmptyReadModel, projectEvent } from "../projector.ts"; +import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts"; +import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; +import { + OrchestrationEngineService, + type OrchestrationEngineShape, +} from "../Services/OrchestrationEngine.ts"; + +interface CommandEnvelope { + command: OrchestrationCommand; + result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>; + startedAtMs: number; +} + +function commandToAggregateRef(command: OrchestrationCommand): { + readonly aggregateKind: "project" | "thread"; + readonly aggregateId: ProjectId | ThreadId; +} { + switch (command.type) { + case "project.create": + case "project.meta.update": + case "project.delete": + return { + aggregateKind: "project", + aggregateId: command.projectId, + }; + default: + return { + aggregateKind: "thread", + aggregateId: command.threadId, + }; + } +} + +const makeOrchestrationEngine = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const eventStore = yield* OrchestrationEventStore; + const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository; + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + + let readModel = createEmptyReadModel(new Date().toISOString()); + + const commandQueue = yield* Queue.unbounded(); + const eventPubSub = yield* PubSub.unbounded(); + + const processEnvelope = (envelope: CommandEnvelope): Effect.Effect => { + const dispatchStartSequence = readModel.snapshotSequence; + const processingStartedAtMs = Date.now(); + const aggregateRef = commandToAggregateRef(envelope.command); + const baseMetricAttributes = { + commandType: envelope.command.type, + aggregateKind: aggregateRef.aggregateKind, + } as const; + const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () { + const persistedEvents = yield* Stream.runCollect( + eventStore.readFromSequence(dispatchStartSequence), + ).pipe(Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk))); + if (persistedEvents.length === 0) { + return; + } + + let nextReadModel = readModel; + for (const persistedEvent of persistedEvents) { + nextReadModel = yield* projectEvent(nextReadModel, persistedEvent); + } + readModel = nextReadModel; + + for (const persistedEvent of persistedEvents) { + yield* PubSub.publish(eventPubSub, persistedEvent); + } + }); + + return Effect.exit( + Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "orchestration.command_id": envelope.command.commandId, + "orchestration.command_type": envelope.command.type, + "orchestration.aggregate_kind": aggregateRef.aggregateKind, + "orchestration.aggregate_id": aggregateRef.aggregateId, + }); + + const existingReceipt = yield* commandReceiptRepository.getByCommandId({ + commandId: envelope.command.commandId, + }); + if (Option.isSome(existingReceipt)) { + if (existingReceipt.value.status === "accepted") { + return { + sequence: existingReceipt.value.resultSequence, + }; + } + return yield* new OrchestrationCommandPreviouslyRejectedError({ + commandId: envelope.command.commandId, + detail: existingReceipt.value.error ?? "Previously rejected.", + }); + } + + const eventBase = yield* decideOrchestrationCommand({ + command: envelope.command, + readModel, + }); + const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase]; + const committedCommand = yield* sql + .withTransaction( + Effect.gen(function* () { + const committedEvents: OrchestrationEvent[] = []; + let nextReadModel = readModel; + + for (const nextEvent of eventBases) { + const savedEvent = yield* eventStore.append(nextEvent); + nextReadModel = yield* projectEvent(nextReadModel, savedEvent); + yield* projectionPipeline.projectEvent(savedEvent); + committedEvents.push(savedEvent); + } + + const lastSavedEvent = committedEvents.at(-1) ?? null; + if (lastSavedEvent === null) { + return yield* new OrchestrationCommandInvariantError({ + commandType: envelope.command.type, + detail: "Command produced no events.", + }); + } + + yield* commandReceiptRepository.upsert({ + commandId: envelope.command.commandId, + aggregateKind: lastSavedEvent.aggregateKind, + aggregateId: lastSavedEvent.aggregateId, + acceptedAt: lastSavedEvent.occurredAt, + resultSequence: lastSavedEvent.sequence, + status: "accepted", + error: null, + }); + + return { + committedEvents, + lastSequence: lastSavedEvent.sequence, + nextReadModel, + } as const; + }), + ) + .pipe( + Effect.catchTag("SqlError", (sqlError) => + Effect.fail( + toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError), + ), + ), + ); + + readModel = committedCommand.nextReadModel; + for (const [index, event] of committedCommand.committedEvents.entries()) { + yield* PubSub.publish(eventPubSub, event); + if (index === 0) { + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandAckDuration, + metricAttributes({ + ...baseMetricAttributes, + ackEventType: event.type, + }), + ), + Duration.millis(Math.max(0, Date.now() - envelope.startedAtMs)), + ); + } + } + return { sequence: committedCommand.lastSequence }; + }).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)), + ).pipe( + Effect.flatMap((exit) => + Effect.gen(function* () { + const outcome = Exit.isSuccess(exit) + ? "success" + : Cause.hasInterruptsOnly(exit.cause) + ? "interrupt" + : "failure"; + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandDuration, + metricAttributes(baseMetricAttributes), + ), + Duration.millis(Math.max(0, Date.now() - processingStartedAtMs)), + ); + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandsTotal, + metricAttributes({ + ...baseMetricAttributes, + outcome, + }), + ), + 1, + ); + + if (Exit.isSuccess(exit)) { + yield* Deferred.succeed(envelope.result, exit.value); + return; + } + + const error = Cause.squash(exit.cause) as OrchestrationDispatchError; + if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) { + yield* reconcileReadModelAfterDispatchFailure.pipe( + Effect.catch(() => + Effect.logWarning( + "failed to reconcile orchestration read model after dispatch failure", + ).pipe( + Effect.annotateLogs({ + commandId: envelope.command.commandId, + snapshotSequence: readModel.snapshotSequence, + }), + ), + ), + ); + + if (Schema.is(OrchestrationCommandInvariantError)(error)) { + yield* commandReceiptRepository + .upsert({ + commandId: envelope.command.commandId, + aggregateKind: aggregateRef.aggregateKind, + aggregateId: aggregateRef.aggregateId, + acceptedAt: new Date().toISOString(), + resultSequence: readModel.snapshotSequence, + status: "rejected", + error: error.message, + }) + .pipe(Effect.catch(() => Effect.void)); + } + } + + yield* Deferred.fail(envelope.result, error); + }), + ), + ); + }; + + yield* projectionPipeline.bootstrap; + readModel = yield* projectionSnapshotQuery.getSnapshot(); + + const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope))); + yield* Effect.forkScoped(worker); + yield* Effect.logDebug("orchestration engine started").pipe( + Effect.annotateLogs({ sequence: readModel.snapshotSequence }), + ); + + const getReadModel: OrchestrationEngineShape["getReadModel"] = () => + Effect.sync((): OrchestrationReadModel => readModel); + + const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) => + eventStore.readFromSequence(fromSequenceExclusive); + + const dispatch: OrchestrationEngineShape["dispatch"] = (command) => + Effect.gen(function* () { + const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>(); + yield* Queue.offer(commandQueue, { command, result, startedAtMs: Date.now() }); + return yield* Deferred.await(result); + }); + + return { + getReadModel, + readEvents, + dispatch, + // Each access creates a fresh PubSub subscription so that multiple + // consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.) + // each independently receive all domain events. + get streamDomainEvents(): OrchestrationEngineShape["streamDomainEvents"] { + return Stream.fromPubSub(eventPubSub); + }, + } satisfies OrchestrationEngineShape; +}); + +export const OrchestrationEngineLive = Layer.effect( + OrchestrationEngineService, + makeOrchestrationEngine, +); diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts new file mode 100644 index 0000000000..d60f0cf722 --- /dev/null +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts @@ -0,0 +1,67 @@ +import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect"; +import { afterEach, describe, expect, it } from "vitest"; + +import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; +import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; +import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; +import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts"; +import { makeOrchestrationReactor } from "./OrchestrationReactor.ts"; + +describe("OrchestrationReactor", () => { + let runtime: ManagedRuntime.ManagedRuntime | null = null; + + afterEach(async () => { + if (runtime) { + await runtime.dispose(); + } + runtime = null; + }); + + it("starts provider ingestion, provider command, and checkpoint reactors", async () => { + const started: string[] = []; + + runtime = ManagedRuntime.make( + Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe( + Layer.provideMerge( + Layer.succeed(ProviderRuntimeIngestionService, { + start: () => { + started.push("provider-runtime-ingestion"); + return Effect.void; + }, + drain: Effect.void, + }), + ), + Layer.provideMerge( + Layer.succeed(ProviderCommandReactor, { + start: () => { + started.push("provider-command-reactor"); + return Effect.void; + }, + drain: Effect.void, + }), + ), + Layer.provideMerge( + Layer.succeed(CheckpointReactor, { + start: () => { + started.push("checkpoint-reactor"); + return Effect.void; + }, + drain: Effect.void, + }), + ), + ), + ); + + const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor)); + const scope = await Effect.runPromise(Scope.make("sequential")); + await Effect.runPromise(reactor.start().pipe(Scope.provide(scope))); + + expect(started).toEqual([ + "provider-runtime-ingestion", + "provider-command-reactor", + "checkpoint-reactor", + ]); + + await Effect.runPromise(Scope.close(scope, Exit.void)); + }); +}); diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts new file mode 100644 index 0000000000..99d30c57a2 --- /dev/null +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts @@ -0,0 +1,30 @@ +import { Effect, Layer } from "effect"; + +import { + OrchestrationReactor, + type OrchestrationReactorShape, +} from "../Services/OrchestrationReactor.ts"; +import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; +import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; +import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; + +export const makeOrchestrationReactor = Effect.gen(function* () { + const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService; + const providerCommandReactor = yield* ProviderCommandReactor; + const checkpointReactor = yield* CheckpointReactor; + + const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () { + yield* providerRuntimeIngestion.start(); + yield* providerCommandReactor.start(); + yield* checkpointReactor.start(); + }); + + return { + start, + } satisfies OrchestrationReactorShape; +}); + +export const OrchestrationReactorLive = Layer.effect( + OrchestrationReactor, + makeOrchestrationReactor, +); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts new file mode 100644 index 0000000000..1850745469 --- /dev/null +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -0,0 +1,1955 @@ +import { + CheckpointRef, + CommandId, + CorrelationId, + EventId, + MessageId, + ProjectId, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; +import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; +import { + makeSqlitePersistenceLive, + SqlitePersistenceMemory, +} from "../../persistence/Layers/Sqlite.ts"; +import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts"; +import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; +import { + ORCHESTRATION_PROJECTOR_NAMES, + OrchestrationProjectionPipelineLive, +} from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; +import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; +import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts"; +import { ServerConfig } from "../../config.ts"; + +const makeProjectionPipelinePrefixedTestLayer = (prefix: string) => + OrchestrationProjectionPipelineLive.pipe( + Layer.provideMerge(OrchestrationEventStoreLive), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix })), + Layer.provideMerge(SqlitePersistenceMemory), + Layer.provideMerge(NodeServices.layer), + ); + +const exists = (filePath: string) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const fileInfo = yield* Effect.result(fileSystem.stat(filePath)); + return fileInfo._tag === "Success"; + }); + +const BaseTestLayer = makeProjectionPipelinePrefixedTestLayer("t3-projection-pipeline-test-"); + +it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { + it.effect("bootstraps all projection states and writes projection rows", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = new Date().toISOString(); + + yield* eventStore.append({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-1"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-1"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-1"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-1"), + metadata: {}, + payload: { + projectId: ProjectId.makeUnsafe("project-1"), + title: "Project 1", + workspaceRoot: "/tmp/project-1", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.created", + eventId: EventId.makeUnsafe("evt-2"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-1"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-2"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-2"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-1"), + projectId: ProjectId.makeUnsafe("project-1"), + title: "Thread 1", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-3"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-1"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-3"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-3"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-1"), + messageId: MessageId.makeUnsafe("message-1"), + role: "assistant", + text: "hello", + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + yield* projectionPipeline.bootstrap; + + const projectRows = yield* sql<{ + readonly projectId: string; + readonly title: string; + readonly scriptsJson: string; + }>` + SELECT + project_id AS "projectId", + title, + scripts_json AS "scriptsJson" + FROM projection_projects + `; + assert.deepEqual(projectRows, [ + { projectId: "project-1", title: "Project 1", scriptsJson: "[]" }, + ]); + + const messageRows = yield* sql<{ + readonly messageId: string; + readonly text: string; + }>` + SELECT + message_id AS "messageId", + text + FROM projection_thread_messages + `; + assert.deepEqual(messageRows, [{ messageId: "message-1", text: "hello" }]); + + const stateRows = yield* sql<{ + readonly projector: string; + readonly lastAppliedSequence: number; + }>` + SELECT + projector, + last_applied_sequence AS "lastAppliedSequence" + FROM projection_state + ORDER BY projector ASC + `; + assert.equal(stateRows.length, Object.keys(ORCHESTRATION_PROJECTOR_NAMES).length); + for (const row of stateRows) { + assert.equal(row.lastAppliedSequence, 3); + } + }), + ); +}); + +it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-base-")))( + "OrchestrationProjectionPipeline", + (it) => { + it.effect("stores message attachment references without mutating payloads", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = new Date().toISOString(); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-attachments"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-attachments"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-attachments"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-attachments"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-attachments"), + messageId: MessageId.makeUnsafe("message-attachments"), + role: "user", + text: "Inspect this", + attachments: [ + { + type: "image", + id: "thread-attachments-att-1", + name: "example.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + yield* projectionPipeline.bootstrap; + + const rows = yield* sql<{ + readonly attachmentsJson: string | null; + }>` + SELECT + attachments_json AS "attachmentsJson" + FROM projection_thread_messages + WHERE message_id = 'message-attachments' + `; + assert.equal(rows.length, 1); + assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [ + { + type: "image", + id: "thread-attachments-att-1", + name: "example.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ]); + }), + ); + }, +); + +it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-safe-")))( + "OrchestrationProjectionPipeline", + (it) => { + it.effect("preserves mixed image attachment metadata as-is", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = new Date().toISOString(); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-attachments-safe"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-attachments-safe"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-attachments-safe"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-attachments-safe"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-attachments-safe"), + messageId: MessageId.makeUnsafe("message-attachments-safe"), + role: "user", + text: "Inspect this", + attachments: [ + { + type: "image", + id: "thread-attachments-safe-att-1", + name: "untrusted.exe", + mimeType: "image/x-unknown", + sizeBytes: 5, + }, + { + type: "image", + id: "thread-attachments-safe-att-2", + name: "not-image.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + yield* projectionPipeline.bootstrap; + + const rows = yield* sql<{ + readonly attachmentsJson: string | null; + }>` + SELECT + attachments_json AS "attachmentsJson" + FROM projection_thread_messages + WHERE message_id = 'message-attachments-safe' + `; + assert.equal(rows.length, 1); + assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [ + { + type: "image", + id: "thread-attachments-safe-att-1", + name: "untrusted.exe", + mimeType: "image/x-unknown", + sizeBytes: 5, + }, + { + type: "image", + id: "thread-attachments-safe-att-2", + name: "not-image.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ]); + }), + ); + }, +); + +it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { + it.effect( + "passes explicit empty attachment arrays through the projection pipeline to clear attachments", + () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = new Date().toISOString(); + const later = new Date(Date.now() + 1_000).toISOString(); + + yield* eventStore.append({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-clear-attachments-1"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-clear-attachments"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-clear-attachments-1"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-clear-attachments-1"), + metadata: {}, + payload: { + projectId: ProjectId.makeUnsafe("project-clear-attachments"), + title: "Project Clear Attachments", + workspaceRoot: "/tmp/project-clear-attachments", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.created", + eventId: EventId.makeUnsafe("evt-clear-attachments-2"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-clear-attachments-2"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-clear-attachments-2"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-clear-attachments"), + projectId: ProjectId.makeUnsafe("project-clear-attachments"), + title: "Thread Clear Attachments", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-clear-attachments-3"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-clear-attachments-3"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-clear-attachments-3"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-clear-attachments"), + messageId: MessageId.makeUnsafe("message-clear-attachments"), + role: "user", + text: "Has attachments", + attachments: [ + { + type: "image", + id: "thread-clear-attachments-att-1", + name: "clear.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-clear-attachments-4"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"), + occurredAt: later, + commandId: CommandId.makeUnsafe("cmd-clear-attachments-4"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-clear-attachments-4"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-clear-attachments"), + messageId: MessageId.makeUnsafe("message-clear-attachments"), + role: "user", + text: "", + attachments: [], + turnId: null, + streaming: false, + createdAt: now, + updatedAt: later, + }, + }); + + yield* projectionPipeline.bootstrap; + + const rows = yield* sql<{ + readonly attachmentsJson: string | null; + }>` + SELECT + attachments_json AS "attachmentsJson" + FROM projection_thread_messages + WHERE message_id = 'message-clear-attachments' + `; + assert.equal(rows.length, 1); + assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), []); + }), + ); +}); + +it.layer( + Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-overwrite-")), +)("OrchestrationProjectionPipeline", (it) => { + it.effect("overwrites stored attachment references when a message updates attachments", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = new Date().toISOString(); + const later = new Date(Date.now() + 1_000).toISOString(); + + yield* eventStore.append({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-overwrite-1"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-overwrite"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-overwrite-1"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-overwrite-1"), + metadata: {}, + payload: { + projectId: ProjectId.makeUnsafe("project-overwrite"), + title: "Project Overwrite", + workspaceRoot: "/tmp/project-overwrite", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.created", + eventId: EventId.makeUnsafe("evt-overwrite-2"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-overwrite"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-overwrite-2"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-overwrite-2"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-overwrite"), + projectId: ProjectId.makeUnsafe("project-overwrite"), + title: "Thread Overwrite", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-overwrite-3"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-overwrite"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-overwrite-3"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-overwrite-3"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-overwrite"), + messageId: MessageId.makeUnsafe("message-overwrite"), + role: "user", + text: "first image", + attachments: [ + { + type: "image", + id: "thread-overwrite-att-1", + name: "file.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-overwrite-4"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-overwrite"), + occurredAt: later, + commandId: CommandId.makeUnsafe("cmd-overwrite-4"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-overwrite-4"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-overwrite"), + messageId: MessageId.makeUnsafe("message-overwrite"), + role: "user", + text: "", + attachments: [ + { + type: "image", + id: "thread-overwrite-att-2", + name: "file.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + turnId: null, + streaming: false, + createdAt: now, + updatedAt: later, + }, + }); + + yield* projectionPipeline.bootstrap; + + const rows = yield* sql<{ + readonly attachmentsJson: string | null; + }>` + SELECT attachments_json AS "attachmentsJson" + FROM projection_thread_messages + WHERE message_id = 'message-overwrite' + `; + assert.equal(rows.length, 1); + assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [ + { + type: "image", + id: "thread-overwrite-att-2", + name: "file.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ]); + }), + ); +}); + +it.layer( + Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-rollback-")), +)("OrchestrationProjectionPipeline", (it) => { + it.effect("does not persist attachment files when projector transaction rolls back", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const path = yield* Path.Path; + const sql = yield* SqlClient.SqlClient; + const now = new Date().toISOString(); + + const appendAndProject = (event: Parameters[0]) => + eventStore + .append(event) + .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); + + yield* appendAndProject({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-rollback-1"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-rollback"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-rollback-1"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-rollback-1"), + metadata: {}, + payload: { + projectId: ProjectId.makeUnsafe("project-rollback"), + title: "Project Rollback", + workspaceRoot: "/tmp/project-rollback", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.created", + eventId: EventId.makeUnsafe("evt-rollback-2"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-rollback"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-rollback-2"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-rollback-2"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-rollback"), + projectId: ProjectId.makeUnsafe("project-rollback"), + title: "Thread Rollback", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + yield* sql` + CREATE TRIGGER fail_thread_messages_projection_state_update + BEFORE UPDATE ON projection_state + WHEN NEW.projector = 'projection.thread-messages' + BEGIN + SELECT RAISE(ABORT, 'forced-projection-state-failure'); + END; + `; + + const result = yield* Effect.result( + appendAndProject({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-rollback-3"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-rollback"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-rollback-3"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-rollback-3"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-rollback"), + messageId: MessageId.makeUnsafe("message-rollback"), + role: "user", + text: "Rollback me", + attachments: [ + { + type: "image", + id: "thread-rollback-att-1", + name: "rollback.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + }), + ); + assert.equal(result._tag, "Failure"); + + const rows = yield* sql<{ + readonly count: number; + }>` + SELECT COUNT(*) AS "count" + FROM projection_thread_messages + WHERE message_id = 'message-rollback' + `; + assert.equal(rows[0]?.count ?? 0, 0); + + const { attachmentsDir } = yield* ServerConfig; + const attachmentPath = path.join(attachmentsDir, "thread-rollback-att-1.png"); + assert.isFalse(yield* exists(attachmentPath)); + yield* sql`DROP TRIGGER IF EXISTS fail_thread_messages_projection_state_update`; + }), + ); +}); + +it.layer( + Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-overwrite-")), +)("OrchestrationProjectionPipeline", (it) => { + it.effect("removes unreferenced attachment files when a thread is reverted", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const { attachmentsDir } = yield* ServerConfig; + const now = new Date().toISOString(); + const threadId = ThreadId.makeUnsafe("Thread Revert.Files"); + const keepAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000001"; + const removeAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000002"; + const otherThreadAttachmentId = + "thread-revert-files-extra-00000000-0000-4000-8000-000000000003"; + + const appendAndProject = (event: Parameters[0]) => + eventStore + .append(event) + .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); + + yield* appendAndProject({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-revert-files-1"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-revert-files"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-revert-files-1"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-files-1"), + metadata: {}, + payload: { + projectId: ProjectId.makeUnsafe("project-revert-files"), + title: "Project Revert Files", + workspaceRoot: "/tmp/project-revert-files", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.created", + eventId: EventId.makeUnsafe("evt-revert-files-2"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-revert-files-2"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-files-2"), + metadata: {}, + payload: { + threadId, + projectId: ProjectId.makeUnsafe("project-revert-files"), + title: "Thread Revert Files", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.turn-diff-completed", + eventId: EventId.makeUnsafe("evt-revert-files-3"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-revert-files-3"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-files-3"), + metadata: {}, + payload: { + threadId, + turnId: TurnId.makeUnsafe("turn-keep"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert-files/turn/1"), + status: "ready", + files: [], + assistantMessageId: MessageId.makeUnsafe("message-keep"), + completedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-revert-files-4"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-revert-files-4"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-files-4"), + metadata: {}, + payload: { + threadId, + messageId: MessageId.makeUnsafe("message-keep"), + role: "assistant", + text: "Keep", + attachments: [ + { + type: "image", + id: keepAttachmentId, + name: "keep.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + turnId: TurnId.makeUnsafe("turn-keep"), + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.turn-diff-completed", + eventId: EventId.makeUnsafe("evt-revert-files-5"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-revert-files-5"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-files-5"), + metadata: {}, + payload: { + threadId, + turnId: TurnId.makeUnsafe("turn-remove"), + checkpointTurnCount: 2, + checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert-files/turn/2"), + status: "ready", + files: [], + assistantMessageId: MessageId.makeUnsafe("message-remove"), + completedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-revert-files-6"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-revert-files-6"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-files-6"), + metadata: {}, + payload: { + threadId, + messageId: MessageId.makeUnsafe("message-remove"), + role: "assistant", + text: "Remove", + attachments: [ + { + type: "image", + id: removeAttachmentId, + name: "remove.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + turnId: TurnId.makeUnsafe("turn-remove"), + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.png`); + const removePath = path.join(attachmentsDir, `${removeAttachmentId}.png`); + yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true }); + yield* fileSystem.writeFileString(keepPath, "keep"); + yield* fileSystem.writeFileString(removePath, "remove"); + const otherThreadPath = path.join(attachmentsDir, `${otherThreadAttachmentId}.png`); + yield* fileSystem.writeFileString(otherThreadPath, "other"); + assert.isTrue(yield* exists(keepPath)); + assert.isTrue(yield* exists(removePath)); + assert.isTrue(yield* exists(otherThreadPath)); + + yield* appendAndProject({ + type: "thread.reverted", + eventId: EventId.makeUnsafe("evt-revert-files-7"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-revert-files-7"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-files-7"), + metadata: {}, + payload: { + threadId, + turnCount: 1, + }, + }); + + assert.isTrue(yield* exists(keepPath)); + assert.isFalse(yield* exists(removePath)); + assert.isTrue(yield* exists(otherThreadPath)); + }), + ); +}); + +it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-revert-")))( + "OrchestrationProjectionPipeline", + (it) => { + it.effect("removes thread attachment directory when thread is deleted", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const { attachmentsDir } = yield* ServerConfig; + const now = new Date().toISOString(); + const threadId = ThreadId.makeUnsafe("Thread Delete.Files"); + const attachmentId = "thread-delete-files-00000000-0000-4000-8000-000000000001"; + const otherThreadAttachmentId = + "thread-delete-files-extra-00000000-0000-4000-8000-000000000002"; + + const appendAndProject = (event: Parameters[0]) => + eventStore + .append(event) + .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); + + yield* appendAndProject({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-delete-files-1"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-delete-files"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-delete-files-1"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-delete-files-1"), + metadata: {}, + payload: { + projectId: ProjectId.makeUnsafe("project-delete-files"), + title: "Project Delete Files", + workspaceRoot: "/tmp/project-delete-files", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.created", + eventId: EventId.makeUnsafe("evt-delete-files-2"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-delete-files-2"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-delete-files-2"), + metadata: {}, + payload: { + threadId, + projectId: ProjectId.makeUnsafe("project-delete-files"), + title: "Thread Delete Files", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-delete-files-3"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-delete-files-3"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-delete-files-3"), + metadata: {}, + payload: { + threadId, + messageId: MessageId.makeUnsafe("message-delete-files"), + role: "user", + text: "Delete", + attachments: [ + { + type: "image", + id: attachmentId, + name: "delete.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + const threadAttachmentPath = path.join(attachmentsDir, `${attachmentId}.png`); + const otherThreadAttachmentPath = path.join( + attachmentsDir, + `${otherThreadAttachmentId}.png`, + ); + yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true }); + yield* fileSystem.writeFileString(threadAttachmentPath, "delete"); + yield* fileSystem.writeFileString(otherThreadAttachmentPath, "other-thread"); + assert.isTrue(yield* exists(threadAttachmentPath)); + assert.isTrue(yield* exists(otherThreadAttachmentPath)); + + yield* appendAndProject({ + type: "thread.deleted", + eventId: EventId.makeUnsafe("evt-delete-files-4"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-delete-files-4"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-delete-files-4"), + metadata: {}, + payload: { + threadId, + deletedAt: now, + }, + }); + + assert.isFalse(yield* exists(threadAttachmentPath)); + assert.isTrue(yield* exists(otherThreadAttachmentPath)); + }), + ); + }, +); + +it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-delete-")))( + "OrchestrationProjectionPipeline", + (it) => { + it.effect("ignores unsafe thread ids for attachment cleanup paths", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const now = new Date().toISOString(); + const { attachmentsDir: attachmentsRootDir, stateDir } = yield* ServerConfig; + const attachmentsSentinelPath = path.join(attachmentsRootDir, "sentinel.txt"); + const stateDirSentinelPath = path.join(stateDir, "state-sentinel.txt"); + yield* fileSystem.makeDirectory(attachmentsRootDir, { recursive: true }); + yield* fileSystem.writeFileString(attachmentsSentinelPath, "keep-attachments-root"); + yield* fileSystem.writeFileString(stateDirSentinelPath, "keep-state-dir"); + + yield* eventStore.append({ + type: "thread.deleted", + eventId: EventId.makeUnsafe("evt-unsafe-thread-delete"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe(".."), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-unsafe-thread-delete"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-unsafe-thread-delete"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe(".."), + deletedAt: now, + }, + }); + + yield* projectionPipeline.bootstrap; + + assert.isTrue(yield* exists(attachmentsRootDir)); + assert.isTrue(yield* exists(attachmentsSentinelPath)); + assert.isTrue(yield* exists(stateDirSentinelPath)); + }), + ); + }, +); + +it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { + it.effect("resumes from projector last_applied_sequence without replaying older events", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = new Date().toISOString(); + + yield* eventStore.append({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-a1"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-a"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-a1"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-a1"), + metadata: {}, + payload: { + projectId: ProjectId.makeUnsafe("project-a"), + title: "Project A", + workspaceRoot: "/tmp/project-a", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.created", + eventId: EventId.makeUnsafe("evt-a2"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-a"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-a2"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-a2"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-a"), + projectId: ProjectId.makeUnsafe("project-a"), + title: "Thread A", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-a3"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-a"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-a3"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-a3"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-a"), + messageId: MessageId.makeUnsafe("message-a"), + role: "assistant", + text: "hello", + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + yield* projectionPipeline.bootstrap; + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-a4"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-a"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-a4"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-a4"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-a"), + messageId: MessageId.makeUnsafe("message-a"), + role: "assistant", + text: " world", + turnId: null, + streaming: true, + createdAt: now, + updatedAt: now, + }, + }); + + yield* projectionPipeline.bootstrap; + yield* projectionPipeline.bootstrap; + + const messageRows = yield* sql<{ readonly text: string }>` + SELECT text FROM projection_thread_messages WHERE message_id = 'message-a' + `; + assert.deepEqual(messageRows, [{ text: "hello world" }]); + + const stateRows = yield* sql<{ + readonly projector: string; + readonly lastAppliedSequence: number; + }>` + SELECT + projector, + last_applied_sequence AS "lastAppliedSequence" + FROM projection_state + `; + const maxSequenceRows = yield* sql<{ readonly maxSequence: number }>` + SELECT MAX(sequence) AS "maxSequence" FROM orchestration_events + `; + const maxSequence = maxSequenceRows[0]?.maxSequence ?? 0; + for (const row of stateRows) { + assert.equal(row.lastAppliedSequence, maxSequence); + } + }), + ); + + it.effect("keeps accumulated assistant text when completion payload text is empty", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = new Date().toISOString(); + + yield* eventStore.append({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-empty-1"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-empty"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-empty-1"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-empty-1"), + metadata: {}, + payload: { + projectId: ProjectId.makeUnsafe("project-empty"), + title: "Project Empty", + workspaceRoot: "/tmp/project-empty", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.created", + eventId: EventId.makeUnsafe("evt-empty-2"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-empty"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-empty-2"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-empty-2"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-empty"), + projectId: ProjectId.makeUnsafe("project-empty"), + title: "Thread Empty", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-empty-3"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-empty"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-empty-3"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-empty-3"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-empty"), + messageId: MessageId.makeUnsafe("assistant-empty"), + role: "assistant", + text: "Hello", + turnId: null, + streaming: true, + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-empty-4"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-empty"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-empty-4"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-empty-4"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-empty"), + messageId: MessageId.makeUnsafe("assistant-empty"), + role: "assistant", + text: " world", + turnId: null, + streaming: true, + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-empty-5"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-empty"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-empty-5"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-empty-5"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-empty"), + messageId: MessageId.makeUnsafe("assistant-empty"), + role: "assistant", + text: "", + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + yield* projectionPipeline.bootstrap; + + const messageRows = yield* sql<{ readonly text: string; readonly isStreaming: unknown }>` + SELECT + text, + is_streaming AS "isStreaming" + FROM projection_thread_messages + WHERE message_id = 'assistant-empty' + `; + assert.equal(messageRows.length, 1); + assert.equal(messageRows[0]?.text, "Hello world"); + assert.isFalse(Boolean(messageRows[0]?.isStreaming)); + }), + ); + + it.effect( + "resolves turn-count conflicts when checkpoint completion rewrites provisional turns", + () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const appendAndProject = (event: Parameters[0]) => + eventStore + .append(event) + .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); + + yield* appendAndProject({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-conflict-1"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-conflict"), + occurredAt: "2026-02-26T13:00:00.000Z", + commandId: CommandId.makeUnsafe("cmd-conflict-1"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-conflict-1"), + metadata: {}, + payload: { + projectId: ProjectId.makeUnsafe("project-conflict"), + title: "Project Conflict", + workspaceRoot: "/tmp/project-conflict", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-02-26T13:00:00.000Z", + updatedAt: "2026-02-26T13:00:00.000Z", + }, + }); + + yield* appendAndProject({ + type: "thread.created", + eventId: EventId.makeUnsafe("evt-conflict-2"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-conflict"), + occurredAt: "2026-02-26T13:00:01.000Z", + commandId: CommandId.makeUnsafe("cmd-conflict-2"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-conflict-2"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-conflict"), + projectId: ProjectId.makeUnsafe("project-conflict"), + title: "Thread Conflict", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: "2026-02-26T13:00:01.000Z", + updatedAt: "2026-02-26T13:00:01.000Z", + }, + }); + + yield* appendAndProject({ + type: "thread.turn-interrupt-requested", + eventId: EventId.makeUnsafe("evt-conflict-3"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-conflict"), + occurredAt: "2026-02-26T13:00:02.000Z", + commandId: CommandId.makeUnsafe("cmd-conflict-3"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-conflict-3"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-conflict"), + turnId: TurnId.makeUnsafe("turn-interrupted"), + createdAt: "2026-02-26T13:00:02.000Z", + }, + }); + + yield* appendAndProject({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-conflict-4"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-conflict"), + occurredAt: "2026-02-26T13:00:03.000Z", + commandId: CommandId.makeUnsafe("cmd-conflict-4"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-conflict-4"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-conflict"), + messageId: MessageId.makeUnsafe("assistant-conflict"), + role: "assistant", + text: "done", + turnId: TurnId.makeUnsafe("turn-completed"), + streaming: false, + createdAt: "2026-02-26T13:00:03.000Z", + updatedAt: "2026-02-26T13:00:03.000Z", + }, + }); + + yield* appendAndProject({ + type: "thread.turn-diff-completed", + eventId: EventId.makeUnsafe("evt-conflict-5"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-conflict"), + occurredAt: "2026-02-26T13:00:04.000Z", + commandId: CommandId.makeUnsafe("cmd-conflict-5"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-conflict-5"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-conflict"), + turnId: TurnId.makeUnsafe("turn-completed"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-conflict/turn/1"), + status: "ready", + files: [], + assistantMessageId: MessageId.makeUnsafe("assistant-conflict"), + completedAt: "2026-02-26T13:00:04.000Z", + }, + }); + + const turnRows = yield* sql<{ + readonly turnId: string; + readonly checkpointTurnCount: number | null; + readonly status: string; + }>` + SELECT + turn_id AS "turnId", + checkpoint_turn_count AS "checkpointTurnCount", + state AS "status" + FROM projection_turns + WHERE thread_id = 'thread-conflict' + ORDER BY + CASE + WHEN checkpoint_turn_count IS NULL THEN 1 + ELSE 0 + END ASC, + checkpoint_turn_count ASC, + requested_at ASC + `; + assert.deepEqual(turnRows, [ + { turnId: "turn-completed", checkpointTurnCount: 1, status: "completed" }, + { turnId: "turn-interrupted", checkpointTurnCount: null, status: "interrupted" }, + ]); + }), + ); + + it.effect("does not fallback-retain messages whose turnId is removed by revert", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const appendAndProject = (event: Parameters[0]) => + eventStore + .append(event) + .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); + + yield* appendAndProject({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-revert-1"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-revert"), + occurredAt: "2026-02-26T12:00:00.000Z", + commandId: CommandId.makeUnsafe("cmd-revert-1"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-1"), + metadata: {}, + payload: { + projectId: ProjectId.makeUnsafe("project-revert"), + title: "Project Revert", + workspaceRoot: "/tmp/project-revert", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-02-26T12:00:00.000Z", + updatedAt: "2026-02-26T12:00:00.000Z", + }, + }); + + yield* appendAndProject({ + type: "thread.created", + eventId: EventId.makeUnsafe("evt-revert-2"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-revert"), + occurredAt: "2026-02-26T12:00:01.000Z", + commandId: CommandId.makeUnsafe("cmd-revert-2"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-2"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-revert"), + projectId: ProjectId.makeUnsafe("project-revert"), + title: "Thread Revert", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: "2026-02-26T12:00:01.000Z", + updatedAt: "2026-02-26T12:00:01.000Z", + }, + }); + + yield* appendAndProject({ + type: "thread.turn-diff-completed", + eventId: EventId.makeUnsafe("evt-revert-3"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-revert"), + occurredAt: "2026-02-26T12:00:02.000Z", + commandId: CommandId.makeUnsafe("cmd-revert-3"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-3"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-revert"), + turnId: TurnId.makeUnsafe("turn-1"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert/turn/1"), + status: "ready", + files: [], + assistantMessageId: MessageId.makeUnsafe("assistant-keep"), + completedAt: "2026-02-26T12:00:02.000Z", + }, + }); + + yield* appendAndProject({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-revert-4"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-revert"), + occurredAt: "2026-02-26T12:00:02.100Z", + commandId: CommandId.makeUnsafe("cmd-revert-4"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-4"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-revert"), + messageId: MessageId.makeUnsafe("assistant-keep"), + role: "assistant", + text: "kept", + turnId: TurnId.makeUnsafe("turn-1"), + streaming: false, + createdAt: "2026-02-26T12:00:02.100Z", + updatedAt: "2026-02-26T12:00:02.100Z", + }, + }); + + yield* appendAndProject({ + type: "thread.turn-diff-completed", + eventId: EventId.makeUnsafe("evt-revert-5"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-revert"), + occurredAt: "2026-02-26T12:00:03.000Z", + commandId: CommandId.makeUnsafe("cmd-revert-5"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-5"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-revert"), + turnId: TurnId.makeUnsafe("turn-2"), + checkpointTurnCount: 2, + checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert/turn/2"), + status: "ready", + files: [], + assistantMessageId: MessageId.makeUnsafe("assistant-remove"), + completedAt: "2026-02-26T12:00:03.000Z", + }, + }); + + yield* appendAndProject({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-revert-6"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-revert"), + occurredAt: "2026-02-26T12:00:03.050Z", + commandId: CommandId.makeUnsafe("cmd-revert-6"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-6"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-revert"), + messageId: MessageId.makeUnsafe("user-remove"), + role: "user", + text: "removed", + turnId: TurnId.makeUnsafe("turn-2"), + streaming: false, + createdAt: "2026-02-26T12:00:03.050Z", + updatedAt: "2026-02-26T12:00:03.050Z", + }, + }); + + yield* appendAndProject({ + type: "thread.message-sent", + eventId: EventId.makeUnsafe("evt-revert-7"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-revert"), + occurredAt: "2026-02-26T12:00:03.100Z", + commandId: CommandId.makeUnsafe("cmd-revert-7"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-7"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-revert"), + messageId: MessageId.makeUnsafe("assistant-remove"), + role: "assistant", + text: "removed", + turnId: TurnId.makeUnsafe("turn-2"), + streaming: false, + createdAt: "2026-02-26T12:00:03.100Z", + updatedAt: "2026-02-26T12:00:03.100Z", + }, + }); + + yield* appendAndProject({ + type: "thread.reverted", + eventId: EventId.makeUnsafe("evt-revert-8"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-revert"), + occurredAt: "2026-02-26T12:00:04.000Z", + commandId: CommandId.makeUnsafe("cmd-revert-8"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-revert-8"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-revert"), + turnCount: 1, + }, + }); + + const messageRows = yield* sql<{ + readonly messageId: string; + readonly turnId: string | null; + readonly role: string; + }>` + SELECT + message_id AS "messageId", + turn_id AS "turnId", + role + FROM projection_thread_messages + WHERE thread_id = 'thread-revert' + ORDER BY created_at ASC, message_id ASC + `; + assert.deepEqual(messageRows, [ + { + messageId: "assistant-keep", + turnId: "turn-1", + role: "assistant", + }, + ]); + }), + ); +}); + +it.effect("restores pending turn-start metadata across projection pipeline restart", () => + Effect.gen(function* () { + const { dbPath } = yield* ServerConfig; + const persistenceLayer = makeSqlitePersistenceLive(dbPath); + const firstProjectionLayer = OrchestrationProjectionPipelineLive.pipe( + Layer.provideMerge(OrchestrationEventStoreLive), + Layer.provideMerge(persistenceLayer), + ); + const secondProjectionLayer = OrchestrationProjectionPipelineLive.pipe( + Layer.provideMerge(OrchestrationEventStoreLive), + Layer.provideMerge(persistenceLayer), + ); + + const threadId = ThreadId.makeUnsafe("thread-restart"); + const turnId = TurnId.makeUnsafe("turn-restart"); + const messageId = MessageId.makeUnsafe("message-restart"); + const sourcePlanThreadId = ThreadId.makeUnsafe("thread-plan-source"); + const sourcePlanId = "plan-source"; + const turnStartedAt = "2026-02-26T14:00:00.000Z"; + const sessionSetAt = "2026-02-26T14:00:05.000Z"; + + yield* Effect.gen(function* () { + const eventStore = yield* OrchestrationEventStore; + const projectionPipeline = yield* OrchestrationProjectionPipeline; + + yield* eventStore.append({ + type: "thread.turn-start-requested", + eventId: EventId.makeUnsafe("evt-restart-1"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: turnStartedAt, + commandId: CommandId.makeUnsafe("cmd-restart-1"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-restart-1"), + metadata: {}, + payload: { + threadId, + messageId, + sourceProposedPlan: { + threadId: sourcePlanThreadId, + planId: sourcePlanId, + }, + runtimeMode: "approval-required", + createdAt: turnStartedAt, + }, + }); + + yield* projectionPipeline.bootstrap; + }).pipe(Effect.provide(firstProjectionLayer)); + + const turnRows = yield* Effect.gen(function* () { + const eventStore = yield* OrchestrationEventStore; + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const sql = yield* SqlClient.SqlClient; + + yield* eventStore.append({ + type: "thread.session-set", + eventId: EventId.makeUnsafe("evt-restart-2"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: sessionSetAt, + commandId: CommandId.makeUnsafe("cmd-restart-2"), + causationEventId: null, + correlationId: CorrelationId.makeUnsafe("cmd-restart-2"), + metadata: {}, + payload: { + threadId, + session: { + threadId, + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: turnId, + lastError: null, + updatedAt: sessionSetAt, + }, + }, + }); + + yield* projectionPipeline.bootstrap; + + const pendingRows = yield* sql<{ readonly threadId: string }>` + SELECT thread_id AS "threadId" + FROM projection_turns + WHERE thread_id = ${threadId} + AND turn_id IS NULL + AND state = 'pending' + `; + assert.deepEqual(pendingRows, []); + + return yield* sql<{ + readonly turnId: string; + readonly userMessageId: string | null; + readonly sourceProposedPlanThreadId: string | null; + readonly sourceProposedPlanId: string | null; + readonly startedAt: string; + }>` + SELECT + turn_id AS "turnId", + pending_message_id AS "userMessageId", + source_proposed_plan_thread_id AS "sourceProposedPlanThreadId", + source_proposed_plan_id AS "sourceProposedPlanId", + started_at AS "startedAt" + FROM projection_turns + WHERE turn_id = ${turnId} + `; + }).pipe(Effect.provide(secondProjectionLayer)); + + assert.deepEqual(turnRows, [ + { + turnId: "turn-restart", + userMessageId: "message-restart", + sourceProposedPlanThreadId: "thread-plan-source", + sourceProposedPlanId: "plan-source", + startedAt: turnStartedAt, + }, + ]); + }).pipe( + Effect.provide( + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-projection-pipeline-restart-", + }), + NodeServices.layer, + ), + ), + ), +); + +const engineLayer = it.layer( + OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), + Layer.provide(OrchestrationProjectionPipelineLive), + Layer.provide(OrchestrationEventStoreLive), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provideMerge(SqlitePersistenceMemory), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-projection-pipeline-engine-dispatch-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ), +); + +engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { + it.effect("projects dispatched engine events immediately", () => + Effect.gen(function* () { + const engine = yield* OrchestrationEngineService; + const sql = yield* SqlClient.SqlClient; + const createdAt = new Date().toISOString(); + + yield* engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-live-project"), + projectId: ProjectId.makeUnsafe("project-live"), + title: "Live Project", + workspaceRoot: "/tmp/project-live", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }); + + const projectRows = yield* sql<{ readonly title: string; readonly scriptsJson: string }>` + SELECT + title, + scripts_json AS "scriptsJson" + FROM projection_projects + WHERE project_id = 'project-live' + `; + assert.deepEqual(projectRows, [{ title: "Live Project", scriptsJson: "[]" }]); + + const projectorRows = yield* sql<{ readonly lastAppliedSequence: number }>` + SELECT + last_applied_sequence AS "lastAppliedSequence" + FROM projection_state + WHERE projector = 'projection.projects' + `; + assert.deepEqual(projectorRows, [{ lastAppliedSequence: 1 }]); + }), + ); + + it.effect("projects persist updated scripts from project.meta.update", () => + Effect.gen(function* () { + const engine = yield* OrchestrationEngineService; + const sql = yield* SqlClient.SqlClient; + const createdAt = new Date().toISOString(); + + yield* engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-scripts-project-create"), + projectId: ProjectId.makeUnsafe("project-scripts"), + title: "Scripts Project", + workspaceRoot: "/tmp/project-scripts", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }); + + yield* engine.dispatch({ + type: "project.meta.update", + commandId: CommandId.makeUnsafe("cmd-scripts-project-update"), + projectId: ProjectId.makeUnsafe("project-scripts"), + scripts: [ + { + id: "script-1", + name: "Build", + command: "bun run build", + icon: "build", + runOnWorktreeCreate: false, + }, + ], + defaultModelSelection: { + provider: "codex", + model: "gpt-5", + }, + }); + + const projectRows = yield* sql<{ + readonly scriptsJson: string; + readonly defaultModelSelection: string; + }>` + SELECT + scripts_json AS "scriptsJson", + default_model_selection_json AS "defaultModelSelection" + FROM projection_projects + WHERE project_id = 'project-scripts' + `; + assert.deepEqual(projectRows, [ + { + scriptsJson: + '[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]', + defaultModelSelection: '{"provider":"codex","model":"gpt-5"}', + }, + ]); + }), + ); +}); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts new file mode 100644 index 0000000000..0844cf8bb0 --- /dev/null +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -0,0 +1,1306 @@ +import { + ApprovalRequestId, + type ChatAttachment, + type OrchestrationEvent, +} from "@t3tools/contracts"; +import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts"; +import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts"; +import { ProjectionPendingApprovalRepository } from "../../persistence/Services/ProjectionPendingApprovals.ts"; +import { ProjectionProjectRepository } from "../../persistence/Services/ProjectionProjects.ts"; +import { ProjectionStateRepository } from "../../persistence/Services/ProjectionState.ts"; +import { ProjectionThreadActivityRepository } from "../../persistence/Services/ProjectionThreadActivities.ts"; +import { type ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts"; +import { + type ProjectionThreadMessage, + ProjectionThreadMessageRepository, +} from "../../persistence/Services/ProjectionThreadMessages.ts"; +import { + type ProjectionThreadProposedPlan, + ProjectionThreadProposedPlanRepository, +} from "../../persistence/Services/ProjectionThreadProposedPlans.ts"; +import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts"; +import { + type ProjectionTurn, + ProjectionTurnRepository, +} from "../../persistence/Services/ProjectionTurns.ts"; +import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts"; +import { ProjectionPendingApprovalRepositoryLive } from "../../persistence/Layers/ProjectionPendingApprovals.ts"; +import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/ProjectionProjects.ts"; +import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts"; +import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts"; +import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts"; +import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts"; +import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts"; +import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; +import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts"; +import { ServerConfig } from "../../config.ts"; +import { + OrchestrationProjectionPipeline, + type OrchestrationProjectionPipelineShape, +} from "../Services/ProjectionPipeline.ts"; +import { + attachmentRelativePath, + parseAttachmentIdFromRelativePath, + parseThreadSegmentFromAttachmentId, + toSafeThreadAttachmentSegment, +} from "../../attachmentStore.ts"; + +export const ORCHESTRATION_PROJECTOR_NAMES = { + projects: "projection.projects", + threads: "projection.threads", + threadMessages: "projection.thread-messages", + threadProposedPlans: "projection.thread-proposed-plans", + threadActivities: "projection.thread-activities", + threadSessions: "projection.thread-sessions", + threadTurns: "projection.thread-turns", + checkpoints: "projection.checkpoints", + pendingApprovals: "projection.pending-approvals", +} as const; + +type ProjectorName = + (typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES]; + +interface ProjectorDefinition { + readonly name: ProjectorName; + readonly apply: ( + event: OrchestrationEvent, + attachmentSideEffects: AttachmentSideEffects, + ) => Effect.Effect; +} + +interface AttachmentSideEffects { + readonly deletedThreadIds: Set; + readonly prunedThreadRelativePaths: Map>; +} + +const materializeAttachmentsForProjection = Effect.fn("materializeAttachmentsForProjection")( + (input: { readonly attachments: ReadonlyArray }) => + Effect.succeed(input.attachments.length === 0 ? [] : input.attachments), +); + +function extractActivityRequestId(payload: unknown): ApprovalRequestId | null { + if (typeof payload !== "object" || payload === null) { + return null; + } + const requestId = (payload as Record).requestId; + return typeof requestId === "string" ? ApprovalRequestId.makeUnsafe(requestId) : null; +} + +function retainProjectionMessagesAfterRevert( + messages: ReadonlyArray, + turns: ReadonlyArray, + turnCount: number, +): ReadonlyArray { + const retainedMessageIds = new Set(); + const retainedTurnIds = new Set(); + const keptTurns = turns.filter( + (turn) => + turn.turnId !== null && + turn.checkpointTurnCount !== null && + turn.checkpointTurnCount <= turnCount, + ); + for (const turn of keptTurns) { + if (turn.turnId !== null) { + retainedTurnIds.add(turn.turnId); + } + if (turn.pendingMessageId !== null) { + retainedMessageIds.add(turn.pendingMessageId); + } + if (turn.assistantMessageId !== null) { + retainedMessageIds.add(turn.assistantMessageId); + } + } + + for (const message of messages) { + if (message.role === "system") { + retainedMessageIds.add(message.messageId); + continue; + } + if (message.turnId !== null && retainedTurnIds.has(message.turnId)) { + retainedMessageIds.add(message.messageId); + } + } + + const retainedUserCount = messages.filter( + (message) => message.role === "user" && retainedMessageIds.has(message.messageId), + ).length; + const missingUserCount = Math.max(0, turnCount - retainedUserCount); + if (missingUserCount > 0) { + const fallbackUserMessages = messages + .filter( + (message) => + message.role === "user" && + !retainedMessageIds.has(message.messageId) && + (message.turnId === null || retainedTurnIds.has(message.turnId)), + ) + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || + left.messageId.localeCompare(right.messageId), + ) + .slice(0, missingUserCount); + for (const message of fallbackUserMessages) { + retainedMessageIds.add(message.messageId); + } + } + + const retainedAssistantCount = messages.filter( + (message) => message.role === "assistant" && retainedMessageIds.has(message.messageId), + ).length; + const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount); + if (missingAssistantCount > 0) { + const fallbackAssistantMessages = messages + .filter( + (message) => + message.role === "assistant" && + !retainedMessageIds.has(message.messageId) && + (message.turnId === null || retainedTurnIds.has(message.turnId)), + ) + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || + left.messageId.localeCompare(right.messageId), + ) + .slice(0, missingAssistantCount); + for (const message of fallbackAssistantMessages) { + retainedMessageIds.add(message.messageId); + } + } + + return messages.filter((message) => retainedMessageIds.has(message.messageId)); +} + +function retainProjectionActivitiesAfterRevert( + activities: ReadonlyArray, + turns: ReadonlyArray, + turnCount: number, +): ReadonlyArray { + const retainedTurnIds = new Set( + turns + .filter( + (turn) => + turn.turnId !== null && + turn.checkpointTurnCount !== null && + turn.checkpointTurnCount <= turnCount, + ) + .flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])), + ); + return activities.filter( + (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId), + ); +} + +function retainProjectionProposedPlansAfterRevert( + proposedPlans: ReadonlyArray, + turns: ReadonlyArray, + turnCount: number, +): ReadonlyArray { + const retainedTurnIds = new Set( + turns + .filter( + (turn) => + turn.turnId !== null && + turn.checkpointTurnCount !== null && + turn.checkpointTurnCount <= turnCount, + ) + .flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])), + ); + return proposedPlans.filter( + (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId), + ); +} + +function collectThreadAttachmentRelativePaths( + threadId: string, + messages: ReadonlyArray, +): Set { + const threadSegment = toSafeThreadAttachmentSegment(threadId); + if (!threadSegment) { + return new Set(); + } + const relativePaths = new Set(); + for (const message of messages) { + for (const attachment of message.attachments ?? []) { + if (attachment.type !== "image") { + continue; + } + const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id); + if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { + continue; + } + relativePaths.add(attachmentRelativePath(attachment)); + } + } + return relativePaths; +} + +const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function* ( + sideEffects: AttachmentSideEffects, +) { + const serverConfig = yield* Effect.service(ServerConfig); + const fileSystem = yield* Effect.service(FileSystem.FileSystem); + const path = yield* Effect.service(Path.Path); + + const attachmentsRootDir = serverConfig.attachmentsDir; + const readAttachmentRootEntries = fileSystem + .readDirectory(attachmentsRootDir, { recursive: false }) + .pipe(Effect.catch(() => Effect.succeed([] as Array))); + + const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")( + function* (threadSegment: string, entry: string) { + const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/"); + if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) { + return; + } + const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry); + if (!attachmentId) { + return; + } + const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId); + if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { + return; + } + yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), { + force: true, + }); + }, + ); + + const deleteThreadAttachments = Effect.fn("deleteThreadAttachments")(function* ( + threadId: string, + ) { + const threadSegment = toSafeThreadAttachmentSegment(threadId); + if (!threadSegment) { + yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", { + threadId, + }); + return; + } + + const entries = yield* readAttachmentRootEntries; + yield* Effect.forEach( + entries, + (entry) => removeDeletedThreadAttachmentEntry(threadSegment, entry), + { + concurrency: 1, + }, + ); + }); + + const pruneThreadAttachmentEntry = Effect.fn("pruneThreadAttachmentEntry")(function* ( + threadSegment: string, + keptThreadRelativePaths: Set, + entry: string, + ) { + const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/"); + if (relativePath.length === 0 || relativePath.includes("/")) { + return; + } + const attachmentId = parseAttachmentIdFromRelativePath(relativePath); + if (!attachmentId) { + return; + } + const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId); + if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { + return; + } + + const absolutePath = path.join(attachmentsRootDir, relativePath); + const fileInfo = yield* fileSystem + .stat(absolutePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!fileInfo || fileInfo.type !== "File") { + return; + } + + if (!keptThreadRelativePaths.has(relativePath)) { + yield* fileSystem.remove(absolutePath, { force: true }); + } + }); + + const pruneThreadAttachments = Effect.fn("pruneThreadAttachments")(function* ( + threadId: string, + keptThreadRelativePaths: Set, + ) { + if (sideEffects.deletedThreadIds.has(threadId)) { + return; + } + + const threadSegment = toSafeThreadAttachmentSegment(threadId); + if (!threadSegment) { + yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId }); + return; + } + + const entries = yield* readAttachmentRootEntries; + yield* Effect.forEach( + entries, + (entry) => pruneThreadAttachmentEntry(threadSegment, keptThreadRelativePaths, entry), + { concurrency: 1 }, + ); + }); + + yield* Effect.forEach(sideEffects.deletedThreadIds, deleteThreadAttachments, { + concurrency: 1, + }); + + yield* Effect.forEach( + sideEffects.prunedThreadRelativePaths.entries(), + ([threadId, keptThreadRelativePaths]) => + pruneThreadAttachments(threadId, keptThreadRelativePaths), + { concurrency: 1 }, + ); +}); + +const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectionPipeline")( + function* () { + const sql = yield* SqlClient.SqlClient; + const eventStore = yield* OrchestrationEventStore; + const projectionStateRepository = yield* ProjectionStateRepository; + const projectionProjectRepository = yield* ProjectionProjectRepository; + const projectionThreadRepository = yield* ProjectionThreadRepository; + const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository; + const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository; + const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository; + const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository; + const projectionTurnRepository = yield* ProjectionTurnRepository; + const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository; + + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + + const applyProjectsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyProjectsProjection", + )(function* (event, _attachmentSideEffects) { + switch (event.type) { + case "project.created": + yield* projectionProjectRepository.upsert({ + projectId: event.payload.projectId, + title: event.payload.title, + workspaceRoot: event.payload.workspaceRoot, + defaultModelSelection: event.payload.defaultModelSelection, + scripts: event.payload.scripts, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + deletedAt: null, + }); + return; + + case "project.meta-updated": { + const existingRow = yield* projectionProjectRepository.getById({ + projectId: event.payload.projectId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionProjectRepository.upsert({ + ...existingRow.value, + ...(event.payload.title !== undefined ? { title: event.payload.title } : {}), + ...(event.payload.workspaceRoot !== undefined + ? { workspaceRoot: event.payload.workspaceRoot } + : {}), + ...(event.payload.defaultModelSelection !== undefined + ? { defaultModelSelection: event.payload.defaultModelSelection } + : {}), + ...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}), + updatedAt: event.payload.updatedAt, + }); + return; + } + + case "project.deleted": { + const existingRow = yield* projectionProjectRepository.getById({ + projectId: event.payload.projectId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionProjectRepository.upsert({ + ...existingRow.value, + deletedAt: event.payload.deletedAt, + updatedAt: event.payload.deletedAt, + }); + return; + } + + default: + return; + } + }); + + const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadsProjection", + )(function* (event, attachmentSideEffects) { + switch (event.type) { + case "thread.created": + yield* projectionThreadRepository.upsert({ + threadId: event.payload.threadId, + projectId: event.payload.projectId, + title: event.payload.title, + modelSelection: event.payload.modelSelection, + runtimeMode: event.payload.runtimeMode, + interactionMode: event.payload.interactionMode, + branch: event.payload.branch, + worktreePath: event.payload.worktreePath, + latestTurnId: null, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + archivedAt: null, + deletedAt: null, + }); + return; + + case "thread.archived": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + archivedAt: event.payload.archivedAt, + updatedAt: event.payload.updatedAt, + }); + return; + } + + case "thread.unarchived": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + archivedAt: null, + updatedAt: event.payload.updatedAt, + }); + return; + } + + case "thread.meta-updated": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + ...(event.payload.title !== undefined ? { title: event.payload.title } : {}), + ...(event.payload.modelSelection !== undefined + ? { modelSelection: event.payload.modelSelection } + : {}), + ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}), + ...(event.payload.worktreePath !== undefined + ? { worktreePath: event.payload.worktreePath } + : {}), + updatedAt: event.payload.updatedAt, + }); + return; + } + + case "thread.runtime-mode-set": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + runtimeMode: event.payload.runtimeMode, + updatedAt: event.payload.updatedAt, + }); + return; + } + + case "thread.interaction-mode-set": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + interactionMode: event.payload.interactionMode, + updatedAt: event.payload.updatedAt, + }); + return; + } + + case "thread.deleted": { + attachmentSideEffects.deletedThreadIds.add(event.payload.threadId); + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + deletedAt: event.payload.deletedAt, + updatedAt: event.payload.deletedAt, + }); + return; + } + + case "thread.message-sent": + case "thread.proposed-plan-upserted": + case "thread.activity-appended": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + updatedAt: event.occurredAt, + }); + return; + } + + case "thread.session-set": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + latestTurnId: event.payload.session.activeTurnId, + updatedAt: event.occurredAt, + }); + return; + } + + case "thread.turn-diff-completed": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + latestTurnId: event.payload.turnId, + updatedAt: event.occurredAt, + }); + return; + } + + case "thread.reverted": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + latestTurnId: null, + updatedAt: event.occurredAt, + }); + return; + } + + default: + return; + } + }); + + const applyThreadMessagesProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadMessagesProjection", + )(function* (event, attachmentSideEffects) { + switch (event.type) { + case "thread.message-sent": { + const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({ + messageId: event.payload.messageId, + }); + const previousMessage = Option.getOrUndefined(existingMessage); + const nextText = Option.match(existingMessage, { + onNone: () => event.payload.text, + onSome: (message) => { + if (event.payload.streaming) { + return `${message.text}${event.payload.text}`; + } + if (event.payload.text.length === 0) { + return message.text; + } + return event.payload.text; + }, + }); + const nextAttachments = + event.payload.attachments !== undefined + ? yield* materializeAttachmentsForProjection({ + attachments: event.payload.attachments, + }) + : previousMessage?.attachments; + yield* projectionThreadMessageRepository.upsert({ + messageId: event.payload.messageId, + threadId: event.payload.threadId, + turnId: event.payload.turnId, + role: event.payload.role, + text: nextText, + ...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}), + isStreaming: event.payload.streaming, + createdAt: previousMessage?.createdAt ?? event.payload.createdAt, + updatedAt: event.payload.updatedAt, + }); + return; + } + + case "thread.reverted": { + const existingRows = yield* projectionThreadMessageRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + if (existingRows.length === 0) { + return; + } + + const existingTurns = yield* projectionTurnRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + const keptRows = retainProjectionMessagesAfterRevert( + existingRows, + existingTurns, + event.payload.turnCount, + ); + if (keptRows.length === existingRows.length) { + return; + } + + yield* projectionThreadMessageRepository.deleteByThreadId({ + threadId: event.payload.threadId, + }); + yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, { + concurrency: 1, + }).pipe(Effect.asVoid); + attachmentSideEffects.prunedThreadRelativePaths.set( + event.payload.threadId, + collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows), + ); + return; + } + + default: + return; + } + }); + + const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadProposedPlansProjection", + )(function* (event, _attachmentSideEffects) { + switch (event.type) { + case "thread.proposed-plan-upserted": + yield* projectionThreadProposedPlanRepository.upsert({ + planId: event.payload.proposedPlan.id, + threadId: event.payload.threadId, + turnId: event.payload.proposedPlan.turnId, + planMarkdown: event.payload.proposedPlan.planMarkdown, + implementedAt: event.payload.proposedPlan.implementedAt, + implementationThreadId: event.payload.proposedPlan.implementationThreadId, + createdAt: event.payload.proposedPlan.createdAt, + updatedAt: event.payload.proposedPlan.updatedAt, + }); + return; + + case "thread.reverted": { + const existingRows = yield* projectionThreadProposedPlanRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + if (existingRows.length === 0) { + return; + } + + const existingTurns = yield* projectionTurnRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + const keptRows = retainProjectionProposedPlansAfterRevert( + existingRows, + existingTurns, + event.payload.turnCount, + ); + if (keptRows.length === existingRows.length) { + return; + } + + yield* projectionThreadProposedPlanRepository.deleteByThreadId({ + threadId: event.payload.threadId, + }); + yield* Effect.forEach(keptRows, projectionThreadProposedPlanRepository.upsert, { + concurrency: 1, + }).pipe(Effect.asVoid); + return; + } + + default: + return; + } + }); + + const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadActivitiesProjection", + )(function* (event, _attachmentSideEffects) { + switch (event.type) { + case "thread.activity-appended": + yield* projectionThreadActivityRepository.upsert({ + activityId: event.payload.activity.id, + threadId: event.payload.threadId, + turnId: event.payload.activity.turnId, + tone: event.payload.activity.tone, + kind: event.payload.activity.kind, + summary: event.payload.activity.summary, + payload: event.payload.activity.payload, + ...(event.payload.activity.sequence !== undefined + ? { sequence: event.payload.activity.sequence } + : {}), + createdAt: event.payload.activity.createdAt, + }); + return; + + case "thread.reverted": { + const existingRows = yield* projectionThreadActivityRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + if (existingRows.length === 0) { + return; + } + const existingTurns = yield* projectionTurnRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + const keptRows = retainProjectionActivitiesAfterRevert( + existingRows, + existingTurns, + event.payload.turnCount, + ); + if (keptRows.length === existingRows.length) { + return; + } + yield* projectionThreadActivityRepository.deleteByThreadId({ + threadId: event.payload.threadId, + }); + yield* Effect.forEach(keptRows, projectionThreadActivityRepository.upsert, { + concurrency: 1, + }).pipe(Effect.asVoid); + return; + } + + default: + return; + } + }); + + const applyThreadSessionsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadSessionsProjection", + )(function* (event, _attachmentSideEffects) { + if (event.type !== "thread.session-set") { + return; + } + yield* projectionThreadSessionRepository.upsert({ + threadId: event.payload.threadId, + status: event.payload.session.status, + providerName: event.payload.session.providerName, + runtimeMode: event.payload.session.runtimeMode, + activeTurnId: event.payload.session.activeTurnId, + lastError: event.payload.session.lastError, + updatedAt: event.payload.session.updatedAt, + }); + }); + + const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadTurnsProjection", + )(function* (event, _attachmentSideEffects) { + switch (event.type) { + case "thread.turn-start-requested": { + yield* projectionTurnRepository.replacePendingTurnStart({ + threadId: event.payload.threadId, + messageId: event.payload.messageId, + sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null, + sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null, + requestedAt: event.payload.createdAt, + }); + return; + } + + case "thread.session-set": { + const turnId = event.payload.session.activeTurnId; + if (turnId === null || event.payload.session.status !== "running") { + return; + } + + const existingTurn = yield* projectionTurnRepository.getByTurnId({ + threadId: event.payload.threadId, + turnId, + }); + const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ + threadId: event.payload.threadId, + }); + if (Option.isSome(existingTurn)) { + const nextState = + existingTurn.value.state === "completed" || existingTurn.value.state === "error" + ? existingTurn.value.state + : "running"; + yield* projectionTurnRepository.upsertByTurnId({ + ...existingTurn.value, + state: nextState, + pendingMessageId: + existingTurn.value.pendingMessageId ?? + (Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null), + sourceProposedPlanThreadId: + existingTurn.value.sourceProposedPlanThreadId ?? + (Option.isSome(pendingTurnStart) + ? pendingTurnStart.value.sourceProposedPlanThreadId + : null), + sourceProposedPlanId: + existingTurn.value.sourceProposedPlanId ?? + (Option.isSome(pendingTurnStart) + ? pendingTurnStart.value.sourceProposedPlanId + : null), + startedAt: + existingTurn.value.startedAt ?? + (Option.isSome(pendingTurnStart) + ? pendingTurnStart.value.requestedAt + : event.occurredAt), + requestedAt: + existingTurn.value.requestedAt ?? + (Option.isSome(pendingTurnStart) + ? pendingTurnStart.value.requestedAt + : event.occurredAt), + }); + } else { + yield* projectionTurnRepository.upsertByTurnId({ + turnId, + threadId: event.payload.threadId, + pendingMessageId: Option.isSome(pendingTurnStart) + ? pendingTurnStart.value.messageId + : null, + sourceProposedPlanThreadId: Option.isSome(pendingTurnStart) + ? pendingTurnStart.value.sourceProposedPlanThreadId + : null, + sourceProposedPlanId: Option.isSome(pendingTurnStart) + ? pendingTurnStart.value.sourceProposedPlanId + : null, + assistantMessageId: null, + state: "running", + requestedAt: Option.isSome(pendingTurnStart) + ? pendingTurnStart.value.requestedAt + : event.occurredAt, + startedAt: Option.isSome(pendingTurnStart) + ? pendingTurnStart.value.requestedAt + : event.occurredAt, + completedAt: null, + checkpointTurnCount: null, + checkpointRef: null, + checkpointStatus: null, + checkpointFiles: [], + }); + } + + yield* projectionTurnRepository.deletePendingTurnStartByThreadId({ + threadId: event.payload.threadId, + }); + return; + } + + case "thread.message-sent": { + if (event.payload.turnId === null || event.payload.role !== "assistant") { + return; + } + const existingTurn = yield* projectionTurnRepository.getByTurnId({ + threadId: event.payload.threadId, + turnId: event.payload.turnId, + }); + if (Option.isSome(existingTurn)) { + yield* projectionTurnRepository.upsertByTurnId({ + ...existingTurn.value, + assistantMessageId: event.payload.messageId, + state: event.payload.streaming + ? existingTurn.value.state + : existingTurn.value.state === "interrupted" + ? "interrupted" + : existingTurn.value.state === "error" + ? "error" + : "completed", + completedAt: event.payload.streaming + ? existingTurn.value.completedAt + : (existingTurn.value.completedAt ?? event.payload.updatedAt), + startedAt: existingTurn.value.startedAt ?? event.payload.createdAt, + requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt, + }); + return; + } + yield* projectionTurnRepository.upsertByTurnId({ + turnId: event.payload.turnId, + threadId: event.payload.threadId, + pendingMessageId: null, + sourceProposedPlanThreadId: null, + sourceProposedPlanId: null, + assistantMessageId: event.payload.messageId, + state: event.payload.streaming ? "running" : "completed", + requestedAt: event.payload.createdAt, + startedAt: event.payload.createdAt, + completedAt: event.payload.streaming ? null : event.payload.updatedAt, + checkpointTurnCount: null, + checkpointRef: null, + checkpointStatus: null, + checkpointFiles: [], + }); + return; + } + + case "thread.turn-interrupt-requested": { + if (event.payload.turnId === undefined) { + return; + } + const existingTurn = yield* projectionTurnRepository.getByTurnId({ + threadId: event.payload.threadId, + turnId: event.payload.turnId, + }); + if (Option.isSome(existingTurn)) { + yield* projectionTurnRepository.upsertByTurnId({ + ...existingTurn.value, + state: "interrupted", + completedAt: existingTurn.value.completedAt ?? event.payload.createdAt, + startedAt: existingTurn.value.startedAt ?? event.payload.createdAt, + requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt, + }); + return; + } + yield* projectionTurnRepository.upsertByTurnId({ + turnId: event.payload.turnId, + threadId: event.payload.threadId, + pendingMessageId: null, + sourceProposedPlanThreadId: null, + sourceProposedPlanId: null, + assistantMessageId: null, + state: "interrupted", + requestedAt: event.payload.createdAt, + startedAt: event.payload.createdAt, + completedAt: event.payload.createdAt, + checkpointTurnCount: null, + checkpointRef: null, + checkpointStatus: null, + checkpointFiles: [], + }); + return; + } + + case "thread.turn-diff-completed": { + const existingTurn = yield* projectionTurnRepository.getByTurnId({ + threadId: event.payload.threadId, + turnId: event.payload.turnId, + }); + const nextState = event.payload.status === "error" ? "error" : "completed"; + yield* projectionTurnRepository.clearCheckpointTurnConflict({ + threadId: event.payload.threadId, + turnId: event.payload.turnId, + checkpointTurnCount: event.payload.checkpointTurnCount, + }); + + if (Option.isSome(existingTurn)) { + yield* projectionTurnRepository.upsertByTurnId({ + ...existingTurn.value, + assistantMessageId: event.payload.assistantMessageId, + state: nextState, + checkpointTurnCount: event.payload.checkpointTurnCount, + checkpointRef: event.payload.checkpointRef, + checkpointStatus: event.payload.status, + checkpointFiles: event.payload.files, + startedAt: existingTurn.value.startedAt ?? event.payload.completedAt, + requestedAt: existingTurn.value.requestedAt ?? event.payload.completedAt, + completedAt: event.payload.completedAt, + }); + return; + } + yield* projectionTurnRepository.upsertByTurnId({ + turnId: event.payload.turnId, + threadId: event.payload.threadId, + pendingMessageId: null, + sourceProposedPlanThreadId: null, + sourceProposedPlanId: null, + assistantMessageId: event.payload.assistantMessageId, + state: nextState, + requestedAt: event.payload.completedAt, + startedAt: event.payload.completedAt, + completedAt: event.payload.completedAt, + checkpointTurnCount: event.payload.checkpointTurnCount, + checkpointRef: event.payload.checkpointRef, + checkpointStatus: event.payload.status, + checkpointFiles: event.payload.files, + }); + return; + } + + case "thread.reverted": { + const existingTurns = yield* projectionTurnRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + const keptTurns = existingTurns.filter( + (turn) => + turn.turnId !== null && + turn.checkpointTurnCount !== null && + turn.checkpointTurnCount <= event.payload.turnCount, + ); + yield* projectionTurnRepository.deleteByThreadId({ + threadId: event.payload.threadId, + }); + yield* Effect.forEach( + keptTurns, + (turn) => + turn.turnId === null + ? Effect.void + : projectionTurnRepository.upsertByTurnId({ + ...turn, + turnId: turn.turnId, + }), + { concurrency: 1 }, + ).pipe(Effect.asVoid); + return; + } + + default: + return; + } + }); + + const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void; + + const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyPendingApprovalsProjection", + )(function* (event, _attachmentSideEffects) { + switch (event.type) { + case "thread.activity-appended": { + const requestId = + extractActivityRequestId(event.payload.activity.payload) ?? + event.metadata.requestId ?? + null; + if (requestId === null) { + return; + } + const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({ + requestId, + }); + if (event.payload.activity.kind === "approval.resolved") { + const resolvedDecisionRaw = + typeof event.payload.activity.payload === "object" && + event.payload.activity.payload !== null && + "decision" in event.payload.activity.payload + ? (event.payload.activity.payload as { decision?: unknown }).decision + : null; + const resolvedDecision = + resolvedDecisionRaw === "accept" || + resolvedDecisionRaw === "acceptForSession" || + resolvedDecisionRaw === "decline" || + resolvedDecisionRaw === "cancel" + ? resolvedDecisionRaw + : null; + yield* projectionPendingApprovalRepository.upsert({ + requestId, + threadId: Option.isSome(existingRow) + ? existingRow.value.threadId + : event.payload.threadId, + turnId: Option.isSome(existingRow) + ? existingRow.value.turnId + : event.payload.activity.turnId, + status: "resolved", + decision: resolvedDecision, + createdAt: Option.isSome(existingRow) + ? existingRow.value.createdAt + : event.payload.activity.createdAt, + resolvedAt: event.payload.activity.createdAt, + }); + return; + } + if (Option.isSome(existingRow) && existingRow.value.status === "resolved") { + return; + } + yield* projectionPendingApprovalRepository.upsert({ + requestId, + threadId: event.payload.threadId, + turnId: event.payload.activity.turnId, + status: "pending", + decision: null, + createdAt: Option.isSome(existingRow) + ? existingRow.value.createdAt + : event.payload.activity.createdAt, + resolvedAt: null, + }); + return; + } + + case "thread.approval-response-requested": { + const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({ + requestId: event.payload.requestId, + }); + yield* projectionPendingApprovalRepository.upsert({ + requestId: event.payload.requestId, + threadId: Option.isSome(existingRow) + ? existingRow.value.threadId + : event.payload.threadId, + turnId: Option.isSome(existingRow) ? existingRow.value.turnId : null, + status: "resolved", + decision: event.payload.decision, + createdAt: Option.isSome(existingRow) + ? existingRow.value.createdAt + : event.payload.createdAt, + resolvedAt: event.payload.createdAt, + }); + return; + } + + default: + return; + } + }); + + const projectors: ReadonlyArray = [ + { + name: ORCHESTRATION_PROJECTOR_NAMES.projects, + apply: applyProjectsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages, + apply: applyThreadMessagesProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans, + apply: applyThreadProposedPlansProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities, + apply: applyThreadActivitiesProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions, + apply: applyThreadSessionsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns, + apply: applyThreadTurnsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints, + apply: applyCheckpointsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals, + apply: applyPendingApprovalsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threads, + apply: applyThreadsProjection, + }, + ]; + + const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* ( + projector: ProjectorDefinition, + event: OrchestrationEvent, + ) { + const attachmentSideEffects: AttachmentSideEffects = { + deletedThreadIds: new Set(), + prunedThreadRelativePaths: new Map>(), + }; + + yield* sql.withTransaction( + projector.apply(event, attachmentSideEffects).pipe( + Effect.flatMap(() => + projectionStateRepository.upsert({ + projector: projector.name, + lastAppliedSequence: event.sequence, + updatedAt: event.occurredAt, + }), + ), + ), + ); + + yield* runAttachmentSideEffects(attachmentSideEffects).pipe( + Effect.catch((cause) => + Effect.logWarning("failed to apply projected attachment side-effects", { + projector: projector.name, + sequence: event.sequence, + eventType: event.type, + cause, + }), + ), + ); + }); + + const bootstrapProjector = (projector: ProjectorDefinition) => + projectionStateRepository + .getByProjector({ + projector: projector.name, + }) + .pipe( + Effect.flatMap((stateRow) => + Stream.runForEach( + eventStore.readFromSequence( + Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0, + ), + (event) => runProjectorForEvent(projector, event), + ), + ), + ); + + const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) => + Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), { + concurrency: 1, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(ServerConfig, serverConfig), + Effect.asVoid, + Effect.catchTag("SqlError", (sqlError) => + Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)), + ), + ); + + const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach( + projectors, + bootstrapProjector, + { concurrency: 1 }, + ).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(ServerConfig, serverConfig), + Effect.asVoid, + Effect.tap(() => + Effect.logDebug("orchestration projection pipeline bootstrapped").pipe( + Effect.annotateLogs({ projectors: projectors.length }), + ), + ), + Effect.catchTag("SqlError", (sqlError) => + Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)), + ), + ); + + return { + bootstrap, + projectEvent, + } satisfies OrchestrationProjectionPipelineShape; + }, +); + +export const OrchestrationProjectionPipelineLive = Layer.effect( + OrchestrationProjectionPipeline, + makeOrchestrationProjectionPipeline(), +).pipe( + Layer.provideMerge(ProjectionProjectRepositoryLive), + Layer.provideMerge(ProjectionThreadRepositoryLive), + Layer.provideMerge(ProjectionThreadMessageRepositoryLive), + Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive), + Layer.provideMerge(ProjectionThreadActivityRepositoryLive), + Layer.provideMerge(ProjectionThreadSessionRepositoryLive), + Layer.provideMerge(ProjectionTurnRepositoryLive), + Layer.provideMerge(ProjectionPendingApprovalRepositoryLive), + Layer.provideMerge(ProjectionStateRepositoryLive), +); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts new file mode 100644 index 0000000000..c038bc9d2c --- /dev/null +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -0,0 +1,627 @@ +import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; +import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; + +const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); +const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); +const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); +const asEventId = (value: string): EventId => EventId.makeUnsafe(value); +const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value); + +const projectionSnapshotLayer = it.layer( + OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)), +); + +projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { + it.effect("hydrates read model from projection tables and computes snapshot sequence", () => + Effect.gen(function* () { + const snapshotQuery = yield* ProjectionSnapshotQuery; + const sql = yield* SqlClient.SqlClient; + + yield* sql`DELETE FROM projection_projects`; + yield* sql`DELETE FROM projection_state`; + yield* sql`DELETE FROM projection_thread_proposed_plans`; + yield* sql`DELETE FROM projection_turns`; + + yield* sql` + INSERT INTO projection_projects ( + project_id, + title, + workspace_root, + default_model_selection_json, + scripts_json, + created_at, + updated_at, + deleted_at + ) + VALUES ( + 'project-1', + 'Project 1', + '/tmp/project-1', + '{"provider":"codex","model":"gpt-5-codex"}', + '[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]', + '2026-02-24T00:00:00.000Z', + '2026-02-24T00:00:01.000Z', + NULL + ) + `; + + yield* sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model_selection_json, + branch, + worktree_path, + latest_turn_id, + created_at, + updated_at, + deleted_at + ) + VALUES ( + 'thread-1', + 'project-1', + 'Thread 1', + '{"provider":"codex","model":"gpt-5-codex"}', + NULL, + NULL, + 'turn-1', + '2026-02-24T00:00:02.000Z', + '2026-02-24T00:00:03.000Z', + NULL + ) + `; + + yield* sql` + INSERT INTO projection_thread_messages ( + message_id, + thread_id, + turn_id, + role, + text, + is_streaming, + created_at, + updated_at + ) + VALUES ( + 'message-1', + 'thread-1', + 'turn-1', + 'assistant', + 'hello from projection', + 0, + '2026-02-24T00:00:04.000Z', + '2026-02-24T00:00:05.000Z' + ) + `; + + yield* sql` + INSERT INTO projection_thread_proposed_plans ( + plan_id, + thread_id, + turn_id, + plan_markdown, + implemented_at, + implementation_thread_id, + created_at, + updated_at + ) + VALUES ( + 'plan-1', + 'thread-1', + 'turn-1', + '# Ship it', + '2026-02-24T00:00:05.500Z', + 'thread-2', + '2026-02-24T00:00:05.000Z', + '2026-02-24T00:00:05.500Z' + ) + `; + + yield* sql` + INSERT INTO projection_thread_activities ( + activity_id, + thread_id, + turn_id, + tone, + kind, + summary, + payload_json, + created_at + ) + VALUES ( + 'activity-1', + 'thread-1', + 'turn-1', + 'info', + 'runtime.note', + 'provider started', + '{"stage":"start"}', + '2026-02-24T00:00:06.000Z' + ) + `; + + yield* sql` + INSERT INTO projection_thread_sessions ( + thread_id, + status, + provider_name, + provider_session_id, + provider_thread_id, + runtime_mode, + active_turn_id, + last_error, + updated_at + ) + VALUES ( + 'thread-1', + 'running', + 'codex', + 'provider-session-1', + 'provider-thread-1', + 'approval-required', + 'turn-1', + NULL, + '2026-02-24T00:00:07.000Z' + ) + `; + + yield* sql` + INSERT INTO projection_turns ( + thread_id, + turn_id, + pending_message_id, + source_proposed_plan_thread_id, + source_proposed_plan_id, + assistant_message_id, + state, + requested_at, + started_at, + completed_at, + checkpoint_turn_count, + checkpoint_ref, + checkpoint_status, + checkpoint_files_json + ) + VALUES ( + 'thread-1', + 'turn-1', + NULL, + 'thread-1', + 'plan-1', + 'message-1', + 'completed', + '2026-02-24T00:00:08.000Z', + '2026-02-24T00:00:08.000Z', + '2026-02-24T00:00:08.000Z', + 1, + 'checkpoint-1', + 'ready', + '[{"path":"README.md","kind":"modified","additions":2,"deletions":1}]' + ) + `; + + let sequence = 5; + for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) { + yield* sql` + INSERT INTO projection_state ( + projector, + last_applied_sequence, + updated_at + ) + VALUES ( + ${projector}, + ${sequence}, + '2026-02-24T00:00:09.000Z' + ) + `; + sequence += 1; + } + + const snapshot = yield* snapshotQuery.getSnapshot(); + + assert.equal(snapshot.snapshotSequence, 5); + assert.equal(snapshot.updatedAt, "2026-02-24T00:00:09.000Z"); + assert.deepEqual(snapshot.projects, [ + { + id: asProjectId("project-1"), + title: "Project 1", + workspaceRoot: "/tmp/project-1", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + scripts: [ + { + id: "script-1", + name: "Build", + command: "bun run build", + icon: "build", + runOnWorktreeCreate: false, + }, + ], + createdAt: "2026-02-24T00:00:00.000Z", + updatedAt: "2026-02-24T00:00:01.000Z", + deletedAt: null, + }, + ]); + assert.deepEqual(snapshot.threads, [ + { + id: ThreadId.makeUnsafe("thread-1"), + projectId: asProjectId("project-1"), + title: "Thread 1", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: "default", + runtimeMode: "full-access", + branch: null, + worktreePath: null, + latestTurn: { + turnId: asTurnId("turn-1"), + state: "completed", + requestedAt: "2026-02-24T00:00:08.000Z", + startedAt: "2026-02-24T00:00:08.000Z", + completedAt: "2026-02-24T00:00:08.000Z", + assistantMessageId: asMessageId("message-1"), + sourceProposedPlan: { + threadId: ThreadId.makeUnsafe("thread-1"), + planId: "plan-1", + }, + }, + createdAt: "2026-02-24T00:00:02.000Z", + updatedAt: "2026-02-24T00:00:03.000Z", + archivedAt: null, + deletedAt: null, + messages: [ + { + id: asMessageId("message-1"), + role: "assistant", + text: "hello from projection", + turnId: asTurnId("turn-1"), + streaming: false, + createdAt: "2026-02-24T00:00:04.000Z", + updatedAt: "2026-02-24T00:00:05.000Z", + }, + ], + proposedPlans: [ + { + id: "plan-1", + turnId: asTurnId("turn-1"), + planMarkdown: "# Ship it", + implementedAt: "2026-02-24T00:00:05.500Z", + implementationThreadId: ThreadId.makeUnsafe("thread-2"), + createdAt: "2026-02-24T00:00:05.000Z", + updatedAt: "2026-02-24T00:00:05.500Z", + }, + ], + activities: [ + { + id: asEventId("activity-1"), + tone: "info", + kind: "runtime.note", + summary: "provider started", + payload: { stage: "start" }, + turnId: asTurnId("turn-1"), + createdAt: "2026-02-24T00:00:06.000Z", + }, + ], + checkpoints: [ + { + turnId: asTurnId("turn-1"), + checkpointTurnCount: 1, + checkpointRef: asCheckpointRef("checkpoint-1"), + status: "ready", + files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }], + assistantMessageId: asMessageId("message-1"), + completedAt: "2026-02-24T00:00:08.000Z", + }, + ], + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: asTurnId("turn-1"), + lastError: null, + updatedAt: "2026-02-24T00:00:07.000Z", + }, + }, + ]); + }), + ); + + it.effect( + "reads targeted project, thread, and count queries without hydrating the full snapshot", + () => + Effect.gen(function* () { + const snapshotQuery = yield* ProjectionSnapshotQuery; + const sql = yield* SqlClient.SqlClient; + + yield* sql`DELETE FROM projection_projects`; + yield* sql`DELETE FROM projection_threads`; + yield* sql`DELETE FROM projection_turns`; + + yield* sql` + INSERT INTO projection_projects ( + project_id, + title, + workspace_root, + default_model_selection_json, + scripts_json, + created_at, + updated_at, + deleted_at + ) + VALUES + ( + 'project-active', + 'Active Project', + '/tmp/workspace', + '{"provider":"codex","model":"gpt-5-codex"}', + '[]', + '2026-03-01T00:00:00.000Z', + '2026-03-01T00:00:01.000Z', + NULL + ), + ( + 'project-deleted', + 'Deleted Project', + '/tmp/deleted', + NULL, + '[]', + '2026-03-01T00:00:02.000Z', + '2026-03-01T00:00:03.000Z', + '2026-03-01T00:00:04.000Z' + ) + `; + + yield* sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model_selection_json, + runtime_mode, + interaction_mode, + branch, + worktree_path, + latest_turn_id, + created_at, + updated_at, + archived_at, + deleted_at + ) + VALUES + ( + 'thread-first', + 'project-active', + 'First Thread', + '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', + 'default', + NULL, + NULL, + NULL, + '2026-03-01T00:00:05.000Z', + '2026-03-01T00:00:06.000Z', + NULL, + NULL + ), + ( + 'thread-second', + 'project-active', + 'Second Thread', + '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', + 'default', + NULL, + NULL, + NULL, + '2026-03-01T00:00:07.000Z', + '2026-03-01T00:00:08.000Z', + NULL, + NULL + ), + ( + 'thread-deleted', + 'project-active', + 'Deleted Thread', + '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', + 'default', + NULL, + NULL, + NULL, + '2026-03-01T00:00:09.000Z', + '2026-03-01T00:00:10.000Z', + NULL, + '2026-03-01T00:00:11.000Z' + ) + `; + + const counts = yield* snapshotQuery.getCounts(); + assert.deepEqual(counts, { + projectCount: 2, + threadCount: 3, + }); + + const project = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/workspace"); + assert.equal(project._tag, "Some"); + if (project._tag === "Some") { + assert.equal(project.value.id, asProjectId("project-active")); + } + + const missingProject = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/missing"); + assert.equal(missingProject._tag, "None"); + + const firstThreadId = yield* snapshotQuery.getFirstActiveThreadIdByProjectId( + asProjectId("project-active"), + ); + assert.equal(firstThreadId._tag, "Some"); + if (firstThreadId._tag === "Some") { + assert.equal(firstThreadId.value, ThreadId.makeUnsafe("thread-first")); + } + }), + ); + + it.effect("reads single-thread checkpoint context without hydrating unrelated threads", () => + Effect.gen(function* () { + const snapshotQuery = yield* ProjectionSnapshotQuery; + const sql = yield* SqlClient.SqlClient; + + yield* sql`DELETE FROM projection_projects`; + yield* sql`DELETE FROM projection_threads`; + yield* sql`DELETE FROM projection_turns`; + + yield* sql` + INSERT INTO projection_projects ( + project_id, + title, + workspace_root, + default_model_selection_json, + scripts_json, + created_at, + updated_at, + deleted_at + ) + VALUES ( + 'project-context', + 'Context Project', + '/tmp/context-workspace', + NULL, + '[]', + '2026-03-02T00:00:00.000Z', + '2026-03-02T00:00:01.000Z', + NULL + ) + `; + + yield* sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model_selection_json, + runtime_mode, + interaction_mode, + branch, + worktree_path, + latest_turn_id, + created_at, + updated_at, + archived_at, + deleted_at + ) + VALUES ( + 'thread-context', + 'project-context', + 'Context Thread', + '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', + 'default', + 'feature/perf', + '/tmp/context-worktree', + NULL, + '2026-03-02T00:00:02.000Z', + '2026-03-02T00:00:03.000Z', + NULL, + NULL + ) + `; + + yield* sql` + INSERT INTO projection_turns ( + thread_id, + turn_id, + pending_message_id, + source_proposed_plan_thread_id, + source_proposed_plan_id, + assistant_message_id, + state, + requested_at, + started_at, + completed_at, + checkpoint_turn_count, + checkpoint_ref, + checkpoint_status, + checkpoint_files_json + ) + VALUES + ( + 'thread-context', + 'turn-1', + NULL, + NULL, + NULL, + NULL, + 'completed', + '2026-03-02T00:00:04.000Z', + '2026-03-02T00:00:04.000Z', + '2026-03-02T00:00:04.000Z', + 1, + 'checkpoint-a', + 'ready', + '[]' + ), + ( + 'thread-context', + 'turn-2', + NULL, + NULL, + NULL, + NULL, + 'completed', + '2026-03-02T00:00:05.000Z', + '2026-03-02T00:00:05.000Z', + '2026-03-02T00:00:05.000Z', + 2, + 'checkpoint-b', + 'ready', + '[]' + ) + `; + + const context = yield* snapshotQuery.getThreadCheckpointContext( + ThreadId.makeUnsafe("thread-context"), + ); + assert.equal(context._tag, "Some"); + if (context._tag === "Some") { + assert.deepEqual(context.value, { + threadId: ThreadId.makeUnsafe("thread-context"), + projectId: asProjectId("project-context"), + workspaceRoot: "/tmp/context-workspace", + worktreePath: "/tmp/context-worktree", + checkpoints: [ + { + turnId: asTurnId("turn-1"), + checkpointTurnCount: 1, + checkpointRef: asCheckpointRef("checkpoint-a"), + status: "ready", + files: [], + assistantMessageId: null, + completedAt: "2026-03-02T00:00:04.000Z", + }, + { + turnId: asTurnId("turn-2"), + checkpointTurnCount: 2, + checkpointRef: asCheckpointRef("checkpoint-b"), + status: "ready", + files: [], + assistantMessageId: null, + completedAt: "2026-03-02T00:00:05.000Z", + }, + ], + }); + } + }), + ); +}); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts new file mode 100644 index 0000000000..da7c695674 --- /dev/null +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -0,0 +1,819 @@ +import { + ChatAttachment, + IsoDateTime, + MessageId, + NonNegativeInt, + OrchestrationCheckpointFile, + OrchestrationProposedPlanId, + OrchestrationReadModel, + ProjectScript, + TurnId, + type OrchestrationCheckpointSummary, + type OrchestrationLatestTurn, + type OrchestrationMessage, + type OrchestrationProposedPlan, + type OrchestrationProject, + type OrchestrationSession, + type OrchestrationThread, + type OrchestrationThreadActivity, + ModelSelection, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { Effect, Layer, Option, Schema, Struct } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; + +import { + isPersistenceError, + toPersistenceDecodeError, + toPersistenceSqlError, + type ProjectionRepositoryError, +} from "../../persistence/Errors.ts"; +import { ProjectionCheckpoint } from "../../persistence/Services/ProjectionCheckpoints.ts"; +import { ProjectionProject } from "../../persistence/Services/ProjectionProjects.ts"; +import { ProjectionState } from "../../persistence/Services/ProjectionState.ts"; +import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts"; +import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts"; +import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts"; +import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts"; +import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts"; +import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts"; +import { + ProjectionSnapshotQuery, + type ProjectionSnapshotCounts, + type ProjectionThreadCheckpointContext, + type ProjectionSnapshotQueryShape, +} from "../Services/ProjectionSnapshotQuery.ts"; + +const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel); +const ProjectionProjectDbRowSchema = ProjectionProject.mapFields( + Struct.assign({ + defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)), + scripts: Schema.fromJsonString(Schema.Array(ProjectScript)), + }), +); +const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( + Struct.assign({ + isStreaming: Schema.Number, + attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))), + }), +); +const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan; +const ProjectionThreadDbRowSchema = ProjectionThread.mapFields( + Struct.assign({ + modelSelection: Schema.fromJsonString(ModelSelection), + }), +); +const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields( + Struct.assign({ + payload: Schema.fromJsonString(Schema.Unknown), + sequence: Schema.NullOr(NonNegativeInt), + }), +); +const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession; +const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields( + Struct.assign({ + files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)), + }), +); +const ProjectionLatestTurnDbRowSchema = Schema.Struct({ + threadId: ProjectionThread.fields.threadId, + turnId: TurnId, + state: Schema.String, + requestedAt: IsoDateTime, + startedAt: Schema.NullOr(IsoDateTime), + completedAt: Schema.NullOr(IsoDateTime), + assistantMessageId: Schema.NullOr(MessageId), + sourceProposedPlanThreadId: Schema.NullOr(ThreadId), + sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId), +}); +const ProjectionStateDbRowSchema = ProjectionState; +const ProjectionCountsRowSchema = Schema.Struct({ + projectCount: Schema.Number, + threadCount: Schema.Number, +}); +const WorkspaceRootLookupInput = Schema.Struct({ + workspaceRoot: Schema.String, +}); +const ProjectIdLookupInput = Schema.Struct({ + projectId: ProjectId, +}); +const ThreadIdLookupInput = Schema.Struct({ + threadId: ThreadId, +}); +const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema; +const ProjectionThreadIdLookupRowSchema = Schema.Struct({ + threadId: ThreadId, +}); +const ProjectionThreadCheckpointContextThreadRowSchema = Schema.Struct({ + threadId: ThreadId, + projectId: ProjectId, + workspaceRoot: Schema.String, + worktreePath: Schema.NullOr(Schema.String), +}); + +const REQUIRED_SNAPSHOT_PROJECTORS = [ + ORCHESTRATION_PROJECTOR_NAMES.projects, + ORCHESTRATION_PROJECTOR_NAMES.threads, + ORCHESTRATION_PROJECTOR_NAMES.threadMessages, + ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans, + ORCHESTRATION_PROJECTOR_NAMES.threadActivities, + ORCHESTRATION_PROJECTOR_NAMES.threadSessions, + ORCHESTRATION_PROJECTOR_NAMES.checkpoints, +] as const; + +function maxIso(left: string | null, right: string): string { + if (left === null) { + return right; + } + return left > right ? left : right; +} + +function computeSnapshotSequence( + stateRows: ReadonlyArray>, +): number { + if (stateRows.length === 0) { + return 0; + } + const sequenceByProjector = new Map( + stateRows.map((row) => [row.projector, row.lastAppliedSequence] as const), + ); + + let minSequence = Number.POSITIVE_INFINITY; + for (const projector of REQUIRED_SNAPSHOT_PROJECTORS) { + const sequence = sequenceByProjector.get(projector); + if (sequence === undefined) { + return 0; + } + if (sequence < minSequence) { + minSequence = sequence; + } + } + + return Number.isFinite(minSequence) ? minSequence : 0; +} + +function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { + return (cause: unknown): ProjectionRepositoryError => + Schema.isSchemaError(cause) + ? toPersistenceDecodeError(decodeOperation)(cause) + : toPersistenceSqlError(sqlOperation)(cause); +} + +const makeProjectionSnapshotQuery = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const listProjectRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionProjectDbRowSchema, + execute: () => + sql` + SELECT + project_id AS "projectId", + title, + workspace_root AS "workspaceRoot", + default_model_selection_json AS "defaultModelSelection", + scripts_json AS "scripts", + created_at AS "createdAt", + updated_at AS "updatedAt", + deleted_at AS "deletedAt" + FROM projection_projects + ORDER BY created_at ASC, project_id ASC + `, + }); + + const listThreadRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionThreadDbRowSchema, + execute: () => + sql` + SELECT + thread_id AS "threadId", + project_id AS "projectId", + title, + model_selection_json AS "modelSelection", + runtime_mode AS "runtimeMode", + interaction_mode AS "interactionMode", + branch, + worktree_path AS "worktreePath", + latest_turn_id AS "latestTurnId", + created_at AS "createdAt", + updated_at AS "updatedAt", + archived_at AS "archivedAt", + deleted_at AS "deletedAt" + FROM projection_threads + ORDER BY created_at ASC, thread_id ASC + `, + }); + + const listThreadMessageRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionThreadMessageDbRowSchema, + execute: () => + sql` + SELECT + message_id AS "messageId", + thread_id AS "threadId", + turn_id AS "turnId", + role, + text, + attachments_json AS "attachments", + is_streaming AS "isStreaming", + created_at AS "createdAt", + updated_at AS "updatedAt" + FROM projection_thread_messages + ORDER BY thread_id ASC, created_at ASC, message_id ASC + `, + }); + + const listThreadProposedPlanRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionThreadProposedPlanDbRowSchema, + execute: () => + sql` + SELECT + plan_id AS "planId", + thread_id AS "threadId", + turn_id AS "turnId", + plan_markdown AS "planMarkdown", + implemented_at AS "implementedAt", + implementation_thread_id AS "implementationThreadId", + created_at AS "createdAt", + updated_at AS "updatedAt" + FROM projection_thread_proposed_plans + ORDER BY thread_id ASC, created_at ASC, plan_id ASC + `, + }); + + const listThreadActivityRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionThreadActivityDbRowSchema, + execute: () => + sql` + SELECT + activity_id AS "activityId", + thread_id AS "threadId", + turn_id AS "turnId", + tone, + kind, + summary, + payload_json AS "payload", + sequence, + created_at AS "createdAt" + FROM projection_thread_activities + ORDER BY + thread_id ASC, + CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC, + sequence ASC, + created_at ASC, + activity_id ASC + `, + }); + + const listThreadSessionRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionThreadSessionDbRowSchema, + execute: () => + sql` + SELECT + thread_id AS "threadId", + status, + provider_name AS "providerName", + provider_session_id AS "providerSessionId", + provider_thread_id AS "providerThreadId", + runtime_mode AS "runtimeMode", + active_turn_id AS "activeTurnId", + last_error AS "lastError", + updated_at AS "updatedAt" + FROM projection_thread_sessions + ORDER BY thread_id ASC + `, + }); + + const listCheckpointRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionCheckpointDbRowSchema, + execute: () => + sql` + SELECT + thread_id AS "threadId", + turn_id AS "turnId", + checkpoint_turn_count AS "checkpointTurnCount", + checkpoint_ref AS "checkpointRef", + checkpoint_status AS "status", + checkpoint_files_json AS "files", + assistant_message_id AS "assistantMessageId", + completed_at AS "completedAt" + FROM projection_turns + WHERE checkpoint_turn_count IS NOT NULL + ORDER BY thread_id ASC, checkpoint_turn_count ASC + `, + }); + + const listLatestTurnRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionLatestTurnDbRowSchema, + execute: () => + sql` + SELECT + thread_id AS "threadId", + turn_id AS "turnId", + state, + requested_at AS "requestedAt", + started_at AS "startedAt", + completed_at AS "completedAt", + assistant_message_id AS "assistantMessageId", + source_proposed_plan_thread_id AS "sourceProposedPlanThreadId", + source_proposed_plan_id AS "sourceProposedPlanId" + FROM projection_turns + WHERE turn_id IS NOT NULL + ORDER BY thread_id ASC, requested_at DESC, turn_id DESC + `, + }); + + const listProjectionStateRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionStateDbRowSchema, + execute: () => + sql` + SELECT + projector, + last_applied_sequence AS "lastAppliedSequence", + updated_at AS "updatedAt" + FROM projection_state + `, + }); + + const readProjectionCounts = SqlSchema.findOne({ + Request: Schema.Void, + Result: ProjectionCountsRowSchema, + execute: () => + sql` + SELECT + (SELECT COUNT(*) FROM projection_projects) AS "projectCount", + (SELECT COUNT(*) FROM projection_threads) AS "threadCount" + `, + }); + + const getActiveProjectRowByWorkspaceRoot = SqlSchema.findOneOption({ + Request: WorkspaceRootLookupInput, + Result: ProjectionProjectLookupRowSchema, + execute: ({ workspaceRoot }) => + sql` + SELECT + project_id AS "projectId", + title, + workspace_root AS "workspaceRoot", + default_model_selection_json AS "defaultModelSelection", + scripts_json AS "scripts", + created_at AS "createdAt", + updated_at AS "updatedAt", + deleted_at AS "deletedAt" + FROM projection_projects + WHERE workspace_root = ${workspaceRoot} + AND deleted_at IS NULL + ORDER BY created_at ASC, project_id ASC + LIMIT 1 + `, + }); + + const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({ + Request: ProjectIdLookupInput, + Result: ProjectionThreadIdLookupRowSchema, + execute: ({ projectId }) => + sql` + SELECT + thread_id AS "threadId" + FROM projection_threads + WHERE project_id = ${projectId} + AND deleted_at IS NULL + ORDER BY created_at ASC, thread_id ASC + LIMIT 1 + `, + }); + + const getThreadCheckpointContextThreadRow = SqlSchema.findOneOption({ + Request: ThreadIdLookupInput, + Result: ProjectionThreadCheckpointContextThreadRowSchema, + execute: ({ threadId }) => + sql` + SELECT + threads.thread_id AS "threadId", + threads.project_id AS "projectId", + projects.workspace_root AS "workspaceRoot", + threads.worktree_path AS "worktreePath" + FROM projection_threads AS threads + INNER JOIN projection_projects AS projects + ON projects.project_id = threads.project_id + WHERE threads.thread_id = ${threadId} + AND threads.deleted_at IS NULL + LIMIT 1 + `, + }); + + const listCheckpointRowsByThread = SqlSchema.findAll({ + Request: ThreadIdLookupInput, + Result: ProjectionCheckpointDbRowSchema, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + turn_id AS "turnId", + checkpoint_turn_count AS "checkpointTurnCount", + checkpoint_ref AS "checkpointRef", + checkpoint_status AS "status", + checkpoint_files_json AS "files", + assistant_message_id AS "assistantMessageId", + completed_at AS "completedAt" + FROM projection_turns + WHERE thread_id = ${threadId} + AND checkpoint_turn_count IS NOT NULL + ORDER BY checkpoint_turn_count ASC + `, + }); + + const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () => + sql + .withTransaction( + Effect.gen(function* () { + const [ + projectRows, + threadRows, + messageRows, + proposedPlanRows, + activityRows, + sessionRows, + checkpointRows, + latestTurnRows, + stateRows, + ] = yield* Effect.all([ + listProjectRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listProjects:query", + "ProjectionSnapshotQuery.getSnapshot:listProjects:decodeRows", + ), + ), + ), + listThreadRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listThreads:query", + "ProjectionSnapshotQuery.getSnapshot:listThreads:decodeRows", + ), + ), + ), + listThreadMessageRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query", + "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows", + ), + ), + ), + listThreadProposedPlanRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query", + "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows", + ), + ), + ), + listThreadActivityRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query", + "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows", + ), + ), + ), + listThreadSessionRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query", + "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows", + ), + ), + ), + listCheckpointRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query", + "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows", + ), + ), + ), + listLatestTurnRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query", + "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows", + ), + ), + ), + listProjectionStateRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listProjectionState:query", + "ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows", + ), + ), + ), + ]); + + const messagesByThread = new Map>(); + const proposedPlansByThread = new Map>(); + const activitiesByThread = new Map>(); + const checkpointsByThread = new Map>(); + const sessionsByThread = new Map(); + const latestTurnByThread = new Map(); + + let updatedAt: string | null = null; + + for (const row of projectRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + } + for (const row of threadRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + } + for (const row of stateRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + } + + for (const row of messageRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + const threadMessages = messagesByThread.get(row.threadId) ?? []; + threadMessages.push({ + id: row.messageId, + role: row.role, + text: row.text, + ...(row.attachments !== null ? { attachments: row.attachments } : {}), + turnId: row.turnId, + streaming: row.isStreaming === 1, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + }); + messagesByThread.set(row.threadId, threadMessages); + } + + for (const row of proposedPlanRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? []; + threadProposedPlans.push({ + id: row.planId, + turnId: row.turnId, + planMarkdown: row.planMarkdown, + implementedAt: row.implementedAt, + implementationThreadId: row.implementationThreadId, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + }); + proposedPlansByThread.set(row.threadId, threadProposedPlans); + } + + for (const row of activityRows) { + updatedAt = maxIso(updatedAt, row.createdAt); + const threadActivities = activitiesByThread.get(row.threadId) ?? []; + threadActivities.push({ + id: row.activityId, + tone: row.tone, + kind: row.kind, + summary: row.summary, + payload: row.payload, + turnId: row.turnId, + ...(row.sequence !== null ? { sequence: row.sequence } : {}), + createdAt: row.createdAt, + }); + activitiesByThread.set(row.threadId, threadActivities); + } + + for (const row of checkpointRows) { + updatedAt = maxIso(updatedAt, row.completedAt); + const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? []; + threadCheckpoints.push({ + turnId: row.turnId, + checkpointTurnCount: row.checkpointTurnCount, + checkpointRef: row.checkpointRef, + status: row.status, + files: row.files, + assistantMessageId: row.assistantMessageId, + completedAt: row.completedAt, + }); + checkpointsByThread.set(row.threadId, threadCheckpoints); + } + + for (const row of latestTurnRows) { + updatedAt = maxIso(updatedAt, row.requestedAt); + if (row.startedAt !== null) { + updatedAt = maxIso(updatedAt, row.startedAt); + } + if (row.completedAt !== null) { + updatedAt = maxIso(updatedAt, row.completedAt); + } + if (latestTurnByThread.has(row.threadId)) { + continue; + } + latestTurnByThread.set(row.threadId, { + turnId: row.turnId, + state: + row.state === "error" + ? "error" + : row.state === "interrupted" + ? "interrupted" + : row.state === "completed" + ? "completed" + : "running", + requestedAt: row.requestedAt, + startedAt: row.startedAt, + completedAt: row.completedAt, + assistantMessageId: row.assistantMessageId, + ...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null + ? { + sourceProposedPlan: { + threadId: row.sourceProposedPlanThreadId, + planId: row.sourceProposedPlanId, + }, + } + : {}), + }); + } + + for (const row of sessionRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + sessionsByThread.set(row.threadId, { + threadId: row.threadId, + status: row.status, + providerName: row.providerName, + runtimeMode: row.runtimeMode, + activeTurnId: row.activeTurnId, + lastError: row.lastError, + updatedAt: row.updatedAt, + }); + } + + const projects: ReadonlyArray = projectRows.map((row) => ({ + id: row.projectId, + title: row.title, + workspaceRoot: row.workspaceRoot, + defaultModelSelection: row.defaultModelSelection, + scripts: row.scripts, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + deletedAt: row.deletedAt, + })); + + const threads: ReadonlyArray = threadRows.map((row) => ({ + id: row.threadId, + projectId: row.projectId, + title: row.title, + modelSelection: row.modelSelection, + runtimeMode: row.runtimeMode, + interactionMode: row.interactionMode, + branch: row.branch, + worktreePath: row.worktreePath, + latestTurn: latestTurnByThread.get(row.threadId) ?? null, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + archivedAt: row.archivedAt, + deletedAt: row.deletedAt, + messages: messagesByThread.get(row.threadId) ?? [], + proposedPlans: proposedPlansByThread.get(row.threadId) ?? [], + activities: activitiesByThread.get(row.threadId) ?? [], + checkpoints: checkpointsByThread.get(row.threadId) ?? [], + session: sessionsByThread.get(row.threadId) ?? null, + })); + + const snapshot = { + snapshotSequence: computeSnapshotSequence(stateRows), + projects, + threads, + updatedAt: updatedAt ?? new Date(0).toISOString(), + }; + + return yield* decodeReadModel(snapshot).pipe( + Effect.mapError( + toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"), + ), + ); + }), + ) + .pipe( + Effect.mapError((error) => { + if (isPersistenceError(error)) { + return error; + } + return toPersistenceSqlError("ProjectionSnapshotQuery.getSnapshot:query")(error); + }), + ); + + const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () => + readProjectionCounts(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getCounts:query", + "ProjectionSnapshotQuery.getCounts:decodeRow", + ), + ), + Effect.map( + (row): ProjectionSnapshotCounts => ({ + projectCount: row.projectCount, + threadCount: row.threadCount, + }), + ), + ); + + const getActiveProjectByWorkspaceRoot: ProjectionSnapshotQueryShape["getActiveProjectByWorkspaceRoot"] = + (workspaceRoot) => + getActiveProjectRowByWorkspaceRoot({ workspaceRoot }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:query", + "ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:decodeRow", + ), + ), + Effect.map( + Option.map( + (row): OrchestrationProject => ({ + id: row.projectId, + title: row.title, + workspaceRoot: row.workspaceRoot, + defaultModelSelection: row.defaultModelSelection, + scripts: row.scripts, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + deletedAt: row.deletedAt, + }), + ), + ), + ); + + const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape["getFirstActiveThreadIdByProjectId"] = + (projectId) => + getFirstActiveThreadIdByProject({ projectId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:query", + "ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:decodeRow", + ), + ), + Effect.map(Option.map((row) => row.threadId)), + ); + + const getThreadCheckpointContext: ProjectionSnapshotQueryShape["getThreadCheckpointContext"] = ( + threadId, + ) => + Effect.gen(function* () { + const threadRow = yield* getThreadCheckpointContextThreadRow({ threadId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:query", + "ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:decodeRow", + ), + ), + ); + if (Option.isNone(threadRow)) { + return Option.none(); + } + + const checkpointRows = yield* listCheckpointRowsByThread({ threadId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:query", + "ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:decodeRows", + ), + ), + ); + + return Option.some({ + threadId: threadRow.value.threadId, + projectId: threadRow.value.projectId, + workspaceRoot: threadRow.value.workspaceRoot, + worktreePath: threadRow.value.worktreePath, + checkpoints: checkpointRows.map( + (row): OrchestrationCheckpointSummary => ({ + turnId: row.turnId, + checkpointTurnCount: row.checkpointTurnCount, + checkpointRef: row.checkpointRef, + status: row.status, + files: row.files, + assistantMessageId: row.assistantMessageId, + completedAt: row.completedAt, + }), + ), + }); + }); + + return { + getSnapshot, + getCounts, + getActiveProjectByWorkspaceRoot, + getFirstActiveThreadIdByProjectId, + getThreadCheckpointContext, + } satisfies ProjectionSnapshotQueryShape; +}); + +export const OrchestrationProjectionSnapshotQueryLive = Layer.effect( + ProjectionSnapshotQuery, + makeProjectionSnapshotQuery, +); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts new file mode 100644 index 0000000000..ca3dc04517 --- /dev/null +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -0,0 +1,1582 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts"; +import { + ApprovalRequestId, + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + EventId, + MessageId, + ProjectId, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { deriveServerPaths, ServerConfig } from "../../config.ts"; +import { TextGenerationError } from "@t3tools/contracts"; +import { ProviderAdapterRequestError } from "../../provider/Errors.ts"; +import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; +import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { + ProviderService, + type ProviderServiceShape, +} from "../../provider/Services/ProviderService.ts"; +import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts"; +import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts"; +import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; +import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; +import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts"; +import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; +import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { ServerSettingsService } from "../../serverSettings.ts"; + +const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); +const asApprovalRequestId = (value: string): ApprovalRequestId => + ApprovalRequestId.makeUnsafe(value); +const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); +const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); + +const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) => + Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer))); + +async function waitFor( + predicate: () => boolean | Promise, + timeoutMs = 2000, +): Promise { + const deadline = Date.now() + timeoutMs; + const poll = async (): Promise => { + if (await predicate()) { + return; + } + if (Date.now() >= deadline) { + throw new Error("Timed out waiting for expectation."); + } + await new Promise((resolve) => setTimeout(resolve, 10)); + return poll(); + }; + + return poll(); +} + +describe("ProviderCommandReactor", () => { + let runtime: ManagedRuntime.ManagedRuntime< + OrchestrationEngineService | ProviderCommandReactor, + unknown + > | null = null; + let scope: Scope.Closeable | null = null; + const createdStateDirs = new Set(); + const createdBaseDirs = new Set(); + + afterEach(async () => { + if (scope) { + await Effect.runPromise(Scope.close(scope, Exit.void)); + } + scope = null; + if (runtime) { + await runtime.dispose(); + } + runtime = null; + for (const stateDir of createdStateDirs) { + fs.rmSync(stateDir, { recursive: true, force: true }); + } + createdStateDirs.clear(); + for (const baseDir of createdBaseDirs) { + fs.rmSync(baseDir, { recursive: true, force: true }); + } + createdBaseDirs.clear(); + }); + + async function createHarness(input?: { + readonly baseDir?: string; + readonly threadModelSelection?: ModelSelection; + readonly sessionModelSwitch?: "unsupported" | "in-session"; + }) { + const now = new Date().toISOString(); + const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-")); + createdBaseDirs.add(baseDir); + const { stateDir } = deriveServerPathsSync(baseDir, undefined); + createdStateDirs.add(stateDir); + const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); + let nextSessionIndex = 1; + const runtimeSessions: Array = []; + const modelSelection = input?.threadModelSelection ?? { + provider: "codex", + model: "gpt-5-codex", + }; + const startSession = vi.fn((_: unknown, input: unknown) => { + const sessionIndex = nextSessionIndex++; + const resumeCursor = + typeof input === "object" && input !== null && "resumeCursor" in input + ? input.resumeCursor + : undefined; + const threadId = + typeof input === "object" && + input !== null && + "threadId" in input && + typeof input.threadId === "string" + ? ThreadId.makeUnsafe(input.threadId) + : ThreadId.makeUnsafe(`thread-${sessionIndex}`); + const session: ProviderSession = { + provider: modelSelection.provider, + status: "ready" as const, + runtimeMode: + typeof input === "object" && + input !== null && + "runtimeMode" in input && + (input.runtimeMode === "approval-required" || input.runtimeMode === "full-access") + ? input.runtimeMode + : "full-access", + ...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}), + threadId, + resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` }, + createdAt: now, + updatedAt: now, + }; + runtimeSessions.push(session); + return Effect.succeed(session); + }); + const sendTurn = vi.fn((_: unknown) => + Effect.succeed({ + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-1"), + }), + ); + const interruptTurn = vi.fn((_: unknown) => Effect.void); + const respondToRequest = vi.fn(() => Effect.void); + const respondToUserInput = vi.fn(() => Effect.void); + const stopSession = vi.fn((input: unknown) => + Effect.sync(() => { + const threadId = + typeof input === "object" && input !== null && "threadId" in input + ? (input as { threadId?: ThreadId }).threadId + : undefined; + if (!threadId) { + return; + } + const index = runtimeSessions.findIndex((session) => session.threadId === threadId); + if (index >= 0) { + runtimeSessions.splice(index, 1); + } + }), + ); + const renameBranch = vi.fn((input: unknown) => + Effect.succeed({ + branch: + typeof input === "object" && + input !== null && + "newBranch" in input && + typeof input.newBranch === "string" + ? input.newBranch + : "renamed-branch", + }), + ); + const generateBranchName = vi.fn((_) => + Effect.fail( + new TextGenerationError({ + operation: "generateBranchName", + detail: "disabled in test harness", + }), + ), + ); + const generateThreadTitle = vi.fn((_) => + Effect.fail( + new TextGenerationError({ + operation: "generateThreadTitle", + detail: "disabled in test harness", + }), + ), + ); + + const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; + const service: ProviderServiceShape = { + startSession: startSession as ProviderServiceShape["startSession"], + sendTurn: sendTurn as ProviderServiceShape["sendTurn"], + interruptTurn: interruptTurn as ProviderServiceShape["interruptTurn"], + respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"], + respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"], + stopSession: stopSession as ProviderServiceShape["stopSession"], + listSessions: () => Effect.succeed(runtimeSessions), + getCapabilities: (_provider) => + Effect.succeed({ + sessionModelSwitch: input?.sessionModelSwitch ?? "in-session", + }), + rollbackConversation: () => unsupported(), + streamEvents: Stream.fromPubSub(runtimeEventPubSub), + }; + + const orchestrationLayer = OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), + Layer.provide(OrchestrationProjectionPipelineLive), + Layer.provide(OrchestrationEventStoreLive), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(SqlitePersistenceMemory), + ); + const layer = ProviderCommandReactorLive.pipe( + Layer.provideMerge(orchestrationLayer), + Layer.provideMerge(Layer.succeed(ProviderService, service)), + Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)), + Layer.provideMerge( + Layer.mock(TextGeneration, { + generateBranchName, + generateThreadTitle, + }), + ), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)), + Layer.provideMerge(NodeServices.layer), + ); + const runtime = ManagedRuntime.make(layer); + + const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); + const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor)); + scope = await Effect.runPromise(Scope.make("sequential")); + await Effect.runPromise(reactor.start().pipe(Scope.provide(scope))); + const drain = () => Effect.runPromise(reactor.drain); + + await Effect.runPromise( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-create"), + projectId: asProjectId("project-1"), + title: "Provider Project", + workspaceRoot: "/tmp/provider-project", + defaultModelSelection: modelSelection, + createdAt: now, + }), + ); + await Effect.runPromise( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-create"), + threadId: ThreadId.makeUnsafe("thread-1"), + projectId: asProjectId("project-1"), + title: "Thread", + modelSelection: modelSelection, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt: now, + }), + ); + + return { + engine, + startSession, + sendTurn, + interruptTurn, + respondToRequest, + respondToUserInput, + stopSession, + renameBranch, + generateBranchName, + generateThreadTitle, + stateDir, + drain, + }; + } + + it("reacts to thread.turn.start by ensuring session and sending provider turn", 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-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-1"), + role: "user", + text: "hello reactor", + 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); + expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1")); + expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ + cwd: "/tmp/provider-project", + modelSelection: { + provider: "codex", + 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?.threadId).toBe("thread-1"); + expect(thread?.session?.runtimeMode).toBe("approval-required"); + }); + + it("generates a thread title on the first turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + const seededTitle = "Please investigate reconnect failures after restar..."; + harness.generateThreadTitle.mockReturnValue(Effect.succeed({ title: "Generated title" })); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-title-seed"), + threadId: ThreadId.makeUnsafe("thread-1"), + title: seededTitle, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-title"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-title"), + role: "user", + text: "Please investigate reconnect failures after restarting the session.", + attachments: [], + }, + titleSeed: seededTitle, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1); + expect(harness.generateThreadTitle.mock.calls[0]?.[0]).toMatchObject({ + message: "Please investigate reconnect failures after restarting the session.", + }); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + return ( + readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title === + "Generated title" + ); + }); + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.title).toBe("Generated title"); + }); + + it("does not overwrite an existing custom thread title on the first turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + const seededTitle = "Please investigate reconnect failures after restar..."; + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-title-custom"), + threadId: ThreadId.makeUnsafe("thread-1"), + title: "Keep this custom title", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-title-preserve"), + role: "user", + text: "Please investigate reconnect failures after restarting the session.", + attachments: [], + }, + titleSeed: seededTitle, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + expect(harness.generateThreadTitle).not.toHaveBeenCalled(); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.title).toBe("Keep this custom title"); + }); + + it("matches the client-seeded title even when the outgoing prompt is reformatted", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + const seededTitle = "Fix reconnect spinner on resume"; + harness.generateThreadTitle.mockReturnValue( + Effect.succeed({ + title: "Reconnect spinner resume bug", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"), + threadId: ThreadId.makeUnsafe("thread-1"), + title: seededTitle, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-title-formatted"), + role: "user", + text: "[effort:high]\\n\\nFix reconnect spinner on resume", + attachments: [], + }, + titleSeed: seededTitle, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1); + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + return ( + readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title === + "Reconnect spinner resume bug" + ); + }); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.title).toBe("Reconnect spinner resume bug"); + }); + + it("generates a worktree branch name for the first turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-branch"), + threadId: ThreadId.makeUnsafe("thread-1"), + branch: "t3code/1234abcd", + worktreePath: "/tmp/provider-project-worktree", + }), + ); + + harness.generateBranchName.mockImplementation((input: unknown) => + Effect.succeed({ + branch: + typeof input === "object" && + input !== null && + "modelSelection" in input && + typeof input.modelSelection === "object" && + input.modelSelection !== null && + "model" in input.modelSelection && + typeof input.modelSelection.model === "string" + ? `feature/${input.modelSelection.model}` + : "feature/generated", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-branch-model"), + role: "user", + text: "Add a safer reconnect backoff.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.generateBranchName.mock.calls.length === 1); + expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({ + message: "Add a safer reconnect backoff.", + }); + }); + + it("forwards codex model options through session start and turn send", 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-fast"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-fast"), + role: "user", + text: "hello fast mode", + attachments: [], + }, + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + reasoningEffort: "high", + fastMode: true, + }, + }, + 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({ + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + reasoningEffort: "high", + fastMode: true, + }, + }, + }); + expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ + threadId: ThreadId.makeUnsafe("thread-1"), + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + reasoningEffort: "high", + fastMode: true, + }, + }, + }); + }); + + it("forwards claude effort options through session start and turn send", async () => { + const harness = await createHarness({ + threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, + }); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-claude-effort"), + role: "user", + text: "hello with effort", + attachments: [], + }, + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "max", + }, + }, + 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({ + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "max", + }, + }, + }); + expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ + threadId: ThreadId.makeUnsafe("thread-1"), + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "max", + }, + }, + }); + }); + + it("forwards claude fast mode options through session start and turn send", async () => { + const harness = await createHarness({ + threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" }, + }); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-claude-fast-mode"), + role: "user", + text: "hello with fast mode", + attachments: [], + }, + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + fastMode: true, + }, + }, + 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({ + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + fastMode: true, + }, + }, + }); + expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ + threadId: ThreadId.makeUnsafe("thread-1"), + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + fastMode: true, + }, + }, + }); + }); + + it("forwards plan interaction mode to the provider turn request", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.interaction-mode.set", + commandId: CommandId.makeUnsafe("cmd-interaction-mode-set-plan"), + threadId: ThreadId.makeUnsafe("thread-1"), + interactionMode: "plan", + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-plan"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-plan"), + role: "user", + text: "plan this change", + attachments: [], + }, + interactionMode: "plan", + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ + threadId: ThreadId.makeUnsafe("thread-1"), + interactionMode: "plan", + }); + }); + + it("rejects a first turn when requested provider conflicts with the thread model", async () => { + const harness = await createHarness({ + threadModelSelection: { provider: "codex", model: "gpt-5-codex" }, + }); + 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: [], + }, + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + return ( + thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ?? + false + ); + }); + + expect(harness.startSession).not.toHaveBeenCalled(); + expect(harness.sendTurn).not.toHaveBeenCalled(); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.session).toBeNull(); + expect( + thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"), + ).toMatchObject({ + summary: "Provider turn start failed", + payload: { + detail: expect.stringContaining("cannot switch to 'claudeAgent'"), + }, + }); + }); + + it("preserves the active session model when in-session model switching is unsupported", async () => { + const harness = await createHarness({ sessionModelSwitch: "unsupported" }); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-unsupported-1"), + role: "user", + text: "first", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-unsupported-2"), + role: "user", + text: "second", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.sendTurn.mock.calls.length === 2); + + expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({ + threadId: ThreadId.makeUnsafe("thread-1"), + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + }); + }); + + it("reuses the same provider session when runtime mode 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-unchanged-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-unchanged-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-unchanged-2"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-unchanged-2"), + role: "user", + text: "second", + attachments: [], + }, + 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("restarts claude sessions when claude effort changes", async () => { + const harness = await createHarness({ + threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, + }); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-claude-effort-1"), + role: "user", + text: "first claude turn", + attachments: [], + }, + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "medium", + }, + }, + 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-claude-effort-2"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-claude-effort-2"), + role: "user", + text: "second claude turn", + attachments: [], + }, + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "max", + }, + }, + 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.startSession.mock.calls[1]?.[1]).toMatchObject({ + resumeCursor: { opaque: "resume-1" }, + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "max", + }, + }, + }); + }); + + it("restarts the provider session when runtime mode is updated on the thread", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access"), + threadId: ThreadId.makeUnsafe("thread-1"), + runtimeMode: "full-access", + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-runtime-mode-1"), + role: "user", + text: "first", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + 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.runtime-mode.set", + commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + return thread?.runtimeMode === "approval-required"; + }); + await waitFor(() => harness.startSession.mock.calls.length === 2); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-2"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-runtime-mode-2"), + role: "user", + text: "second", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + createdAt: now, + }), + ); + + 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"), + resumeCursor: { opaque: "resume-1" }, + runtimeMode: "approval-required", + }); + expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({ + threadId: ThreadId.makeUnsafe("thread-1"), + }); + + 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?.runtimeMode).toBe("approval-required"); + }); + + it("does not inject derived model options when restarting claude on runtime mode changes", async () => { + const harness = await createHarness({ + threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" }, + }); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-runtime-mode-claude"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "ready", + providerName: "claudeAgent", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-claude-no-options"), + threadId: ThreadId.makeUnsafe("thread-1"), + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.startSession.mock.calls.length === 1); + + expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + }, + runtimeMode: "approval-required", + }); + }); + + it("rejects provider changes after a thread is already bound to a session provider", 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: [], + }, + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + return ( + thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ?? + false + ); + }); + + expect(harness.startSession.mock.calls.length).toBe(1); + expect(harness.sendTurn.mock.calls.length).toBe(1); + expect(harness.stopSession.mock.calls.length).toBe(0); + + 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("codex"); + expect(thread?.session?.runtimeMode).toBe("approval-required"); + expect( + thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"), + ).toMatchObject({ + payload: { + detail: expect.stringContaining("cannot switch to 'claudeAgent'"), + }, + }); + }); + + it("does not stop the active session when restart fails before rebind", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access-2"), + threadId: ThreadId.makeUnsafe("thread-1"), + runtimeMode: "full-access", + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-restart-failure-1"), + role: "user", + text: "first", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + createdAt: now, + }), + ); + + await waitFor(() => harness.startSession.mock.calls.length === 1); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + + harness.startSession.mockImplementationOnce( + (_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never, + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-restart-failure"), + threadId: ThreadId.makeUnsafe("thread-1"), + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + return thread?.runtimeMode === "approval-required"; + }); + await waitFor(() => harness.startSession.mock.calls.length === 2); + await harness.drain(); + + expect(harness.stopSession.mock.calls.length).toBe(0); + expect(harness.sendTurn.mock.calls.length).toBe(1); + + 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?.runtimeMode).toBe("full-access"); + }); + + it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: asTurnId("turn-1"), + lastError: null, + updatedAt: now, + }, + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.interrupt", + commandId: CommandId.makeUnsafe("cmd-turn-interrupt"), + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: asTurnId("turn-1"), + createdAt: now, + }), + ); + + await waitFor(() => harness.interruptTurn.mock.calls.length === 1); + expect(harness.interruptTurn.mock.calls[0]?.[0]).toEqual({ + threadId: "thread-1", + }); + }); + + it("reacts to thread.approval.respond by forwarding provider approval response", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-for-approval"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.approval.respond", + commandId: CommandId.makeUnsafe("cmd-approval-respond"), + threadId: ThreadId.makeUnsafe("thread-1"), + requestId: asApprovalRequestId("approval-request-1"), + decision: "accept", + createdAt: now, + }), + ); + + await waitFor(() => harness.respondToRequest.mock.calls.length === 1); + expect(harness.respondToRequest.mock.calls[0]?.[0]).toEqual({ + threadId: "thread-1", + requestId: "approval-request-1", + decision: "accept", + }); + }); + + it("reacts to thread.user-input.respond by forwarding structured user input answers", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.user-input.respond", + commandId: CommandId.makeUnsafe("cmd-user-input-respond"), + threadId: ThreadId.makeUnsafe("thread-1"), + requestId: asApprovalRequestId("user-input-request-1"), + answers: { + sandbox_mode: "workspace-write", + }, + createdAt: now, + }), + ); + + await waitFor(() => harness.respondToUserInput.mock.calls.length === 1); + expect(harness.respondToUserInput.mock.calls[0]?.[0]).toEqual({ + threadId: "thread-1", + requestId: "user-input-request-1", + answers: { + sandbox_mode: "workspace-write", + }, + }); + }); + + it("surfaces stale provider approval request failures without faking approval resolution", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + harness.respondToRequest.mockImplementation(() => + Effect.fail( + new ProviderAdapterRequestError({ + provider: "codex", + method: "session/request_permission", + detail: "Unknown pending permission request: approval-request-1", + }), + ), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-for-approval-error"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.activity.append", + commandId: CommandId.makeUnsafe("cmd-approval-requested"), + threadId: ThreadId.makeUnsafe("thread-1"), + activity: { + id: EventId.makeUnsafe("activity-approval-requested"), + tone: "approval", + kind: "approval.requested", + summary: "Command approval requested", + payload: { + requestId: "approval-request-1", + requestKind: "command", + }, + turnId: null, + createdAt: now, + }, + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.approval.respond", + commandId: CommandId.makeUnsafe("cmd-approval-respond-stale"), + threadId: ThreadId.makeUnsafe("thread-1"), + requestId: asApprovalRequestId("approval-request-1"), + decision: "acceptForSession", + createdAt: now, + }), + ); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + if (!thread) return false; + return thread.activities.some( + (activity) => activity.kind === "provider.approval.respond.failed", + ); + }); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread).toBeDefined(); + + const failureActivity = thread?.activities.find( + (activity) => activity.kind === "provider.approval.respond.failed", + ); + expect(failureActivity).toBeDefined(); + expect(failureActivity?.payload).toMatchObject({ + requestId: "approval-request-1", + detail: expect.stringContaining("Stale pending approval request: approval-request-1"), + }); + + const resolvedActivity = thread?.activities.find( + (activity) => + activity.kind === "approval.resolved" && + typeof activity.payload === "object" && + activity.payload !== null && + (activity.payload as Record).requestId === "approval-request-1", + ); + expect(resolvedActivity).toBeUndefined(); + }); + + it("surfaces stale provider user-input failures without faking user-input resolution", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + harness.respondToUserInput.mockImplementation(() => + Effect.fail( + new ProviderAdapterRequestError({ + provider: "claudeAgent", + method: "item/tool/respondToUserInput", + detail: "Unknown pending user-input request: user-input-request-1", + }), + ), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input-error"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "running", + providerName: "claudeAgent", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.activity.append", + commandId: CommandId.makeUnsafe("cmd-user-input-requested"), + threadId: ThreadId.makeUnsafe("thread-1"), + activity: { + id: EventId.makeUnsafe("activity-user-input-requested"), + tone: "info", + kind: "user-input.requested", + summary: "User input requested", + payload: { + requestId: "user-input-request-1", + questions: [ + { + id: "sandbox_mode", + header: "Sandbox", + question: "Which mode should be used?", + options: [ + { + label: "workspace-write", + description: "Allow workspace writes only", + }, + ], + }, + ], + }, + turnId: null, + createdAt: now, + }, + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.user-input.respond", + commandId: CommandId.makeUnsafe("cmd-user-input-respond-stale"), + threadId: ThreadId.makeUnsafe("thread-1"), + requestId: asApprovalRequestId("user-input-request-1"), + answers: { + sandbox_mode: "workspace-write", + }, + createdAt: now, + }), + ); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + if (!thread) return false; + return thread.activities.some( + (activity) => activity.kind === "provider.user-input.respond.failed", + ); + }); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread).toBeDefined(); + + const failureActivity = thread?.activities.find( + (activity) => activity.kind === "provider.user-input.respond.failed", + ); + expect(failureActivity).toBeDefined(); + expect(failureActivity?.payload).toMatchObject({ + requestId: "user-input-request-1", + detail: expect.stringContaining("Stale pending user-input request: user-input-request-1"), + }); + + const resolvedActivity = thread?.activities.find( + (activity) => + activity.kind === "user-input.resolved" && + typeof activity.payload === "object" && + activity.payload !== null && + (activity.payload as Record).requestId === "user-input-request-1", + ); + expect(resolvedActivity).toBeUndefined(); + }); + + it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-for-stop"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.stop", + commandId: CommandId.makeUnsafe("cmd-session-stop"), + threadId: ThreadId.makeUnsafe("thread-1"), + createdAt: now, + }), + ); + + await waitFor(() => harness.stopSession.mock.calls.length === 1); + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.session).not.toBeNull(); + expect(thread?.session?.status).toBe("stopped"); + expect(thread?.session?.threadId).toBe("thread-1"); + expect(thread?.session?.activeTurnId).toBeNull(); + }); +}); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts new file mode 100644 index 0000000000..419e3f3bf2 --- /dev/null +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -0,0 +1,817 @@ +import { + type ChatAttachment, + CommandId, + EventId, + type ModelSelection, + type OrchestrationEvent, + ProviderKind, + type OrchestrationSession, + ThreadId, + type ProviderSession, + type RuntimeMode, + type TurnId, +} from "@t3tools/contracts"; +import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect"; +import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; + +import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts"; +import { GitCore } from "../../git/Services/GitCore.ts"; +import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts"; +import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts"; +import { TextGeneration } from "../../git/Services/TextGeneration.ts"; +import { ProviderService } from "../../provider/Services/ProviderService.ts"; +import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; +import { + ProviderCommandReactor, + type ProviderCommandReactorShape, +} from "../Services/ProviderCommandReactor.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; + +type ProviderIntentEvent = Extract< + OrchestrationEvent, + { + type: + | "thread.runtime-mode-set" + | "thread.turn-start-requested" + | "thread.turn-interrupt-requested" + | "thread.approval-response-requested" + | "thread.user-input-response-requested" + | "thread.session-stop-requested"; + } +>; + +function toNonEmptyProviderInput(value: string | undefined): string | undefined { + const normalized = value?.trim(); + return normalized && normalized.length > 0 ? normalized : undefined; +} + +function mapProviderSessionStatusToOrchestrationStatus( + status: "connecting" | "ready" | "running" | "error" | "closed", +): OrchestrationSession["status"] { + switch (status) { + case "connecting": + return "starting"; + case "running": + return "running"; + case "error": + return "error"; + case "closed": + return "stopped"; + case "ready": + default: + return "ready"; + } +} + +const turnStartKeyForEvent = (event: ProviderIntentEvent): string => + event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`; + +const serverCommandId = (tag: string): CommandId => + CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`); + +const HANDLED_TURN_START_KEY_MAX = 10_000; +const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30); +const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access"; +const WORKTREE_BRANCH_PREFIX = "t3code"; +const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`); +const DEFAULT_THREAD_TITLE = "New thread"; + +function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean { + const trimmedCurrentTitle = currentTitle.trim(); + if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) { + return true; + } + + const trimmedTitleSeed = titleSeed?.trim(); + return trimmedTitleSeed !== undefined && trimmedTitleSeed.length > 0 + ? trimmedCurrentTitle === trimmedTitleSeed + : false; +} + +function isUnknownPendingApprovalRequestError(cause: Cause.Cause): boolean { + const error = Cause.squash(cause); + if (Schema.is(ProviderAdapterRequestError)(error)) { + const detail = error.detail.toLowerCase(); + return ( + detail.includes("unknown pending approval request") || + detail.includes("unknown pending permission request") + ); + } + const message = Cause.pretty(cause); + return ( + message.includes("unknown pending approval request") || + message.includes("unknown pending permission request") + ); +} + +function isUnknownPendingUserInputRequestError(cause: Cause.Cause): boolean { + const error = Cause.squash(cause); + if (Schema.is(ProviderAdapterRequestError)(error)) { + return error.detail.toLowerCase().includes("unknown pending user-input request"); + } + return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request"); +} + +function stalePendingRequestDetail( + requestKind: "approval" | "user-input", + requestId: string, +): string { + return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`; +} + +function isTemporaryWorktreeBranch(branch: string): boolean { + return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase()); +} + +function buildGeneratedWorktreeBranchName(raw: string): string { + const normalized = raw + .trim() + .toLowerCase() + .replace(/^refs\/heads\//, "") + .replace(/['"`]/g, ""); + + const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`) + ? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length) + : normalized; + + const branchFragment = withoutPrefix + .replace(/[^a-z0-9/_-]+/g, "-") + .replace(/\/+/g, "/") + .replace(/-+/g, "-") + .replace(/^[./_-]+|[./_-]+$/g, "") + .slice(0, 64) + .replace(/[./_-]+$/g, ""); + + const safeFragment = branchFragment.length > 0 ? branchFragment : "update"; + return `${WORKTREE_BRANCH_PREFIX}/${safeFragment}`; +} + +const make = Effect.gen(function* () { + const orchestrationEngine = yield* OrchestrationEngineService; + const providerService = yield* ProviderService; + const git = yield* GitCore; + const textGeneration = yield* TextGeneration; + const serverSettingsService = yield* ServerSettingsService; + const handledTurnStartKeys = yield* Cache.make({ + capacity: HANDLED_TURN_START_KEY_MAX, + timeToLive: HANDLED_TURN_START_KEY_TTL, + lookup: () => Effect.succeed(true), + }); + + const hasHandledTurnStartRecently = (key: string) => + Cache.getOption(handledTurnStartKeys, key).pipe( + Effect.flatMap((cached) => + Cache.set(handledTurnStartKeys, key, true).pipe(Effect.as(Option.isSome(cached))), + ), + ); + + const threadModelSelections = new Map(); + + const appendProviderFailureActivity = (input: { + readonly threadId: ThreadId; + readonly kind: + | "provider.turn.start.failed" + | "provider.turn.interrupt.failed" + | "provider.approval.respond.failed" + | "provider.user-input.respond.failed" + | "provider.session.stop.failed"; + readonly summary: string; + readonly detail: string; + readonly turnId: TurnId | null; + readonly createdAt: string; + readonly requestId?: string; + }) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: serverCommandId("provider-failure-activity"), + threadId: input.threadId, + activity: { + id: EventId.makeUnsafe(crypto.randomUUID()), + tone: "error", + kind: input.kind, + summary: input.summary, + payload: { + detail: input.detail, + ...(input.requestId ? { requestId: input.requestId } : {}), + }, + turnId: input.turnId, + createdAt: input.createdAt, + }, + createdAt: input.createdAt, + }); + + const setThreadSession = (input: { + readonly threadId: ThreadId; + readonly session: OrchestrationSession; + readonly createdAt: string; + }) => + orchestrationEngine.dispatch({ + type: "thread.session.set", + commandId: serverCommandId("provider-session-set"), + threadId: input.threadId, + session: input.session, + createdAt: input.createdAt, + }); + + const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) { + const readModel = yield* orchestrationEngine.getReadModel(); + return readModel.threads.find((entry) => entry.id === threadId); + }); + + const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* ( + threadId: ThreadId, + createdAt: string, + options?: { + readonly modelSelection?: ModelSelection; + }, + ) { + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === threadId); + if (!thread) { + return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`)); + } + + const desiredRuntimeMode = thread.runtimeMode; + const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)( + thread.session?.providerName, + ) + ? thread.session.providerName + : undefined; + const requestedModelSelection = options?.modelSelection; + const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider; + if ( + requestedModelSelection !== undefined && + requestedModelSelection.provider !== threadProvider + ) { + return yield* new ProviderAdapterRequestError({ + provider: threadProvider, + method: "thread.turn.start", + detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`, + }); + } + const preferredProvider: ProviderKind = currentProvider ?? threadProvider; + const desiredModelSelection = requestedModelSelection ?? thread.modelSelection; + const effectiveCwd = resolveThreadWorkspaceCwd({ + thread, + projects: readModel.projects, + }); + + const resolveActiveSession = (threadId: ThreadId) => + providerService + .listSessions() + .pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId))); + + const startProviderSession = (input?: { + readonly resumeCursor?: unknown; + readonly provider?: ProviderKind; + }) => + providerService.startSession(threadId, { + threadId, + ...(preferredProvider ? { provider: preferredProvider } : {}), + ...(effectiveCwd ? { cwd: effectiveCwd } : {}), + modelSelection: desiredModelSelection, + ...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}), + runtimeMode: desiredRuntimeMode, + }); + + const bindSessionToThread = (session: ProviderSession) => + setThreadSession({ + threadId, + session: { + threadId, + status: mapProviderSessionStatusToOrchestrationStatus(session.status), + providerName: session.provider, + runtimeMode: desiredRuntimeMode, + // Provider turn ids are not orchestration turn ids. + activeTurnId: null, + lastError: session.lastError ?? null, + updatedAt: session.updatedAt, + }, + createdAt, + }); + + const existingSessionThreadId = + thread.session && thread.session.status !== "stopped" ? thread.id : null; + if (existingSessionThreadId) { + const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode; + const providerChanged = + requestedModelSelection !== undefined && + requestedModelSelection.provider !== currentProvider; + const activeSession = yield* resolveActiveSession(existingSessionThreadId); + const sessionModelSwitch = + currentProvider === undefined + ? "in-session" + : (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch; + const modelChanged = + requestedModelSelection !== undefined && + requestedModelSelection.model !== activeSession?.model; + const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session"; + const previousModelSelection = threadModelSelections.get(threadId); + const shouldRestartForModelSelectionChange = + currentProvider === "claudeAgent" && + requestedModelSelection !== undefined && + !Equal.equals(previousModelSelection, requestedModelSelection); + + if ( + !runtimeModeChanged && + !providerChanged && + !shouldRestartForModelChange && + !shouldRestartForModelSelectionChange + ) { + return existingSessionThreadId; + } + + const resumeCursor = + providerChanged || shouldRestartForModelChange + ? undefined + : (activeSession?.resumeCursor ?? undefined); + yield* Effect.logInfo("provider command reactor restarting provider session", { + threadId, + existingSessionThreadId, + currentProvider, + desiredProvider: desiredModelSelection.provider, + currentRuntimeMode: thread.session?.runtimeMode, + desiredRuntimeMode: thread.runtimeMode, + runtimeModeChanged, + providerChanged, + modelChanged, + shouldRestartForModelChange, + shouldRestartForModelSelectionChange, + hasResumeCursor: resumeCursor !== undefined, + }); + const restartedSession = yield* startProviderSession( + resumeCursor !== undefined ? { resumeCursor } : undefined, + ); + yield* Effect.logInfo("provider command reactor restarted provider session", { + threadId, + previousSessionId: existingSessionThreadId, + restartedSessionThreadId: restartedSession.threadId, + provider: restartedSession.provider, + runtimeMode: restartedSession.runtimeMode, + }); + yield* bindSessionToThread(restartedSession); + return restartedSession.threadId; + } + + const startedSession = yield* startProviderSession(undefined); + yield* bindSessionToThread(startedSession); + return startedSession.threadId; + }); + + const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: { + readonly threadId: ThreadId; + readonly messageText: string; + readonly attachments?: ReadonlyArray; + readonly modelSelection?: ModelSelection; + readonly interactionMode?: "default" | "plan"; + readonly createdAt: string; + }) { + const thread = yield* resolveThread(input.threadId); + if (!thread) { + return; + } + yield* ensureSessionForThread( + input.threadId, + input.createdAt, + input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}, + ); + if (input.modelSelection !== undefined) { + threadModelSelections.set(input.threadId, input.modelSelection); + } + const normalizedInput = toNonEmptyProviderInput(input.messageText); + const normalizedAttachments = input.attachments ?? []; + const activeSession = yield* providerService + .listSessions() + .pipe( + Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)), + ); + const sessionModelSwitch = + activeSession === undefined + ? "in-session" + : (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch; + const requestedModelSelection = + input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection; + const modelForTurn = + sessionModelSwitch === "unsupported" + ? activeSession?.model !== undefined + ? { + ...requestedModelSelection, + model: activeSession.model, + } + : requestedModelSelection + : input.modelSelection; + + yield* providerService.sendTurn({ + threadId: input.threadId, + ...(normalizedInput ? { input: normalizedInput } : {}), + ...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}), + ...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}), + ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}), + }); + }); + + const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn( + "maybeGenerateAndRenameWorktreeBranchForFirstTurn", + )(function* (input: { + readonly threadId: ThreadId; + readonly branch: string | null; + readonly worktreePath: string | null; + readonly messageText: string; + readonly attachments?: ReadonlyArray; + }) { + if (!input.branch || !input.worktreePath) { + return; + } + if (!isTemporaryWorktreeBranch(input.branch)) { + return; + } + + const oldBranch = input.branch; + const cwd = input.worktreePath; + const attachments = input.attachments ?? []; + yield* Effect.gen(function* () { + const { textGenerationModelSelection: modelSelection } = + yield* serverSettingsService.getSettings; + + const generated = yield* textGeneration.generateBranchName({ + cwd, + message: input.messageText, + ...(attachments.length > 0 ? { attachments } : {}), + modelSelection, + }); + if (!generated) return; + + const targetBranch = buildGeneratedWorktreeBranchName(generated.branch); + if (targetBranch === oldBranch) return; + + const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }); + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: serverCommandId("worktree-branch-rename"), + threadId: input.threadId, + branch: renamed.branch, + worktreePath: cwd, + }); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider command reactor failed to generate or rename worktree branch", { + threadId: input.threadId, + cwd, + oldBranch, + cause: Cause.pretty(cause), + }), + ), + ); + }); + + const maybeGenerateThreadTitleForFirstTurn = Effect.fn("maybeGenerateThreadTitleForFirstTurn")( + function* (input: { + readonly threadId: ThreadId; + readonly cwd: string; + readonly messageText: string; + readonly attachments?: ReadonlyArray; + readonly titleSeed?: string; + }) { + const attachments = input.attachments ?? []; + yield* Effect.gen(function* () { + const { textGenerationModelSelection: modelSelection } = + yield* serverSettingsService.getSettings; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: input.cwd, + message: input.messageText, + ...(attachments.length > 0 ? { attachments } : {}), + modelSelection, + }); + if (!generated) return; + + const thread = yield* resolveThread(input.threadId); + if (!thread) return; + if (!canReplaceThreadTitle(thread.title, input.titleSeed)) { + return; + } + + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: serverCommandId("thread-title-rename"), + threadId: input.threadId, + title: generated.title, + }); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider command reactor failed to generate or rename thread title", { + threadId: input.threadId, + cwd: input.cwd, + cause: Cause.pretty(cause), + }), + ), + ); + }, + ); + + const processTurnStartRequested = Effect.fn("processTurnStartRequested")(function* ( + event: Extract, + ) { + const key = turnStartKeyForEvent(event); + if (yield* hasHandledTurnStartRecently(key)) { + return; + } + + const thread = yield* resolveThread(event.payload.threadId); + if (!thread) { + return; + } + + const message = thread.messages.find((entry) => entry.id === event.payload.messageId); + if (!message || message.role !== "user") { + yield* appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.turn.start.failed", + summary: "Provider turn start failed", + detail: `User message '${event.payload.messageId}' was not found for turn start request.`, + turnId: null, + createdAt: event.payload.createdAt, + }); + return; + } + + const isFirstUserMessageTurn = + thread.messages.filter((entry) => entry.role === "user").length === 1; + if (isFirstUserMessageTurn) { + const generationCwd = + resolveThreadWorkspaceCwd({ + thread, + projects: (yield* orchestrationEngine.getReadModel()).projects, + }) ?? process.cwd(); + const generationInput = { + messageText: message.text, + ...(message.attachments !== undefined ? { attachments: message.attachments } : {}), + ...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}), + }; + + yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({ + threadId: event.payload.threadId, + branch: thread.branch, + worktreePath: thread.worktreePath, + ...generationInput, + }).pipe(Effect.forkScoped); + + if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) { + yield* maybeGenerateThreadTitleForFirstTurn({ + threadId: event.payload.threadId, + cwd: generationCwd, + ...generationInput, + }).pipe(Effect.forkScoped); + } + } + + yield* sendTurnForThread({ + threadId: event.payload.threadId, + messageText: message.text, + ...(message.attachments !== undefined ? { attachments: message.attachments } : {}), + ...(event.payload.modelSelection !== undefined + ? { modelSelection: event.payload.modelSelection } + : {}), + interactionMode: event.payload.interactionMode, + createdAt: event.payload.createdAt, + }).pipe( + Effect.catchCause((cause) => + appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.turn.start.failed", + summary: "Provider turn start failed", + detail: Cause.pretty(cause), + turnId: null, + createdAt: event.payload.createdAt, + }), + ), + ); + }); + + const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* ( + event: Extract, + ) { + const thread = yield* resolveThread(event.payload.threadId); + if (!thread) { + return; + } + const hasSession = thread.session && thread.session.status !== "stopped"; + if (!hasSession) { + return yield* appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.turn.interrupt.failed", + summary: "Provider turn interrupt failed", + detail: "No active provider session is bound to this thread.", + turnId: event.payload.turnId ?? null, + createdAt: event.payload.createdAt, + }); + } + + // Orchestration turn ids are not provider turn ids, so interrupt by session. + yield* providerService.interruptTurn({ threadId: event.payload.threadId }); + }); + + const processApprovalResponseRequested = Effect.fn("processApprovalResponseRequested")(function* ( + event: Extract, + ) { + const thread = yield* resolveThread(event.payload.threadId); + if (!thread) { + return; + } + const hasSession = thread.session && thread.session.status !== "stopped"; + if (!hasSession) { + return yield* appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.approval.respond.failed", + summary: "Provider approval response failed", + detail: "No active provider session is bound to this thread.", + turnId: null, + createdAt: event.payload.createdAt, + requestId: event.payload.requestId, + }); + } + + yield* providerService + .respondToRequest({ + threadId: event.payload.threadId, + requestId: event.payload.requestId, + decision: event.payload.decision, + }) + .pipe( + Effect.catchCause((cause) => + Effect.gen(function* () { + yield* appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.approval.respond.failed", + summary: "Provider approval response failed", + detail: isUnknownPendingApprovalRequestError(cause) + ? stalePendingRequestDetail("approval", event.payload.requestId) + : Cause.pretty(cause), + turnId: null, + createdAt: event.payload.createdAt, + requestId: event.payload.requestId, + }); + + if (!isUnknownPendingApprovalRequestError(cause)) return; + }), + ), + ); + }); + + const processUserInputResponseRequested = Effect.fn("processUserInputResponseRequested")( + function* ( + event: Extract, + ) { + const thread = yield* resolveThread(event.payload.threadId); + if (!thread) { + return; + } + const hasSession = thread.session && thread.session.status !== "stopped"; + if (!hasSession) { + return yield* appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.user-input.respond.failed", + summary: "Provider user input response failed", + detail: "No active provider session is bound to this thread.", + turnId: null, + createdAt: event.payload.createdAt, + requestId: event.payload.requestId, + }); + } + + yield* providerService + .respondToUserInput({ + threadId: event.payload.threadId, + requestId: event.payload.requestId, + answers: event.payload.answers, + }) + .pipe( + Effect.catchCause((cause) => + appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.user-input.respond.failed", + summary: "Provider user input response failed", + detail: isUnknownPendingUserInputRequestError(cause) + ? stalePendingRequestDetail("user-input", event.payload.requestId) + : Cause.pretty(cause), + turnId: null, + createdAt: event.payload.createdAt, + requestId: event.payload.requestId, + }), + ), + ); + }, + ); + + const processSessionStopRequested = Effect.fn("processSessionStopRequested")(function* ( + event: Extract, + ) { + const thread = yield* resolveThread(event.payload.threadId); + if (!thread) { + return; + } + + const now = event.payload.createdAt; + if (thread.session && thread.session.status !== "stopped") { + yield* providerService.stopSession({ threadId: thread.id }); + } + + yield* setThreadSession({ + threadId: thread.id, + session: { + threadId: thread.id, + status: "stopped", + providerName: thread.session?.providerName ?? null, + runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE, + activeTurnId: null, + lastError: thread.session?.lastError ?? null, + updatedAt: now, + }, + createdAt: now, + }); + }); + + const processDomainEvent = Effect.fn("processDomainEvent")(function* ( + event: ProviderIntentEvent, + ) { + yield* Effect.annotateCurrentSpan({ + "orchestration.event_type": event.type, + "orchestration.thread_id": event.payload.threadId, + ...(event.commandId ? { "orchestration.command_id": event.commandId } : {}), + }); + yield* increment(orchestrationEventsProcessedTotal, { + eventType: event.type, + }); + switch (event.type) { + case "thread.runtime-mode-set": { + const thread = yield* resolveThread(event.payload.threadId); + if (!thread?.session || thread.session.status === "stopped") { + return; + } + const cachedModelSelection = threadModelSelections.get(event.payload.threadId); + yield* ensureSessionForThread( + event.payload.threadId, + event.occurredAt, + cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {}, + ); + return; + } + case "thread.turn-start-requested": + yield* processTurnStartRequested(event); + return; + case "thread.turn-interrupt-requested": + yield* processTurnInterruptRequested(event); + return; + case "thread.approval-response-requested": + yield* processApprovalResponseRequested(event); + return; + case "thread.user-input-response-requested": + yield* processUserInputResponseRequested(event); + return; + case "thread.session-stop-requested": + yield* processSessionStopRequested(event); + return; + } + }); + + const processDomainEventSafely = (event: ProviderIntentEvent) => + processDomainEvent(event).pipe( + Effect.catchCause((cause) => { + if (Cause.hasInterruptsOnly(cause)) { + return Effect.failCause(cause); + } + return Effect.logWarning("provider command reactor failed to process event", { + eventType: event.type, + cause: Cause.pretty(cause), + }); + }), + ); + + const worker = yield* makeDrainableWorker(processDomainEventSafely); + + const start: ProviderCommandReactorShape["start"] = Effect.fn("start")(function* () { + const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) { + if ( + event.type === "thread.runtime-mode-set" || + event.type === "thread.turn-start-requested" || + event.type === "thread.turn-interrupt-requested" || + event.type === "thread.approval-response-requested" || + event.type === "thread.user-input-response-requested" || + event.type === "thread.session-stop-requested" + ) { + return yield* worker.enqueue(event); + } + }); + + yield* Effect.forkScoped( + Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent), + ); + }); + + return { + start, + drain: worker.drain, + } satisfies ProviderCommandReactorShape; +}); + +export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts new file mode 100644 index 0000000000..6c27e1010c --- /dev/null +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -0,0 +1,2387 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import type { + OrchestrationReadModel, + ProviderRuntimeEvent, + ProviderSession, +} from "@t3tools/contracts"; +import { + ApprovalRequestId, + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + EventId, + MessageId, + ProjectId, + ProviderItemId, + type ServerSettings, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect"; +import { afterEach, describe, expect, it } from "vitest"; + +import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; +import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { + ProviderService, + type ProviderServiceShape, +} from "../../provider/Services/ProviderService.ts"; +import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; +import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; +import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts"; +import { + OrchestrationEngineService, + type OrchestrationEngineShape, +} from "../Services/OrchestrationEngine.ts"; +import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; +import { ServerConfig } from "../../config.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; + +function makeTestServerSettingsLayer(overrides: Partial = {}) { + return ServerSettingsService.layerTest(overrides); +} + +const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); +const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value); +const asEventId = (value: string): EventId => EventId.makeUnsafe(value); +const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); +const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value); +const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); + +type LegacyProviderRuntimeEvent = { + readonly type: string; + readonly eventId: EventId; + readonly provider: ProviderRuntimeEvent["provider"]; + readonly createdAt: string; + readonly threadId: ThreadId; + readonly turnId?: string | undefined; + readonly itemId?: string | undefined; + readonly requestId?: string | undefined; + readonly payload?: unknown | undefined; + readonly [key: string]: unknown; +}; + +type LegacyTurnCompletedEvent = LegacyProviderRuntimeEvent & { + readonly type: "turn.completed"; + readonly payload?: undefined; + readonly status: "completed" | "failed" | "interrupted" | "cancelled"; + readonly errorMessage?: string | undefined; +}; + +function isLegacyTurnCompletedEvent( + event: LegacyProviderRuntimeEvent, +): event is LegacyTurnCompletedEvent { + return ( + event.type === "turn.completed" && + event.payload === undefined && + typeof event.status === "string" + ); +} + +function createProviderServiceHarness() { + const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); + const runtimeSessions: ProviderSession[] = []; + + const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; + const service: ProviderServiceShape = { + startSession: () => unsupported(), + sendTurn: () => unsupported(), + interruptTurn: () => unsupported(), + respondToRequest: () => unsupported(), + respondToUserInput: () => unsupported(), + stopSession: () => unsupported(), + listSessions: () => Effect.succeed([...runtimeSessions]), + getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), + rollbackConversation: () => unsupported(), + streamEvents: Stream.fromPubSub(runtimeEventPubSub), + }; + + const setSession = (session: ProviderSession): void => { + const existingIndex = runtimeSessions.findIndex((entry) => entry.threadId === session.threadId); + if (existingIndex >= 0) { + runtimeSessions[existingIndex] = session; + return; + } + runtimeSessions.push(session); + }; + + const normalizeLegacyEvent = (event: LegacyProviderRuntimeEvent): ProviderRuntimeEvent => { + if (isLegacyTurnCompletedEvent(event)) { + const normalized: Extract = { + ...(event as Omit, "payload">), + payload: { + state: event.status, + ...(typeof event.errorMessage === "string" ? { errorMessage: event.errorMessage } : {}), + }, + }; + return normalized; + } + + return event as ProviderRuntimeEvent; + }; + + const emit = (event: LegacyProviderRuntimeEvent): void => { + Effect.runSync(PubSub.publish(runtimeEventPubSub, normalizeLegacyEvent(event))); + }; + + return { + service, + emit, + setSession, + }; +} + +async function waitForThread( + engine: OrchestrationEngineShape, + predicate: (thread: ProviderRuntimeTestThread) => boolean, + timeoutMs = 2000, + threadId: ThreadId = asThreadId("thread-1"), +) { + const deadline = Date.now() + timeoutMs; + const poll = async (): Promise => { + const readModel = await Effect.runPromise(engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === threadId); + if (thread && predicate(thread)) { + return thread; + } + if (Date.now() >= deadline) { + throw new Error("Timed out waiting for thread state"); + } + await new Promise((resolve) => setTimeout(resolve, 10)); + return poll(); + }; + return poll(); +} + +type ProviderRuntimeTestReadModel = OrchestrationReadModel; +type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number]; +type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number]; +type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number]; +type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number]; +type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number]; + +describe("ProviderRuntimeIngestion", () => { + let runtime: ManagedRuntime.ManagedRuntime< + OrchestrationEngineService | ProviderRuntimeIngestionService, + 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) { + await Effect.runPromise(Scope.close(scope, Exit.void)); + } + scope = null; + if (runtime) { + await runtime.dispose(); + } + runtime = null; + for (const dir of tempDirs.splice(0)) { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + async function createHarness(options?: { serverSettings?: Partial }) { + const workspaceRoot = makeTempDir("t3-provider-project-"); + fs.mkdirSync(path.join(workspaceRoot, ".git")); + const provider = createProviderServiceHarness(); + const orchestrationLayer = OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), + Layer.provide(OrchestrationProjectionPipelineLive), + Layer.provide(OrchestrationEventStoreLive), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(SqlitePersistenceMemory), + ); + const layer = ProviderRuntimeIngestionLive.pipe( + Layer.provideMerge(orchestrationLayer), + Layer.provideMerge(SqlitePersistenceMemory), + Layer.provideMerge(Layer.succeed(ProviderService, provider.service)), + Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(NodeServices.layer), + ); + runtime = ManagedRuntime.make(layer); + const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); + const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService)); + scope = await Effect.runPromise(Scope.make("sequential")); + await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope))); + const drain = () => Effect.runPromise(ingestion.drain); + + const createdAt = new Date().toISOString(); + await Effect.runPromise( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-provider-project-create"), + projectId: asProjectId("project-1"), + title: "Provider Project", + workspaceRoot, + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + await Effect.runPromise( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-create"), + threadId: ThreadId.makeUnsafe("thread-1"), + projectId: asProjectId("project-1"), + title: "Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + await Effect.runPromise( + engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-seed"), + threadId: ThreadId.makeUnsafe("thread-1"), + session: { + threadId: ThreadId.makeUnsafe("thread-1"), + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: createdAt, + lastError: null, + }, + createdAt, + }), + ); + provider.setSession({ + provider: "codex", + status: "ready", + runtimeMode: "approval-required", + threadId: ThreadId.makeUnsafe("thread-1"), + createdAt, + updatedAt: createdAt, + }); + + return { + engine, + emit: provider.emit, + setProviderSession: provider.setSession, + drain, + }; + } + + it("maps turn started/completed events into thread session updates", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started"), + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: now, + turnId: asTurnId("turn-1"), + }); + + await waitForThread( + harness.engine, + (thread) => thread.session?.status === "running" && thread.session?.activeTurnId === "turn-1", + ); + + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-turn-completed"), + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + turnId: asTurnId("turn-1"), + payload: { + state: "failed", + errorMessage: "turn failed", + }, + }); + + const thread = await waitForThread( + harness.engine, + (entry) => + entry.session?.status === "error" && + entry.session?.activeTurnId === null && + entry.session?.lastError === "turn failed", + ); + expect(thread.session?.status).toBe("error"); + expect(thread.session?.lastError).toBe("turn failed"); + }); + + it("applies provider session.state.changed transitions directly", async () => { + const harness = await createHarness(); + const waitingAt = new Date().toISOString(); + + harness.emit({ + type: "session.state.changed", + eventId: asEventId("evt-session-state-waiting"), + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: waitingAt, + payload: { + state: "waiting", + reason: "awaiting approval", + }, + }); + + let thread = await waitForThread( + harness.engine, + (entry) => entry.session?.status === "running" && entry.session?.activeTurnId === null, + ); + expect(thread.session?.status).toBe("running"); + expect(thread.session?.lastError).toBeNull(); + + harness.emit({ + type: "session.state.changed", + eventId: asEventId("evt-session-state-error"), + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + payload: { + state: "error", + reason: "provider crashed", + }, + }); + + thread = await waitForThread( + harness.engine, + (entry) => + entry.session?.status === "error" && + entry.session?.activeTurnId === null && + entry.session?.lastError === "provider crashed", + ); + expect(thread.session?.status).toBe("error"); + expect(thread.session?.lastError).toBe("provider crashed"); + + harness.emit({ + type: "session.state.changed", + eventId: asEventId("evt-session-state-stopped"), + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + payload: { + state: "stopped", + }, + }); + + thread = await waitForThread( + harness.engine, + (entry) => + entry.session?.status === "stopped" && + entry.session?.activeTurnId === null && + entry.session?.lastError === "provider crashed", + ); + expect(thread.session?.status).toBe("stopped"); + expect(thread.session?.lastError).toBe("provider crashed"); + + harness.emit({ + type: "session.state.changed", + eventId: asEventId("evt-session-state-ready"), + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + payload: { + state: "ready", + }, + }); + + thread = await waitForThread( + harness.engine, + (entry) => + entry.session?.status === "ready" && + entry.session?.activeTurnId === null && + entry.session?.lastError === null, + ); + expect(thread.session?.status).toBe("ready"); + expect(thread.session?.lastError).toBeNull(); + }); + + it("does not clear active turn when session/thread started arrives mid-turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-midturn-lifecycle"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-midturn-lifecycle"), + }); + + await waitForThread( + harness.engine, + (thread) => + thread.session?.status === "running" && + thread.session?.activeTurnId === "turn-midturn-lifecycle", + ); + + harness.emit({ + type: "thread.started", + eventId: asEventId("evt-thread-started-midturn-lifecycle"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: asThreadId("thread-1"), + }); + harness.emit({ + type: "session.started", + eventId: asEventId("evt-session-started-midturn-lifecycle"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: asThreadId("thread-1"), + }); + + await harness.drain(); + const midReadModel = await Effect.runPromise(harness.engine.getReadModel()); + const midThread = midReadModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + expect(midThread?.session?.status).toBe("running"); + expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle"); + + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-turn-completed-midturn-lifecycle"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-midturn-lifecycle"), + status: "completed", + }); + + await waitForThread( + harness.engine, + (thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null, + ); + }); + + 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: "claudeAgent", + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: seededAt, + lastError: null, + }, + createdAt: seededAt, + }), + ); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-claude-placeholder"), + provider: "claudeAgent", + 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: "claudeAgent", + 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 auxiliary turn completions from a different provider thread", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-primary"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-primary"), + }); + + await waitForThread( + harness.engine, + (thread) => + thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary", + ); + + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-turn-completed-aux"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-aux"), + status: "completed", + }); + + await harness.drain(); + const midReadModel = await Effect.runPromise(harness.engine.getReadModel()); + const midThread = midReadModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + expect(midThread?.session?.status).toBe("running"); + expect(midThread?.session?.activeTurnId).toBe("turn-primary"); + + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-turn-completed-primary"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-primary"), + 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(); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-guarded"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-guarded-main"), + }); + + await waitForThread( + harness.engine, + (thread) => + thread.session?.status === "running" && + thread.session?.activeTurnId === "turn-guarded-main", + ); + + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-turn-completed-guarded-other"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-guarded-other"), + status: "completed", + }); + + await harness.drain(); + const midReadModel = await Effect.runPromise(harness.engine.getReadModel()); + const midThread = midReadModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + expect(midThread?.session?.status).toBe("running"); + expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main"); + + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-turn-completed-guarded-main"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-guarded-main"), + status: "completed", + }); + + await waitForThread( + harness.engine, + (thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null, + ); + }); + + it("maps canonical content delta/item completed into finalized assistant messages", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "content.delta", + eventId: asEventId("evt-message-delta-1"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-2"), + itemId: asItemId("item-1"), + payload: { + streamKind: "assistant_text", + delta: "hello", + }, + }); + harness.emit({ + type: "content.delta", + eventId: asEventId("evt-message-delta-2"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-2"), + itemId: asItemId("item-1"), + payload: { + streamKind: "assistant_text", + delta: " world", + }, + }); + harness.emit({ + type: "item.completed", + eventId: asEventId("evt-message-completed"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-2"), + itemId: asItemId("item-1"), + payload: { + itemType: "assistant_message", + status: "completed", + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.messages.some( + (message: ProviderRuntimeTestMessage) => + message.id === "assistant:item-1" && !message.streaming, + ), + ); + const message = thread.messages.find( + (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-1", + ); + expect(message?.text).toBe("hello world"); + expect(message?.streaming).toBe(false); + }); + + it("uses assistant item completion detail when no assistant deltas were streamed", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "item.completed", + eventId: asEventId("evt-assistant-item-completed-no-delta"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-no-delta"), + itemId: asItemId("item-no-delta"), + payload: { + itemType: "assistant_message", + status: "completed", + detail: "assistant-only final text", + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.messages.some( + (message: ProviderRuntimeTestMessage) => + message.id === "assistant:item-no-delta" && !message.streaming, + ), + ); + const message = thread.messages.find( + (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-no-delta", + ); + expect(message?.text).toBe("assistant-only final text"); + expect(message?.streaming).toBe(false); + }); + + it("projects completed plan items into first-class proposed plans", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "turn.proposed.completed", + eventId: asEventId("evt-plan-item-completed"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-plan-final"), + payload: { + planMarkdown: "## Ship plan\n\n- wire projection\n- render follow-up", + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.proposedPlans.some( + (proposedPlan: ProviderRuntimeTestProposedPlan) => + proposedPlan.id === "plan:thread-1:turn:turn-plan-final", + ), + ); + const proposedPlan = thread.proposedPlans.find( + (entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-plan-final", + ); + expect(proposedPlan?.planMarkdown).toBe( + "## Ship plan\n\n- wire projection\n- render follow-up", + ); + }); + + it("marks the source proposed plan implemented only after the target turn starts", async () => { + const harness = await createHarness(); + const sourceThreadId = asThreadId("thread-plan"); + const targetThreadId = asThreadId("thread-implement"); + const sourceTurnId = asTurnId("turn-plan-source"); + const targetTurnId = asTurnId("turn-plan-implement"); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source"), + threadId: sourceThreadId, + projectId: asProjectId("project-1"), + title: "Plan Source", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: "plan", + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-plan-source"), + threadId: sourceThreadId, + session: { + threadId: sourceThreadId, + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: createdAt, + lastError: null, + }, + createdAt, + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target"), + threadId: targetThreadId, + projectId: asProjectId("project-1"), + title: "Plan Target", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-plan-target"), + threadId: targetThreadId, + session: { + threadId: targetThreadId, + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: createdAt, + lastError: null, + }, + createdAt, + }), + ); + harness.setProviderSession({ + provider: "codex", + status: "ready", + runtimeMode: "approval-required", + threadId: targetThreadId, + createdAt, + updatedAt: createdAt, + activeTurnId: targetTurnId, + }); + + harness.emit({ + type: "turn.proposed.completed", + eventId: asEventId("evt-plan-source-completed"), + provider: "codex", + createdAt, + threadId: sourceThreadId, + turnId: sourceTurnId, + payload: { + planMarkdown: "# Source plan", + }, + }); + + const sourceThreadWithPlan = await waitForThread( + harness.engine, + (thread) => + thread.proposedPlans.some( + (proposedPlan: ProviderRuntimeTestProposedPlan) => + proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" && + proposedPlan.implementedAt === null, + ), + 2_000, + sourceThreadId, + ); + const sourcePlan = sourceThreadWithPlan.proposedPlans.find( + (entry: ProviderRuntimeTestProposedPlan) => + entry.id === "plan:thread-plan:turn:turn-plan-source", + ); + expect(sourcePlan).toBeDefined(); + if (!sourcePlan) { + throw new Error("Expected source plan to exist."); + } + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target"), + threadId: targetThreadId, + message: { + messageId: asMessageId("msg-plan-target"), + role: "user", + text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan", + attachments: [], + }, + sourceProposedPlan: { + threadId: sourceThreadId, + planId: sourcePlan.id, + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: new Date().toISOString(), + }), + ); + + const sourceThreadBeforeStart = await waitForThread( + harness.engine, + (thread) => + thread.proposedPlans.some( + (proposedPlan: ProviderRuntimeTestProposedPlan) => + proposedPlan.id === sourcePlan.id && proposedPlan.implementedAt === null, + ), + 2_000, + sourceThreadId, + ); + expect( + sourceThreadBeforeStart.proposedPlans.find((entry) => entry.id === sourcePlan.id), + ).toMatchObject({ + implementedAt: null, + implementationThreadId: null, + }); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-plan-target-started"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: targetThreadId, + turnId: targetTurnId, + }); + + const sourceThreadAfterStart = await waitForThread( + harness.engine, + (thread) => + thread.proposedPlans.some( + (proposedPlan: ProviderRuntimeTestProposedPlan) => + proposedPlan.id === sourcePlan.id && + proposedPlan.implementedAt !== null && + proposedPlan.implementationThreadId === targetThreadId, + ), + 2_000, + sourceThreadId, + ); + expect( + sourceThreadAfterStart.proposedPlans.find((entry) => entry.id === sourcePlan.id), + ).toMatchObject({ + implementationThreadId: "thread-implement", + }); + }); + + it("does not mark the source proposed plan implemented for a rejected turn.started event", async () => { + const harness = await createHarness(); + const sourceThreadId = asThreadId("thread-plan"); + const targetThreadId = asThreadId("thread-1"); + const sourceTurnId = asTurnId("turn-plan-source"); + const activeTurnId = asTurnId("turn-already-running"); + const staleTurnId = asTurnId("turn-stale-start"); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-guarded"), + threadId: sourceThreadId, + projectId: asProjectId("project-1"), + title: "Plan Source", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: "plan", + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-guarded"), + threadId: sourceThreadId, + session: { + threadId: sourceThreadId, + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: createdAt, + lastError: null, + }, + createdAt, + }), + ); + harness.setProviderSession({ + provider: "codex", + status: "running", + runtimeMode: "approval-required", + threadId: targetThreadId, + createdAt, + updatedAt: createdAt, + activeTurnId, + }); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-already-running"), + provider: "codex", + createdAt, + threadId: targetThreadId, + turnId: activeTurnId, + }); + + await waitForThread( + harness.engine, + (thread) => + thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId, + 2_000, + targetThreadId, + ); + + harness.emit({ + type: "turn.proposed.completed", + eventId: asEventId("evt-plan-source-completed-guarded"), + provider: "codex", + createdAt, + threadId: sourceThreadId, + turnId: sourceTurnId, + payload: { + planMarkdown: "# Source plan", + }, + }); + + const sourceThreadWithPlan = await waitForThread( + harness.engine, + (thread) => + thread.proposedPlans.some( + (proposedPlan: ProviderRuntimeTestProposedPlan) => + proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" && + proposedPlan.implementedAt === null, + ), + 2_000, + sourceThreadId, + ); + const sourcePlan = sourceThreadWithPlan.proposedPlans.find( + (entry: ProviderRuntimeTestProposedPlan) => + entry.id === "plan:thread-plan:turn:turn-plan-source", + ); + expect(sourcePlan).toBeDefined(); + if (!sourcePlan) { + throw new Error("Expected source plan to exist."); + } + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-guarded"), + threadId: targetThreadId, + message: { + messageId: asMessageId("msg-plan-target-guarded"), + role: "user", + text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan", + attachments: [], + }, + sourceProposedPlan: { + threadId: sourceThreadId, + planId: sourcePlan.id, + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: new Date().toISOString(), + }), + ); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-stale-plan-implementation"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: targetThreadId, + turnId: staleTurnId, + }); + + await harness.drain(); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const sourceThreadAfterRejectedStart = readModel.threads.find( + (entry) => entry.id === sourceThreadId, + ); + expect( + sourceThreadAfterRejectedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id), + ).toMatchObject({ + implementedAt: null, + implementationThreadId: null, + }); + + const targetThreadAfterRejectedStart = readModel.threads.find( + (entry) => entry.id === targetThreadId, + ); + expect(targetThreadAfterRejectedStart?.session?.status).toBe("running"); + expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId); + }); + + it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => { + const harness = await createHarness(); + const sourceThreadId = asThreadId("thread-plan"); + const targetThreadId = asThreadId("thread-implement"); + const sourceTurnId = asTurnId("turn-plan-source"); + const expectedTurnId = asTurnId("turn-plan-implement"); + const replayedTurnId = asTurnId("turn-replayed"); + const createdAt = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-unrelated"), + threadId: sourceThreadId, + projectId: asProjectId("project-1"), + title: "Plan Source", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: "plan", + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-unrelated"), + threadId: sourceThreadId, + session: { + threadId: sourceThreadId, + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: createdAt, + lastError: null, + }, + createdAt, + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target-unrelated"), + threadId: targetThreadId, + projectId: asProjectId("project-1"), + title: "Plan Target", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.makeUnsafe("cmd-session-set-plan-target-unrelated"), + threadId: targetThreadId, + session: { + threadId: targetThreadId, + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: createdAt, + lastError: null, + }, + createdAt, + }), + ); + + harness.emit({ + type: "turn.proposed.completed", + eventId: asEventId("evt-plan-source-completed-unrelated"), + provider: "codex", + createdAt, + threadId: sourceThreadId, + turnId: sourceTurnId, + payload: { + planMarkdown: "# Source plan", + }, + }); + + const sourceThreadWithPlan = await waitForThread( + harness.engine, + (thread) => + thread.proposedPlans.some( + (proposedPlan: ProviderRuntimeTestProposedPlan) => + proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" && + proposedPlan.implementedAt === null, + ), + 2_000, + sourceThreadId, + ); + const sourcePlan = sourceThreadWithPlan.proposedPlans.find( + (entry: ProviderRuntimeTestProposedPlan) => + entry.id === "plan:thread-plan:turn:turn-plan-source", + ); + expect(sourcePlan).toBeDefined(); + if (!sourcePlan) { + throw new Error("Expected source plan to exist."); + } + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-unrelated"), + threadId: targetThreadId, + message: { + messageId: asMessageId("msg-plan-target-unrelated"), + role: "user", + text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan", + attachments: [], + }, + sourceProposedPlan: { + threadId: sourceThreadId, + planId: sourcePlan.id, + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: new Date().toISOString(), + }), + ); + + harness.setProviderSession({ + provider: "codex", + status: "running", + runtimeMode: "approval-required", + threadId: targetThreadId, + createdAt, + updatedAt: createdAt, + activeTurnId: expectedTurnId, + }); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-unrelated-plan-implementation"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: targetThreadId, + turnId: replayedTurnId, + }); + + await harness.drain(); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const sourceThreadAfterUnrelatedStart = readModel.threads.find( + (entry) => entry.id === sourceThreadId, + ); + expect( + sourceThreadAfterUnrelatedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id), + ).toMatchObject({ + implementedAt: null, + implementationThreadId: null, + }); + }); + + it("finalizes buffered proposed-plan deltas into a first-class proposed plan on turn completion", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-plan-buffer"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-plan-buffer"), + }); + + await waitForThread( + harness.engine, + (thread) => + thread.session?.status === "running" && thread.session?.activeTurnId === "turn-plan-buffer", + ); + + harness.emit({ + type: "turn.proposed.delta", + eventId: asEventId("evt-plan-delta-1"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-plan-buffer"), + payload: { + delta: "## Buffered plan\n\n- first", + }, + }); + harness.emit({ + type: "turn.proposed.delta", + eventId: asEventId("evt-plan-delta-2"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-plan-buffer"), + payload: { + delta: "\n- second", + }, + }); + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-turn-completed-plan-buffer"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-plan-buffer"), + payload: { + state: "completed", + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.proposedPlans.some( + (proposedPlan: ProviderRuntimeTestProposedPlan) => + proposedPlan.id === "plan:thread-1:turn:turn-plan-buffer", + ), + ); + const proposedPlan = thread.proposedPlans.find( + (entry: ProviderRuntimeTestProposedPlan) => + entry.id === "plan:thread-1:turn:turn-plan-buffer", + ); + expect(proposedPlan?.planMarkdown).toBe("## Buffered plan\n\n- first\n- second"); + }); + + it("buffers assistant deltas by default until completion", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-buffered"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-buffered"), + }); + await waitForThread( + harness.engine, + (thread) => + thread.session?.status === "running" && thread.session?.activeTurnId === "turn-buffered", + ); + + harness.emit({ + type: "content.delta", + eventId: asEventId("evt-message-delta-buffered"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-buffered"), + itemId: asItemId("item-buffered"), + payload: { + streamKind: "assistant_text", + delta: "buffer me", + }, + }); + + await harness.drain(); + const midReadModel = await Effect.runPromise(harness.engine.getReadModel()); + const midThread = midReadModel.threads.find( + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), + ); + expect( + midThread?.messages.some( + (message: ProviderRuntimeTestMessage) => message.id === "assistant:item-buffered", + ), + ).toBe(false); + + harness.emit({ + type: "item.completed", + eventId: asEventId("evt-message-completed-buffered"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-buffered"), + itemId: asItemId("item-buffered"), + payload: { + itemType: "assistant_message", + status: "completed", + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.messages.some( + (message: ProviderRuntimeTestMessage) => + message.id === "assistant:item-buffered" && !message.streaming, + ), + ); + const message = thread.messages.find( + (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered", + ); + expect(message?.text).toBe("buffer me"); + expect(message?.streaming).toBe(false); + }); + + it("streams assistant deltas when thread.turn.start requests streaming mode", async () => { + const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } }); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-streaming-mode"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("message-streaming-mode"), + role: "user", + text: "stream please", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + await harness.drain(); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-streaming-mode"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-streaming-mode"), + }); + await waitForThread( + harness.engine, + (thread) => + thread.session?.status === "running" && + thread.session?.activeTurnId === "turn-streaming-mode", + ); + + harness.emit({ + type: "content.delta", + eventId: asEventId("evt-message-delta-streaming-mode"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-streaming-mode"), + itemId: asItemId("item-streaming-mode"), + payload: { + streamKind: "assistant_text", + delta: "hello live", + }, + }); + + const liveThread = await waitForThread(harness.engine, (entry) => + entry.messages.some( + (message: ProviderRuntimeTestMessage) => + message.id === "assistant:item-streaming-mode" && + message.streaming && + message.text === "hello live", + ), + ); + const liveMessage = liveThread.messages.find( + (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-streaming-mode", + ); + expect(liveMessage?.streaming).toBe(true); + + harness.emit({ + type: "item.completed", + eventId: asEventId("evt-message-completed-streaming-mode"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-streaming-mode"), + itemId: asItemId("item-streaming-mode"), + payload: { + itemType: "assistant_message", + status: "completed", + detail: "hello live", + }, + }); + + const finalThread = await waitForThread(harness.engine, (entry) => + entry.messages.some( + (message: ProviderRuntimeTestMessage) => + message.id === "assistant:item-streaming-mode" && !message.streaming, + ), + ); + const finalMessage = finalThread.messages.find( + (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-streaming-mode", + ); + expect(finalMessage?.text).toBe("hello live"); + expect(finalMessage?.streaming).toBe(false); + }); + + it("spills oversized buffered deltas and still finalizes full assistant text", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + const oversizedText = "x".repeat(40_000); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-buffer-spill"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-buffer-spill"), + }); + await waitForThread( + harness.engine, + (thread) => + thread.session?.status === "running" && + thread.session?.activeTurnId === "turn-buffer-spill", + ); + + harness.emit({ + type: "content.delta", + eventId: asEventId("evt-message-delta-buffer-spill"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-buffer-spill"), + itemId: asItemId("item-buffer-spill"), + payload: { + streamKind: "assistant_text", + delta: oversizedText, + }, + }); + harness.emit({ + type: "item.completed", + eventId: asEventId("evt-message-completed-buffer-spill"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-buffer-spill"), + itemId: asItemId("item-buffer-spill"), + payload: { + itemType: "assistant_message", + status: "completed", + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.messages.some( + (message: ProviderRuntimeTestMessage) => + message.id === "assistant:item-buffer-spill" && !message.streaming, + ), + ); + const message = thread.messages.find( + (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffer-spill", + ); + expect(message?.text.length).toBe(oversizedText.length); + expect(message?.text).toBe(oversizedText); + expect(message?.streaming).toBe(false); + }); + + it("does not duplicate assistant completion when item.completed is followed by turn.completed", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-for-complete-dedup"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-complete-dedup"), + }); + + await waitForThread( + harness.engine, + (thread) => + thread.session?.status === "running" && + thread.session?.activeTurnId === "turn-complete-dedup", + ); + + harness.emit({ + type: "content.delta", + eventId: asEventId("evt-message-delta-for-complete-dedup"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-complete-dedup"), + itemId: asItemId("item-complete-dedup"), + payload: { + streamKind: "assistant_text", + delta: "done", + }, + }); + harness.emit({ + type: "item.completed", + eventId: asEventId("evt-message-completed-for-complete-dedup"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-complete-dedup"), + itemId: asItemId("item-complete-dedup"), + payload: { + itemType: "assistant_message", + status: "completed", + }, + }); + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-turn-completed-for-complete-dedup"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-complete-dedup"), + payload: { + state: "completed", + }, + }); + + await waitForThread( + harness.engine, + (thread) => + thread.session?.status === "ready" && + thread.session?.activeTurnId === null && + thread.messages.some( + (message: ProviderRuntimeTestMessage) => + message.id === "assistant:item-complete-dedup" && !message.streaming, + ), + ); + + const events = await Effect.runPromise( + Stream.runCollect(harness.engine.readEvents(0)).pipe( + Effect.map((chunk) => Array.from(chunk)), + ), + ); + const completionEvents = events.filter((event) => { + if (event.type !== "thread.message-sent") { + return false; + } + return ( + event.payload.messageId === "assistant:item-complete-dedup" && + event.payload.streaming === false + ); + }); + expect(completionEvents).toHaveLength(1); + }); + + it("maps canonical request events into approval activities with requestKind", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "request.opened", + eventId: asEventId("evt-request-opened"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + requestId: ApprovalRequestId.makeUnsafe("req-open"), + payload: { + requestType: "command_execution_approval", + detail: "pwd", + }, + }); + + harness.emit({ + type: "request.resolved", + eventId: asEventId("evt-request-resolved"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + requestId: ApprovalRequestId.makeUnsafe("req-open"), + payload: { + requestType: "command_execution_approval", + decision: "accept", + }, + }); + + await waitForThread( + harness.engine, + (entry) => + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested", + ) && + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "approval.resolved", + ), + ); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread).toBeDefined(); + + const requested = thread?.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.id === "evt-request-opened", + ); + const requestedPayload = + requested?.payload && typeof requested.payload === "object" + ? (requested.payload as Record) + : undefined; + expect(requestedPayload?.requestKind).toBe("command"); + expect(requestedPayload?.requestType).toBe("command_execution_approval"); + + const resolved = thread?.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.id === "evt-request-resolved", + ); + const resolvedPayload = + resolved?.payload && typeof resolved.payload === "object" + ? (resolved.payload as Record) + : undefined; + expect(resolvedPayload?.requestKind).toBe("command"); + expect(resolvedPayload?.requestType).toBe("command_execution_approval"); + }); + + it("maps runtime.error into errored session state", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "runtime.error", + eventId: asEventId("evt-runtime-error"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-3"), + payload: { + message: "runtime exploded", + }, + }); + + const thread = await waitForThread( + harness.engine, + (entry) => + entry.session?.status === "error" && + entry.session?.activeTurnId === "turn-3" && + entry.session?.lastError === "runtime exploded", + ); + expect(thread.session?.status).toBe("error"); + expect(thread.session?.lastError).toBe("runtime exploded"); + }); + + it("records runtime.error activities from the typed payload message", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "runtime.error", + eventId: asEventId("evt-runtime-error-activity"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-runtime-error-activity"), + payload: { + message: "runtime activity exploded", + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"), + ); + const activity = thread.activities.find( + (entry: ProviderRuntimeTestActivity) => entry.id === "evt-runtime-error-activity", + ); + const activityPayload = + activity?.payload && typeof activity.payload === "object" + ? (activity.payload as Record) + : undefined; + + expect(activity?.kind).toBe("runtime.error"); + expect(activityPayload?.message).toBe("runtime activity exploded"); + }); + + it("keeps the session running when a runtime.warning arrives during an active turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-warning-turn-started"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-warning"), + payload: {}, + }); + + harness.emit({ + type: "runtime.warning", + eventId: asEventId("evt-warning-runtime"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-warning"), + payload: { + message: "Reconnecting... 2/5", + detail: { + willRetry: true, + }, + }, + }); + + const thread = await waitForThread( + harness.engine, + (entry) => + entry.session?.status === "running" && + entry.session?.activeTurnId === "turn-warning" && + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => + activity.id === "evt-warning-runtime" && activity.kind === "runtime.warning", + ), + ); + expect(thread.session?.status).toBe("running"); + expect(thread.session?.activeTurnId).toBe("turn-warning"); + expect(thread.session?.lastError).toBeNull(); + }); + + it("maps session/thread lifecycle and item.started into session/activity projections", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "session.started", + eventId: asEventId("evt-session-started"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + message: "session started", + }); + harness.emit({ + type: "thread.started", + eventId: asEventId("evt-thread-started"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + }); + harness.emit({ + type: "item.started", + eventId: asEventId("evt-tool-started"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-9"), + payload: { + itemType: "command_execution", + status: "in_progress", + title: "Read file", + detail: "/tmp/file.ts", + }, + }); + + const thread = await waitForThread( + harness.engine, + (entry) => + entry.session?.status === "ready" && + entry.session?.activeTurnId === null && + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "tool.started", + ), + ); + + expect(thread.session?.status).toBe("ready"); + expect( + thread.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "tool.started", + ), + ).toBe(true); + }); + + it("consumes P1 runtime events into thread metadata, diff checkpoints, and activities", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "thread.metadata.updated", + eventId: asEventId("evt-thread-metadata-updated"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + payload: { + name: "Renamed by provider", + metadata: { source: "provider" }, + }, + }); + + harness.emit({ + type: "turn.plan.updated", + eventId: asEventId("evt-turn-plan-updated"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-p1"), + payload: { + explanation: "Working through the plan", + plan: [ + { step: "Inspect files", status: "completed" }, + { step: "Apply patch", status: "in_progress" }, + ], + }, + }); + + harness.emit({ + type: "item.updated", + eventId: asEventId("evt-item-updated"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-p1"), + itemId: asItemId("item-p1-tool"), + payload: { + itemType: "command_execution", + status: "in_progress", + title: "Run tests", + detail: "bun test", + data: { pid: 123 }, + }, + }); + + harness.emit({ + type: "runtime.warning", + eventId: asEventId("evt-runtime-warning"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-p1"), + payload: { + message: "Provider got slow", + detail: { latencyMs: 1500 }, + }, + }); + + harness.emit({ + type: "turn.diff.updated", + eventId: asEventId("evt-turn-diff-updated"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-p1"), + itemId: asItemId("item-p1-assistant"), + payload: { + unifiedDiff: "diff --git a/file.txt b/file.txt\n+hello\n", + }, + }); + + const thread = await waitForThread( + harness.engine, + (entry) => + entry.title === "Renamed by provider" && + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "turn.plan.updated", + ) && + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "tool.updated", + ) && + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "runtime.warning", + ) && + entry.checkpoints.some( + (checkpoint: ProviderRuntimeTestCheckpoint) => checkpoint.turnId === "turn-p1", + ), + ); + + expect(thread.title).toBe("Renamed by provider"); + + const planActivity = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.id === "evt-turn-plan-updated", + ); + const planPayload = + planActivity?.payload && typeof planActivity.payload === "object" + ? (planActivity.payload as Record) + : undefined; + expect(planActivity?.kind).toBe("turn.plan.updated"); + expect(Array.isArray(planPayload?.plan)).toBe(true); + + const toolUpdate = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.id === "evt-item-updated", + ); + const toolUpdatePayload = + toolUpdate?.payload && typeof toolUpdate.payload === "object" + ? (toolUpdate.payload as Record) + : undefined; + expect(toolUpdate?.kind).toBe("tool.updated"); + expect(toolUpdatePayload?.itemType).toBe("command_execution"); + expect(toolUpdatePayload?.status).toBe("in_progress"); + + const warning = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.id === "evt-runtime-warning", + ); + const warningPayload = + warning?.payload && typeof warning.payload === "object" + ? (warning.payload as Record) + : undefined; + expect(warning?.kind).toBe("runtime.warning"); + expect(warningPayload?.message).toBe("Provider got slow"); + + const checkpoint = thread.checkpoints.find( + (entry: ProviderRuntimeTestCheckpoint) => entry.turnId === "turn-p1", + ); + expect(checkpoint?.status).toBe("missing"); + expect(checkpoint?.assistantMessageId).toBe("assistant:item-p1-assistant"); + expect(checkpoint?.checkpointRef).toBe("provider-diff:evt-turn-diff-updated"); + }); + + it("projects context window updates into normalized thread activities", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "thread.token-usage.updated", + eventId: asEventId("evt-thread-token-usage-updated"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + payload: { + usage: { + usedTokens: 1075, + totalProcessedTokens: 10_200, + maxTokens: 128_000, + inputTokens: 1000, + cachedInputTokens: 500, + outputTokens: 50, + reasoningOutputTokens: 25, + lastUsedTokens: 1075, + lastInputTokens: 1000, + lastCachedInputTokens: 500, + lastOutputTokens: 50, + lastReasoningOutputTokens: 25, + compactsAutomatically: true, + }, + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", + ), + ); + + const usageActivity = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", + ); + expect(usageActivity).toBeDefined(); + expect(usageActivity?.payload).toMatchObject({ + usedTokens: 1075, + totalProcessedTokens: 10_200, + maxTokens: 128_000, + inputTokens: 1000, + cachedInputTokens: 500, + outputTokens: 50, + reasoningOutputTokens: 25, + lastUsedTokens: 1075, + compactsAutomatically: true, + }); + }); + + it("projects Codex camelCase token usage payloads into normalized thread activities", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "thread.token-usage.updated", + eventId: asEventId("evt-thread-token-usage-updated-camel"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + payload: { + usage: { + usedTokens: 126, + totalProcessedTokens: 11_839, + maxTokens: 258_400, + inputTokens: 120, + cachedInputTokens: 0, + outputTokens: 6, + reasoningOutputTokens: 0, + lastUsedTokens: 126, + lastInputTokens: 120, + lastCachedInputTokens: 0, + lastOutputTokens: 6, + lastReasoningOutputTokens: 0, + compactsAutomatically: true, + }, + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", + ), + ); + + const usageActivity = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", + ); + expect(usageActivity?.payload).toMatchObject({ + usedTokens: 126, + totalProcessedTokens: 11_839, + maxTokens: 258_400, + inputTokens: 120, + cachedInputTokens: 0, + outputTokens: 6, + reasoningOutputTokens: 0, + lastUsedTokens: 126, + lastInputTokens: 120, + lastOutputTokens: 6, + compactsAutomatically: true, + }); + }); + + it("projects Claude usage snapshots with context window into normalized thread activities", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "thread.token-usage.updated", + eventId: asEventId("evt-thread-token-usage-updated-claude-window"), + provider: "claudeAgent", + createdAt: now, + threadId: asThreadId("thread-1"), + payload: { + usage: { + usedTokens: 31_251, + lastUsedTokens: 31_251, + maxTokens: 200_000, + toolUses: 25, + durationMs: 43_567, + }, + }, + raw: { + source: "claude.sdk.message", + method: "claude/result/success", + payload: {}, + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", + ), + ); + + const usageActivity = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", + ); + expect(usageActivity?.payload).toMatchObject({ + usedTokens: 31_251, + lastUsedTokens: 31_251, + maxTokens: 200_000, + toolUses: 25, + durationMs: 43_567, + }); + }); + + it("projects compacted thread state into context compaction activities", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "thread.state.changed", + eventId: asEventId("evt-thread-compacted"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-1"), + payload: { + state: "compacted", + detail: { source: "provider" }, + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction", + ), + ); + + const activity = thread.activities.find( + (candidate: ProviderRuntimeTestActivity) => candidate.kind === "context-compaction", + ); + expect(activity?.summary).toBe("Context compacted"); + expect(activity?.tone).toBe("info"); + }); + + it("projects Codex task lifecycle chunks into thread activities", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "task.started", + eventId: asEventId("evt-task-started"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-task-1"), + payload: { + taskId: "turn-task-1", + taskType: "plan", + }, + }); + + harness.emit({ + type: "task.progress", + eventId: asEventId("evt-task-progress"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-task-1"), + payload: { + taskId: "turn-task-1", + description: "Comparing the desktop rollout chunks to the app-server stream.", + summary: "Code reviewer is validating the desktop rollout chunks.", + }, + }); + + harness.emit({ + type: "task.completed", + eventId: asEventId("evt-task-completed"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-task-1"), + payload: { + taskId: "turn-task-1", + status: "completed", + summary: "\n# Plan title\n", + }, + }); + harness.emit({ + type: "turn.proposed.completed", + eventId: asEventId("evt-task-proposed-plan-completed"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-task-1"), + payload: { + planMarkdown: "# Plan title", + }, + }); + + const thread = await waitForThread( + harness.engine, + (entry) => + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "task.completed", + ) && + entry.proposedPlans.some( + (proposedPlan: ProviderRuntimeTestProposedPlan) => + proposedPlan.id === "plan:thread-1:turn:turn-task-1", + ), + ); + + const started = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-started", + ); + const progress = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-progress", + ); + const completed = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-completed", + ); + + const progressPayload = + progress?.payload && typeof progress.payload === "object" + ? (progress.payload as Record) + : undefined; + const completedPayload = + completed?.payload && typeof completed.payload === "object" + ? (completed.payload as Record) + : undefined; + + expect(started?.kind).toBe("task.started"); + expect(started?.summary).toBe("Plan task started"); + expect(progress?.kind).toBe("task.progress"); + expect(progressPayload?.detail).toBe("Code reviewer is validating the desktop rollout chunks."); + expect(progressPayload?.summary).toBe( + "Code reviewer is validating the desktop rollout chunks.", + ); + expect(completed?.kind).toBe("task.completed"); + expect(completedPayload?.detail).toBe("\n# Plan title\n"); + expect( + thread.proposedPlans.find( + (entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-task-1", + )?.planMarkdown, + ).toBe("# Plan title"); + }); + + it("projects structured user input request and resolution as thread activities", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "user-input.requested", + eventId: asEventId("evt-user-input-requested"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-user-input"), + requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"), + payload: { + questions: [ + { + id: "sandbox_mode", + header: "Sandbox", + question: "Which mode should be used?", + options: [ + { + label: "workspace-write", + description: "Allow workspace writes only", + }, + ], + }, + ], + }, + }); + + harness.emit({ + type: "user-input.resolved", + eventId: asEventId("evt-user-input-resolved"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-user-input"), + requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"), + payload: { + answers: { + sandbox_mode: "workspace-write", + }, + }, + }); + + const thread = await waitForThread( + harness.engine, + (entry) => + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "user-input.requested", + ) && + entry.activities.some( + (activity: ProviderRuntimeTestActivity) => activity.kind === "user-input.resolved", + ), + ); + + const requested = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.id === "evt-user-input-requested", + ); + expect(requested?.kind).toBe("user-input.requested"); + + const resolved = thread.activities.find( + (activity: ProviderRuntimeTestActivity) => activity.id === "evt-user-input-resolved", + ); + const resolvedPayload = + resolved?.payload && typeof resolved.payload === "object" + ? (resolved.payload as Record) + : undefined; + expect(resolved?.kind).toBe("user-input.resolved"); + expect(resolvedPayload?.answers).toEqual({ + sandbox_mode: "workspace-write", + }); + }); + + it("continues processing runtime events after a single event handler failure", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "content.delta", + eventId: asEventId("evt-invalid-delta"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-invalid"), + itemId: asItemId("item-invalid"), + payload: { + streamKind: "assistant_text", + delta: undefined, + }, + } as unknown as ProviderRuntimeEvent); + + harness.emit({ + type: "runtime.error", + eventId: asEventId("evt-runtime-error-after-failure"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-after-failure"), + payload: { + message: "runtime still processed", + }, + }); + + const thread = await waitForThread( + harness.engine, + (entry) => + entry.session?.status === "error" && + entry.session?.activeTurnId === "turn-after-failure" && + entry.session?.lastError === "runtime still processed", + ); + expect(thread.session?.status).toBe("error"); + expect(thread.session?.lastError).toBe("runtime still processed"); + }); +}); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts new file mode 100644 index 0000000000..8d3fb5d752 --- /dev/null +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -0,0 +1,1272 @@ +import { + ApprovalRequestId, + type AssistantDeliveryMode, + CommandId, + MessageId, + type OrchestrationEvent, + type OrchestrationProposedPlanId, + CheckpointRef, + isToolLifecycleItemType, + ThreadId, + type ThreadTokenUsageSnapshot, + TurnId, + type OrchestrationThreadActivity, + type ProviderRuntimeEvent, +} from "@t3tools/contracts"; +import { Cache, Cause, Duration, Effect, Layer, Option, Stream } from "effect"; +import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; + +import { ProviderService } from "../../provider/Services/ProviderService.ts"; +import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts"; +import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; +import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts"; +import { isGitRepository } from "../../git/Utils.ts"; +import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; +import { + ProviderRuntimeIngestionService, + type ProviderRuntimeIngestionShape, +} from "../Services/ProviderRuntimeIngestion.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; + +const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`; +const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId => + CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`); + +const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000; +const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120); +const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000; +const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120); +const BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY = 10_000; +const BUFFERED_PROPOSED_PLAN_BY_ID_TTL = Duration.minutes(120); +const MAX_BUFFERED_ASSISTANT_CHARS = 24_000; +const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0"; + +type TurnStartRequestedDomainEvent = Extract< + OrchestrationEvent, + { type: "thread.turn-start-requested" } +>; + +type RuntimeIngestionInput = + | { + source: "runtime"; + event: ProviderRuntimeEvent; + } + | { + source: "domain"; + event: TurnStartRequestedDomainEvent; + }; + +function toTurnId(value: TurnId | string | undefined): TurnId | undefined { + return value === undefined ? undefined : TurnId.makeUnsafe(String(value)); +} + +function toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined { + return value === undefined ? undefined : ApprovalRequestId.makeUnsafe(value); +} + +function sameId(left: string | null | undefined, right: string | null | undefined): boolean { + if (left === null || left === undefined || right === null || right === undefined) { + return false; + } + return left === right; +} + +function truncateDetail(value: string, limit = 180): string { + return value.length > limit ? `${value.slice(0, limit - 3)}...` : value; +} + +function normalizeProposedPlanMarkdown(planMarkdown: string | undefined): string | undefined { + const trimmed = planMarkdown?.trim(); + if (!trimmed) { + return undefined; + } + return trimmed; +} + +function proposedPlanIdForTurn(threadId: ThreadId, turnId: TurnId): string { + return `plan:${threadId}:turn:${turnId}`; +} + +function proposedPlanIdFromEvent(event: ProviderRuntimeEvent, threadId: ThreadId): string { + const turnId = toTurnId(event.turnId); + if (turnId) { + return proposedPlanIdForTurn(threadId, turnId); + } + if (event.itemId) { + return `plan:${threadId}:item:${event.itemId}`; + } + return `plan:${threadId}:event:${event.eventId}`; +} + +function buildContextWindowActivityPayload( + event: ProviderRuntimeEvent, +): ThreadTokenUsageSnapshot | undefined { + if (event.type !== "thread.token-usage.updated" || event.payload.usage.usedTokens <= 0) { + return undefined; + } + return event.payload.usage; +} + +function normalizeRuntimeTurnState( + value: string | undefined, +): "completed" | "failed" | "interrupted" | "cancelled" { + switch (value) { + case "failed": + case "interrupted": + case "cancelled": + case "completed": + return value; + default: + return "completed"; + } +} + +function orchestrationSessionStatusFromRuntimeState( + state: "starting" | "running" | "waiting" | "ready" | "interrupted" | "stopped" | "error", +): "starting" | "running" | "ready" | "interrupted" | "stopped" | "error" { + switch (state) { + case "starting": + return "starting"; + case "running": + case "waiting": + return "running"; + case "ready": + return "ready"; + case "interrupted": + return "interrupted"; + case "stopped": + return "stopped"; + case "error": + return "error"; + } +} + +function requestKindFromCanonicalRequestType( + requestType: string | undefined, +): "command" | "file-read" | "file-change" | undefined { + switch (requestType) { + case "command_execution_approval": + case "exec_command_approval": + return "command"; + case "file_read_approval": + return "file-read"; + case "file_change_approval": + case "apply_patch_approval": + return "file-change"; + default: + return undefined; + } +} + +function runtimeEventToActivities( + event: ProviderRuntimeEvent, +): ReadonlyArray { + const maybeSequence = (() => { + const eventWithSequence = event as ProviderRuntimeEvent & { sessionSequence?: number }; + return eventWithSequence.sessionSequence !== undefined + ? { sequence: eventWithSequence.sessionSequence } + : {}; + })(); + switch (event.type) { + case "request.opened": { + if (event.payload.requestType === "tool_user_input") { + return []; + } + const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType); + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "approval", + kind: "approval.requested", + summary: + requestKind === "command" + ? "Command approval requested" + : requestKind === "file-read" + ? "File-read approval requested" + : requestKind === "file-change" + ? "File-change approval requested" + : "Approval requested", + payload: { + requestId: toApprovalRequestId(event.requestId), + ...(requestKind ? { requestKind } : {}), + requestType: event.payload.requestType, + ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "request.resolved": { + if (event.payload.requestType === "tool_user_input") { + return []; + } + const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType); + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "approval", + kind: "approval.resolved", + summary: "Approval resolved", + payload: { + requestId: toApprovalRequestId(event.requestId), + ...(requestKind ? { requestKind } : {}), + requestType: event.payload.requestType, + ...(event.payload.decision ? { decision: event.payload.decision } : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "runtime.error": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "error", + kind: "runtime.error", + summary: "Runtime error", + payload: { + message: truncateDetail(event.payload.message), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "runtime.warning": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "info", + kind: "runtime.warning", + summary: "Runtime warning", + payload: { + message: truncateDetail(event.payload.message), + ...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "turn.plan.updated": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "info", + kind: "turn.plan.updated", + summary: "Plan updated", + payload: { + plan: event.payload.plan, + ...(event.payload.explanation !== undefined + ? { explanation: event.payload.explanation } + : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "user-input.requested": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "info", + kind: "user-input.requested", + summary: "User input requested", + payload: { + ...(event.requestId ? { requestId: event.requestId } : {}), + questions: event.payload.questions, + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "user-input.resolved": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "info", + kind: "user-input.resolved", + summary: "User input submitted", + payload: { + ...(event.requestId ? { requestId: event.requestId } : {}), + answers: event.payload.answers, + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "task.started": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "info", + kind: "task.started", + summary: + event.payload.taskType === "plan" + ? "Plan task started" + : event.payload.taskType + ? `${event.payload.taskType} task started` + : "Task started", + payload: { + taskId: event.payload.taskId, + ...(event.payload.taskType ? { taskType: event.payload.taskType } : {}), + ...(event.payload.description + ? { detail: truncateDetail(event.payload.description) } + : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "task.progress": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "info", + kind: "task.progress", + summary: "Reasoning update", + payload: { + taskId: event.payload.taskId, + detail: truncateDetail(event.payload.summary ?? event.payload.description), + ...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}), + ...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}), + ...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "task.completed": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: event.payload.status === "failed" ? "error" : "info", + kind: "task.completed", + summary: + event.payload.status === "failed" + ? "Task failed" + : event.payload.status === "stopped" + ? "Task stopped" + : "Task completed", + payload: { + taskId: event.payload.taskId, + status: event.payload.status, + ...(event.payload.summary ? { detail: truncateDetail(event.payload.summary) } : {}), + ...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "thread.state.changed": { + if (event.payload.state !== "compacted") { + return []; + } + + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "info", + kind: "context-compaction", + summary: "Context compacted", + payload: { + state: event.payload.state, + ...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "thread.token-usage.updated": { + const payload = buildContextWindowActivityPayload(event); + if (!payload) { + return []; + } + + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "info", + kind: "context-window.updated", + summary: "Context window updated", + payload, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "item.updated": { + if (!isToolLifecycleItemType(event.payload.itemType)) { + return []; + } + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "tool", + kind: "tool.updated", + summary: event.payload.title ?? "Tool updated", + payload: { + itemType: event.payload.itemType, + ...(event.payload.status ? { status: event.payload.status } : {}), + ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}), + ...(event.payload.data !== undefined ? { data: event.payload.data } : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "item.completed": { + if (!isToolLifecycleItemType(event.payload.itemType)) { + return []; + } + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "tool", + kind: "tool.completed", + summary: event.payload.title ?? "Tool", + payload: { + itemType: event.payload.itemType, + ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "item.started": { + if (!isToolLifecycleItemType(event.payload.itemType)) { + return []; + } + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "tool", + kind: "tool.started", + summary: `${event.payload.title ?? "Tool"} started`, + payload: { + itemType: event.payload.itemType, + ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}), + }, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + default: + break; + } + + return []; +} + +const make = Effect.fn("make")(function* () { + const orchestrationEngine = yield* OrchestrationEngineService; + const providerService = yield* ProviderService; + const projectionTurnRepository = yield* ProjectionTurnRepository; + const serverSettingsService = yield* ServerSettingsService; + + const turnMessageIdsByTurnKey = yield* Cache.make>({ + capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY, + timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL, + lookup: () => Effect.succeed(new Set()), + }); + + const bufferedAssistantTextByMessageId = yield* Cache.make({ + capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY, + timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL, + lookup: () => Effect.succeed(""), + }); + + const bufferedProposedPlanById = yield* Cache.make({ + capacity: BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY, + timeToLive: BUFFERED_PROPOSED_PLAN_BY_ID_TTL, + lookup: () => Effect.succeed({ text: "", createdAt: "" }), + }); + + const isGitRepoForThread = Effect.fn("isGitRepoForThread")(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, messageId: MessageId) => + Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe( + Effect.flatMap((existingIds) => + Cache.set( + turnMessageIdsByTurnKey, + providerTurnKey(threadId, turnId), + Option.match(existingIds, { + onNone: () => new Set([messageId]), + onSome: (ids) => { + const nextIds = new Set(ids); + nextIds.add(messageId); + return nextIds; + }, + }), + ), + ), + ); + + const forgetAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) => + Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe( + Effect.flatMap((existingIds) => + Option.match(existingIds, { + onNone: () => Effect.void, + onSome: (ids) => { + const nextIds = new Set(ids); + nextIds.delete(messageId); + if (nextIds.size === 0) { + return Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)); + } + return Cache.set(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId), nextIds); + }, + }), + ), + ); + + const getAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) => + Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe( + Effect.map((existingIds) => + Option.getOrElse(existingIds, (): Set => new Set()), + ), + ); + + const clearAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) => + Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)); + + const appendBufferedAssistantText = (messageId: MessageId, delta: string) => + Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe( + Effect.flatMap( + Effect.fn("appendBufferedAssistantText")(function* (existingText) { + const nextText = Option.match(existingText, { + onNone: () => delta, + onSome: (text) => `${text}${delta}`, + }); + if (nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS) { + yield* Cache.set(bufferedAssistantTextByMessageId, messageId, nextText); + return ""; + } + + // Safety valve: flush full buffered text as an assistant delta to cap memory. + yield* Cache.invalidate(bufferedAssistantTextByMessageId, messageId); + return nextText; + }), + ), + ); + + const takeBufferedAssistantText = (messageId: MessageId) => + Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe( + Effect.flatMap((existingText) => + Cache.invalidate(bufferedAssistantTextByMessageId, messageId).pipe( + Effect.as(Option.getOrElse(existingText, () => "")), + ), + ), + ); + + const clearBufferedAssistantText = (messageId: MessageId) => + Cache.invalidate(bufferedAssistantTextByMessageId, messageId); + + const appendBufferedProposedPlan = (planId: string, delta: string, createdAt: string) => + Cache.getOption(bufferedProposedPlanById, planId).pipe( + Effect.flatMap((existingEntry) => { + const existing = Option.getOrUndefined(existingEntry); + return Cache.set(bufferedProposedPlanById, planId, { + text: `${existing?.text ?? ""}${delta}`, + createdAt: + existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt, + }); + }), + ); + + const takeBufferedProposedPlan = (planId: string) => + Cache.getOption(bufferedProposedPlanById, planId).pipe( + Effect.flatMap((existingEntry) => + Cache.invalidate(bufferedProposedPlanById, planId).pipe( + Effect.as(Option.getOrUndefined(existingEntry)), + ), + ), + ); + + const clearBufferedProposedPlan = (planId: string) => + Cache.invalidate(bufferedProposedPlanById, planId); + + const clearAssistantMessageState = (messageId: MessageId) => + clearBufferedAssistantText(messageId); + + const finalizeAssistantMessage = Effect.fn("finalizeAssistantMessage")(function* (input: { + event: ProviderRuntimeEvent; + threadId: ThreadId; + messageId: MessageId; + turnId?: TurnId; + createdAt: string; + commandTag: string; + finalDeltaCommandTag: string; + fallbackText?: string; + }) { + const bufferedText = yield* takeBufferedAssistantText(input.messageId); + const text = + bufferedText.length > 0 + ? bufferedText + : (input.fallbackText?.trim().length ?? 0) > 0 + ? input.fallbackText! + : ""; + + if (text.length > 0) { + yield* orchestrationEngine.dispatch({ + type: "thread.message.assistant.delta", + commandId: providerCommandId(input.event, input.finalDeltaCommandTag), + threadId: input.threadId, + messageId: input.messageId, + delta: text, + ...(input.turnId ? { turnId: input.turnId } : {}), + createdAt: input.createdAt, + }); + } + + yield* orchestrationEngine.dispatch({ + type: "thread.message.assistant.complete", + commandId: providerCommandId(input.event, input.commandTag), + threadId: input.threadId, + messageId: input.messageId, + ...(input.turnId ? { turnId: input.turnId } : {}), + createdAt: input.createdAt, + }); + yield* clearAssistantMessageState(input.messageId); + }); + + const upsertProposedPlan = Effect.fn("upsertProposedPlan")(function* (input: { + event: ProviderRuntimeEvent; + threadId: ThreadId; + threadProposedPlans: ReadonlyArray<{ + id: string; + createdAt: string; + implementedAt: string | null; + implementationThreadId: ThreadId | null; + }>; + planId: string; + turnId?: TurnId; + planMarkdown: string | undefined; + createdAt: string; + updatedAt: string; + }) { + const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown); + if (!planMarkdown) { + return; + } + + const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId); + yield* orchestrationEngine.dispatch({ + type: "thread.proposed-plan.upsert", + commandId: providerCommandId(input.event, "proposed-plan-upsert"), + threadId: input.threadId, + proposedPlan: { + id: input.planId, + turnId: input.turnId ?? null, + planMarkdown, + implementedAt: existingPlan?.implementedAt ?? null, + implementationThreadId: existingPlan?.implementationThreadId ?? null, + createdAt: existingPlan?.createdAt ?? input.createdAt, + updatedAt: input.updatedAt, + }, + createdAt: input.updatedAt, + }); + }); + + const finalizeBufferedProposedPlan = Effect.fn("finalizeBufferedProposedPlan")(function* (input: { + event: ProviderRuntimeEvent; + threadId: ThreadId; + threadProposedPlans: ReadonlyArray<{ + id: string; + createdAt: string; + implementedAt: string | null; + implementationThreadId: ThreadId | null; + }>; + planId: string; + turnId?: TurnId; + fallbackMarkdown?: string; + updatedAt: string; + }) { + const bufferedPlan = yield* takeBufferedProposedPlan(input.planId); + const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text); + const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown); + const planMarkdown = bufferedMarkdown ?? fallbackMarkdown; + if (!planMarkdown) { + return; + } + + yield* upsertProposedPlan({ + event: input.event, + threadId: input.threadId, + threadProposedPlans: input.threadProposedPlans, + planId: input.planId, + ...(input.turnId ? { turnId: input.turnId } : {}), + planMarkdown, + createdAt: + bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0 + ? bufferedPlan.createdAt + : input.updatedAt, + updatedAt: input.updatedAt, + }); + yield* clearBufferedProposedPlan(input.planId); + }); + + const clearTurnStateForSession = Effect.fn("clearTurnStateForSession")(function* ( + threadId: ThreadId, + ) { + const prefix = `${threadId}:`; + const proposedPlanPrefix = `plan:${threadId}:`; + const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey)); + const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById)); + yield* Effect.forEach( + turnKeys, + Effect.fn(function* (key) { + if (!key.startsWith(prefix)) { + return; + } + + const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key); + if (Option.isSome(messageIds)) { + yield* Effect.forEach(messageIds.value, clearAssistantMessageState, { + concurrency: 1, + }).pipe(Effect.asVoid); + } + + yield* Cache.invalidate(turnMessageIdsByTurnKey, key); + }), + { concurrency: 1 }, + ).pipe(Effect.asVoid); + yield* Effect.forEach( + proposedPlanKeys, + (key) => + key.startsWith(proposedPlanPrefix) + ? Cache.invalidate(bufferedProposedPlanById, key) + : Effect.void, + { concurrency: 1 }, + ).pipe(Effect.asVoid); + }); + + const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn( + "getSourceProposedPlanReferenceForPendingTurnStart", + )(function* (threadId: ThreadId) { + const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ + threadId, + }); + if (Option.isNone(pendingTurnStart)) { + return null; + } + + const sourceThreadId = pendingTurnStart.value.sourceProposedPlanThreadId; + const sourcePlanId = pendingTurnStart.value.sourceProposedPlanId; + if (sourceThreadId === null || sourcePlanId === null) { + return null; + } + + return { + sourceThreadId, + sourcePlanId, + } as const; + }); + + const getExpectedProviderTurnIdForThread = Effect.fn("getExpectedProviderTurnIdForThread")( + function* (threadId: ThreadId) { + const sessions = yield* providerService.listSessions(); + const session = sessions.find((entry) => entry.threadId === threadId); + return session?.activeTurnId; + }, + ); + + const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fn( + "getSourceProposedPlanReferenceForAcceptedTurnStart", + )(function* (threadId: ThreadId, eventTurnId: TurnId | undefined) { + if (eventTurnId === undefined) { + return null; + } + + const expectedTurnId = yield* getExpectedProviderTurnIdForThread(threadId); + if (!sameId(expectedTurnId, eventTurnId)) { + return null; + } + + return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId); + }); + + const markSourceProposedPlanImplemented = Effect.fn("markSourceProposedPlanImplemented")( + function* ( + sourceThreadId: ThreadId, + sourcePlanId: OrchestrationProposedPlanId, + implementationThreadId: ThreadId, + implementedAt: string, + ) { + const readModel = yield* orchestrationEngine.getReadModel(); + const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId); + const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId); + if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) { + return; + } + + yield* orchestrationEngine.dispatch({ + type: "thread.proposed-plan.upsert", + commandId: CommandId.makeUnsafe( + `provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`, + ), + threadId: sourceThread.id, + proposedPlan: { + ...sourcePlan, + implementedAt, + implementationThreadId, + updatedAt: implementedAt, + }, + createdAt: implementedAt, + }); + }, + ); + + const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* ( + event: ProviderRuntimeEvent, + ) { + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === event.threadId); + if (!thread) return; + + const now = event.createdAt; + const eventTurnId = toTurnId(event.turnId); + const activeTurnId = thread.session?.activeTurnId ?? null; + + const conflictsWithActiveTurn = + activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); + const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined; + + const shouldApplyThreadLifecycle = (() => { + if (!STRICT_PROVIDER_LIFECYCLE_GUARD) { + return true; + } + switch (event.type) { + case "session.exited": + return true; + case "session.started": + case "thread.started": + return true; + case "turn.started": + return !conflictsWithActiveTurn; + case "turn.completed": + if (conflictsWithActiveTurn || missingTurnForActiveTurn) { + return false; + } + // Only the active turn may close the lifecycle state. + if (activeTurnId !== null && eventTurnId !== undefined) { + return sameId(activeTurnId, eventTurnId); + } + // If no active turn is tracked, accept completion scoped to this thread. + return true; + default: + return true; + } + })(); + const acceptedTurnStartedSourcePlan = + event.type === "turn.started" && shouldApplyThreadLifecycle + ? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId) + : null; + + if ( + event.type === "session.started" || + event.type === "session.state.changed" || + event.type === "session.exited" || + event.type === "thread.started" || + event.type === "turn.started" || + event.type === "turn.completed" + ) { + const nextActiveTurnId = + event.type === "turn.started" + ? (eventTurnId ?? null) + : event.type === "turn.completed" || event.type === "session.exited" + ? null + : activeTurnId; + const status = (() => { + switch (event.type) { + case "session.state.changed": + return orchestrationSessionStatusFromRuntimeState(event.payload.state); + case "turn.started": + return "running"; + case "session.exited": + return "stopped"; + case "turn.completed": + return normalizeRuntimeTurnState(event.payload.state) === "failed" ? "error" : "ready"; + case "session.started": + case "thread.started": + // Provider thread/session start notifications can arrive during an + // active turn; preserve turn-running state in that case. + return activeTurnId !== null ? "running" : "ready"; + } + })(); + const lastError = + event.type === "session.state.changed" && event.payload.state === "error" + ? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error") + : event.type === "turn.completed" && + normalizeRuntimeTurnState(event.payload.state) === "failed" + ? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed") + : status === "ready" + ? null + : (thread.session?.lastError ?? null); + + if (shouldApplyThreadLifecycle) { + if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) { + yield* markSourceProposedPlanImplemented( + acceptedTurnStartedSourcePlan.sourceThreadId, + acceptedTurnStartedSourcePlan.sourcePlanId, + thread.id, + now, + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider runtime ingestion failed to mark source proposed plan", { + eventId: event.eventId, + eventType: event.type, + cause: Cause.pretty(cause), + }), + ), + ); + } + + yield* orchestrationEngine.dispatch({ + type: "thread.session.set", + commandId: providerCommandId(event, "thread-session-set"), + threadId: thread.id, + session: { + threadId: thread.id, + status, + providerName: event.provider, + runtimeMode: thread.session?.runtimeMode ?? "full-access", + activeTurnId: nextActiveTurnId, + lastError, + updatedAt: now, + }, + createdAt: now, + }); + } + } + + const assistantDelta = + event.type === "content.delta" && event.payload.streamKind === "assistant_text" + ? event.payload.delta + : undefined; + const proposedPlanDelta = + event.type === "turn.proposed.delta" ? event.payload.delta : undefined; + + if (assistantDelta && assistantDelta.length > 0) { + const assistantMessageId = MessageId.makeUnsafe( + `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, + ); + const turnId = toTurnId(event.turnId); + if (turnId) { + yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); + } + + const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( + serverSettingsService.getSettings, + (settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"), + ); + if (assistantDeliveryMode === "buffered") { + const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta); + if (spillChunk.length > 0) { + yield* orchestrationEngine.dispatch({ + type: "thread.message.assistant.delta", + commandId: providerCommandId(event, "assistant-delta-buffer-spill"), + threadId: thread.id, + messageId: assistantMessageId, + delta: spillChunk, + ...(turnId ? { turnId } : {}), + createdAt: now, + }); + } + } else { + yield* orchestrationEngine.dispatch({ + type: "thread.message.assistant.delta", + commandId: providerCommandId(event, "assistant-delta"), + threadId: thread.id, + messageId: assistantMessageId, + delta: assistantDelta, + ...(turnId ? { turnId } : {}), + createdAt: now, + }); + } + } + + if (proposedPlanDelta && proposedPlanDelta.length > 0) { + const planId = proposedPlanIdFromEvent(event, thread.id); + yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now); + } + + const assistantCompletion = + event.type === "item.completed" && event.payload.itemType === "assistant_message" + ? { + messageId: MessageId.makeUnsafe( + `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, + ), + fallbackText: event.payload.detail, + } + : undefined; + const proposedPlanCompletion = + event.type === "turn.proposed.completed" + ? { + planId: proposedPlanIdFromEvent(event, thread.id), + turnId: toTurnId(event.turnId), + planMarkdown: event.payload.planMarkdown, + } + : undefined; + + 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); + } + + yield* finalizeAssistantMessage({ + event, + threadId: thread.id, + messageId: assistantMessageId, + ...(turnId ? { turnId } : {}), + createdAt: now, + commandTag: "assistant-complete", + finalDeltaCommandTag: "assistant-delta-finalize", + ...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText + ? { fallbackText: assistantCompletion.fallbackText } + : {}), + }); + + if (turnId) { + yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId); + } + } + + if (proposedPlanCompletion) { + yield* finalizeBufferedProposedPlan({ + event, + threadId: thread.id, + threadProposedPlans: thread.proposedPlans, + planId: proposedPlanCompletion.planId, + ...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}), + fallbackMarkdown: proposedPlanCompletion.planMarkdown, + updatedAt: now, + }); + } + + if (event.type === "turn.completed") { + const turnId = toTurnId(event.turnId); + if (turnId) { + const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId); + yield* Effect.forEach( + assistantMessageIds, + (assistantMessageId) => + finalizeAssistantMessage({ + event, + threadId: thread.id, + messageId: assistantMessageId, + turnId, + createdAt: now, + commandTag: "assistant-complete-finalize", + finalDeltaCommandTag: "assistant-delta-finalize-fallback", + }), + { concurrency: 1 }, + ).pipe(Effect.asVoid); + yield* clearAssistantMessageIdsForTurn(thread.id, turnId); + + yield* finalizeBufferedProposedPlan({ + event, + threadId: thread.id, + threadProposedPlans: thread.proposedPlans, + planId: proposedPlanIdForTurn(thread.id, turnId), + turnId, + updatedAt: now, + }); + } + } + + if (event.type === "session.exited") { + yield* clearTurnStateForSession(thread.id); + } + + if (event.type === "runtime.error") { + const runtimeErrorMessage = event.payload.message; + + const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD + ? true + : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId); + + if (shouldApplyRuntimeError) { + yield* orchestrationEngine.dispatch({ + type: "thread.session.set", + commandId: providerCommandId(event, "runtime-error-session-set"), + threadId: thread.id, + session: { + threadId: thread.id, + status: "error", + providerName: event.provider, + runtimeMode: thread.session?.runtimeMode ?? "full-access", + activeTurnId: eventTurnId ?? null, + lastError: runtimeErrorMessage, + updatedAt: now, + }, + createdAt: now, + }); + } + } + + if (event.type === "thread.metadata.updated" && event.payload.name) { + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: providerCommandId(event, "thread-meta-update"), + threadId: thread.id, + title: event.payload.name, + }); + } + + if (event.type === "turn.diff.updated") { + const turnId = toTurnId(event.turnId); + if (turnId && (yield* isGitRepoForThread(thread.id))) { + // Skip if a checkpoint already exists for this turn. A real + // (non-placeholder) capture from CheckpointReactor should not + // be clobbered, and dispatching a duplicate placeholder for the + // same turnId would produce an unstable checkpointTurnCount. + if (thread.checkpoints.some((c) => c.turnId === turnId)) { + // Already tracked; no-op. + } else { + const assistantMessageId = MessageId.makeUnsafe( + `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, + ); + const maxTurnCount = thread.checkpoints.reduce( + (max, c) => Math.max(max, c.checkpointTurnCount), + 0, + ); + yield* orchestrationEngine.dispatch({ + type: "thread.turn.diff.complete", + commandId: providerCommandId(event, "thread-turn-diff-complete"), + threadId: thread.id, + turnId, + completedAt: now, + checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`), + status: "missing", + files: [], + assistantMessageId, + checkpointTurnCount: maxTurnCount + 1, + createdAt: now, + }); + } + } + } + + const activities = runtimeEventToActivities(event); + yield* Effect.forEach(activities, (activity) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: providerCommandId(event, "thread-activity-append"), + threadId: thread.id, + activity, + createdAt: activity.createdAt, + }), + ).pipe(Effect.asVoid); + }); + + const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void; + + const processInput = (input: RuntimeIngestionInput) => + input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event); + + const processInputSafely = (input: RuntimeIngestionInput) => + processInput(input).pipe( + Effect.catchCause((cause) => { + if (Cause.hasInterruptsOnly(cause)) { + return Effect.failCause(cause); + } + return Effect.logWarning("provider runtime ingestion failed to process event", { + source: input.source, + eventId: input.event.eventId, + eventType: input.event.type, + cause: Cause.pretty(cause), + }); + }), + ); + + const worker = yield* makeDrainableWorker(processInputSafely); + + const start: ProviderRuntimeIngestionShape["start"] = Effect.fn("start")(function* () { + yield* Effect.forkScoped( + Stream.runForEach(providerService.streamEvents, (event) => + worker.enqueue({ source: "runtime", event }), + ), + ); + yield* Effect.forkScoped( + Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { + if (event.type !== "thread.turn-start-requested") { + return Effect.void; + } + return worker.enqueue({ source: "domain", event }); + }), + ); + }); + + return { + start, + drain: worker.drain, + } satisfies ProviderRuntimeIngestionShape; +}); + +export const ProviderRuntimeIngestionLive = Layer.effect( + ProviderRuntimeIngestionService, + make(), +).pipe(Layer.provide(ProjectionTurnRepositoryLive)); diff --git a/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts b/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts new file mode 100644 index 0000000000..56c526c08b --- /dev/null +++ b/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts @@ -0,0 +1,18 @@ +import { Effect, Layer, PubSub, Stream } from "effect"; + +import { + RuntimeReceiptBus, + type RuntimeReceiptBusShape, + type OrchestrationRuntimeReceipt, +} from "../Services/RuntimeReceiptBus.ts"; + +const makeRuntimeReceiptBus = Effect.gen(function* () { + const pubSub = yield* PubSub.unbounded(); + + return { + publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid), + stream: Stream.fromPubSub(pubSub), + } satisfies RuntimeReceiptBusShape; +}); + +export const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus); diff --git a/apps/server/src/orchestration/Normalizer.ts b/apps/server/src/orchestration/Normalizer.ts new file mode 100644 index 0000000000..69863b7f0a --- /dev/null +++ b/apps/server/src/orchestration/Normalizer.ts @@ -0,0 +1,121 @@ +import { Effect, FileSystem, Path } from "effect"; +import { + type ClientOrchestrationCommand, + type OrchestrationCommand, + OrchestrationDispatchCommandError, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, +} from "@t3tools/contracts"; + +import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore"; +import { ServerConfig } from "../config"; +import { parseBase64DataUrl } from "../imageMime"; +import { WorkspacePaths } from "../workspace/Services/WorkspacePaths"; + +export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + const workspacePaths = yield* WorkspacePaths; + + const normalizeProjectWorkspaceRoot = (workspaceRoot: string) => + workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe( + Effect.mapError( + (cause) => + new OrchestrationDispatchCommandError({ + message: cause.message, + }), + ), + ); + + if (command.type === "project.create") { + return { + ...command, + workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot), + } satisfies OrchestrationCommand; + } + + if (command.type === "project.meta.update" && command.workspaceRoot !== undefined) { + return { + ...command, + workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot), + } satisfies OrchestrationCommand; + } + + if (command.type !== "thread.turn.start") { + return command as OrchestrationCommand; + } + + const normalizedAttachments = yield* Effect.forEach( + command.message.attachments, + (attachment) => + Effect.gen(function* () { + const parsed = parseBase64DataUrl(attachment.dataUrl); + if (!parsed || !parsed.mimeType.startsWith("image/")) { + return yield* new OrchestrationDispatchCommandError({ + message: `Invalid image attachment payload for '${attachment.name}'.`, + }); + } + + const bytes = Buffer.from(parsed.base64, "base64"); + if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + return yield* new OrchestrationDispatchCommandError({ + message: `Image attachment '${attachment.name}' is empty or too large.`, + }); + } + + const attachmentId = createAttachmentId(command.threadId); + if (!attachmentId) { + return yield* new OrchestrationDispatchCommandError({ + message: "Failed to create a safe attachment id.", + }); + } + + const persistedAttachment = { + type: "image" as const, + id: attachmentId, + name: attachment.name, + mimeType: parsed.mimeType.toLowerCase(), + sizeBytes: bytes.byteLength, + }; + + const attachmentPath = resolveAttachmentPath({ + attachmentsDir: serverConfig.attachmentsDir, + attachment: persistedAttachment, + }); + if (!attachmentPath) { + return yield* new OrchestrationDispatchCommandError({ + message: `Failed to resolve persisted path for '${attachment.name}'.`, + }); + } + + yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe( + Effect.mapError( + () => + new OrchestrationDispatchCommandError({ + message: `Failed to create attachment directory for '${attachment.name}'.`, + }), + ), + ); + yield* fileSystem.writeFile(attachmentPath, bytes).pipe( + Effect.mapError( + () => + new OrchestrationDispatchCommandError({ + message: `Failed to persist attachment '${attachment.name}'.`, + }), + ), + ); + + return persistedAttachment; + }), + { concurrency: 1 }, + ); + + return { + ...command, + message: { + ...command.message, + attachments: normalizedAttachments, + }, + } satisfies OrchestrationCommand; + }); diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts new file mode 100644 index 0000000000..f7ebf69344 --- /dev/null +++ b/apps/server/src/orchestration/Schemas.ts @@ -0,0 +1,52 @@ +import { + ProjectCreatedPayload as ContractsProjectCreatedPayloadSchema, + ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema, + ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema, + ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema, + ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema, + ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema, + ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema, + ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema, + ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema, + ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema, + ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema, + ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema, + ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema, + ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema, + ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema, + ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema, + ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema, + ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema, + ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema, + ThreadCheckpointRevertRequestedPayload as ContractsThreadCheckpointRevertRequestedPayloadSchema, + ThreadSessionStopRequestedPayload as ContractsThreadSessionStopRequestedPayloadSchema, +} from "@t3tools/contracts"; + +// Server-internal alias surface, backed by contract schemas as the source of truth. +export const ProjectCreatedPayload = ContractsProjectCreatedPayloadSchema; +export const ProjectMetaUpdatedPayload = ContractsProjectMetaUpdatedPayloadSchema; +export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema; + +export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema; +export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema; +export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema; +export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema; +export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema; +export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema; +export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema; + +export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema; +export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema; +export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema; +export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema; +export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema; +export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema; + +export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema; +export const ThreadTurnInterruptRequestedPayload = + ContractsThreadTurnInterruptRequestedPayloadSchema; +export const ThreadApprovalResponseRequestedPayload = + ContractsThreadApprovalResponseRequestedPayloadSchema; +export const ThreadCheckpointRevertRequestedPayload = + ContractsThreadCheckpointRevertRequestedPayloadSchema; +export const ThreadSessionStopRequestedPayload = ContractsThreadSessionStopRequestedPayloadSchema; diff --git a/apps/server/src/orchestration/Services/CheckpointReactor.ts b/apps/server/src/orchestration/Services/CheckpointReactor.ts new file mode 100644 index 0000000000..539ac784cd --- /dev/null +++ b/apps/server/src/orchestration/Services/CheckpointReactor.ts @@ -0,0 +1,40 @@ +/** + * CheckpointReactor - Checkpoint reaction service interface. + * + * Owns background workers that react to orchestration checkpoint lifecycle + * events and apply checkpoint side effects. + * + * @module CheckpointReactor + */ +import { ServiceMap } from "effect"; +import type { Effect, Scope } from "effect"; + +/** + * CheckpointReactorShape - Service API for checkpoint reactor lifecycle. + */ +export interface CheckpointReactorShape { + /** + * Start the checkpoint reactor. + * + * The returned effect must be run in a scope so all worker fibers can be + * finalized on shutdown. + * + * Consumes both orchestration-domain and provider-runtime events via an + * internal queue. + */ + readonly start: () => Effect.Effect; + + /** + * Resolves when the internal processing queue is empty and idle. + * Intended for test use to replace timing-sensitive sleeps. + */ + readonly drain: Effect.Effect; +} + +/** + * CheckpointReactor - Service tag for checkpoint reactor workers. + */ +export class CheckpointReactor extends ServiceMap.Service< + CheckpointReactor, + CheckpointReactorShape +>()("t3/orchestration/Services/CheckpointReactor") {} diff --git a/apps/server/src/orchestration/Services/OrchestrationEngine.ts b/apps/server/src/orchestration/Services/OrchestrationEngine.ts new file mode 100644 index 0000000000..33ac75049f --- /dev/null +++ b/apps/server/src/orchestration/Services/OrchestrationEngine.ts @@ -0,0 +1,80 @@ +/** + * OrchestrationEngineService - Service interface for orchestration command handling. + * + * Owns command validation/dispatch and in-memory read-model updates backed by + * `OrchestrationEventStore` persistence. It does not own provider process + * management or transport concerns (e.g. websocket request parsing). + * + * Uses Effect `ServiceMap.Service` for dependency injection. Command dispatch, + * replay, and unknown-input decoding all return typed domain errors. + * + * @module OrchestrationEngineService + */ +import type { + OrchestrationCommand, + OrchestrationEvent, + OrchestrationReadModel, +} from "@t3tools/contracts"; +import { ServiceMap } from "effect"; +import type { Effect, Stream } from "effect"; + +import type { OrchestrationDispatchError } from "../Errors.ts"; +import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts"; + +/** + * OrchestrationEngineShape - Service API for orchestration command and event flow. + */ +export interface OrchestrationEngineShape { + /** + * Read the current in-memory orchestration read model. + * + * @returns Effect containing the latest read model. + */ + readonly getReadModel: () => Effect.Effect; + + /** + * Replay persisted orchestration events from an exclusive sequence cursor. + * + * @param fromSequenceExclusive - Sequence cursor (exclusive). + * @returns Stream containing ordered events. + */ + readonly readEvents: ( + fromSequenceExclusive: number, + ) => Stream.Stream; + + /** + * Dispatch a validated orchestration command. + * + * @param command - Valid orchestration command. + * @returns Effect containing the sequence of the persisted event. + * + * Dispatch is serialized through an internal queue and deduplicated via + * command receipts. + */ + readonly dispatch: ( + command: OrchestrationCommand, + ) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>; + + /** + * Stream persisted domain events in dispatch order. + * + * This is a hot runtime stream (new events only), not a historical replay. + */ + readonly streamDomainEvents: Stream.Stream; +} + +/** + * OrchestrationEngineService - Service tag for orchestration engine access. + * + * @example + * ```ts + * const program = Effect.gen(function* () { + * const engine = yield* OrchestrationEngineService + * return yield* engine.getReadModel() + * }) + * ``` + */ +export class OrchestrationEngineService extends ServiceMap.Service< + OrchestrationEngineService, + OrchestrationEngineShape +>()("t3/orchestration/Services/OrchestrationEngine/OrchestrationEngineService") {} diff --git a/apps/server/src/orchestration/Services/OrchestrationReactor.ts b/apps/server/src/orchestration/Services/OrchestrationReactor.ts new file mode 100644 index 0000000000..9b628eebda --- /dev/null +++ b/apps/server/src/orchestration/Services/OrchestrationReactor.ts @@ -0,0 +1,31 @@ +/** + * OrchestrationReactor - Composite orchestration reactor service interface. + * + * Coordinates startup of orchestration runtime reactors that translate domain + * events into downstream side effects. + * + * @module OrchestrationReactor + */ +import { ServiceMap } from "effect"; +import type { Effect, Scope } from "effect"; + +/** + * OrchestrationReactorShape - Service API for orchestration reactor lifecycle. + */ +export interface OrchestrationReactorShape { + /** + * Start orchestration-side reactors for provider/runtime/checkpoint flows. + * + * The returned effect must be run in a scope so all worker fibers can be + * finalized on shutdown. + */ + readonly start: () => Effect.Effect; +} + +/** + * OrchestrationReactor - Service tag for orchestration reactor coordination. + */ +export class OrchestrationReactor extends ServiceMap.Service< + OrchestrationReactor, + OrchestrationReactorShape +>()("t3/orchestration/Services/OrchestrationReactor") {} diff --git a/apps/server/src/orchestration/Services/ProjectionPipeline.ts b/apps/server/src/orchestration/Services/ProjectionPipeline.ts new file mode 100644 index 0000000000..f8c86bf09b --- /dev/null +++ b/apps/server/src/orchestration/Services/ProjectionPipeline.ts @@ -0,0 +1,42 @@ +/** + * OrchestrationProjectionPipeline - Event projection pipeline service interface. + * + * Coordinates projection bootstrap/replay and per-event projection updates for + * orchestration read models. + * + * @module OrchestrationProjectionPipeline + */ +import type { OrchestrationEvent } from "@t3tools/contracts"; +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../../persistence/Errors.ts"; + +/** + * OrchestrationProjectionPipelineShape - Service API for projection execution. + */ +export interface OrchestrationProjectionPipelineShape { + /** + * Bootstrap projections by replaying persisted events. + * + * Resumes each projector from its stored projection-state cursor. + */ + readonly bootstrap: Effect.Effect; + + /** + * Project a single orchestration event into projection repositories. + * + * Projectors are executed sequentially to preserve deterministic ordering. + */ + readonly projectEvent: ( + event: OrchestrationEvent, + ) => Effect.Effect; +} + +/** + * OrchestrationProjectionPipeline - Service tag for orchestration projections. + */ +export class OrchestrationProjectionPipeline extends ServiceMap.Service< + OrchestrationProjectionPipeline, + OrchestrationProjectionPipelineShape +>()("t3/orchestration/Services/ProjectionPipeline/OrchestrationProjectionPipeline") {} diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts new file mode 100644 index 0000000000..a7673dc32e --- /dev/null +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -0,0 +1,80 @@ +/** + * ProjectionSnapshotQuery - Read-model snapshot query service interface. + * + * Exposes the current orchestration projection snapshot for read-only API + * access. + * + * @module ProjectionSnapshotQuery + */ +import type { + OrchestrationCheckpointSummary, + OrchestrationProject, + OrchestrationReadModel, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { ServiceMap } from "effect"; +import type { Option } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../../persistence/Errors.ts"; + +export interface ProjectionSnapshotCounts { + readonly projectCount: number; + readonly threadCount: number; +} + +export interface ProjectionThreadCheckpointContext { + readonly threadId: ThreadId; + readonly projectId: ProjectId; + readonly workspaceRoot: string; + readonly worktreePath: string | null; + readonly checkpoints: ReadonlyArray; +} + +/** + * ProjectionSnapshotQueryShape - Service API for read-model snapshots. + */ +export interface ProjectionSnapshotQueryShape { + /** + * Read the latest orchestration projection snapshot. + * + * Rehydrates from projection tables and derives snapshot sequence from + * projector cursor state. + */ + readonly getSnapshot: () => Effect.Effect; + + /** + * Read aggregate projection counts without hydrating the full read model. + */ + readonly getCounts: () => Effect.Effect; + + /** + * Read the active project for an exact workspace root match. + */ + readonly getActiveProjectByWorkspaceRoot: ( + workspaceRoot: string, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Read the earliest active thread for a project. + */ + readonly getFirstActiveThreadIdByProjectId: ( + projectId: ProjectId, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Read the checkpoint context needed to resolve a single thread diff. + */ + readonly getThreadCheckpointContext: ( + threadId: ThreadId, + ) => Effect.Effect, ProjectionRepositoryError>; +} + +/** + * ProjectionSnapshotQuery - Service tag for projection snapshot queries. + */ +export class ProjectionSnapshotQuery extends ServiceMap.Service< + ProjectionSnapshotQuery, + ProjectionSnapshotQueryShape +>()("t3/orchestration/Services/ProjectionSnapshotQuery") {} diff --git a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts b/apps/server/src/orchestration/Services/ProviderCommandReactor.ts new file mode 100644 index 0000000000..8f96d8fb99 --- /dev/null +++ b/apps/server/src/orchestration/Services/ProviderCommandReactor.ts @@ -0,0 +1,40 @@ +/** + * ProviderCommandReactor - Provider command reaction service interface. + * + * Owns background workers that react to orchestration intent events and + * dispatch provider-side command execution. + * + * @module ProviderCommandReactor + */ +import { ServiceMap } from "effect"; +import type { Effect, Scope } from "effect"; + +/** + * ProviderCommandReactorShape - Service API for provider command reactors. + */ +export interface ProviderCommandReactorShape { + /** + * Start reacting to provider-intent orchestration domain events. + * + * The returned effect must be run in a scope so all worker fibers can be + * finalized on shutdown. + * + * Filters orchestration domain events to provider-intent types before + * processing. + */ + readonly start: () => Effect.Effect; + + /** + * Resolves when the internal processing queue is empty and idle. + * Intended for test use to replace timing-sensitive sleeps. + */ + readonly drain: Effect.Effect; +} + +/** + * ProviderCommandReactor - Service tag for provider command reaction workers. + */ +export class ProviderCommandReactor extends ServiceMap.Service< + ProviderCommandReactor, + ProviderCommandReactorShape +>()("t3/orchestration/Services/ProviderCommandReactor") {} diff --git a/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts new file mode 100644 index 0000000000..f1b95762a2 --- /dev/null +++ b/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts @@ -0,0 +1,40 @@ +/** + * ProviderRuntimeIngestionService - Provider runtime ingestion service interface. + * + * Owns background workers that consume provider runtime streams and emit + * orchestration commands/events. + * + * @module ProviderRuntimeIngestionService + */ +import { ServiceMap } from "effect"; +import type { Effect, Scope } from "effect"; + +/** + * ProviderRuntimeIngestionShape - Service API for runtime ingestion lifecycle. + */ +export interface ProviderRuntimeIngestionShape { + /** + * Start ingesting provider runtime events into orchestration commands. + * + * The returned effect must be run in a scope so all worker fibers can be + * finalized on shutdown. + * + * Uses an internal queue and continues after non-interrupt failures by + * logging warnings. + */ + readonly start: () => Effect.Effect; + + /** + * Resolves when the internal processing queue is empty and idle. + * Intended for test use to replace timing-sensitive sleeps. + */ + readonly drain: Effect.Effect; +} + +/** + * ProviderRuntimeIngestionService - Service tag for runtime ingestion workers. + */ +export class ProviderRuntimeIngestionService extends ServiceMap.Service< + ProviderRuntimeIngestionService, + ProviderRuntimeIngestionShape +>()("t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService") {} diff --git a/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts b/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts new file mode 100644 index 0000000000..a08ff91685 --- /dev/null +++ b/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts @@ -0,0 +1,49 @@ +import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts"; +import { Schema, ServiceMap } from "effect"; +import type { Effect, Stream } from "effect"; + +export const CheckpointBaselineCapturedReceipt = Schema.Struct({ + type: Schema.Literal("checkpoint.baseline.captured"), + threadId: ThreadId, + checkpointTurnCount: NonNegativeInt, + checkpointRef: CheckpointRef, + createdAt: IsoDateTime, +}); +export type CheckpointBaselineCapturedReceipt = typeof CheckpointBaselineCapturedReceipt.Type; + +export const CheckpointDiffFinalizedReceipt = Schema.Struct({ + type: Schema.Literal("checkpoint.diff.finalized"), + threadId: ThreadId, + turnId: TurnId, + checkpointTurnCount: NonNegativeInt, + checkpointRef: CheckpointRef, + status: Schema.Literals(["ready", "missing", "error"]), + createdAt: IsoDateTime, +}); +export type CheckpointDiffFinalizedReceipt = typeof CheckpointDiffFinalizedReceipt.Type; + +export const TurnProcessingQuiescedReceipt = Schema.Struct({ + type: Schema.Literal("turn.processing.quiesced"), + threadId: ThreadId, + turnId: TurnId, + checkpointTurnCount: NonNegativeInt, + createdAt: IsoDateTime, +}); +export type TurnProcessingQuiescedReceipt = typeof TurnProcessingQuiescedReceipt.Type; + +export const OrchestrationRuntimeReceipt = Schema.Union([ + CheckpointBaselineCapturedReceipt, + CheckpointDiffFinalizedReceipt, + TurnProcessingQuiescedReceipt, +]); +export type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Type; + +export interface RuntimeReceiptBusShape { + readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect; + readonly stream: Stream.Stream; +} + +export class RuntimeReceiptBus extends ServiceMap.Service< + RuntimeReceiptBus, + RuntimeReceiptBusShape +>()("t3/orchestration/Services/RuntimeReceiptBus") {} diff --git a/apps/server/src/orchestration/commandInvariants.test.ts b/apps/server/src/orchestration/commandInvariants.test.ts new file mode 100644 index 0000000000..43d665a2c9 --- /dev/null +++ b/apps/server/src/orchestration/commandInvariants.test.ts @@ -0,0 +1,220 @@ +import { describe, expect, it } from "vitest"; +import { + MessageId, + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + ProjectId, + ThreadId, + type OrchestrationCommand, + type OrchestrationReadModel, +} from "@t3tools/contracts"; +import { Effect } from "effect"; + +import { + findThreadById, + listThreadsByProjectId, + requireNonNegativeInteger, + requireThread, + requireThreadAbsent, +} from "./commandInvariants.ts"; + +const now = new Date().toISOString(); + +const readModel: OrchestrationReadModel = { + snapshotSequence: 2, + updatedAt: now, + projects: [ + { + id: ProjectId.makeUnsafe("project-a"), + title: "Project A", + workspaceRoot: "/tmp/project-a", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + scripts: [], + createdAt: now, + updatedAt: now, + deletedAt: null, + }, + { + id: ProjectId.makeUnsafe("project-b"), + title: "Project B", + workspaceRoot: "/tmp/project-b", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + scripts: [], + createdAt: now, + updatedAt: now, + deletedAt: null, + }, + ], + threads: [ + { + id: ThreadId.makeUnsafe("thread-1"), + projectId: ProjectId.makeUnsafe("project-a"), + title: "Thread A", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + latestTurn: null, + messages: [], + session: null, + activities: [], + proposedPlans: [], + checkpoints: [], + deletedAt: null, + }, + { + id: ThreadId.makeUnsafe("thread-2"), + projectId: ProjectId.makeUnsafe("project-b"), + title: "Thread B", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + latestTurn: null, + messages: [], + session: null, + activities: [], + proposedPlans: [], + checkpoints: [], + deletedAt: null, + }, + ], +}; + +const messageSendCommand: OrchestrationCommand = { + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: MessageId.makeUnsafe("msg-1"), + role: "user", + text: "hello", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, +}; + +describe("commandInvariants", () => { + it("finds threads by id and project", () => { + expect(findThreadById(readModel, ThreadId.makeUnsafe("thread-1"))?.projectId).toBe("project-a"); + expect(findThreadById(readModel, ThreadId.makeUnsafe("missing"))).toBeUndefined(); + expect( + listThreadsByProjectId(readModel, ProjectId.makeUnsafe("project-b")).map( + (thread) => thread.id, + ), + ).toEqual([ThreadId.makeUnsafe("thread-2")]); + }); + + it("requires existing thread", async () => { + const thread = await Effect.runPromise( + requireThread({ + readModel, + command: messageSendCommand, + threadId: ThreadId.makeUnsafe("thread-1"), + }), + ); + expect(thread.id).toBe(ThreadId.makeUnsafe("thread-1")); + + await expect( + Effect.runPromise( + requireThread({ + readModel, + command: messageSendCommand, + threadId: ThreadId.makeUnsafe("missing"), + }), + ), + ).rejects.toThrow("does not exist"); + }); + + it("requires missing thread for create flows", async () => { + await Effect.runPromise( + requireThreadAbsent({ + readModel, + command: { + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-2"), + threadId: ThreadId.makeUnsafe("thread-3"), + projectId: ProjectId.makeUnsafe("project-a"), + title: "new", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + }, + threadId: ThreadId.makeUnsafe("thread-3"), + }), + ); + + await expect( + Effect.runPromise( + requireThreadAbsent({ + readModel, + command: { + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-3"), + threadId: ThreadId.makeUnsafe("thread-1"), + projectId: ProjectId.makeUnsafe("project-a"), + title: "dup", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + }, + threadId: ThreadId.makeUnsafe("thread-1"), + }), + ), + ).rejects.toThrow("already exists"); + }); + + it("requires non-negative integers", async () => { + await Effect.runPromise( + requireNonNegativeInteger({ + commandType: "thread.checkpoint.revert", + field: "turnCount", + value: 0, + }), + ); + + await expect( + Effect.runPromise( + requireNonNegativeInteger({ + commandType: "thread.checkpoint.revert", + field: "turnCount", + value: -1, + }), + ), + ).rejects.toThrow("greater than or equal to 0"); + }); +}); diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.ts new file mode 100644 index 0000000000..009fdb190e --- /dev/null +++ b/apps/server/src/orchestration/commandInvariants.ts @@ -0,0 +1,159 @@ +import type { + OrchestrationCommand, + OrchestrationProject, + OrchestrationReadModel, + OrchestrationThread, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { Effect } from "effect"; + +import { OrchestrationCommandInvariantError } from "./Errors.ts"; + +function invariantError(commandType: string, detail: string): OrchestrationCommandInvariantError { + return new OrchestrationCommandInvariantError({ + commandType, + detail, + }); +} + +export function findThreadById( + readModel: OrchestrationReadModel, + threadId: ThreadId, +): OrchestrationThread | undefined { + return readModel.threads.find((thread) => thread.id === threadId); +} + +export function findProjectById( + readModel: OrchestrationReadModel, + projectId: ProjectId, +): OrchestrationProject | undefined { + return readModel.projects.find((project) => project.id === projectId); +} + +export function listThreadsByProjectId( + readModel: OrchestrationReadModel, + projectId: ProjectId, +): ReadonlyArray { + return readModel.threads.filter((thread) => thread.projectId === projectId); +} + +export function requireProject(input: { + readonly readModel: OrchestrationReadModel; + readonly command: OrchestrationCommand; + readonly projectId: ProjectId; +}): Effect.Effect { + const project = findProjectById(input.readModel, input.projectId); + if (project) { + return Effect.succeed(project); + } + return Effect.fail( + invariantError( + input.command.type, + `Project '${input.projectId}' does not exist for command '${input.command.type}'.`, + ), + ); +} + +export function requireProjectAbsent(input: { + readonly readModel: OrchestrationReadModel; + readonly command: OrchestrationCommand; + readonly projectId: ProjectId; +}): Effect.Effect { + if (!findProjectById(input.readModel, input.projectId)) { + return Effect.void; + } + return Effect.fail( + invariantError( + input.command.type, + `Project '${input.projectId}' already exists and cannot be created twice.`, + ), + ); +} + +export function requireThread(input: { + readonly readModel: OrchestrationReadModel; + readonly command: OrchestrationCommand; + readonly threadId: ThreadId; +}): Effect.Effect { + const thread = findThreadById(input.readModel, input.threadId); + if (thread) { + return Effect.succeed(thread); + } + return Effect.fail( + invariantError( + input.command.type, + `Thread '${input.threadId}' does not exist for command '${input.command.type}'.`, + ), + ); +} + +export function requireThreadArchived(input: { + readonly readModel: OrchestrationReadModel; + readonly command: OrchestrationCommand; + readonly threadId: ThreadId; +}): Effect.Effect { + return requireThread(input).pipe( + Effect.flatMap((thread) => + thread.archivedAt !== null + ? Effect.succeed(thread) + : Effect.fail( + invariantError( + input.command.type, + `Thread '${input.threadId}' is not archived for command '${input.command.type}'.`, + ), + ), + ), + ); +} + +export function requireThreadNotArchived(input: { + readonly readModel: OrchestrationReadModel; + readonly command: OrchestrationCommand; + readonly threadId: ThreadId; +}): Effect.Effect { + return requireThread(input).pipe( + Effect.flatMap((thread) => + thread.archivedAt === null + ? Effect.succeed(thread) + : Effect.fail( + invariantError( + input.command.type, + `Thread '${input.threadId}' is already archived and cannot handle command '${input.command.type}'.`, + ), + ), + ), + ); +} + +export function requireThreadAbsent(input: { + readonly readModel: OrchestrationReadModel; + readonly command: OrchestrationCommand; + readonly threadId: ThreadId; +}): Effect.Effect { + if (!findThreadById(input.readModel, input.threadId)) { + return Effect.void; + } + return Effect.fail( + invariantError( + input.command.type, + `Thread '${input.threadId}' already exists and cannot be created twice.`, + ), + ); +} + +export function requireNonNegativeInteger(input: { + readonly commandType: OrchestrationCommand["type"]; + readonly field: string; + readonly value: number; +}): Effect.Effect { + if (Number.isInteger(input.value) && input.value >= 0) { + return Effect.void; + } + return Effect.fail( + invariantError( + input.commandType, + `${input.field} must be an integer greater than or equal to 0.`, + ), + ); +} diff --git a/apps/server/src/orchestration/decider.projectScripts.test.ts b/apps/server/src/orchestration/decider.projectScripts.test.ts new file mode 100644 index 0000000000..465865549b --- /dev/null +++ b/apps/server/src/orchestration/decider.projectScripts.test.ts @@ -0,0 +1,369 @@ +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + EventId, + MessageId, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vitest"; +import { Effect } from "effect"; + +import { decideOrchestrationCommand } from "./decider.ts"; +import { createEmptyReadModel, projectEvent } from "./projector.ts"; + +const asEventId = (value: string): EventId => EventId.makeUnsafe(value); +const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); +const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); + +describe("decider project scripts", () => { + it("emits empty scripts on project.create", async () => { + const now = new Date().toISOString(); + const readModel = createEmptyReadModel(now); + + const result = await Effect.runPromise( + decideOrchestrationCommand({ + command: { + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-create-scripts"), + projectId: asProjectId("project-scripts"), + title: "Scripts", + workspaceRoot: "/tmp/scripts", + createdAt: now, + }, + readModel, + }), + ); + + const event = Array.isArray(result) ? result[0] : result; + expect(event.type).toBe("project.created"); + expect((event.payload as { scripts: unknown[] }).scripts).toEqual([]); + }); + + it("propagates scripts in project.meta.update payload", async () => { + const now = new Date().toISOString(); + const initial = createEmptyReadModel(now); + const readModel = await Effect.runPromise( + projectEvent(initial, { + sequence: 1, + eventId: asEventId("evt-project-create-scripts"), + aggregateKind: "project", + aggregateId: asProjectId("project-scripts"), + type: "project.created", + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-project-create-scripts"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-project-create-scripts"), + metadata: {}, + payload: { + projectId: asProjectId("project-scripts"), + title: "Scripts", + workspaceRoot: "/tmp/scripts", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }), + ); + + const scripts = [ + { + id: "lint", + name: "Lint", + command: "bun run lint", + icon: "lint", + runOnWorktreeCreate: false, + }, + ] as const; + + const result = await Effect.runPromise( + decideOrchestrationCommand({ + command: { + type: "project.meta.update", + commandId: CommandId.makeUnsafe("cmd-project-update-scripts"), + projectId: asProjectId("project-scripts"), + scripts: Array.from(scripts), + }, + readModel, + }), + ); + + const event = Array.isArray(result) ? result[0] : result; + expect(event.type).toBe("project.meta-updated"); + expect((event.payload as { scripts?: unknown[] }).scripts).toEqual(scripts); + }); + + it("emits user message and turn-start-requested events for thread.turn.start", async () => { + const now = new Date().toISOString(); + const initial = createEmptyReadModel(now); + const withProject = await Effect.runPromise( + projectEvent(initial, { + sequence: 1, + eventId: asEventId("evt-project-create"), + aggregateKind: "project", + aggregateId: asProjectId("project-1"), + type: "project.created", + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-project-create"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-project-create"), + metadata: {}, + payload: { + projectId: asProjectId("project-1"), + title: "Project", + workspaceRoot: "/tmp/project", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }), + ); + const readModel = await Effect.runPromise( + projectEvent(withProject, { + sequence: 2, + eventId: asEventId("evt-thread-create"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-1"), + type: "thread.created", + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-thread-create"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-thread-create"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-1"), + projectId: asProjectId("project-1"), + title: "Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }), + ); + + const result = await Effect.runPromise( + decideOrchestrationCommand({ + command: { + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("message-user-1"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + reasoningEffort: "high", + fastMode: true, + }, + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }, + readModel, + }), + ); + + expect(Array.isArray(result)).toBe(true); + const events = Array.isArray(result) ? result : [result]; + expect(events).toHaveLength(2); + expect(events[0]?.type).toBe("thread.message-sent"); + const turnStartEvent = events[1]; + expect(turnStartEvent?.type).toBe("thread.turn-start-requested"); + expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null); + if (turnStartEvent?.type !== "thread.turn-start-requested") { + return; + } + expect(turnStartEvent.payload).toMatchObject({ + threadId: ThreadId.makeUnsafe("thread-1"), + messageId: asMessageId("message-user-1"), + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + reasoningEffort: "high", + fastMode: true, + }, + }, + runtimeMode: "approval-required", + }); + }); + + it("emits thread.runtime-mode-set from thread.runtime-mode.set", async () => { + const now = new Date().toISOString(); + const initial = createEmptyReadModel(now); + const withProject = await Effect.runPromise( + projectEvent(initial, { + sequence: 1, + eventId: asEventId("evt-project-create"), + aggregateKind: "project", + aggregateId: asProjectId("project-1"), + type: "project.created", + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-project-create"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-project-create"), + metadata: {}, + payload: { + projectId: asProjectId("project-1"), + title: "Project", + workspaceRoot: "/tmp/project", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }), + ); + const readModel = await Effect.runPromise( + projectEvent(withProject, { + sequence: 2, + eventId: asEventId("evt-thread-create"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-1"), + type: "thread.created", + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-thread-create"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-thread-create"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-1"), + projectId: asProjectId("project-1"), + title: "Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }), + ); + + const result = await Effect.runPromise( + decideOrchestrationCommand({ + command: { + type: "thread.runtime-mode.set", + commandId: CommandId.makeUnsafe("cmd-runtime-mode-set"), + threadId: ThreadId.makeUnsafe("thread-1"), + runtimeMode: "approval-required", + createdAt: now, + }, + readModel, + }), + ); + + const singleResult = Array.isArray(result) ? null : result; + if (singleResult === null) { + throw new Error("Expected a single runtime-mode-set event."); + } + expect(singleResult).toMatchObject({ + type: "thread.runtime-mode-set", + payload: { + threadId: ThreadId.makeUnsafe("thread-1"), + runtimeMode: "approval-required", + }, + }); + }); + + it("emits thread.interaction-mode-set from thread.interaction-mode.set", async () => { + const now = new Date().toISOString(); + const initial = createEmptyReadModel(now); + const withProject = await Effect.runPromise( + projectEvent(initial, { + sequence: 1, + eventId: asEventId("evt-project-create"), + aggregateKind: "project", + aggregateId: asProjectId("project-1"), + type: "project.created", + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-project-create"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-project-create"), + metadata: {}, + payload: { + projectId: asProjectId("project-1"), + title: "Project", + workspaceRoot: "/tmp/project", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }), + ); + const readModel = await Effect.runPromise( + projectEvent(withProject, { + sequence: 2, + eventId: asEventId("evt-thread-create"), + aggregateKind: "thread", + aggregateId: ThreadId.makeUnsafe("thread-1"), + type: "thread.created", + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-thread-create"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-thread-create"), + metadata: {}, + payload: { + threadId: ThreadId.makeUnsafe("thread-1"), + projectId: asProjectId("project-1"), + title: "Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }), + ); + + const result = await Effect.runPromise( + decideOrchestrationCommand({ + command: { + type: "thread.interaction-mode.set", + commandId: CommandId.makeUnsafe("cmd-interaction-mode-set"), + threadId: ThreadId.makeUnsafe("thread-1"), + interactionMode: "plan", + createdAt: now, + }, + readModel, + }), + ); + + const singleResult = Array.isArray(result) ? null : result; + if (singleResult === null) { + throw new Error("Expected a single interaction-mode-set event."); + } + expect(singleResult).toMatchObject({ + type: "thread.interaction-mode-set", + payload: { + threadId: ThreadId.makeUnsafe("thread-1"), + interactionMode: "plan", + }, + }); + }); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts new file mode 100644 index 0000000000..22f5bcb280 --- /dev/null +++ b/apps/server/src/orchestration/decider.ts @@ -0,0 +1,689 @@ +import type { + OrchestrationCommand, + OrchestrationEvent, + OrchestrationReadModel, +} from "@t3tools/contracts"; +import { Effect } from "effect"; + +import { OrchestrationCommandInvariantError } from "./Errors.ts"; +import { + requireProject, + requireProjectAbsent, + requireThread, + requireThreadArchived, + requireThreadAbsent, + requireThreadNotArchived, +} from "./commandInvariants.ts"; + +const nowIso = () => new Date().toISOString(); +const defaultMetadata: Omit = { + eventId: crypto.randomUUID() as OrchestrationEvent["eventId"], + aggregateKind: "thread", + aggregateId: "" as OrchestrationEvent["aggregateId"], + occurredAt: nowIso(), + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, +}; + +function withEventBase( + input: Pick & { + readonly aggregateKind: OrchestrationEvent["aggregateKind"]; + readonly aggregateId: OrchestrationEvent["aggregateId"]; + readonly occurredAt: string; + readonly metadata?: OrchestrationEvent["metadata"]; + }, +): Omit { + return { + ...defaultMetadata, + eventId: crypto.randomUUID() as OrchestrationEvent["eventId"], + aggregateKind: input.aggregateKind, + aggregateId: input.aggregateId, + occurredAt: input.occurredAt, + commandId: input.commandId, + correlationId: input.commandId, + metadata: input.metadata ?? {}, + }; +} + +export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({ + command, + readModel, +}: { + readonly command: OrchestrationCommand; + readonly readModel: OrchestrationReadModel; +}): Effect.fn.Return< + Omit | ReadonlyArray>, + OrchestrationCommandInvariantError +> { + switch (command.type) { + case "project.create": { + yield* requireProjectAbsent({ + readModel, + command, + projectId: command.projectId, + }); + + return { + ...withEventBase({ + aggregateKind: "project", + aggregateId: command.projectId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "project.created", + payload: { + projectId: command.projectId, + title: command.title, + workspaceRoot: command.workspaceRoot, + defaultModelSelection: command.defaultModelSelection ?? null, + scripts: [], + createdAt: command.createdAt, + updatedAt: command.createdAt, + }, + }; + } + + case "project.meta.update": { + yield* requireProject({ + readModel, + command, + projectId: command.projectId, + }); + const occurredAt = nowIso(); + return { + ...withEventBase({ + aggregateKind: "project", + aggregateId: command.projectId, + occurredAt, + commandId: command.commandId, + }), + type: "project.meta-updated", + payload: { + projectId: command.projectId, + ...(command.title !== undefined ? { title: command.title } : {}), + ...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}), + ...(command.defaultModelSelection !== undefined + ? { defaultModelSelection: command.defaultModelSelection } + : {}), + ...(command.scripts !== undefined ? { scripts: command.scripts } : {}), + updatedAt: occurredAt, + }, + }; + } + + case "project.delete": { + yield* requireProject({ + readModel, + command, + projectId: command.projectId, + }); + const occurredAt = nowIso(); + return { + ...withEventBase({ + aggregateKind: "project", + aggregateId: command.projectId, + occurredAt, + commandId: command.commandId, + }), + type: "project.deleted", + payload: { + projectId: command.projectId, + deletedAt: occurredAt, + }, + }; + } + + case "thread.create": { + yield* requireProject({ + readModel, + command, + projectId: command.projectId, + }); + yield* requireThreadAbsent({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.created", + payload: { + threadId: command.threadId, + projectId: command.projectId, + title: command.title, + modelSelection: command.modelSelection, + runtimeMode: command.runtimeMode, + interactionMode: command.interactionMode, + branch: command.branch, + worktreePath: command.worktreePath, + createdAt: command.createdAt, + updatedAt: command.createdAt, + }, + }; + } + + case "thread.delete": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + const occurredAt = nowIso(); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt, + commandId: command.commandId, + }), + type: "thread.deleted", + payload: { + threadId: command.threadId, + deletedAt: occurredAt, + }, + }; + } + + case "thread.archive": { + yield* requireThreadNotArchived({ + readModel, + command, + threadId: command.threadId, + }); + const occurredAt = nowIso(); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt, + commandId: command.commandId, + }), + type: "thread.archived", + payload: { + threadId: command.threadId, + archivedAt: occurredAt, + updatedAt: occurredAt, + }, + }; + } + + case "thread.unarchive": { + yield* requireThreadArchived({ + readModel, + command, + threadId: command.threadId, + }); + const occurredAt = nowIso(); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt, + commandId: command.commandId, + }), + type: "thread.unarchived", + payload: { + threadId: command.threadId, + updatedAt: occurredAt, + }, + }; + } + + case "thread.meta.update": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + const occurredAt = nowIso(); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt, + commandId: command.commandId, + }), + type: "thread.meta-updated", + payload: { + threadId: command.threadId, + ...(command.title !== undefined ? { title: command.title } : {}), + ...(command.modelSelection !== undefined + ? { modelSelection: command.modelSelection } + : {}), + ...(command.branch !== undefined ? { branch: command.branch } : {}), + ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}), + updatedAt: occurredAt, + }, + }; + } + + case "thread.runtime-mode.set": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + const occurredAt = nowIso(); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt, + commandId: command.commandId, + }), + type: "thread.runtime-mode-set", + payload: { + threadId: command.threadId, + runtimeMode: command.runtimeMode, + updatedAt: occurredAt, + }, + }; + } + + case "thread.interaction-mode.set": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + const occurredAt = nowIso(); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt, + commandId: command.commandId, + }), + type: "thread.interaction-mode-set", + payload: { + threadId: command.threadId, + interactionMode: command.interactionMode, + updatedAt: occurredAt, + }, + }; + } + + case "thread.turn.start": { + const targetThread = yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + const sourceProposedPlan = command.sourceProposedPlan; + const sourceThread = sourceProposedPlan + ? yield* requireThread({ + readModel, + command, + threadId: sourceProposedPlan.threadId, + }) + : null; + const sourcePlan = + sourceProposedPlan && sourceThread + ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId) + : null; + if (sourceProposedPlan && !sourcePlan) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`, + }); + } + if (sourceThread && sourceThread.projectId !== targetThread.projectId) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`, + }); + } + const userMessageEvent: Omit = { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.message-sent", + payload: { + threadId: command.threadId, + messageId: command.message.messageId, + role: "user", + text: command.message.text, + attachments: command.message.attachments, + turnId: null, + streaming: false, + createdAt: command.createdAt, + updatedAt: command.createdAt, + }, + }; + const turnStartRequestedEvent: Omit = { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + causationEventId: userMessageEvent.eventId, + type: "thread.turn-start-requested", + payload: { + threadId: command.threadId, + messageId: command.message.messageId, + ...(command.modelSelection !== undefined + ? { modelSelection: command.modelSelection } + : {}), + ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}), + runtimeMode: targetThread.runtimeMode, + interactionMode: targetThread.interactionMode, + ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}), + createdAt: command.createdAt, + }, + }; + return [userMessageEvent, turnStartRequestedEvent]; + } + + case "thread.turn.interrupt": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.turn-interrupt-requested", + payload: { + threadId: command.threadId, + ...(command.turnId !== undefined ? { turnId: command.turnId } : {}), + createdAt: command.createdAt, + }, + }; + } + + case "thread.approval.respond": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + metadata: { + requestId: command.requestId, + }, + }), + type: "thread.approval-response-requested", + payload: { + threadId: command.threadId, + requestId: command.requestId, + decision: command.decision, + createdAt: command.createdAt, + }, + }; + } + + case "thread.user-input.respond": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + metadata: { + requestId: command.requestId, + }, + }), + type: "thread.user-input-response-requested", + payload: { + threadId: command.threadId, + requestId: command.requestId, + answers: command.answers, + createdAt: command.createdAt, + }, + }; + } + + case "thread.checkpoint.revert": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.checkpoint-revert-requested", + payload: { + threadId: command.threadId, + turnCount: command.turnCount, + createdAt: command.createdAt, + }, + }; + } + + case "thread.session.stop": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.session-stop-requested", + payload: { + threadId: command.threadId, + createdAt: command.createdAt, + }, + }; + } + + case "thread.session.set": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + metadata: {}, + }), + type: "thread.session-set", + payload: { + threadId: command.threadId, + session: command.session, + }, + }; + } + + case "thread.message.assistant.delta": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.message-sent", + payload: { + threadId: command.threadId, + messageId: command.messageId, + role: "assistant", + text: command.delta, + turnId: command.turnId ?? null, + streaming: true, + createdAt: command.createdAt, + updatedAt: command.createdAt, + }, + }; + } + + case "thread.message.assistant.complete": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.message-sent", + payload: { + threadId: command.threadId, + messageId: command.messageId, + role: "assistant", + text: "", + turnId: command.turnId ?? null, + streaming: false, + createdAt: command.createdAt, + updatedAt: command.createdAt, + }, + }; + } + + case "thread.proposed-plan.upsert": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.proposed-plan-upserted", + payload: { + threadId: command.threadId, + proposedPlan: command.proposedPlan, + }, + }; + } + + case "thread.turn.diff.complete": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.turn-diff-completed", + payload: { + threadId: command.threadId, + turnId: command.turnId, + checkpointTurnCount: command.checkpointTurnCount, + checkpointRef: command.checkpointRef, + status: command.status, + files: command.files, + assistantMessageId: command.assistantMessageId ?? null, + completedAt: command.completedAt, + }, + }; + } + + case "thread.revert.complete": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.reverted", + payload: { + threadId: command.threadId, + turnCount: command.turnCount, + }, + }; + } + + case "thread.activity.append": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + const requestId = + typeof command.activity.payload === "object" && + command.activity.payload !== null && + "requestId" in command.activity.payload && + typeof (command.activity.payload as { requestId?: unknown }).requestId === "string" + ? ((command.activity.payload as { requestId: string }) + .requestId as OrchestrationEvent["metadata"]["requestId"]) + : undefined; + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + ...(requestId !== undefined ? { metadata: { requestId } } : {}), + }), + type: "thread.activity-appended", + payload: { + threadId: command.threadId, + activity: command.activity, + }, + }; + } + + default: { + command satisfies never; + const fallback = command as never as { type: string }; + return yield* new OrchestrationCommandInvariantError({ + commandType: fallback.type, + detail: `Unknown command type: ${fallback.type}`, + }); + } + } +}); diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts new file mode 100644 index 0000000000..3dcdd19250 --- /dev/null +++ b/apps/server/src/orchestration/projector.test.ts @@ -0,0 +1,915 @@ +import { + CommandId, + EventId, + ProjectId, + ThreadId, + type OrchestrationEvent, +} from "@t3tools/contracts"; +import { Effect } from "effect"; +import { describe, expect, it } from "vitest"; + +import { createEmptyReadModel, projectEvent } from "./projector.ts"; + +function makeEvent(input: { + sequence: number; + type: OrchestrationEvent["type"]; + occurredAt: string; + aggregateKind: OrchestrationEvent["aggregateKind"]; + aggregateId: string; + commandId: string | null; + payload: unknown; +}): OrchestrationEvent { + return { + sequence: input.sequence, + eventId: EventId.makeUnsafe(`event-${input.sequence}`), + type: input.type, + aggregateKind: input.aggregateKind, + aggregateId: + input.aggregateKind === "project" + ? ProjectId.makeUnsafe(input.aggregateId) + : ThreadId.makeUnsafe(input.aggregateId), + occurredAt: input.occurredAt, + commandId: input.commandId === null ? null : CommandId.makeUnsafe(input.commandId), + causationEventId: null, + correlationId: null, + metadata: {}, + payload: input.payload as never, + } as OrchestrationEvent; +} + +describe("orchestration projector", () => { + it("applies thread.created events", async () => { + const now = new Date().toISOString(); + const model = createEmptyReadModel(now); + + const next = await Effect.runPromise( + projectEvent( + model, + makeEvent({ + sequence: 1, + type: "thread.created", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: now, + commandId: "cmd-thread-create", + payload: { + threadId: "thread-1", + projectId: "project-1", + title: "demo", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }), + ), + ); + + expect(next.snapshotSequence).toBe(1); + expect(next.threads).toEqual([ + { + id: "thread-1", + projectId: "project-1", + title: "demo", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurn: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + session: null, + }, + ]); + }); + + it("fails when event payload cannot be decoded by runtime schema", async () => { + const now = new Date().toISOString(); + const model = createEmptyReadModel(now); + + await expect( + Effect.runPromise( + projectEvent( + model, + makeEvent({ + sequence: 1, + type: "thread.created", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: now, + commandId: "cmd-invalid", + payload: { + // missing required threadId + projectId: "project-1", + title: "demo", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }), + ), + ), + ).rejects.toBeDefined(); + }); + + it("applies thread.archived and thread.unarchived events", async () => { + const now = new Date().toISOString(); + const later = new Date(Date.parse(now) + 1_000).toISOString(); + const created = await Effect.runPromise( + projectEvent( + createEmptyReadModel(now), + makeEvent({ + sequence: 1, + type: "thread.created", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: now, + commandId: "cmd-thread-create", + payload: { + threadId: "thread-1", + projectId: "project-1", + title: "demo", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }), + ), + ); + + const archived = await Effect.runPromise( + projectEvent( + created, + makeEvent({ + sequence: 2, + type: "thread.archived", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: later, + commandId: "cmd-thread-archive", + payload: { + threadId: "thread-1", + archivedAt: later, + updatedAt: later, + }, + }), + ), + ); + expect(archived.threads[0]?.archivedAt).toBe(later); + + const unarchived = await Effect.runPromise( + projectEvent( + archived, + makeEvent({ + sequence: 3, + type: "thread.unarchived", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: later, + commandId: "cmd-thread-unarchive", + payload: { + threadId: "thread-1", + updatedAt: later, + }, + }), + ), + ); + expect(unarchived.threads[0]?.archivedAt).toBeNull(); + }); + + it("keeps projector forward-compatible for unhandled event types", async () => { + const now = new Date().toISOString(); + const model = createEmptyReadModel(now); + + const next = await Effect.runPromise( + projectEvent( + model, + makeEvent({ + sequence: 7, + type: "thread.turn-start-requested", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: "2026-01-01T00:00:00.000Z", + commandId: "cmd-unhandled", + payload: { + threadId: "thread-1", + messageId: "message-1", + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:00.000Z", + }, + }), + ), + ); + + expect(next.snapshotSequence).toBe(7); + expect(next.updatedAt).toBe("2026-01-01T00:00:00.000Z"); + expect(next.threads).toEqual([]); + }); + + it("tracks latest turn id from session lifecycle events", async () => { + const createdAt = "2026-02-23T08:00:00.000Z"; + const startedAt = "2026-02-23T08:00:05.000Z"; + const model = createEmptyReadModel(createdAt); + + const afterCreate = await Effect.runPromise( + projectEvent( + model, + makeEvent({ + sequence: 1, + type: "thread.created", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: createdAt, + commandId: "cmd-create", + payload: { + threadId: "thread-1", + projectId: "project-1", + title: "demo", + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + updatedAt: createdAt, + }, + }), + ), + ); + + const afterRunning = await Effect.runPromise( + projectEvent( + afterCreate, + makeEvent({ + sequence: 2, + type: "thread.session-set", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: startedAt, + commandId: "cmd-running", + payload: { + threadId: "thread-1", + session: { + threadId: "thread-1", + status: "running", + providerName: "codex", + providerSessionId: "session-1", + providerThreadId: "provider-thread-1", + runtimeMode: "approval-required", + activeTurnId: "turn-1", + lastError: null, + updatedAt: startedAt, + }, + }, + }), + ), + ); + + const thread = afterRunning.threads[0]; + expect(thread?.latestTurn?.turnId).toBe("turn-1"); + expect(thread?.session?.status).toBe("running"); + }); + + it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => { + const createdAt = "2026-02-23T08:00:00.000Z"; + const updatedAt = "2026-02-23T08:00:05.000Z"; + const model = createEmptyReadModel(createdAt); + + const afterCreate = await Effect.runPromise( + projectEvent( + model, + makeEvent({ + sequence: 1, + type: "thread.created", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: createdAt, + commandId: "cmd-create", + payload: { + threadId: "thread-1", + projectId: "project-1", + title: "demo", + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + updatedAt: createdAt, + }, + }), + ), + ); + + const afterUpdate = await Effect.runPromise( + projectEvent( + afterCreate, + makeEvent({ + sequence: 2, + type: "thread.runtime-mode-set", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: updatedAt, + commandId: "cmd-runtime-mode-set", + payload: { + threadId: "thread-1", + runtimeMode: "approval-required", + updatedAt, + }, + }), + ), + ); + + expect(afterUpdate.threads[0]?.runtimeMode).toBe("approval-required"); + expect(afterUpdate.threads[0]?.updatedAt).toBe(updatedAt); + }); + + it("marks assistant messages completed with non-streaming updates", async () => { + const createdAt = "2026-02-23T09:00:00.000Z"; + const deltaAt = "2026-02-23T09:00:01.000Z"; + const completeAt = "2026-02-23T09:00:03.500Z"; + const model = createEmptyReadModel(createdAt); + + const afterCreate = await Effect.runPromise( + projectEvent( + model, + makeEvent({ + sequence: 1, + type: "thread.created", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: createdAt, + commandId: "cmd-create", + payload: { + threadId: "thread-1", + projectId: "project-1", + title: "demo", + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + updatedAt: createdAt, + }, + }), + ), + ); + + const afterDelta = await Effect.runPromise( + projectEvent( + afterCreate, + makeEvent({ + sequence: 2, + type: "thread.message-sent", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: deltaAt, + commandId: "cmd-delta", + payload: { + threadId: "thread-1", + messageId: "assistant:msg-1", + role: "assistant", + text: "hello", + turnId: "turn-1", + streaming: true, + createdAt: deltaAt, + updatedAt: deltaAt, + }, + }), + ), + ); + + const afterComplete = await Effect.runPromise( + projectEvent( + afterDelta, + makeEvent({ + sequence: 3, + type: "thread.message-sent", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: completeAt, + commandId: "cmd-complete", + payload: { + threadId: "thread-1", + messageId: "assistant:msg-1", + role: "assistant", + text: "", + turnId: "turn-1", + streaming: false, + createdAt: completeAt, + updatedAt: completeAt, + }, + }), + ), + ); + + const message = afterComplete.threads[0]?.messages[0]; + expect(message?.id).toBe("assistant:msg-1"); + expect(message?.text).toBe("hello"); + expect(message?.streaming).toBe(false); + expect(message?.updatedAt).toBe(completeAt); + }); + + it("prunes reverted turn messages from in-memory thread snapshot", async () => { + const createdAt = "2026-02-23T10:00:00.000Z"; + const model = createEmptyReadModel(createdAt); + + const afterCreate = await Effect.runPromise( + projectEvent( + model, + makeEvent({ + sequence: 1, + type: "thread.created", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: createdAt, + commandId: "cmd-create", + payload: { + threadId: "thread-1", + projectId: "project-1", + title: "demo", + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + updatedAt: createdAt, + }, + }), + ), + ); + + const events: ReadonlyArray = [ + makeEvent({ + sequence: 2, + type: "thread.message-sent", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: "2026-02-23T10:00:01.000Z", + commandId: "cmd-user-1", + payload: { + threadId: "thread-1", + messageId: "user-msg-1", + role: "user", + text: "First edit", + turnId: null, + streaming: false, + createdAt: "2026-02-23T10:00:01.000Z", + updatedAt: "2026-02-23T10:00:01.000Z", + }, + }), + makeEvent({ + sequence: 3, + type: "thread.message-sent", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: "2026-02-23T10:00:02.000Z", + commandId: "cmd-assistant-1", + payload: { + threadId: "thread-1", + messageId: "assistant-msg-1", + role: "assistant", + text: "Updated README to v2.\n", + turnId: "turn-1", + streaming: false, + createdAt: "2026-02-23T10:00:02.000Z", + updatedAt: "2026-02-23T10:00:02.000Z", + }, + }), + makeEvent({ + sequence: 4, + type: "thread.turn-diff-completed", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: "2026-02-23T10:00:02.500Z", + commandId: "cmd-turn-1-complete", + payload: { + threadId: "thread-1", + turnId: "turn-1", + checkpointTurnCount: 1, + checkpointRef: "refs/t3/checkpoints/thread-1/turn/1", + status: "ready", + files: [], + assistantMessageId: "assistant-msg-1", + completedAt: "2026-02-23T10:00:02.500Z", + }, + }), + makeEvent({ + sequence: 5, + type: "thread.activity-appended", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: "2026-02-23T10:00:02.750Z", + commandId: "cmd-activity-1", + payload: { + threadId: "thread-1", + activity: { + id: "activity-1", + tone: "tool", + kind: "tool.started", + summary: "Edit file started", + payload: { toolKind: "command" }, + turnId: "turn-1", + createdAt: "2026-02-23T10:00:02.750Z", + }, + }, + }), + makeEvent({ + sequence: 6, + type: "thread.message-sent", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: "2026-02-23T10:00:03.000Z", + commandId: "cmd-user-2", + payload: { + threadId: "thread-1", + messageId: "user-msg-2", + role: "user", + text: "Second edit", + turnId: null, + streaming: false, + createdAt: "2026-02-23T10:00:03.000Z", + updatedAt: "2026-02-23T10:00:03.000Z", + }, + }), + makeEvent({ + sequence: 7, + type: "thread.message-sent", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: "2026-02-23T10:00:04.000Z", + commandId: "cmd-assistant-2", + payload: { + threadId: "thread-1", + messageId: "assistant-msg-2", + role: "assistant", + text: "Updated README to v3.\n", + turnId: "turn-2", + streaming: false, + createdAt: "2026-02-23T10:00:04.000Z", + updatedAt: "2026-02-23T10:00:04.000Z", + }, + }), + makeEvent({ + sequence: 8, + type: "thread.turn-diff-completed", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: "2026-02-23T10:00:04.500Z", + commandId: "cmd-turn-2-complete", + payload: { + threadId: "thread-1", + turnId: "turn-2", + checkpointTurnCount: 2, + checkpointRef: "refs/t3/checkpoints/thread-1/turn/2", + status: "ready", + files: [], + assistantMessageId: "assistant-msg-2", + completedAt: "2026-02-23T10:00:04.500Z", + }, + }), + makeEvent({ + sequence: 9, + type: "thread.activity-appended", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: "2026-02-23T10:00:04.750Z", + commandId: "cmd-activity-2", + payload: { + threadId: "thread-1", + activity: { + id: "activity-2", + tone: "tool", + kind: "tool.completed", + summary: "Edit file complete", + payload: { toolKind: "command" }, + turnId: "turn-2", + createdAt: "2026-02-23T10:00:04.750Z", + }, + }, + }), + makeEvent({ + sequence: 10, + type: "thread.reverted", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: "2026-02-23T10:00:05.000Z", + commandId: "cmd-revert", + payload: { + threadId: "thread-1", + turnCount: 1, + }, + }), + ]; + + const afterRevert = await events.reduce>>( + (statePromise, event) => + statePromise.then((state) => Effect.runPromise(projectEvent(state, event))), + Promise.resolve(afterCreate), + ); + + const thread = afterRevert.threads[0]; + expect(thread?.messages.map((message) => ({ role: message.role, text: message.text }))).toEqual( + [ + { role: "user", text: "First edit" }, + { role: "assistant", text: "Updated README to v2.\n" }, + ], + ); + expect( + thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })), + ).toEqual([{ id: "activity-1", turnId: "turn-1" }]); + expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]); + expect(thread?.latestTurn?.turnId).toBe("turn-1"); + }); + + it("does not fallback-retain messages tied to removed turn IDs", async () => { + const createdAt = "2026-02-26T12:00:00.000Z"; + const model = createEmptyReadModel(createdAt); + + const afterCreate = await Effect.runPromise( + projectEvent( + model, + makeEvent({ + sequence: 1, + type: "thread.created", + aggregateKind: "thread", + aggregateId: "thread-revert", + occurredAt: createdAt, + commandId: "cmd-create-revert", + payload: { + threadId: "thread-revert", + projectId: "project-1", + title: "demo", + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + updatedAt: createdAt, + }, + }), + ), + ); + + const events: ReadonlyArray = [ + makeEvent({ + sequence: 2, + type: "thread.turn-diff-completed", + aggregateKind: "thread", + aggregateId: "thread-revert", + occurredAt: "2026-02-26T12:00:01.000Z", + commandId: "cmd-turn-1", + payload: { + threadId: "thread-revert", + turnId: "turn-1", + checkpointTurnCount: 1, + checkpointRef: "refs/t3/checkpoints/thread-revert/turn/1", + status: "ready", + files: [], + assistantMessageId: "assistant-keep", + completedAt: "2026-02-26T12:00:01.000Z", + }, + }), + makeEvent({ + sequence: 3, + type: "thread.message-sent", + aggregateKind: "thread", + aggregateId: "thread-revert", + occurredAt: "2026-02-26T12:00:01.100Z", + commandId: "cmd-assistant-keep", + payload: { + threadId: "thread-revert", + messageId: "assistant-keep", + role: "assistant", + text: "kept", + turnId: "turn-1", + streaming: false, + createdAt: "2026-02-26T12:00:01.100Z", + updatedAt: "2026-02-26T12:00:01.100Z", + }, + }), + makeEvent({ + sequence: 4, + type: "thread.turn-diff-completed", + aggregateKind: "thread", + aggregateId: "thread-revert", + occurredAt: "2026-02-26T12:00:02.000Z", + commandId: "cmd-turn-2", + payload: { + threadId: "thread-revert", + turnId: "turn-2", + checkpointTurnCount: 2, + checkpointRef: "refs/t3/checkpoints/thread-revert/turn/2", + status: "ready", + files: [], + assistantMessageId: "assistant-remove", + completedAt: "2026-02-26T12:00:02.000Z", + }, + }), + makeEvent({ + sequence: 5, + type: "thread.message-sent", + aggregateKind: "thread", + aggregateId: "thread-revert", + occurredAt: "2026-02-26T12:00:02.050Z", + commandId: "cmd-user-remove", + payload: { + threadId: "thread-revert", + messageId: "user-remove", + role: "user", + text: "removed", + turnId: "turn-2", + streaming: false, + createdAt: "2026-02-26T12:00:02.050Z", + updatedAt: "2026-02-26T12:00:02.050Z", + }, + }), + makeEvent({ + sequence: 6, + type: "thread.message-sent", + aggregateKind: "thread", + aggregateId: "thread-revert", + occurredAt: "2026-02-26T12:00:02.100Z", + commandId: "cmd-assistant-remove", + payload: { + threadId: "thread-revert", + messageId: "assistant-remove", + role: "assistant", + text: "removed", + turnId: "turn-2", + streaming: false, + createdAt: "2026-02-26T12:00:02.100Z", + updatedAt: "2026-02-26T12:00:02.100Z", + }, + }), + makeEvent({ + sequence: 7, + type: "thread.reverted", + aggregateKind: "thread", + aggregateId: "thread-revert", + occurredAt: "2026-02-26T12:00:03.000Z", + commandId: "cmd-revert", + payload: { + threadId: "thread-revert", + turnCount: 1, + }, + }), + ]; + + const afterRevert = await events.reduce>>( + (statePromise, event) => + statePromise.then((state) => Effect.runPromise(projectEvent(state, event))), + Promise.resolve(afterCreate), + ); + + const thread = afterRevert.threads[0]; + expect( + thread?.messages.map((message) => ({ + id: message.id, + role: message.role, + turnId: message.turnId, + })), + ).toEqual([{ id: "assistant-keep", role: "assistant", turnId: "turn-1" }]); + }); + + it("caps message and checkpoint retention for long-lived threads", async () => { + const createdAt = "2026-03-01T10:00:00.000Z"; + const model = createEmptyReadModel(createdAt); + + const afterCreate = await Effect.runPromise( + projectEvent( + model, + makeEvent({ + sequence: 1, + type: "thread.created", + aggregateKind: "thread", + aggregateId: "thread-capped", + occurredAt: createdAt, + commandId: "cmd-create-capped", + payload: { + threadId: "thread-capped", + projectId: "project-1", + title: "capped", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + updatedAt: createdAt, + }, + }), + ), + ); + + const messageEvents: ReadonlyArray = Array.from( + { length: 2_100 }, + (_, index) => + makeEvent({ + sequence: index + 2, + type: "thread.message-sent", + aggregateKind: "thread", + aggregateId: "thread-capped", + occurredAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`, + commandId: `cmd-message-${index}`, + payload: { + threadId: "thread-capped", + messageId: `msg-${index}`, + role: "assistant", + text: `message-${index}`, + turnId: `turn-${index}`, + streaming: false, + createdAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`, + updatedAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`, + }, + }), + ); + const afterMessages = await messageEvents.reduce< + Promise> + >( + (statePromise, event) => + statePromise.then((state) => Effect.runPromise(projectEvent(state, event))), + Promise.resolve(afterCreate), + ); + + const checkpointEvents: ReadonlyArray = Array.from( + { length: 600 }, + (_, index) => + makeEvent({ + sequence: index + 2_102, + type: "thread.turn-diff-completed", + aggregateKind: "thread", + aggregateId: "thread-capped", + occurredAt: `2026-03-01T10:30:${String(index % 60).padStart(2, "0")}.000Z`, + commandId: `cmd-checkpoint-${index}`, + payload: { + threadId: "thread-capped", + turnId: `turn-${index}`, + checkpointTurnCount: index + 1, + checkpointRef: `refs/t3/checkpoints/thread-capped/turn/${index + 1}`, + status: "ready", + files: [], + assistantMessageId: `msg-${index}`, + completedAt: `2026-03-01T10:30:${String(index % 60).padStart(2, "0")}.000Z`, + }, + }), + ); + const finalState = await checkpointEvents.reduce< + Promise> + >( + (statePromise, event) => + statePromise.then((state) => Effect.runPromise(projectEvent(state, event))), + Promise.resolve(afterMessages), + ); + + const thread = finalState.threads[0]; + expect(thread?.messages).toHaveLength(2_000); + expect(thread?.messages[0]?.id).toBe("msg-100"); + expect(thread?.messages.at(-1)?.id).toBe("msg-2099"); + expect(thread?.checkpoints).toHaveLength(500); + expect(thread?.checkpoints[0]?.turnId).toBe("turn-100"); + expect(thread?.checkpoints.at(-1)?.turnId).toBe("turn-599"); + }); +}); diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts new file mode 100644 index 0000000000..deb8a6d44d --- /dev/null +++ b/apps/server/src/orchestration/projector.ts @@ -0,0 +1,654 @@ +import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from "@t3tools/contracts"; +import { + OrchestrationCheckpointSummary, + OrchestrationMessage, + OrchestrationSession, + OrchestrationThread, +} from "@t3tools/contracts"; +import { Effect, Schema } from "effect"; + +import { toProjectorDecodeError, type OrchestrationProjectorDecodeError } from "./Errors.ts"; +import { + MessageSentPayloadSchema, + ProjectCreatedPayload, + ProjectDeletedPayload, + ProjectMetaUpdatedPayload, + ThreadActivityAppendedPayload, + ThreadArchivedPayload, + ThreadCreatedPayload, + ThreadDeletedPayload, + ThreadInteractionModeSetPayload, + ThreadMetaUpdatedPayload, + ThreadProposedPlanUpsertedPayload, + ThreadRuntimeModeSetPayload, + ThreadUnarchivedPayload, + ThreadRevertedPayload, + ThreadSessionSetPayload, + ThreadTurnDiffCompletedPayload, +} from "./Schemas.ts"; + +type ThreadPatch = Partial>; +const MAX_THREAD_MESSAGES = 2_000; +const MAX_THREAD_CHECKPOINTS = 500; + +function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") { + if (status === "error") return "error" as const; + if (status === "missing") return "interrupted" as const; + return "completed" as const; +} + +function updateThread( + threads: ReadonlyArray, + threadId: ThreadId, + patch: ThreadPatch, +): OrchestrationThread[] { + return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread)); +} + +function decodeForEvent( + schema: Schema.Schema, + value: unknown, + eventType: OrchestrationEvent["type"], + field: string, +): Effect.Effect { + return Effect.try({ + try: () => Schema.decodeUnknownSync(schema as any)(value), + catch: (error) => toProjectorDecodeError(`${eventType}:${field}`)(error as Schema.SchemaError), + }); +} + +function retainThreadMessagesAfterRevert( + messages: ReadonlyArray, + retainedTurnIds: ReadonlySet, + turnCount: number, +): ReadonlyArray { + const retainedMessageIds = new Set(); + for (const message of messages) { + if (message.role === "system") { + retainedMessageIds.add(message.id); + continue; + } + if (message.turnId !== null && retainedTurnIds.has(message.turnId)) { + retainedMessageIds.add(message.id); + } + } + + const retainedUserCount = messages.filter( + (message) => message.role === "user" && retainedMessageIds.has(message.id), + ).length; + const missingUserCount = Math.max(0, turnCount - retainedUserCount); + if (missingUserCount > 0) { + const fallbackUserMessages = messages + .filter( + (message) => + message.role === "user" && + !retainedMessageIds.has(message.id) && + (message.turnId === null || retainedTurnIds.has(message.turnId)), + ) + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(0, missingUserCount); + for (const message of fallbackUserMessages) { + retainedMessageIds.add(message.id); + } + } + + const retainedAssistantCount = messages.filter( + (message) => message.role === "assistant" && retainedMessageIds.has(message.id), + ).length; + const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount); + if (missingAssistantCount > 0) { + const fallbackAssistantMessages = messages + .filter( + (message) => + message.role === "assistant" && + !retainedMessageIds.has(message.id) && + (message.turnId === null || retainedTurnIds.has(message.turnId)), + ) + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(0, missingAssistantCount); + for (const message of fallbackAssistantMessages) { + retainedMessageIds.add(message.id); + } + } + + return messages.filter((message) => retainedMessageIds.has(message.id)); +} + +function retainThreadActivitiesAfterRevert( + activities: ReadonlyArray, + retainedTurnIds: ReadonlySet, +): ReadonlyArray { + return activities.filter( + (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId), + ); +} + +function retainThreadProposedPlansAfterRevert( + proposedPlans: ReadonlyArray, + retainedTurnIds: ReadonlySet, +): ReadonlyArray { + return proposedPlans.filter( + (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId), + ); +} + +function compareThreadActivities( + left: OrchestrationThread["activities"][number], + right: OrchestrationThread["activities"][number], +): number { + if (left.sequence !== undefined && right.sequence !== undefined) { + if (left.sequence !== right.sequence) { + return left.sequence - right.sequence; + } + } else if (left.sequence !== undefined) { + return 1; + } else if (right.sequence !== undefined) { + return -1; + } + + return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id); +} + +export function createEmptyReadModel(nowIso: string): OrchestrationReadModel { + return { + snapshotSequence: 0, + projects: [], + threads: [], + updatedAt: nowIso, + }; +} + +export function projectEvent( + model: OrchestrationReadModel, + event: OrchestrationEvent, +): Effect.Effect { + const nextBase: OrchestrationReadModel = { + ...model, + snapshotSequence: event.sequence, + updatedAt: event.occurredAt, + }; + + switch (event.type) { + case "project.created": + return decodeForEvent(ProjectCreatedPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => { + const existing = nextBase.projects.find((entry) => entry.id === payload.projectId); + const nextProject = { + id: payload.projectId, + title: payload.title, + workspaceRoot: payload.workspaceRoot, + defaultModelSelection: payload.defaultModelSelection, + scripts: payload.scripts, + createdAt: payload.createdAt, + updatedAt: payload.updatedAt, + deletedAt: null, + }; + + return { + ...nextBase, + projects: existing + ? nextBase.projects.map((entry) => + entry.id === payload.projectId ? nextProject : entry, + ) + : [...nextBase.projects, nextProject], + }; + }), + ); + + case "project.meta-updated": + return decodeForEvent(ProjectMetaUpdatedPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => ({ + ...nextBase, + projects: nextBase.projects.map((project) => + project.id === payload.projectId + ? { + ...project, + ...(payload.title !== undefined ? { title: payload.title } : {}), + ...(payload.workspaceRoot !== undefined + ? { workspaceRoot: payload.workspaceRoot } + : {}), + ...(payload.defaultModelSelection !== undefined + ? { defaultModelSelection: payload.defaultModelSelection } + : {}), + ...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}), + updatedAt: payload.updatedAt, + } + : project, + ), + })), + ); + + case "project.deleted": + return decodeForEvent(ProjectDeletedPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => ({ + ...nextBase, + projects: nextBase.projects.map((project) => + project.id === payload.projectId + ? { + ...project, + deletedAt: payload.deletedAt, + updatedAt: payload.deletedAt, + } + : project, + ), + })), + ); + + case "thread.created": + return Effect.gen(function* () { + const payload = yield* decodeForEvent( + ThreadCreatedPayload, + event.payload, + event.type, + "payload", + ); + const thread: OrchestrationThread = yield* decodeForEvent( + OrchestrationThread, + { + id: payload.threadId, + projectId: payload.projectId, + title: payload.title, + modelSelection: payload.modelSelection, + runtimeMode: payload.runtimeMode, + interactionMode: payload.interactionMode, + branch: payload.branch, + worktreePath: payload.worktreePath, + latestTurn: null, + createdAt: payload.createdAt, + updatedAt: payload.updatedAt, + archivedAt: null, + deletedAt: null, + messages: [], + activities: [], + checkpoints: [], + session: null, + }, + event.type, + "thread", + ); + const existing = nextBase.threads.find((entry) => entry.id === thread.id); + return { + ...nextBase, + threads: existing + ? nextBase.threads.map((entry) => (entry.id === thread.id ? thread : entry)) + : [...nextBase.threads, thread], + }; + }); + + case "thread.deleted": + return decodeForEvent(ThreadDeletedPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => ({ + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + deletedAt: payload.deletedAt, + updatedAt: payload.deletedAt, + }), + })), + ); + + case "thread.archived": + return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => ({ + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + archivedAt: payload.archivedAt, + updatedAt: payload.updatedAt, + }), + })), + ); + + case "thread.unarchived": + return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => ({ + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + archivedAt: null, + updatedAt: payload.updatedAt, + }), + })), + ); + + case "thread.meta-updated": + return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => ({ + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + ...(payload.title !== undefined ? { title: payload.title } : {}), + ...(payload.modelSelection !== undefined + ? { modelSelection: payload.modelSelection } + : {}), + ...(payload.branch !== undefined ? { branch: payload.branch } : {}), + ...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}), + updatedAt: payload.updatedAt, + }), + })), + ); + + case "thread.runtime-mode-set": + return decodeForEvent(ThreadRuntimeModeSetPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => ({ + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + runtimeMode: payload.runtimeMode, + updatedAt: payload.updatedAt, + }), + })), + ); + + case "thread.interaction-mode-set": + return decodeForEvent( + ThreadInteractionModeSetPayload, + event.payload, + event.type, + "payload", + ).pipe( + Effect.map((payload) => ({ + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + interactionMode: payload.interactionMode, + updatedAt: payload.updatedAt, + }), + })), + ); + + case "thread.message-sent": + return Effect.gen(function* () { + const payload = yield* decodeForEvent( + MessageSentPayloadSchema, + event.payload, + event.type, + "payload", + ); + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); + if (!thread) { + return nextBase; + } + + const message: OrchestrationMessage = yield* decodeForEvent( + OrchestrationMessage, + { + id: payload.messageId, + role: payload.role, + text: payload.text, + ...(payload.attachments !== undefined ? { attachments: payload.attachments } : {}), + turnId: payload.turnId, + streaming: payload.streaming, + createdAt: payload.createdAt, + updatedAt: payload.updatedAt, + }, + event.type, + "message", + ); + + const existingMessage = thread.messages.find((entry) => entry.id === message.id); + const messages = existingMessage + ? thread.messages.map((entry) => + entry.id === message.id + ? { + ...entry, + text: message.streaming + ? `${entry.text}${message.text}` + : message.text.length > 0 + ? message.text + : entry.text, + streaming: message.streaming, + updatedAt: message.updatedAt, + turnId: message.turnId, + ...(message.attachments !== undefined + ? { attachments: message.attachments } + : {}), + } + : entry, + ) + : [...thread.messages, message]; + const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES); + + return { + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + messages: cappedMessages, + updatedAt: event.occurredAt, + }), + }; + }); + + case "thread.session-set": + return Effect.gen(function* () { + const payload = yield* decodeForEvent( + ThreadSessionSetPayload, + event.payload, + event.type, + "payload", + ); + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); + if (!thread) { + return nextBase; + } + + const session: OrchestrationSession = yield* decodeForEvent( + OrchestrationSession, + payload.session, + event.type, + "session", + ); + + return { + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + session, + latestTurn: + session.status === "running" && session.activeTurnId !== null + ? { + turnId: session.activeTurnId, + state: "running", + requestedAt: + thread.latestTurn?.turnId === session.activeTurnId + ? thread.latestTurn.requestedAt + : session.updatedAt, + startedAt: + thread.latestTurn?.turnId === session.activeTurnId + ? (thread.latestTurn.startedAt ?? session.updatedAt) + : session.updatedAt, + completedAt: null, + assistantMessageId: + thread.latestTurn?.turnId === session.activeTurnId + ? thread.latestTurn.assistantMessageId + : null, + } + : thread.latestTurn, + updatedAt: event.occurredAt, + }), + }; + }); + + case "thread.proposed-plan-upserted": + return Effect.gen(function* () { + const payload = yield* decodeForEvent( + ThreadProposedPlanUpsertedPayload, + event.payload, + event.type, + "payload", + ); + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); + if (!thread) { + return nextBase; + } + + const proposedPlans = [ + ...thread.proposedPlans.filter((entry) => entry.id !== payload.proposedPlan.id), + payload.proposedPlan, + ] + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(-200); + + return { + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + proposedPlans, + updatedAt: event.occurredAt, + }), + }; + }); + + case "thread.turn-diff-completed": + return Effect.gen(function* () { + const payload = yield* decodeForEvent( + ThreadTurnDiffCompletedPayload, + event.payload, + event.type, + "payload", + ); + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); + if (!thread) { + return nextBase; + } + + const checkpoint = yield* decodeForEvent( + OrchestrationCheckpointSummary, + { + turnId: payload.turnId, + checkpointTurnCount: payload.checkpointTurnCount, + checkpointRef: payload.checkpointRef, + status: payload.status, + files: payload.files, + assistantMessageId: payload.assistantMessageId, + completedAt: payload.completedAt, + }, + event.type, + "checkpoint", + ); + + // Do not let a placeholder (status "missing") overwrite a checkpoint + // that has already been captured with a real git ref (status "ready"). + // ProviderRuntimeIngestion may fire multiple turn.diff.updated events + // per turn; without this guard later placeholders would clobber the + // real capture dispatched by CheckpointReactor. + const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId); + if (existing && existing.status !== "missing" && checkpoint.status === "missing") { + return nextBase; + } + + const checkpoints = [ + ...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId), + checkpoint, + ] + .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount) + .slice(-MAX_THREAD_CHECKPOINTS); + + return { + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + checkpoints, + latestTurn: { + turnId: payload.turnId, + state: checkpointStatusToLatestTurnState(payload.status), + requestedAt: + thread.latestTurn?.turnId === payload.turnId + ? thread.latestTurn.requestedAt + : payload.completedAt, + startedAt: + thread.latestTurn?.turnId === payload.turnId + ? (thread.latestTurn.startedAt ?? payload.completedAt) + : payload.completedAt, + completedAt: payload.completedAt, + assistantMessageId: payload.assistantMessageId, + }, + updatedAt: event.occurredAt, + }), + }; + }); + + case "thread.reverted": + return decodeForEvent(ThreadRevertedPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => { + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); + if (!thread) { + return nextBase; + } + + const checkpoints = thread.checkpoints + .filter((entry) => entry.checkpointTurnCount <= payload.turnCount) + .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount) + .slice(-MAX_THREAD_CHECKPOINTS); + const retainedTurnIds = new Set(checkpoints.map((checkpoint) => checkpoint.turnId)); + const messages = retainThreadMessagesAfterRevert( + thread.messages, + retainedTurnIds, + payload.turnCount, + ).slice(-MAX_THREAD_MESSAGES); + const proposedPlans = retainThreadProposedPlansAfterRevert( + thread.proposedPlans, + retainedTurnIds, + ).slice(-200); + const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds); + + const latestCheckpoint = checkpoints.at(-1) ?? null; + const latestTurn = + latestCheckpoint === null + ? null + : { + turnId: latestCheckpoint.turnId, + state: checkpointStatusToLatestTurnState(latestCheckpoint.status), + requestedAt: latestCheckpoint.completedAt, + startedAt: latestCheckpoint.completedAt, + completedAt: latestCheckpoint.completedAt, + assistantMessageId: latestCheckpoint.assistantMessageId, + }; + + return { + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + checkpoints, + messages, + proposedPlans, + activities, + latestTurn, + updatedAt: event.occurredAt, + }), + }; + }), + ); + + case "thread.activity-appended": + return decodeForEvent( + ThreadActivityAppendedPayload, + event.payload, + event.type, + "payload", + ).pipe( + Effect.map((payload) => { + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); + if (!thread) { + return nextBase; + } + + const activities = [ + ...thread.activities.filter((entry) => entry.id !== payload.activity.id), + payload.activity, + ] + .toSorted(compareThreadActivities) + .slice(-500); + + return { + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + activities, + updatedAt: event.occurredAt, + }), + }; + }), + ); + + default: + return Effect.succeed(nextBase); + } +} diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.ts new file mode 100644 index 0000000000..ca03ab5868 --- /dev/null +++ b/apps/server/src/os-jank.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi } from "vitest"; + +import { fixPath } from "./os-jank"; + +describe("fixPath", () => { + it("hydrates PATH on linux using the resolved login shell", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + }; + const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin"); + + fixPath({ + env, + platform: "linux", + readPath, + }); + + expect(readPath).toHaveBeenCalledWith("/bin/zsh"); + expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin"); + }); + + it("does nothing outside macOS and linux even when SHELL is set", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "C:/Program Files/Git/bin/bash.exe", + PATH: "C:\\Windows\\System32", + }; + const readPath = vi.fn(() => "/usr/local/bin:/usr/bin"); + + fixPath({ + env, + platform: "win32", + readPath, + }); + + expect(readPath).not.toHaveBeenCalled(); + expect(env.PATH).toBe("C:\\Windows\\System32"); + }); +}); diff --git a/apps/server/src/os-jank.ts b/apps/server/src/os-jank.ts new file mode 100644 index 0000000000..c3629e8fde --- /dev/null +++ b/apps/server/src/os-jank.ts @@ -0,0 +1,46 @@ +import * as OS from "node:os"; +import { Effect, Path } from "effect"; +import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell"; + +export function fixPath( + options: { + env?: NodeJS.ProcessEnv; + platform?: NodeJS.Platform; + readPath?: typeof readPathFromLoginShell; + } = {}, +): void { + const platform = options.platform ?? process.platform; + if (platform !== "darwin" && platform !== "linux") return; + + const env = options.env ?? process.env; + + try { + const shell = resolveLoginShell(platform, env.SHELL); + if (!shell) return; + const result = (options.readPath ?? readPathFromLoginShell)(shell); + if (result) { + env.PATH = result; + } + } catch { + // Silently ignore — keep default PATH + } +} + +export const expandHomePath = Effect.fn(function* (input: string) { + const { join } = yield* Path.Path; + if (input === "~") { + return OS.homedir(); + } + if (input.startsWith("~/") || input.startsWith("~\\")) { + return join(OS.homedir(), input.slice(2)); + } + return input; +}); + +export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) { + const { join, resolve } = yield* Path.Path; + if (!raw || raw.trim().length === 0) { + return join(OS.homedir(), ".t3"); + } + return resolve(yield* expandHomePath(raw.trim())); +}); diff --git a/apps/server/src/persistence/Errors.ts b/apps/server/src/persistence/Errors.ts new file mode 100644 index 0000000000..cb1cb2f3f8 --- /dev/null +++ b/apps/server/src/persistence/Errors.ts @@ -0,0 +1,105 @@ +import { Schema, SchemaIssue } from "effect"; + +// =============================== +// Core Persistence Errors +// =============================== + +export class PersistenceSqlError extends Schema.TaggedErrorClass()( + "PersistenceSqlError", + { + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `SQL error in ${this.operation}: ${this.detail}`; + } +} + +export class PersistenceDecodeError extends Schema.TaggedErrorClass()( + "PersistenceDecodeError", + { + operation: Schema.String, + issue: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Decode error in ${this.operation}: ${this.issue}`; + } +} + +export function toPersistenceSqlError(operation: string) { + return (cause: unknown): PersistenceSqlError => + new PersistenceSqlError({ + operation, + detail: `Failed to execute ${operation}`, + cause, + }); +} + +export function toPersistenceDecodeError(operation: string) { + return (error: Schema.SchemaError): PersistenceDecodeError => + new PersistenceDecodeError({ + operation, + issue: SchemaIssue.makeFormatterDefault()(error.issue), + cause: error, + }); +} + +export function toPersistenceDecodeCauseError(operation: string) { + return (cause: unknown): PersistenceDecodeError => + new PersistenceDecodeError({ + operation, + issue: `Failed to execute ${operation}`, + cause, + }); +} + +export const isPersistenceError = (u: unknown) => + Schema.is(PersistenceSqlError)(u) || Schema.is(PersistenceDecodeError)(u); + +// =============================== +// Provider Session Repository Errors +// =============================== + +export class ProviderSessionRepositoryValidationError extends Schema.TaggedErrorClass()( + "ProviderSessionRepositoryValidationError", + { + operation: Schema.String, + issue: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Provider session repository validation failed in ${this.operation}: ${this.issue}`; + } +} + +export class ProviderSessionRepositoryPersistenceError extends Schema.TaggedErrorClass()( + "ProviderSessionRepositoryPersistenceError", + { + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Provider session repository persistence error in ${this.operation}: ${this.detail}`; + } +} + +export type OrchestrationEventStoreError = PersistenceSqlError | PersistenceDecodeError; + +export type ProviderSessionRepositoryError = + | ProviderSessionRepositoryValidationError + | ProviderSessionRepositoryPersistenceError; + +export type OrchestrationCommandReceiptRepositoryError = + | PersistenceSqlError + | PersistenceDecodeError; + +export type ProviderSessionRuntimeRepositoryError = PersistenceSqlError | PersistenceDecodeError; + +export type ProjectionRepositoryError = PersistenceSqlError | PersistenceDecodeError; diff --git a/apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts b/apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts new file mode 100644 index 0000000000..33f2856742 --- /dev/null +++ b/apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts @@ -0,0 +1,89 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer } from "effect"; + +import { toPersistenceSqlError } from "../Errors.ts"; + +import { + GetByCommandIdInput, + OrchestrationCommandReceipt, + OrchestrationCommandReceiptRepository, + type OrchestrationCommandReceiptRepositoryShape, +} from "../Services/OrchestrationCommandReceipts.ts"; + +const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertReceiptRow = SqlSchema.void({ + Request: OrchestrationCommandReceipt, + execute: (receipt) => + sql` + INSERT INTO orchestration_command_receipts ( + command_id, + aggregate_kind, + aggregate_id, + accepted_at, + result_sequence, + status, + error + ) + VALUES ( + ${receipt.commandId}, + ${receipt.aggregateKind}, + ${receipt.aggregateId}, + ${receipt.acceptedAt}, + ${receipt.resultSequence}, + ${receipt.status}, + ${receipt.error} + ) + ON CONFLICT (command_id) + DO UPDATE SET + aggregate_kind = excluded.aggregate_kind, + aggregate_id = excluded.aggregate_id, + accepted_at = excluded.accepted_at, + result_sequence = excluded.result_sequence, + status = excluded.status, + error = excluded.error + `, + }); + + const findReceiptByCommandId = SqlSchema.findOneOption({ + Request: GetByCommandIdInput, + Result: OrchestrationCommandReceipt, + execute: ({ commandId }) => + sql` + SELECT + command_id AS "commandId", + aggregate_kind AS "aggregateKind", + aggregate_id AS "aggregateId", + accepted_at AS "acceptedAt", + result_sequence AS "resultSequence", + status, + error + FROM orchestration_command_receipts + WHERE command_id = ${commandId} + `, + }); + + const upsert: OrchestrationCommandReceiptRepositoryShape["upsert"] = (receipt) => + upsertReceiptRow(receipt).pipe( + Effect.mapError(toPersistenceSqlError("OrchestrationCommandReceiptRepository.upsert:query")), + ); + + const getByCommandId: OrchestrationCommandReceiptRepositoryShape["getByCommandId"] = (input) => + findReceiptByCommandId(input).pipe( + Effect.mapError( + toPersistenceSqlError("OrchestrationCommandReceiptRepository.getByCommandId:query"), + ), + ); + + return { + upsert, + getByCommandId, + } satisfies OrchestrationCommandReceiptRepositoryShape; +}); + +export const OrchestrationCommandReceiptRepositoryLive = Layer.effect( + OrchestrationCommandReceiptRepository, + makeOrchestrationCommandReceiptRepository, +); diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts new file mode 100644 index 0000000000..249e9d1e36 --- /dev/null +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts @@ -0,0 +1,119 @@ +import { CommandId, EventId, ProjectId } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import { Effect, Layer, Schema, Stream } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { PersistenceDecodeError } from "../Errors.ts"; +import { OrchestrationEventStore } from "../Services/OrchestrationEventStore.ts"; +import { OrchestrationEventStoreLive } from "./OrchestrationEventStore.ts"; +import { SqlitePersistenceMemory } from "./Sqlite.ts"; + +const layer = it.layer( + OrchestrationEventStoreLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)), +); + +layer("OrchestrationEventStore", (it) => { + it.effect("stores json columns as strings and replays decoded events", () => + Effect.gen(function* () { + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = new Date().toISOString(); + + const appended = yield* eventStore.append({ + type: "project.created", + eventId: EventId.makeUnsafe("evt-store-roundtrip"), + aggregateKind: "project", + aggregateId: ProjectId.makeUnsafe("project-roundtrip"), + occurredAt: now, + commandId: CommandId.makeUnsafe("cmd-store-roundtrip"), + causationEventId: null, + correlationId: CommandId.makeUnsafe("cmd-store-roundtrip"), + metadata: { + adapterKey: "codex", + }, + payload: { + projectId: ProjectId.makeUnsafe("project-roundtrip"), + title: "Roundtrip Project", + workspaceRoot: "/tmp/project-roundtrip", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + + const storedRows = yield* sql<{ + readonly payloadJson: string; + readonly metadataJson: string; + }>` + SELECT + payload_json AS "payloadJson", + metadata_json AS "metadataJson" + FROM orchestration_events + WHERE event_id = ${appended.eventId} + `; + assert.equal(storedRows.length, 1); + assert.equal(typeof storedRows[0]?.payloadJson, "string"); + assert.equal(typeof storedRows[0]?.metadataJson, "string"); + + const replayed = yield* Stream.runCollect(eventStore.readFromSequence(0, 10)).pipe( + Effect.map((chunk) => Array.from(chunk)), + ); + assert.equal(replayed.length, 1); + assert.equal(replayed[0]?.type, "project.created"); + assert.equal(replayed[0]?.metadata.adapterKey, "codex"); + }), + ); + + it.effect("fails with PersistenceDecodeError when stored json is invalid", () => + Effect.gen(function* () { + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = new Date().toISOString(); + + yield* sql` + INSERT INTO orchestration_events ( + event_id, + aggregate_kind, + stream_id, + stream_version, + event_type, + occurred_at, + command_id, + causation_event_id, + correlation_id, + actor_kind, + payload_json, + metadata_json + ) + VALUES ( + ${EventId.makeUnsafe("evt-store-invalid-json")}, + ${"project"}, + ${ProjectId.makeUnsafe("project-invalid-json")}, + ${0}, + ${"project.created"}, + ${now}, + ${CommandId.makeUnsafe("cmd-store-invalid-json")}, + ${null}, + ${null}, + ${"server"}, + ${"{"}, + ${"{}"} + ) + `; + + const replayResult = yield* Effect.result( + Stream.runCollect(eventStore.readFromSequence(0, 10)), + ); + assert.equal(replayResult._tag, "Failure"); + if (replayResult._tag === "Failure") { + assert.ok(Schema.is(PersistenceDecodeError)(replayResult.failure)); + assert.ok( + replayResult.failure.operation.includes( + "OrchestrationEventStore.readFromSequence:decodeRows", + ), + ); + } + }), + ); +}); diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts new file mode 100644 index 0000000000..4d81cf5e8d --- /dev/null +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts @@ -0,0 +1,267 @@ +import { + CommandId, + EventId, + IsoDateTime, + NonNegativeInt, + OrchestrationActorKind, + OrchestrationAggregateKind, + OrchestrationEvent, + OrchestrationEventMetadata, + OrchestrationEventType, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Schema, Stream } from "effect"; + +import { + toPersistenceDecodeError, + toPersistenceSqlError, + type OrchestrationEventStoreError, +} from "../Errors.ts"; +import { + OrchestrationEventStore, + type OrchestrationEventStoreShape, +} from "../Services/OrchestrationEventStore.ts"; + +const decodeEvent = Schema.decodeUnknownEffect(OrchestrationEvent); +const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown); +const EventMetadataFromJsonString = Schema.fromJsonString(OrchestrationEventMetadata); + +const AppendEventRequestSchema = Schema.Struct({ + eventId: EventId, + aggregateKind: OrchestrationAggregateKind, + streamId: Schema.Union([ProjectId, ThreadId]), + type: OrchestrationEventType, + causationEventId: Schema.NullOr(EventId), + correlationId: Schema.NullOr(CommandId), + actorKind: OrchestrationActorKind, + occurredAt: IsoDateTime, + commandId: Schema.NullOr(CommandId), + payloadJson: UnknownFromJsonString, + metadataJson: EventMetadataFromJsonString, +}); + +const OrchestrationEventPersistedRowSchema = Schema.Struct({ + sequence: NonNegativeInt, + eventId: EventId, + type: OrchestrationEventType, + aggregateKind: OrchestrationAggregateKind, + aggregateId: Schema.Union([ProjectId, ThreadId]), + occurredAt: IsoDateTime, + commandId: Schema.NullOr(CommandId), + causationEventId: Schema.NullOr(EventId), + correlationId: Schema.NullOr(CommandId), + payload: UnknownFromJsonString, + metadata: EventMetadataFromJsonString, +}); + +const ReadFromSequenceRequestSchema = Schema.Struct({ + sequenceExclusive: NonNegativeInt, + limit: Schema.Number, +}); +const DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000; +const READ_PAGE_SIZE = 500; + +function inferActorKind( + event: Omit, +): Schema.Schema.Type { + if (event.commandId !== null && event.commandId.startsWith("provider:")) { + return "provider"; + } + if (event.commandId !== null && event.commandId.startsWith("server:")) { + return "server"; + } + if ( + event.metadata.providerTurnId !== undefined || + event.metadata.providerItemId !== undefined || + event.metadata.adapterKey !== undefined + ) { + return "provider"; + } + if (event.commandId === null) { + return "server"; + } + return "client"; +} + +function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { + return (cause: unknown): OrchestrationEventStoreError => + Schema.isSchemaError(cause) + ? toPersistenceDecodeError(decodeOperation)(cause) + : toPersistenceSqlError(sqlOperation)(cause); +} + +const makeEventStore = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const appendEventRow = SqlSchema.findOne({ + Request: AppendEventRequestSchema, + Result: OrchestrationEventPersistedRowSchema, + execute: (request) => + sql` + INSERT INTO orchestration_events ( + event_id, + aggregate_kind, + stream_id, + stream_version, + event_type, + occurred_at, + command_id, + causation_event_id, + correlation_id, + actor_kind, + payload_json, + metadata_json + ) + VALUES ( + ${request.eventId}, + ${request.aggregateKind}, + ${request.streamId}, + COALESCE( + ( + SELECT stream_version + 1 + FROM orchestration_events + WHERE aggregate_kind = ${request.aggregateKind} + AND stream_id = ${request.streamId} + ORDER BY stream_version DESC + LIMIT 1 + ), + 0 + ), + ${request.type}, + ${request.occurredAt}, + ${request.commandId}, + ${request.causationEventId}, + ${request.correlationId}, + ${request.actorKind}, + ${request.payloadJson}, + ${request.metadataJson} + ) + RETURNING + sequence, + event_id AS "eventId", + event_type AS "type", + aggregate_kind AS "aggregateKind", + stream_id AS "aggregateId", + occurred_at AS "occurredAt", + command_id AS "commandId", + causation_event_id AS "causationEventId", + correlation_id AS "correlationId", + payload_json AS "payload", + metadata_json AS "metadata" + `, + }); + + const readEventRowsFromSequence = SqlSchema.findAll({ + Request: ReadFromSequenceRequestSchema, + Result: OrchestrationEventPersistedRowSchema, + execute: (request) => + sql` + SELECT + sequence, + event_id AS "eventId", + event_type AS "type", + aggregate_kind AS "aggregateKind", + stream_id AS "aggregateId", + occurred_at AS "occurredAt", + command_id AS "commandId", + causation_event_id AS "causationEventId", + correlation_id AS "correlationId", + payload_json AS "payload", + metadata_json AS "metadata" + FROM orchestration_events + WHERE sequence > ${request.sequenceExclusive} + ORDER BY sequence ASC + LIMIT ${request.limit} + `, + }); + + const append: OrchestrationEventStoreShape["append"] = (event) => + appendEventRow({ + eventId: event.eventId, + aggregateKind: event.aggregateKind, + streamId: event.aggregateId, + type: event.type, + causationEventId: event.causationEventId, + correlationId: event.correlationId, + actorKind: inferActorKind(event), + occurredAt: event.occurredAt, + commandId: event.commandId, + payloadJson: event.payload, + metadataJson: event.metadata, + }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "OrchestrationEventStore.append:insert", + "OrchestrationEventStore.append:decodeRow", + ), + ), + Effect.flatMap((row) => + decodeEvent(row).pipe( + Effect.mapError(toPersistenceDecodeError("OrchestrationEventStore.append:rowToEvent")), + ), + ), + ); + + const readFromSequence: OrchestrationEventStoreShape["readFromSequence"] = ( + sequenceExclusive, + limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT, + ) => { + const normalizedLimit = Math.max(0, Math.floor(limit)); + if (normalizedLimit === 0) { + return Stream.empty; + } + const readPage = ( + cursor: number, + remaining: number, + ): Stream.Stream => + Stream.fromEffect( + readEventRowsFromSequence({ + sequenceExclusive: cursor, + limit: Math.min(remaining, READ_PAGE_SIZE), + }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "OrchestrationEventStore.readFromSequence:query", + "OrchestrationEventStore.readFromSequence:decodeRows", + ), + ), + Effect.flatMap((rows) => + Effect.forEach(rows, (row) => + decodeEvent(row).pipe( + Effect.mapError( + toPersistenceDecodeError("OrchestrationEventStore.readFromSequence:rowToEvent"), + ), + ), + ), + ), + ), + ).pipe( + Stream.flatMap((events) => { + if (events.length === 0) { + return Stream.empty; + } + const nextRemaining = remaining - events.length; + if (nextRemaining <= 0) { + return Stream.fromIterable(events); + } + return Stream.concat( + Stream.fromIterable(events), + readPage(events[events.length - 1]!.sequence, nextRemaining), + ); + }), + ); + + return readPage(sequenceExclusive, normalizedLimit); + }; + + return { + append, + readFromSequence, + readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER), + } satisfies OrchestrationEventStoreShape; +}); + +export const OrchestrationEventStoreLive = Layer.effect(OrchestrationEventStore, makeEventStore); diff --git a/apps/server/src/persistence/Layers/ProjectionCheckpoints.ts b/apps/server/src/persistence/Layers/ProjectionCheckpoints.ts new file mode 100644 index 0000000000..26ef8fed1b --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionCheckpoints.ts @@ -0,0 +1,213 @@ +import { OrchestrationCheckpointFile } from "@t3tools/contracts"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Option, Schema, Struct } from "effect"; + +import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts"; +import { + DeleteByThreadIdInput, + GetByThreadAndTurnCountInput, + ListByThreadIdInput, + ProjectionCheckpoint, + ProjectionCheckpointRepository, + type ProjectionCheckpointRepositoryShape, +} from "../Services/ProjectionCheckpoints.ts"; + +const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields( + Struct.assign({ + files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)), + }), +); + +function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { + return (cause: unknown) => + Schema.isSchemaError(cause) + ? toPersistenceDecodeError(decodeOperation)(cause) + : toPersistenceSqlError(sqlOperation)(cause); +} + +const makeProjectionCheckpointRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const clearCheckpointConflict = SqlSchema.void({ + Request: GetByThreadAndTurnCountInput, + execute: ({ threadId, checkpointTurnCount }) => + sql` + UPDATE projection_turns + SET + checkpoint_turn_count = NULL, + checkpoint_ref = NULL, + checkpoint_status = NULL, + checkpoint_files_json = '[]' + WHERE thread_id = ${threadId} + AND checkpoint_turn_count = ${checkpointTurnCount} + `, + }); + + const upsertProjectionCheckpointRow = SqlSchema.void({ + Request: ProjectionCheckpointDbRowSchema, + execute: (row) => + sql` + INSERT INTO projection_turns ( + thread_id, + turn_id, + pending_message_id, + assistant_message_id, + state, + requested_at, + started_at, + completed_at, + checkpoint_turn_count, + checkpoint_ref, + checkpoint_status, + checkpoint_files_json + ) + VALUES ( + ${row.threadId}, + ${row.turnId}, + NULL, + ${row.assistantMessageId}, + ${row.status === "error" ? "error" : "completed"}, + ${row.completedAt}, + ${row.completedAt}, + ${row.completedAt}, + ${row.checkpointTurnCount}, + ${row.checkpointRef}, + ${row.status}, + ${row.files} + ) + ON CONFLICT (thread_id, turn_id) + DO UPDATE SET + assistant_message_id = excluded.assistant_message_id, + state = excluded.state, + completed_at = excluded.completed_at, + checkpoint_turn_count = excluded.checkpoint_turn_count, + checkpoint_ref = excluded.checkpoint_ref, + checkpoint_status = excluded.checkpoint_status, + checkpoint_files_json = excluded.checkpoint_files_json + `, + }); + + const listProjectionCheckpointRows = SqlSchema.findAll({ + Request: ListByThreadIdInput, + Result: ProjectionCheckpointDbRowSchema, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + turn_id AS "turnId", + checkpoint_turn_count AS "checkpointTurnCount", + checkpoint_ref AS "checkpointRef", + checkpoint_status AS "status", + checkpoint_files_json AS "files", + assistant_message_id AS "assistantMessageId", + completed_at AS "completedAt" + FROM projection_turns + WHERE thread_id = ${threadId} + AND checkpoint_turn_count IS NOT NULL + ORDER BY checkpoint_turn_count ASC + `, + }); + + const getProjectionCheckpointRow = SqlSchema.findOneOption({ + Request: GetByThreadAndTurnCountInput, + Result: ProjectionCheckpointDbRowSchema, + execute: ({ threadId, checkpointTurnCount }) => + sql` + SELECT + thread_id AS "threadId", + turn_id AS "turnId", + checkpoint_turn_count AS "checkpointTurnCount", + checkpoint_ref AS "checkpointRef", + checkpoint_status AS "status", + checkpoint_files_json AS "files", + assistant_message_id AS "assistantMessageId", + completed_at AS "completedAt" + FROM projection_turns + WHERE thread_id = ${threadId} + AND checkpoint_turn_count = ${checkpointTurnCount} + `, + }); + + const deleteProjectionCheckpointRows = SqlSchema.void({ + Request: DeleteByThreadIdInput, + execute: ({ threadId }) => + sql` + UPDATE projection_turns + SET + checkpoint_turn_count = NULL, + checkpoint_ref = NULL, + checkpoint_status = NULL, + checkpoint_files_json = '[]' + WHERE thread_id = ${threadId} + AND checkpoint_turn_count IS NOT NULL + `, + }); + + const upsertCheckpointRow = (row: Schema.Schema.Type) => + sql.withTransaction( + clearCheckpointConflict({ + threadId: row.threadId, + checkpointTurnCount: row.checkpointTurnCount, + }).pipe(Effect.flatMap(() => upsertProjectionCheckpointRow(row))), + ); + + const upsert: ProjectionCheckpointRepositoryShape["upsert"] = (row) => + upsertCheckpointRow(row).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionCheckpointRepository.upsert:query", + "ProjectionCheckpointRepository.upsert:encodeRequest", + ), + ), + ); + + const listByThreadId: ProjectionCheckpointRepositoryShape["listByThreadId"] = (input) => + listProjectionCheckpointRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionCheckpointRepository.listByThreadId:query", + "ProjectionCheckpointRepository.listByThreadId:decodeRows", + ), + ), + Effect.map((rows) => rows as ReadonlyArray>), + ); + + const getByThreadAndTurnCount: ProjectionCheckpointRepositoryShape["getByThreadAndTurnCount"] = ( + input, + ) => + getProjectionCheckpointRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionCheckpointRepository.getByThreadAndTurnCount:query", + "ProjectionCheckpointRepository.getByThreadAndTurnCount:decodeRow", + ), + ), + Effect.flatMap((rowOption) => + Option.match(rowOption, { + onNone: () => Effect.succeed(Option.none()), + onSome: (row) => + Effect.succeed(Option.some(row as Schema.Schema.Type)), + }), + ), + ); + + const deleteByThreadId: ProjectionCheckpointRepositoryShape["deleteByThreadId"] = (input) => + deleteProjectionCheckpointRows(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionCheckpointRepository.deleteByThreadId:query"), + ), + ); + + return { + upsert, + listByThreadId, + getByThreadAndTurnCount, + deleteByThreadId, + } satisfies ProjectionCheckpointRepositoryShape; +}); + +export const ProjectionCheckpointRepositoryLive = Layer.effect( + ProjectionCheckpointRepository, + makeProjectionCheckpointRepository, +); diff --git a/apps/server/src/persistence/Layers/ProjectionPendingApprovals.ts b/apps/server/src/persistence/Layers/ProjectionPendingApprovals.ts new file mode 100644 index 0000000000..25443a70dc --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionPendingApprovals.ts @@ -0,0 +1,136 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer } from "effect"; + +import { toPersistenceSqlError } from "../Errors.ts"; +import { + GetProjectionPendingApprovalInput, + DeleteProjectionPendingApprovalInput, + ListProjectionPendingApprovalsInput, + ProjectionPendingApproval, + ProjectionPendingApprovalRepository, + type ProjectionPendingApprovalRepositoryShape, +} from "../Services/ProjectionPendingApprovals.ts"; + +const makeProjectionPendingApprovalRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertProjectionPendingApprovalRow = SqlSchema.void({ + Request: ProjectionPendingApproval, + execute: (row) => + sql` + INSERT INTO projection_pending_approvals ( + request_id, + thread_id, + turn_id, + status, + decision, + created_at, + resolved_at + ) + VALUES ( + ${row.requestId}, + ${row.threadId}, + ${row.turnId}, + ${row.status}, + ${row.decision}, + ${row.createdAt}, + ${row.resolvedAt} + ) + ON CONFLICT (request_id) + DO UPDATE SET + thread_id = excluded.thread_id, + turn_id = excluded.turn_id, + status = excluded.status, + decision = excluded.decision, + created_at = excluded.created_at, + resolved_at = excluded.resolved_at + `, + }); + + const listProjectionPendingApprovalRows = SqlSchema.findAll({ + Request: ListProjectionPendingApprovalsInput, + Result: ProjectionPendingApproval, + execute: ({ threadId }) => + sql` + SELECT + request_id AS "requestId", + thread_id AS "threadId", + turn_id AS "turnId", + status, + decision, + created_at AS "createdAt", + resolved_at AS "resolvedAt" + FROM projection_pending_approvals + WHERE thread_id = ${threadId} + ORDER BY created_at ASC, request_id ASC + `, + }); + + const getProjectionPendingApprovalRow = SqlSchema.findOneOption({ + Request: GetProjectionPendingApprovalInput, + Result: ProjectionPendingApproval, + execute: ({ requestId }) => + sql` + SELECT + request_id AS "requestId", + thread_id AS "threadId", + turn_id AS "turnId", + status, + decision, + created_at AS "createdAt", + resolved_at AS "resolvedAt" + FROM projection_pending_approvals + WHERE request_id = ${requestId} + `, + }); + + const deleteProjectionPendingApprovalRow = SqlSchema.void({ + Request: DeleteProjectionPendingApprovalInput, + execute: ({ requestId }) => + sql` + DELETE FROM projection_pending_approvals + WHERE request_id = ${requestId} + `, + }); + + const upsert: ProjectionPendingApprovalRepositoryShape["upsert"] = (row) => + upsertProjectionPendingApprovalRow(row).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionPendingApprovalRepository.upsert:query")), + ); + + const listByThreadId: ProjectionPendingApprovalRepositoryShape["listByThreadId"] = (input) => + listProjectionPendingApprovalRows(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionPendingApprovalRepository.listByThreadId:query"), + ), + ); + + const getByRequestId: ProjectionPendingApprovalRepositoryShape["getByRequestId"] = (input) => + getProjectionPendingApprovalRow(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionPendingApprovalRepository.getByRequestId:query"), + ), + ); + + const deleteByRequestId: ProjectionPendingApprovalRepositoryShape["deleteByRequestId"] = ( + input, + ) => + deleteProjectionPendingApprovalRow(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionPendingApprovalRepository.deleteByRequestId:query"), + ), + ); + + return { + upsert, + listByThreadId, + getByRequestId, + deleteByRequestId, + } satisfies ProjectionPendingApprovalRepositoryShape; +}); + +export const ProjectionPendingApprovalRepositoryLive = Layer.effect( + ProjectionPendingApprovalRepository, + makeProjectionPendingApprovalRepository, +); diff --git a/apps/server/src/persistence/Layers/ProjectionProjects.ts b/apps/server/src/persistence/Layers/ProjectionProjects.ts new file mode 100644 index 0000000000..7ff19f55ae --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionProjects.ts @@ -0,0 +1,140 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Schema, Struct } from "effect"; + +import { ModelSelection, ProjectScript } from "@t3tools/contracts"; +import { toPersistenceSqlError } from "../Errors.ts"; +import { + DeleteProjectionProjectInput, + GetProjectionProjectInput, + ProjectionProject, + ProjectionProjectRepository, + type ProjectionProjectRepositoryShape, +} from "../Services/ProjectionProjects.ts"; + +const ProjectionProjectDbRow = ProjectionProject.mapFields( + Struct.assign({ + defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)), + scripts: Schema.fromJsonString(Schema.Array(ProjectScript)), + }), +); +type ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type; + +const makeProjectionProjectRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertProjectionProjectRow = SqlSchema.void({ + Request: ProjectionProject, + execute: (row) => + sql` + INSERT INTO projection_projects ( + project_id, + title, + workspace_root, + default_model_selection_json, + scripts_json, + created_at, + updated_at, + deleted_at + ) + VALUES ( + ${row.projectId}, + ${row.title}, + ${row.workspaceRoot}, + ${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null}, + ${JSON.stringify(row.scripts)}, + ${row.createdAt}, + ${row.updatedAt}, + ${row.deletedAt} + ) + ON CONFLICT (project_id) + DO UPDATE SET + title = excluded.title, + workspace_root = excluded.workspace_root, + default_model_selection_json = excluded.default_model_selection_json, + scripts_json = excluded.scripts_json, + created_at = excluded.created_at, + updated_at = excluded.updated_at, + deleted_at = excluded.deleted_at + `, + }); + + const getProjectionProjectRow = SqlSchema.findOneOption({ + Request: GetProjectionProjectInput, + Result: ProjectionProjectDbRow, + execute: ({ projectId }) => + sql` + SELECT + project_id AS "projectId", + title, + workspace_root AS "workspaceRoot", + default_model_selection_json AS "defaultModelSelection", + scripts_json AS "scripts", + created_at AS "createdAt", + updated_at AS "updatedAt", + deleted_at AS "deletedAt" + FROM projection_projects + WHERE project_id = ${projectId} + `, + }); + + const listProjectionProjectRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionProjectDbRow, + execute: () => + sql` + SELECT + project_id AS "projectId", + title, + workspace_root AS "workspaceRoot", + default_model_selection_json AS "defaultModelSelection", + scripts_json AS "scripts", + created_at AS "createdAt", + updated_at AS "updatedAt", + deleted_at AS "deletedAt" + FROM projection_projects + ORDER BY created_at ASC, project_id ASC + `, + }); + + const deleteProjectionProjectRow = SqlSchema.void({ + Request: DeleteProjectionProjectInput, + execute: ({ projectId }) => + sql` + DELETE FROM projection_projects + WHERE project_id = ${projectId} + `, + }); + + const upsert: ProjectionProjectRepositoryShape["upsert"] = (row) => + upsertProjectionProjectRow(row).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.upsert:query")), + ); + + const getById: ProjectionProjectRepositoryShape["getById"] = (input) => + getProjectionProjectRow(input).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")), + ); + + const listAll: ProjectionProjectRepositoryShape["listAll"] = () => + listProjectionProjectRows().pipe( + Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")), + ); + + const deleteById: ProjectionProjectRepositoryShape["deleteById"] = (input) => + deleteProjectionProjectRow(input).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.deleteById:query")), + ); + + return { + upsert, + getById, + listAll, + deleteById, + } satisfies ProjectionProjectRepositoryShape; +}); + +export const ProjectionProjectRepositoryLive = Layer.effect( + ProjectionProjectRepository, + makeProjectionProjectRepository, +); diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts new file mode 100644 index 0000000000..b0e1774837 --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts @@ -0,0 +1,123 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import { Effect, Layer, Option } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { SqlitePersistenceMemory } from "./Sqlite.ts"; +import { ProjectionProjectRepositoryLive } from "./ProjectionProjects.ts"; +import { ProjectionThreadRepositoryLive } from "./ProjectionThreads.ts"; +import { ProjectionProjectRepository } from "../Services/ProjectionProjects.ts"; +import { ProjectionThreadRepository } from "../Services/ProjectionThreads.ts"; + +const projectionRepositoriesLayer = it.layer( + Layer.mergeAll( + ProjectionProjectRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)), + ProjectionThreadRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)), + SqlitePersistenceMemory, + ), +); + +projectionRepositoriesLayer("Projection repositories", (it) => { + it.effect("stores SQL NULL for missing project model options", () => + Effect.gen(function* () { + const projects = yield* ProjectionProjectRepository; + const sql = yield* SqlClient.SqlClient; + + yield* projects.upsert({ + projectId: ProjectId.makeUnsafe("project-null-options"), + title: "Null options project", + workspaceRoot: "/tmp/project-null-options", + defaultModelSelection: { + provider: "codex", + model: "gpt-5.4", + }, + scripts: [], + createdAt: "2026-03-24T00:00:00.000Z", + updatedAt: "2026-03-24T00:00:00.000Z", + deletedAt: null, + }); + + const rows = yield* sql<{ + readonly defaultModelSelection: string | null; + }>` + SELECT default_model_selection_json AS "defaultModelSelection" + FROM projection_projects + WHERE project_id = 'project-null-options' + `; + const row = rows[0]; + if (!row) { + return yield* Effect.fail(new Error("Expected projection_projects row to exist.")); + } + + assert.strictEqual( + row.defaultModelSelection, + JSON.stringify({ + provider: "codex", + model: "gpt-5.4", + }), + ); + + const persisted = yield* projects.getById({ + projectId: ProjectId.makeUnsafe("project-null-options"), + }); + assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, { + provider: "codex", + model: "gpt-5.4", + }); + }), + ); + + it.effect("stores JSON for thread model options", () => + Effect.gen(function* () { + const threads = yield* ProjectionThreadRepository; + const sql = yield* SqlClient.SqlClient; + + yield* threads.upsert({ + threadId: ThreadId.makeUnsafe("thread-null-options"), + projectId: ProjectId.makeUnsafe("project-null-options"), + title: "Null options thread", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurnId: null, + createdAt: "2026-03-24T00:00:00.000Z", + updatedAt: "2026-03-24T00:00:00.000Z", + archivedAt: null, + deletedAt: null, + }); + + const rows = yield* sql<{ + readonly modelSelection: string | null; + }>` + SELECT model_selection_json AS "modelSelection" + FROM projection_threads + WHERE thread_id = 'thread-null-options' + `; + const row = rows[0]; + if (!row) { + return yield* Effect.fail(new Error("Expected projection_threads row to exist.")); + } + + assert.strictEqual( + row.modelSelection, + JSON.stringify({ + provider: "claudeAgent", + model: "claude-opus-4-6", + }), + ); + + const persisted = yield* threads.getById({ + threadId: ThreadId.makeUnsafe("thread-null-options"), + }); + assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, { + provider: "claudeAgent", + model: "claude-opus-4-6", + }); + }), + ); +}); diff --git a/apps/server/src/persistence/Layers/ProjectionState.ts b/apps/server/src/persistence/Layers/ProjectionState.ts new file mode 100644 index 0000000000..7c2b8110c7 --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionState.ts @@ -0,0 +1,116 @@ +import { NonNegativeInt } from "@t3tools/contracts"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Schema } from "effect"; + +import { toPersistenceSqlError } from "../Errors.ts"; + +import { + ProjectionStateRepository, + type ProjectionStateRepositoryShape, + GetProjectionStateInput, + ProjectionState, +} from "../Services/ProjectionState.ts"; + +const MinLastAppliedSequenceRowSchema = Schema.Struct({ + minLastAppliedSequence: Schema.NullOr(NonNegativeInt), +}); + +const makeProjectionStateRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertProjectionStateRow = SqlSchema.void({ + Request: ProjectionState, + execute: (row) => + sql` + INSERT INTO projection_state ( + projector, + last_applied_sequence, + updated_at + ) + VALUES ( + ${row.projector}, + ${row.lastAppliedSequence}, + ${row.updatedAt} + ) + ON CONFLICT (projector) + DO UPDATE SET + last_applied_sequence = excluded.last_applied_sequence, + updated_at = excluded.updated_at + `, + }); + + const getProjectionStateRow = SqlSchema.findOneOption({ + Request: GetProjectionStateInput, + Result: ProjectionState, + execute: ({ projector }) => + sql` + SELECT + projector, + last_applied_sequence AS "lastAppliedSequence", + updated_at AS "updatedAt" + FROM projection_state + WHERE projector = ${projector} + `, + }); + + const listProjectionStateRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionState, + execute: () => + sql` + SELECT + projector, + last_applied_sequence AS "lastAppliedSequence", + updated_at AS "updatedAt" + FROM projection_state + ORDER BY projector ASC + `, + }); + + const readMinLastAppliedSequence = SqlSchema.findOne({ + Request: Schema.Void, + Result: MinLastAppliedSequenceRowSchema, + execute: () => + sql` + SELECT + MIN(last_applied_sequence) AS "minLastAppliedSequence" + FROM projection_state + `, + }); + + const upsert: ProjectionStateRepositoryShape["upsert"] = (row) => + upsertProjectionStateRow(row).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionStateRepository.upsert:query")), + ); + + const getByProjector: ProjectionStateRepositoryShape["getByProjector"] = (input) => + getProjectionStateRow(input).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionStateRepository.getByProjector:query")), + ); + + const listAll: ProjectionStateRepositoryShape["listAll"] = () => + listProjectionStateRows(undefined).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionStateRepository.listAll:query")), + ); + + const minLastAppliedSequence: ProjectionStateRepositoryShape["minLastAppliedSequence"] = () => + readMinLastAppliedSequence(undefined).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionStateRepository.minLastAppliedSequence:query"), + ), + Effect.map((row) => row.minLastAppliedSequence), + ); + + return { + upsert, + getByProjector, + listAll, + minLastAppliedSequence, + } satisfies ProjectionStateRepositoryShape; +}); + +export const ProjectionStateRepositoryLive = Layer.effect( + ProjectionStateRepository, + makeProjectionStateRepository, +); diff --git a/apps/server/src/persistence/Layers/ProjectionThreadActivities.ts b/apps/server/src/persistence/Layers/ProjectionThreadActivities.ts new file mode 100644 index 0000000000..8e88cfa785 --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionThreadActivities.ts @@ -0,0 +1,156 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { NonNegativeInt } from "@t3tools/contracts"; +import { Effect, Layer, Schema, Struct } from "effect"; + +import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts"; + +import { + DeleteProjectionThreadActivitiesInput, + ListProjectionThreadActivitiesInput, + ProjectionThreadActivity, + ProjectionThreadActivityRepository, + type ProjectionThreadActivityRepositoryShape, +} from "../Services/ProjectionThreadActivities.ts"; + +const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields( + Struct.assign({ + payload: Schema.fromJsonString(Schema.Unknown), + sequence: Schema.NullOr(NonNegativeInt), + }), +); + +function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { + return (cause: unknown) => + Schema.isSchemaError(cause) + ? toPersistenceDecodeError(decodeOperation)(cause) + : toPersistenceSqlError(sqlOperation)(cause); +} + +const makeProjectionThreadActivityRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertProjectionThreadActivityRow = SqlSchema.void({ + Request: ProjectionThreadActivity, + execute: (row) => + sql` + INSERT INTO projection_thread_activities ( + activity_id, + thread_id, + turn_id, + tone, + kind, + summary, + payload_json, + sequence, + created_at + ) + VALUES ( + ${row.activityId}, + ${row.threadId}, + ${row.turnId}, + ${row.tone}, + ${row.kind}, + ${row.summary}, + ${JSON.stringify(row.payload)}, + ${row.sequence ?? null}, + ${row.createdAt} + ) + ON CONFLICT (activity_id) + DO UPDATE SET + thread_id = excluded.thread_id, + turn_id = excluded.turn_id, + tone = excluded.tone, + kind = excluded.kind, + summary = excluded.summary, + payload_json = excluded.payload_json, + sequence = excluded.sequence, + created_at = excluded.created_at + `, + }); + + const listProjectionThreadActivityRows = SqlSchema.findAll({ + Request: ListProjectionThreadActivitiesInput, + Result: ProjectionThreadActivityDbRowSchema, + execute: ({ threadId }) => + sql` + SELECT + activity_id AS "activityId", + thread_id AS "threadId", + turn_id AS "turnId", + tone, + kind, + summary, + payload_json AS "payload", + sequence, + created_at AS "createdAt" + FROM projection_thread_activities + WHERE thread_id = ${threadId} + ORDER BY + CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC, + sequence ASC, + created_at ASC, + activity_id ASC + `, + }); + + const deleteProjectionThreadActivityRows = SqlSchema.void({ + Request: DeleteProjectionThreadActivitiesInput, + execute: ({ threadId }) => + sql` + DELETE FROM projection_thread_activities + WHERE thread_id = ${threadId} + `, + }); + + const upsert: ProjectionThreadActivityRepositoryShape["upsert"] = (row) => + upsertProjectionThreadActivityRow(row).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionThreadActivityRepository.upsert:query", + "ProjectionThreadActivityRepository.upsert:encodeRequest", + ), + ), + ); + + const listByThreadId: ProjectionThreadActivityRepositoryShape["listByThreadId"] = (input) => + listProjectionThreadActivityRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionThreadActivityRepository.listByThreadId:query", + "ProjectionThreadActivityRepository.listByThreadId:decodeRows", + ), + ), + Effect.map((rows) => + rows.map((row) => ({ + activityId: row.activityId, + threadId: row.threadId, + turnId: row.turnId, + tone: row.tone, + kind: row.kind, + summary: row.summary, + payload: row.payload, + ...(row.sequence !== null ? { sequence: row.sequence } : {}), + createdAt: row.createdAt, + })), + ), + ); + + const deleteByThreadId: ProjectionThreadActivityRepositoryShape["deleteByThreadId"] = (input) => + deleteProjectionThreadActivityRows(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionThreadActivityRepository.deleteByThreadId:query"), + ), + ); + + return { + upsert, + listByThreadId, + deleteByThreadId, + } satisfies ProjectionThreadActivityRepositoryShape; +}); + +export const ProjectionThreadActivityRepositoryLive = Layer.effect( + ProjectionThreadActivityRepository, + makeProjectionThreadActivityRepository, +); diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts new file mode 100644 index 0000000000..5993ad6c20 --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts @@ -0,0 +1,113 @@ +import { MessageId, ThreadId } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; + +import { ProjectionThreadMessageRepository } from "../Services/ProjectionThreadMessages.ts"; +import { ProjectionThreadMessageRepositoryLive } from "./ProjectionThreadMessages.ts"; +import { SqlitePersistenceMemory } from "./Sqlite.ts"; + +const layer = it.layer( + ProjectionThreadMessageRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)), +); + +layer("ProjectionThreadMessageRepository", (it) => { + it.effect("preserves existing attachments when upsert omits attachments", () => + Effect.gen(function* () { + const repository = yield* ProjectionThreadMessageRepository; + const threadId = ThreadId.makeUnsafe("thread-preserve-attachments"); + const messageId = MessageId.makeUnsafe("message-preserve-attachments"); + const createdAt = "2026-02-28T19:00:00.000Z"; + const updatedAt = "2026-02-28T19:00:01.000Z"; + const persistedAttachments = [ + { + type: "image" as const, + id: "thread-preserve-attachments-att-1", + name: "example.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ]; + + yield* repository.upsert({ + messageId, + threadId, + turnId: null, + role: "user", + text: "initial", + attachments: persistedAttachments, + isStreaming: false, + createdAt, + updatedAt, + }); + + yield* repository.upsert({ + messageId, + threadId, + turnId: null, + role: "user", + text: "updated", + isStreaming: false, + createdAt, + updatedAt: "2026-02-28T19:00:02.000Z", + }); + + const rows = yield* repository.listByThreadId({ threadId }); + assert.equal(rows.length, 1); + assert.equal(rows[0]?.text, "updated"); + assert.deepEqual(rows[0]?.attachments, persistedAttachments); + + const rowById = yield* repository.getByMessageId({ messageId }); + assert.equal(rowById._tag, "Some"); + if (rowById._tag === "Some") { + assert.equal(rowById.value.text, "updated"); + assert.deepEqual(rowById.value.attachments, persistedAttachments); + } + }), + ); + + it.effect("allows explicit attachment clearing with an empty array", () => + Effect.gen(function* () { + const repository = yield* ProjectionThreadMessageRepository; + const threadId = ThreadId.makeUnsafe("thread-clear-attachments"); + const messageId = MessageId.makeUnsafe("message-clear-attachments"); + const createdAt = "2026-02-28T19:10:00.000Z"; + + yield* repository.upsert({ + messageId, + threadId, + turnId: null, + role: "assistant", + text: "with attachment", + attachments: [ + { + type: "image", + id: "thread-clear-attachments-att-1", + name: "example.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + isStreaming: false, + createdAt, + updatedAt: "2026-02-28T19:10:01.000Z", + }); + + yield* repository.upsert({ + messageId, + threadId, + turnId: null, + role: "assistant", + text: "cleared", + attachments: [], + isStreaming: false, + createdAt, + updatedAt: "2026-02-28T19:10:02.000Z", + }); + + const rows = yield* repository.listByThreadId({ threadId }); + assert.equal(rows.length, 1); + assert.equal(rows[0]?.text, "cleared"); + assert.deepEqual(rows[0]?.attachments, []); + }), + ); +}); diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts new file mode 100644 index 0000000000..13b7086cec --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts @@ -0,0 +1,184 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Option, Schema, Struct } from "effect"; +import { ChatAttachment } from "@t3tools/contracts"; + +import { toPersistenceSqlError } from "../Errors.ts"; +import { + GetProjectionThreadMessageInput, + ProjectionThreadMessageRepository, + type ProjectionThreadMessageRepositoryShape, + DeleteProjectionThreadMessagesInput, + ListProjectionThreadMessagesInput, + ProjectionThreadMessage, +} from "../Services/ProjectionThreadMessages.ts"; + +const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( + Struct.assign({ + isStreaming: Schema.Number, + attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))), + }), +); + +function toProjectionThreadMessage( + row: Schema.Schema.Type, +): ProjectionThreadMessage { + return { + messageId: row.messageId, + threadId: row.threadId, + turnId: row.turnId, + role: row.role, + text: row.text, + isStreaming: row.isStreaming === 1, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + ...(row.attachments !== null ? { attachments: row.attachments } : {}), + }; +} + +const makeProjectionThreadMessageRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertProjectionThreadMessageRow = SqlSchema.void({ + Request: ProjectionThreadMessage, + execute: (row) => { + const nextAttachmentsJson = + row.attachments !== undefined ? JSON.stringify(row.attachments) : null; + return sql` + INSERT INTO projection_thread_messages ( + message_id, + thread_id, + turn_id, + role, + text, + attachments_json, + is_streaming, + created_at, + updated_at + ) + VALUES ( + ${row.messageId}, + ${row.threadId}, + ${row.turnId}, + ${row.role}, + ${row.text}, + COALESCE( + ${nextAttachmentsJson}, + ( + SELECT attachments_json + FROM projection_thread_messages + WHERE message_id = ${row.messageId} + ) + ), + ${row.isStreaming ? 1 : 0}, + ${row.createdAt}, + ${row.updatedAt} + ) + ON CONFLICT (message_id) + DO UPDATE SET + thread_id = excluded.thread_id, + turn_id = excluded.turn_id, + role = excluded.role, + text = excluded.text, + attachments_json = COALESCE( + excluded.attachments_json, + projection_thread_messages.attachments_json + ), + is_streaming = excluded.is_streaming, + created_at = excluded.created_at, + updated_at = excluded.updated_at + `; + }, + }); + + const getProjectionThreadMessageRow = SqlSchema.findOneOption({ + Request: GetProjectionThreadMessageInput, + Result: ProjectionThreadMessageDbRowSchema, + execute: ({ messageId }) => + sql` + SELECT + message_id AS "messageId", + thread_id AS "threadId", + turn_id AS "turnId", + role, + text, + attachments_json AS "attachments", + is_streaming AS "isStreaming", + created_at AS "createdAt", + updated_at AS "updatedAt" + FROM projection_thread_messages + WHERE message_id = ${messageId} + LIMIT 1 + `, + }); + + const listProjectionThreadMessageRows = SqlSchema.findAll({ + Request: ListProjectionThreadMessagesInput, + Result: ProjectionThreadMessageDbRowSchema, + execute: ({ threadId }) => + sql` + SELECT + message_id AS "messageId", + thread_id AS "threadId", + turn_id AS "turnId", + role, + text, + attachments_json AS "attachments", + is_streaming AS "isStreaming", + created_at AS "createdAt", + updated_at AS "updatedAt" + FROM projection_thread_messages + WHERE thread_id = ${threadId} + ORDER BY created_at ASC, message_id ASC + `, + }); + + const deleteProjectionThreadMessageRows = SqlSchema.void({ + Request: DeleteProjectionThreadMessagesInput, + execute: ({ threadId }) => + sql` + DELETE FROM projection_thread_messages + WHERE thread_id = ${threadId} + `, + }); + + const upsert: ProjectionThreadMessageRepositoryShape["upsert"] = (row) => + upsertProjectionThreadMessageRow(row).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")), + ); + + const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) => + getProjectionThreadMessageRow(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"), + ), + Effect.map(Option.map(toProjectionThreadMessage)), + ); + + const listByThreadId: ProjectionThreadMessageRepositoryShape["listByThreadId"] = (input) => + listProjectionThreadMessageRows(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"), + ), + Effect.map((rows) => rows.map(toProjectionThreadMessage)), + ); + + const deleteByThreadId: ProjectionThreadMessageRepositoryShape["deleteByThreadId"] = (input) => + deleteProjectionThreadMessageRows(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionThreadMessageRepository.deleteByThreadId:query"), + ), + ); + + return { + upsert, + getByMessageId, + listByThreadId, + deleteByThreadId, + } satisfies ProjectionThreadMessageRepositoryShape; +}); + +export const ProjectionThreadMessageRepositoryLive = Layer.effect( + ProjectionThreadMessageRepository, + makeProjectionThreadMessageRepository, +); diff --git a/apps/server/src/persistence/Layers/ProjectionThreadProposedPlans.ts b/apps/server/src/persistence/Layers/ProjectionThreadProposedPlans.ts new file mode 100644 index 0000000000..ccd322feb2 --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionThreadProposedPlans.ts @@ -0,0 +1,110 @@ +import { Effect, Layer } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; + +import { toPersistenceSqlError } from "../Errors.ts"; +import { + DeleteProjectionThreadProposedPlansInput, + ListProjectionThreadProposedPlansInput, + ProjectionThreadProposedPlan, + ProjectionThreadProposedPlanRepository, + type ProjectionThreadProposedPlanRepositoryShape, +} from "../Services/ProjectionThreadProposedPlans.ts"; + +const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertProjectionThreadProposedPlanRow = SqlSchema.void({ + Request: ProjectionThreadProposedPlan, + execute: (row) => sql` + INSERT INTO projection_thread_proposed_plans ( + plan_id, + thread_id, + turn_id, + plan_markdown, + implemented_at, + implementation_thread_id, + created_at, + updated_at + ) + VALUES ( + ${row.planId}, + ${row.threadId}, + ${row.turnId}, + ${row.planMarkdown}, + ${row.implementedAt}, + ${row.implementationThreadId}, + ${row.createdAt}, + ${row.updatedAt} + ) + ON CONFLICT (plan_id) + DO UPDATE SET + thread_id = excluded.thread_id, + turn_id = excluded.turn_id, + plan_markdown = excluded.plan_markdown, + implemented_at = excluded.implemented_at, + implementation_thread_id = excluded.implementation_thread_id, + created_at = excluded.created_at, + updated_at = excluded.updated_at + `, + }); + + const listProjectionThreadProposedPlanRows = SqlSchema.findAll({ + Request: ListProjectionThreadProposedPlansInput, + Result: ProjectionThreadProposedPlan, + execute: ({ threadId }) => sql` + SELECT + plan_id AS "planId", + thread_id AS "threadId", + turn_id AS "turnId", + plan_markdown AS "planMarkdown", + implemented_at AS "implementedAt", + implementation_thread_id AS "implementationThreadId", + created_at AS "createdAt", + updated_at AS "updatedAt" + FROM projection_thread_proposed_plans + WHERE thread_id = ${threadId} + ORDER BY created_at ASC, plan_id ASC + `, + }); + + const deleteProjectionThreadProposedPlanRows = SqlSchema.void({ + Request: DeleteProjectionThreadProposedPlansInput, + execute: ({ threadId }) => sql` + DELETE FROM projection_thread_proposed_plans + WHERE thread_id = ${threadId} + `, + }); + + const upsert: ProjectionThreadProposedPlanRepositoryShape["upsert"] = (row) => + upsertProjectionThreadProposedPlanRow(row).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query")), + ); + + const listByThreadId: ProjectionThreadProposedPlanRepositoryShape["listByThreadId"] = (input) => + listProjectionThreadProposedPlanRows(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionThreadProposedPlanRepository.listByThreadId:query"), + ), + ); + + const deleteByThreadId: ProjectionThreadProposedPlanRepositoryShape["deleteByThreadId"] = ( + input, + ) => + deleteProjectionThreadProposedPlanRows(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionThreadProposedPlanRepository.deleteByThreadId:query"), + ), + ); + + return { + upsert, + listByThreadId, + deleteByThreadId, + } satisfies ProjectionThreadProposedPlanRepositoryShape; +}); + +export const ProjectionThreadProposedPlanRepositoryLive = Layer.effect( + ProjectionThreadProposedPlanRepository, + makeProjectionThreadProposedPlanRepository, +); diff --git a/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts b/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts new file mode 100644 index 0000000000..2499eba196 --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts @@ -0,0 +1,107 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer } from "effect"; + +import { toPersistenceSqlError } from "../Errors.ts"; + +import { + ProjectionThreadSession, + ProjectionThreadSessionRepository, + type ProjectionThreadSessionRepositoryShape, + DeleteProjectionThreadSessionInput, + GetProjectionThreadSessionInput, +} from "../Services/ProjectionThreadSessions.ts"; + +const makeProjectionThreadSessionRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertProjectionThreadSessionRow = SqlSchema.void({ + Request: ProjectionThreadSession, + execute: (row) => + sql` + INSERT INTO projection_thread_sessions ( + thread_id, + status, + provider_name, + runtime_mode, + active_turn_id, + last_error, + updated_at + ) + VALUES ( + ${row.threadId}, + ${row.status}, + ${row.providerName}, + ${row.runtimeMode}, + ${row.activeTurnId}, + ${row.lastError}, + ${row.updatedAt} + ) + ON CONFLICT (thread_id) + DO UPDATE SET + status = excluded.status, + provider_name = excluded.provider_name, + runtime_mode = excluded.runtime_mode, + active_turn_id = excluded.active_turn_id, + last_error = excluded.last_error, + updated_at = excluded.updated_at + `, + }); + + const getProjectionThreadSessionRow = SqlSchema.findOneOption({ + Request: GetProjectionThreadSessionInput, + Result: ProjectionThreadSession, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + status, + provider_name AS "providerName", + runtime_mode AS "runtimeMode", + active_turn_id AS "activeTurnId", + last_error AS "lastError", + updated_at AS "updatedAt" + FROM projection_thread_sessions + WHERE thread_id = ${threadId} + `, + }); + + const deleteProjectionThreadSessionRow = SqlSchema.void({ + Request: DeleteProjectionThreadSessionInput, + execute: ({ threadId }) => + sql` + DELETE FROM projection_thread_sessions + WHERE thread_id = ${threadId} + `, + }); + + const upsert: ProjectionThreadSessionRepositoryShape["upsert"] = (row) => + upsertProjectionThreadSessionRow(row).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionThreadSessionRepository.upsert:query")), + ); + + const getByThreadId: ProjectionThreadSessionRepositoryShape["getByThreadId"] = (input) => + getProjectionThreadSessionRow(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionThreadSessionRepository.getByThreadId:query"), + ), + ); + + const deleteByThreadId: ProjectionThreadSessionRepositoryShape["deleteByThreadId"] = (input) => + deleteProjectionThreadSessionRow(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionThreadSessionRepository.deleteByThreadId:query"), + ), + ); + + return { + upsert, + getByThreadId, + deleteByThreadId, + } satisfies ProjectionThreadSessionRepositoryShape; +}); + +export const ProjectionThreadSessionRepositoryLive = Layer.effect( + ProjectionThreadSessionRepository, + makeProjectionThreadSessionRepository, +); diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts new file mode 100644 index 0000000000..48dd51fdca --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -0,0 +1,166 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Schema, Struct } from "effect"; + +import { toPersistenceSqlError } from "../Errors.ts"; +import { + DeleteProjectionThreadInput, + GetProjectionThreadInput, + ListProjectionThreadsByProjectInput, + ProjectionThread, + ProjectionThreadRepository, + type ProjectionThreadRepositoryShape, +} from "../Services/ProjectionThreads.ts"; +import { ModelSelection } from "@t3tools/contracts"; + +const ProjectionThreadDbRow = ProjectionThread.mapFields( + Struct.assign({ + modelSelection: Schema.fromJsonString(ModelSelection), + }), +); +type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type; + +const makeProjectionThreadRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertProjectionThreadRow = SqlSchema.void({ + Request: ProjectionThread, + execute: (row) => + sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model_selection_json, + runtime_mode, + interaction_mode, + branch, + worktree_path, + latest_turn_id, + created_at, + updated_at, + archived_at, + deleted_at + ) + VALUES ( + ${row.threadId}, + ${row.projectId}, + ${row.title}, + ${JSON.stringify(row.modelSelection)}, + ${row.runtimeMode}, + ${row.interactionMode}, + ${row.branch}, + ${row.worktreePath}, + ${row.latestTurnId}, + ${row.createdAt}, + ${row.updatedAt}, + ${row.archivedAt}, + ${row.deletedAt} + ) + ON CONFLICT (thread_id) + DO UPDATE SET + project_id = excluded.project_id, + title = excluded.title, + model_selection_json = excluded.model_selection_json, + runtime_mode = excluded.runtime_mode, + interaction_mode = excluded.interaction_mode, + branch = excluded.branch, + worktree_path = excluded.worktree_path, + latest_turn_id = excluded.latest_turn_id, + created_at = excluded.created_at, + updated_at = excluded.updated_at, + archived_at = excluded.archived_at, + deleted_at = excluded.deleted_at + `, + }); + + const getProjectionThreadRow = SqlSchema.findOneOption({ + Request: GetProjectionThreadInput, + Result: ProjectionThreadDbRow, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + project_id AS "projectId", + title, + model_selection_json AS "modelSelection", + runtime_mode AS "runtimeMode", + interaction_mode AS "interactionMode", + branch, + worktree_path AS "worktreePath", + latest_turn_id AS "latestTurnId", + created_at AS "createdAt", + updated_at AS "updatedAt", + archived_at AS "archivedAt", + deleted_at AS "deletedAt" + FROM projection_threads + WHERE thread_id = ${threadId} + `, + }); + + const listProjectionThreadRows = SqlSchema.findAll({ + Request: ListProjectionThreadsByProjectInput, + Result: ProjectionThreadDbRow, + execute: ({ projectId }) => + sql` + SELECT + thread_id AS "threadId", + project_id AS "projectId", + title, + model_selection_json AS "modelSelection", + runtime_mode AS "runtimeMode", + interaction_mode AS "interactionMode", + branch, + worktree_path AS "worktreePath", + latest_turn_id AS "latestTurnId", + created_at AS "createdAt", + updated_at AS "updatedAt", + archived_at AS "archivedAt", + deleted_at AS "deletedAt" + FROM projection_threads + WHERE project_id = ${projectId} + ORDER BY created_at ASC, thread_id ASC + `, + }); + + const deleteProjectionThreadRow = SqlSchema.void({ + Request: DeleteProjectionThreadInput, + execute: ({ threadId }) => + sql` + DELETE FROM projection_threads + WHERE thread_id = ${threadId} + `, + }); + + const upsert: ProjectionThreadRepositoryShape["upsert"] = (row) => + upsertProjectionThreadRow(row).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.upsert:query")), + ); + + const getById: ProjectionThreadRepositoryShape["getById"] = (input) => + getProjectionThreadRow(input).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.getById:query")), + ); + + const listByProjectId: ProjectionThreadRepositoryShape["listByProjectId"] = (input) => + listProjectionThreadRows(input).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.listByProjectId:query")), + ); + + const deleteById: ProjectionThreadRepositoryShape["deleteById"] = (input) => + deleteProjectionThreadRow(input).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.deleteById:query")), + ); + + return { + upsert, + getById, + listByProjectId, + deleteById, + } satisfies ProjectionThreadRepositoryShape; +}); + +export const ProjectionThreadRepositoryLive = Layer.effect( + ProjectionThreadRepository, + makeProjectionThreadRepository, +); diff --git a/apps/server/src/persistence/Layers/ProjectionTurns.ts b/apps/server/src/persistence/Layers/ProjectionTurns.ts new file mode 100644 index 0000000000..9b6c9c5771 --- /dev/null +++ b/apps/server/src/persistence/Layers/ProjectionTurns.ts @@ -0,0 +1,351 @@ +import { OrchestrationCheckpointFile } from "@t3tools/contracts"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Option, Schema, Struct } from "effect"; + +import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts"; +import { + ClearCheckpointTurnConflictInput, + DeleteProjectionTurnsByThreadInput, + GetProjectionPendingTurnStartInput, + GetProjectionTurnByTurnIdInput, + ListProjectionTurnsByThreadInput, + ProjectionPendingTurnStart, + ProjectionTurn, + ProjectionTurnById, + ProjectionTurnRepository, + type ProjectionTurnRepositoryShape, +} from "../Services/ProjectionTurns.ts"; + +const ProjectionTurnDbRowSchema = ProjectionTurn.mapFields( + Struct.assign({ + checkpointFiles: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)), + }), +); + +const ProjectionTurnByIdDbRowSchema = ProjectionTurnById.mapFields( + Struct.assign({ + checkpointFiles: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)), + }), +); + +function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { + return (cause: unknown) => + Schema.isSchemaError(cause) + ? toPersistenceDecodeError(decodeOperation)(cause) + : toPersistenceSqlError(sqlOperation)(cause); +} + +const makeProjectionTurnRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertProjectionTurnById = SqlSchema.void({ + Request: ProjectionTurnByIdDbRowSchema, + execute: (row) => + sql` + INSERT INTO projection_turns ( + thread_id, + turn_id, + pending_message_id, + source_proposed_plan_thread_id, + source_proposed_plan_id, + assistant_message_id, + state, + requested_at, + started_at, + completed_at, + checkpoint_turn_count, + checkpoint_ref, + checkpoint_status, + checkpoint_files_json + ) + VALUES ( + ${row.threadId}, + ${row.turnId}, + ${row.pendingMessageId}, + ${row.sourceProposedPlanThreadId}, + ${row.sourceProposedPlanId}, + ${row.assistantMessageId}, + ${row.state}, + ${row.requestedAt}, + ${row.startedAt}, + ${row.completedAt}, + ${row.checkpointTurnCount}, + ${row.checkpointRef}, + ${row.checkpointStatus}, + ${row.checkpointFiles} + ) + ON CONFLICT (thread_id, turn_id) + DO UPDATE SET + pending_message_id = excluded.pending_message_id, + source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id, + source_proposed_plan_id = excluded.source_proposed_plan_id, + assistant_message_id = excluded.assistant_message_id, + state = excluded.state, + requested_at = excluded.requested_at, + started_at = excluded.started_at, + completed_at = excluded.completed_at, + checkpoint_turn_count = excluded.checkpoint_turn_count, + checkpoint_ref = excluded.checkpoint_ref, + checkpoint_status = excluded.checkpoint_status, + checkpoint_files_json = excluded.checkpoint_files_json + `, + }); + + const clearPendingProjectionTurnsByThread = SqlSchema.void({ + Request: DeleteProjectionTurnsByThreadInput, + execute: ({ threadId }) => + sql` + DELETE FROM projection_turns + WHERE thread_id = ${threadId} + AND turn_id IS NULL + AND state = 'pending' + AND checkpoint_turn_count IS NULL + `, + }); + + const insertPendingProjectionTurn = SqlSchema.void({ + Request: ProjectionPendingTurnStart, + execute: (row) => + sql` + INSERT INTO projection_turns ( + thread_id, + turn_id, + pending_message_id, + source_proposed_plan_thread_id, + source_proposed_plan_id, + assistant_message_id, + state, + requested_at, + started_at, + completed_at, + checkpoint_turn_count, + checkpoint_ref, + checkpoint_status, + checkpoint_files_json + ) + VALUES ( + ${row.threadId}, + NULL, + ${row.messageId}, + ${row.sourceProposedPlanThreadId}, + ${row.sourceProposedPlanId}, + NULL, + 'pending', + ${row.requestedAt}, + NULL, + NULL, + NULL, + NULL, + NULL, + '[]' + ) + `, + }); + + const getPendingProjectionTurn = SqlSchema.findOneOption({ + Request: GetProjectionPendingTurnStartInput, + Result: ProjectionPendingTurnStart, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + pending_message_id AS "messageId", + source_proposed_plan_thread_id AS "sourceProposedPlanThreadId", + source_proposed_plan_id AS "sourceProposedPlanId", + requested_at AS "requestedAt" + FROM projection_turns + WHERE thread_id = ${threadId} + AND turn_id IS NULL + AND state = 'pending' + AND pending_message_id IS NOT NULL + AND checkpoint_turn_count IS NULL + ORDER BY requested_at DESC + LIMIT 1 + `, + }); + + const listProjectionTurnsByThread = SqlSchema.findAll({ + Request: ListProjectionTurnsByThreadInput, + Result: ProjectionTurnDbRowSchema, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + turn_id AS "turnId", + pending_message_id AS "pendingMessageId", + source_proposed_plan_thread_id AS "sourceProposedPlanThreadId", + source_proposed_plan_id AS "sourceProposedPlanId", + assistant_message_id AS "assistantMessageId", + state, + requested_at AS "requestedAt", + started_at AS "startedAt", + completed_at AS "completedAt", + checkpoint_turn_count AS "checkpointTurnCount", + checkpoint_ref AS "checkpointRef", + checkpoint_status AS "checkpointStatus", + checkpoint_files_json AS "checkpointFiles" + FROM projection_turns + WHERE thread_id = ${threadId} + ORDER BY + CASE + WHEN checkpoint_turn_count IS NULL THEN 1 + ELSE 0 + END ASC, + checkpoint_turn_count ASC, + requested_at ASC, + turn_id ASC + `, + }); + + const getProjectionTurnByTurnId = SqlSchema.findOneOption({ + Request: GetProjectionTurnByTurnIdInput, + Result: ProjectionTurnByIdDbRowSchema, + execute: ({ threadId, turnId }) => + sql` + SELECT + thread_id AS "threadId", + turn_id AS "turnId", + pending_message_id AS "pendingMessageId", + source_proposed_plan_thread_id AS "sourceProposedPlanThreadId", + source_proposed_plan_id AS "sourceProposedPlanId", + assistant_message_id AS "assistantMessageId", + state, + requested_at AS "requestedAt", + started_at AS "startedAt", + completed_at AS "completedAt", + checkpoint_turn_count AS "checkpointTurnCount", + checkpoint_ref AS "checkpointRef", + checkpoint_status AS "checkpointStatus", + checkpoint_files_json AS "checkpointFiles" + FROM projection_turns + WHERE thread_id = ${threadId} + AND turn_id = ${turnId} + LIMIT 1 + `, + }); + + const clearCheckpointTurnConflictRow = SqlSchema.void({ + Request: ClearCheckpointTurnConflictInput, + execute: ({ threadId, turnId, checkpointTurnCount }) => + sql` + UPDATE projection_turns + SET + checkpoint_turn_count = NULL, + checkpoint_ref = NULL, + checkpoint_status = NULL, + checkpoint_files_json = '[]' + WHERE thread_id = ${threadId} + AND checkpoint_turn_count = ${checkpointTurnCount} + AND (turn_id IS NULL OR turn_id <> ${turnId}) + `, + }); + + const deleteProjectionTurnsByThread = SqlSchema.void({ + Request: DeleteProjectionTurnsByThreadInput, + execute: ({ threadId }) => + sql` + DELETE FROM projection_turns + WHERE thread_id = ${threadId} + `, + }); + + const upsertByTurnId: ProjectionTurnRepositoryShape["upsertByTurnId"] = (row) => + upsertProjectionTurnById(row).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionTurnRepository.upsertByTurnId:query", + "ProjectionTurnRepository.upsertByTurnId:encodeRequest", + ), + ), + ); + + const replacePendingTurnStart: ProjectionTurnRepositoryShape["replacePendingTurnStart"] = (row) => + sql + .withTransaction( + clearPendingProjectionTurnsByThread({ threadId: row.threadId }).pipe( + Effect.flatMap(() => insertPendingProjectionTurn(row)), + ), + ) + .pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionTurnRepository.replacePendingTurnStart:query", + "ProjectionTurnRepository.replacePendingTurnStart:encodeRequest", + ), + ), + ); + + const getPendingTurnStartByThreadId: ProjectionTurnRepositoryShape["getPendingTurnStartByThreadId"] = + (input) => + getPendingProjectionTurn(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionTurnRepository.getPendingTurnStartByThreadId:query"), + ), + ); + + const deletePendingTurnStartByThreadId: ProjectionTurnRepositoryShape["deletePendingTurnStartByThreadId"] = + (input) => + clearPendingProjectionTurnsByThread(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionTurnRepository.deletePendingTurnStartByThreadId:query"), + ), + ); + + const listByThreadId: ProjectionTurnRepositoryShape["listByThreadId"] = (input) => + listProjectionTurnsByThread(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionTurnRepository.listByThreadId:query", + "ProjectionTurnRepository.listByThreadId:decodeRows", + ), + ), + Effect.map((rows) => rows as ReadonlyArray>), + ); + + const getByTurnId: ProjectionTurnRepositoryShape["getByTurnId"] = (input) => + getProjectionTurnByTurnId(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionTurnRepository.getByTurnId:query", + "ProjectionTurnRepository.getByTurnId:decodeRow", + ), + ), + Effect.flatMap((rowOption) => + Option.match(rowOption, { + onNone: () => Effect.succeed(Option.none()), + onSome: (row) => + Effect.succeed(Option.some(row as Schema.Schema.Type)), + }), + ), + ); + + const clearCheckpointTurnConflict: ProjectionTurnRepositoryShape["clearCheckpointTurnConflict"] = + (input) => + clearCheckpointTurnConflictRow(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionTurnRepository.clearCheckpointTurnConflict:query"), + ), + ); + + const deleteByThreadId: ProjectionTurnRepositoryShape["deleteByThreadId"] = (input) => + deleteProjectionTurnsByThread(input).pipe( + Effect.mapError(toPersistenceSqlError("ProjectionTurnRepository.deleteByThreadId:query")), + ); + + return { + upsertByTurnId, + replacePendingTurnStart, + getPendingTurnStartByThreadId, + deletePendingTurnStartByThreadId, + listByThreadId, + getByTurnId, + clearCheckpointTurnConflict, + deleteByThreadId, + } satisfies ProjectionTurnRepositoryShape; +}); + +export const ProjectionTurnRepositoryLive = Layer.effect( + ProjectionTurnRepository, + makeProjectionTurnRepository, +); diff --git a/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts b/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts new file mode 100644 index 0000000000..da3e8bce90 --- /dev/null +++ b/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts @@ -0,0 +1,199 @@ +import { ThreadId } from "@t3tools/contracts"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Option, Schema, Struct } from "effect"; + +import { + toPersistenceDecodeError, + toPersistenceSqlError, + type ProviderSessionRuntimeRepositoryError, +} from "../Errors.ts"; +import { + ProviderSessionRuntime, + ProviderSessionRuntimeRepository, + type ProviderSessionRuntimeRepositoryShape, +} from "../Services/ProviderSessionRuntime.ts"; + +const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields( + Struct.assign({ + resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)), + runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)), + }), +); + +const decodeRuntime = Schema.decodeUnknownEffect(ProviderSessionRuntime); + +const GetRuntimeRequestSchema = Schema.Struct({ + threadId: ThreadId, +}); + +const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema; + +function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { + return (cause: unknown): ProviderSessionRuntimeRepositoryError => + Schema.isSchemaError(cause) + ? toPersistenceDecodeError(decodeOperation)(cause) + : toPersistenceSqlError(sqlOperation)(cause); +} + +const makeProviderSessionRuntimeRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const upsertRuntimeRow = SqlSchema.void({ + Request: ProviderSessionRuntimeDbRowSchema, + execute: (runtime) => + sql` + INSERT INTO provider_session_runtime ( + thread_id, + provider_name, + adapter_key, + runtime_mode, + status, + last_seen_at, + resume_cursor_json, + runtime_payload_json + ) + VALUES ( + ${runtime.threadId}, + ${runtime.providerName}, + ${runtime.adapterKey}, + ${runtime.runtimeMode}, + ${runtime.status}, + ${runtime.lastSeenAt}, + ${runtime.resumeCursor}, + ${runtime.runtimePayload} + ) + ON CONFLICT (thread_id) + DO UPDATE SET + provider_name = excluded.provider_name, + adapter_key = excluded.adapter_key, + runtime_mode = excluded.runtime_mode, + status = excluded.status, + last_seen_at = excluded.last_seen_at, + resume_cursor_json = excluded.resume_cursor_json, + runtime_payload_json = excluded.runtime_payload_json + `, + }); + + const getRuntimeRowByThreadId = SqlSchema.findOneOption({ + Request: GetRuntimeRequestSchema, + Result: ProviderSessionRuntimeDbRowSchema, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + provider_name AS "providerName", + adapter_key AS "adapterKey", + runtime_mode AS "runtimeMode", + status, + last_seen_at AS "lastSeenAt", + resume_cursor_json AS "resumeCursor", + runtime_payload_json AS "runtimePayload" + FROM provider_session_runtime + WHERE thread_id = ${threadId} + `, + }); + + const listRuntimeRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProviderSessionRuntimeDbRowSchema, + execute: () => + sql` + SELECT + thread_id AS "threadId", + provider_name AS "providerName", + adapter_key AS "adapterKey", + runtime_mode AS "runtimeMode", + status, + last_seen_at AS "lastSeenAt", + resume_cursor_json AS "resumeCursor", + runtime_payload_json AS "runtimePayload" + FROM provider_session_runtime + ORDER BY last_seen_at ASC, thread_id ASC + `, + }); + + const deleteRuntimeByThreadId = SqlSchema.void({ + Request: DeleteRuntimeRequestSchema, + execute: ({ threadId }) => + sql` + DELETE FROM provider_session_runtime + WHERE thread_id = ${threadId} + `, + }); + + const upsert: ProviderSessionRuntimeRepositoryShape["upsert"] = (runtime) => + upsertRuntimeRow(runtime).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProviderSessionRuntimeRepository.upsert:query", + "ProviderSessionRuntimeRepository.upsert:encodeRequest", + ), + ), + ); + + const getByThreadId: ProviderSessionRuntimeRepositoryShape["getByThreadId"] = (input) => + getRuntimeRowByThreadId(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProviderSessionRuntimeRepository.getByThreadId:query", + "ProviderSessionRuntimeRepository.getByThreadId:decodeRow", + ), + ), + Effect.flatMap((runtimeRowOption) => + Option.match(runtimeRowOption, { + onNone: () => Effect.succeed(Option.none()), + onSome: (row) => + decodeRuntime(row).pipe( + Effect.mapError( + toPersistenceDecodeError( + "ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime", + ), + ), + Effect.map((runtime) => Option.some(runtime)), + ), + }), + ), + ); + + const list: ProviderSessionRuntimeRepositoryShape["list"] = () => + listRuntimeRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProviderSessionRuntimeRepository.list:query", + "ProviderSessionRuntimeRepository.list:decodeRows", + ), + ), + Effect.flatMap((rows) => + Effect.forEach( + rows, + (row) => + decodeRuntime(row).pipe( + Effect.mapError( + toPersistenceDecodeError("ProviderSessionRuntimeRepository.list:rowToRuntime"), + ), + ), + { concurrency: "unbounded" }, + ), + ), + ); + + const deleteByThreadId: ProviderSessionRuntimeRepositoryShape["deleteByThreadId"] = (input) => + deleteRuntimeByThreadId(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteByThreadId:query"), + ), + ); + + return { + upsert, + getByThreadId, + list, + deleteByThreadId, + } satisfies ProviderSessionRuntimeRepositoryShape; +}); + +export const ProviderSessionRuntimeRepositoryLive = Layer.effect( + ProviderSessionRuntimeRepository, + makeProviderSessionRuntimeRepository, +); diff --git a/apps/server/src/persistence/Layers/Sqlite.ts b/apps/server/src/persistence/Layers/Sqlite.ts new file mode 100644 index 0000000000..58556099db --- /dev/null +++ b/apps/server/src/persistence/Layers/Sqlite.ts @@ -0,0 +1,64 @@ +import { Effect, Layer, FileSystem, Path } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import { ServerConfig } from "../../config.ts"; + +type RuntimeSqliteLayerConfig = { + readonly filename: string; + readonly spanAttributes?: Record; +}; + +type Loader = { + layer: (config: RuntimeSqliteLayerConfig) => Layer.Layer; +}; +const defaultSqliteClientLoaders = { + bun: () => import("@effect/sql-sqlite-bun/SqliteClient"), + node: () => import("../NodeSqliteClient.ts"), +} satisfies Record Promise>; + +const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* ( + config: RuntimeSqliteLayerConfig, +) { + const runtime = process.versions.bun !== undefined ? "bun" : "node"; + const loader = defaultSqliteClientLoaders[runtime]; + const clientModule = yield* Effect.promise(loader); + return clientModule.layer(config); +}, Layer.unwrap); + +const setup = Layer.effectDiscard( + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`PRAGMA journal_mode = WAL;`; + yield* sql`PRAGMA foreign_keys = ON;`; + yield* runMigrations(); + }), +); + +export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* ( + dbPath: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); + + return Layer.provideMerge( + setup, + makeRuntimeSqliteLayer({ + filename: dbPath, + spanAttributes: { + "db.name": path.basename(dbPath), + "service.name": "t3-server", + }, + }), + ); +}, Layer.unwrap); + +export const SqlitePersistenceMemory = Layer.provideMerge( + setup, + makeRuntimeSqliteLayer({ filename: ":memory:" }), +); + +export const layerConfig = Layer.unwrap( + Effect.map(Effect.service(ServerConfig), ({ dbPath }) => makeSqlitePersistenceLive(dbPath)), +); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts new file mode 100644 index 0000000000..a03c3c2d18 --- /dev/null +++ b/apps/server/src/persistence/Migrations.ts @@ -0,0 +1,129 @@ +/** + * MigrationsLive - Migration runner with inline loader + * + * Uses Migrator.make with fromRecord to define migrations inline. + * All migrations are statically imported - no dynamic file system loading. + * + * Migrations run automatically when the MigrationLayer is provided, + * ensuring the database schema is always up-to-date before the application starts. + */ + +import * as Migrator from "effect/unstable/sql/Migrator"; +import * as Layer from "effect/Layer"; +import * as Effect from "effect/Effect"; + +// Import all migrations statically +import Migration0001 from "./Migrations/001_OrchestrationEvents.ts"; +import Migration0002 from "./Migrations/002_OrchestrationCommandReceipts.ts"; +import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts"; +import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts"; +import Migration0005 from "./Migrations/005_Projections.ts"; +import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts"; +import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts"; +import Migration0008 from "./Migrations/008_ProjectionThreadActivitySequence.ts"; +import Migration0009 from "./Migrations/009_ProviderSessionRuntimeMode.ts"; +import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts"; +import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts"; +import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts"; +import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts"; +import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts"; +import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts"; +import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts"; +import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts"; +import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts"; +import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts"; + +/** + * Migration loader with all migrations defined inline. + * + * Key format: "{id}_{name}" where: + * - id: numeric migration ID (determines execution order) + * - name: descriptive name for the migration + * + * Uses Migrator.fromRecord which parses the key format and + * returns migrations sorted by ID. + */ +export const migrationEntries = [ + [1, "OrchestrationEvents", Migration0001], + [2, "OrchestrationCommandReceipts", Migration0002], + [3, "CheckpointDiffBlobs", Migration0003], + [4, "ProviderSessionRuntime", Migration0004], + [5, "Projections", Migration0005], + [6, "ProjectionThreadSessionRuntimeModeColumns", Migration0006], + [7, "ProjectionThreadMessageAttachments", Migration0007], + [8, "ProjectionThreadActivitySequence", Migration0008], + [9, "ProviderSessionRuntimeMode", Migration0009], + [10, "ProjectionThreadsRuntimeMode", Migration0010], + [11, "OrchestrationThreadCreatedRuntimeMode", Migration0011], + [12, "ProjectionThreadsInteractionMode", Migration0012], + [13, "ProjectionThreadProposedPlans", Migration0013], + [14, "ProjectionThreadProposedPlanImplementation", Migration0014], + [15, "ProjectionTurnsSourceProposedPlan", Migration0015], + [16, "CanonicalizeModelSelections", Migration0016], + [17, "ProjectionThreadsArchivedAt", Migration0017], + [18, "ProjectionThreadsArchivedAtIndex", Migration0018], + [19, "ProjectionSnapshotLookupIndexes", Migration0019], +] as const; + +export const makeMigrationLoader = (throughId?: number) => + Migrator.fromRecord( + Object.fromEntries( + migrationEntries + .filter(([id]) => throughId === undefined || id <= throughId) + .map(([id, name, migration]) => [`${id}_${name}`, migration]), + ), + ); + +/** + * Migrator run function - no schema dumping needed + * Uses the base Migrator.make without platform dependencies + */ +const run = Migrator.make({}); + +export interface RunMigrationsOptions { + readonly toMigrationInclusive?: number | undefined; +} + +/** + * Run all pending migrations. + * + * Creates the migrations tracking table (effect_sql_migrations) if it doesn't exist, + * then runs any migrations with ID greater than the latest recorded migration. + * + * Returns array of [id, name] tuples for migrations that were run. + * + * @returns Effect containing array of executed migrations + */ +export const runMigrations = Effect.fn("runMigrations")(function* ({ + toMigrationInclusive, +}: RunMigrationsOptions = {}) { + yield* Effect.log( + toMigrationInclusive === undefined + ? "Running all migrations..." + : `Running migrations 1 through ${toMigrationInclusive}...`, + ); + const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) }); + yield* Effect.log("Migrations ran successfully").pipe( + Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }), + ); + return executedMigrations; +}); + +/** + * Layer that runs migrations when the layer is built. + * + * Use this to ensure migrations run before your application starts. + * Migrations are run automatically - no separate script is needed. + * + * @example + * ```typescript + * import { MigrationsLive } from "@acme/db/Migrations" + * import * as SqliteClient from "@acme/db/SqliteClient" + * + * // Migrations run automatically when SqliteClient is provided + * const AppLayer = MigrationsLive.pipe( + * Layer.provideMerge(SqliteClient.layer({ filename: "database.sqlite" })) + * ) + * ``` + */ +export const MigrationsLive = Layer.effectDiscard(runMigrations()); diff --git a/apps/server/src/persistence/Migrations/001_OrchestrationEvents.ts b/apps/server/src/persistence/Migrations/001_OrchestrationEvents.ts new file mode 100644 index 0000000000..b8e0cd43fa --- /dev/null +++ b/apps/server/src/persistence/Migrations/001_OrchestrationEvents.ts @@ -0,0 +1,44 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE IF NOT EXISTS orchestration_events ( + sequence INTEGER PRIMARY KEY AUTOINCREMENT, + event_id TEXT NOT NULL UNIQUE, + aggregate_kind TEXT NOT NULL, + stream_id TEXT NOT NULL, + stream_version INTEGER NOT NULL, + event_type TEXT NOT NULL, + occurred_at TEXT NOT NULL, + command_id TEXT, + causation_event_id TEXT, + correlation_id TEXT, + actor_kind TEXT NOT NULL, + payload_json TEXT NOT NULL, + metadata_json TEXT NOT NULL + ) + `; + + yield* sql` + CREATE UNIQUE INDEX IF NOT EXISTS idx_orch_events_stream_version + ON orchestration_events(aggregate_kind, stream_id, stream_version) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_orch_events_stream_sequence + ON orchestration_events(aggregate_kind, stream_id, sequence) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_orch_events_command_id + ON orchestration_events(command_id) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_orch_events_correlation_id + ON orchestration_events(correlation_id) + `; +}); diff --git a/apps/server/src/persistence/Migrations/002_OrchestrationCommandReceipts.ts b/apps/server/src/persistence/Migrations/002_OrchestrationCommandReceipts.ts new file mode 100644 index 0000000000..a81f309fbf --- /dev/null +++ b/apps/server/src/persistence/Migrations/002_OrchestrationCommandReceipts.ts @@ -0,0 +1,28 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE IF NOT EXISTS orchestration_command_receipts ( + command_id TEXT PRIMARY KEY, + aggregate_kind TEXT NOT NULL, + aggregate_id TEXT NOT NULL, + accepted_at TEXT NOT NULL, + result_sequence INTEGER NOT NULL, + status TEXT NOT NULL, + error TEXT + ) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_orch_command_receipts_aggregate + ON orchestration_command_receipts(aggregate_kind, aggregate_id) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_orch_command_receipts_sequence + ON orchestration_command_receipts(result_sequence) + `; +}); diff --git a/apps/server/src/persistence/Migrations/003_CheckpointDiffBlobs.ts b/apps/server/src/persistence/Migrations/003_CheckpointDiffBlobs.ts new file mode 100644 index 0000000000..2a5d32a027 --- /dev/null +++ b/apps/server/src/persistence/Migrations/003_CheckpointDiffBlobs.ts @@ -0,0 +1,22 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE IF NOT EXISTS checkpoint_diff_blobs ( + thread_id TEXT NOT NULL, + from_turn_count INTEGER NOT NULL, + to_turn_count INTEGER NOT NULL, + diff TEXT NOT NULL, + created_at TEXT NOT NULL, + UNIQUE (thread_id, from_turn_count, to_turn_count) + ) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_checkpoint_diff_blobs_thread_to_turn + ON checkpoint_diff_blobs(thread_id, to_turn_count) + `; +}); diff --git a/apps/server/src/persistence/Migrations/004_ProviderSessionRuntime.ts b/apps/server/src/persistence/Migrations/004_ProviderSessionRuntime.ts new file mode 100644 index 0000000000..f468ad49cf --- /dev/null +++ b/apps/server/src/persistence/Migrations/004_ProviderSessionRuntime.ts @@ -0,0 +1,29 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE IF NOT EXISTS provider_session_runtime ( + thread_id TEXT PRIMARY KEY, + provider_name TEXT NOT NULL, + adapter_key TEXT NOT NULL, + runtime_mode TEXT NOT NULL DEFAULT 'full-access', + status TEXT NOT NULL, + last_seen_at TEXT NOT NULL, + resume_cursor_json TEXT, + runtime_payload_json TEXT + ) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_status + ON provider_session_runtime(status) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_provider + ON provider_session_runtime(provider_name) + `; +}); diff --git a/apps/server/src/persistence/Migrations/005_Projections.ts b/apps/server/src/persistence/Migrations/005_Projections.ts new file mode 100644 index 0000000000..c950da76a1 --- /dev/null +++ b/apps/server/src/persistence/Migrations/005_Projections.ts @@ -0,0 +1,153 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE IF NOT EXISTS projection_projects ( + project_id TEXT PRIMARY KEY, + title TEXT NOT NULL, + workspace_root TEXT NOT NULL, + default_model TEXT, + scripts_json TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + deleted_at TEXT + ) + `; + + yield* sql` + CREATE TABLE IF NOT EXISTS projection_threads ( + thread_id TEXT PRIMARY KEY, + project_id TEXT NOT NULL, + title TEXT NOT NULL, + model TEXT NOT NULL, + branch TEXT, + worktree_path TEXT, + latest_turn_id TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + deleted_at TEXT + ) + `; + + yield* sql` + CREATE TABLE IF NOT EXISTS projection_thread_messages ( + message_id TEXT PRIMARY KEY, + thread_id TEXT NOT NULL, + turn_id TEXT, + role TEXT NOT NULL, + text TEXT NOT NULL, + is_streaming INTEGER NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ) + `; + + yield* sql` + CREATE TABLE IF NOT EXISTS projection_thread_activities ( + activity_id TEXT PRIMARY KEY, + thread_id TEXT NOT NULL, + turn_id TEXT, + tone TEXT NOT NULL, + kind TEXT NOT NULL, + summary TEXT NOT NULL, + payload_json TEXT NOT NULL, + created_at TEXT NOT NULL + ) + `; + + yield* sql` + CREATE TABLE IF NOT EXISTS projection_thread_sessions ( + thread_id TEXT PRIMARY KEY, + status TEXT NOT NULL, + provider_name TEXT, + provider_session_id TEXT, + provider_thread_id TEXT, + active_turn_id TEXT, + last_error TEXT, + updated_at TEXT NOT NULL + ) + `; + + yield* sql` + CREATE TABLE IF NOT EXISTS projection_turns ( + row_id INTEGER PRIMARY KEY AUTOINCREMENT, + thread_id TEXT NOT NULL, + turn_id TEXT, + pending_message_id TEXT, + assistant_message_id TEXT, + state TEXT NOT NULL, + requested_at TEXT NOT NULL, + started_at TEXT, + completed_at TEXT, + checkpoint_turn_count INTEGER, + checkpoint_ref TEXT, + checkpoint_status TEXT, + checkpoint_files_json TEXT NOT NULL, + UNIQUE (thread_id, turn_id), + UNIQUE (thread_id, checkpoint_turn_count) + ) + `; + + yield* sql` + CREATE TABLE IF NOT EXISTS projection_pending_approvals ( + request_id TEXT PRIMARY KEY, + thread_id TEXT NOT NULL, + turn_id TEXT, + status TEXT NOT NULL, + decision TEXT, + created_at TEXT NOT NULL, + resolved_at TEXT + ) + `; + + yield* sql` + CREATE TABLE IF NOT EXISTS projection_state ( + projector TEXT PRIMARY KEY, + last_applied_sequence INTEGER NOT NULL, + updated_at TEXT NOT NULL + ) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_projects_updated_at + ON projection_projects(updated_at) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_threads_project_id + ON projection_threads(project_id) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_thread_messages_thread_created + ON projection_thread_messages(thread_id, created_at) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_created + ON projection_thread_activities(thread_id, created_at) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_thread_sessions_provider_session + ON projection_thread_sessions(provider_session_id) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_turns_thread_requested + ON projection_turns(thread_id, requested_at) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_turns_thread_checkpoint_completed + ON projection_turns(thread_id, checkpoint_turn_count, completed_at) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_pending_approvals_thread_status + ON projection_pending_approvals(thread_id, status) + `; +}); diff --git a/apps/server/src/persistence/Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts b/apps/server/src/persistence/Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts new file mode 100644 index 0000000000..a988a50976 --- /dev/null +++ b/apps/server/src/persistence/Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts @@ -0,0 +1,19 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +const DEFAULT_RUNTIME_MODE = "full-access"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_thread_sessions + ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access' + `; + + yield* sql` + UPDATE projection_thread_sessions + SET runtime_mode = ${DEFAULT_RUNTIME_MODE} + WHERE runtime_mode IS NULL + `; +}); diff --git a/apps/server/src/persistence/Migrations/007_ProjectionThreadMessageAttachments.ts b/apps/server/src/persistence/Migrations/007_ProjectionThreadMessageAttachments.ts new file mode 100644 index 0000000000..d2cbe5b2b0 --- /dev/null +++ b/apps/server/src/persistence/Migrations/007_ProjectionThreadMessageAttachments.ts @@ -0,0 +1,11 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_thread_messages + ADD COLUMN attachments_json TEXT + `; +}); diff --git a/apps/server/src/persistence/Migrations/008_ProjectionThreadActivitySequence.ts b/apps/server/src/persistence/Migrations/008_ProjectionThreadActivitySequence.ts new file mode 100644 index 0000000000..6000f0c62c --- /dev/null +++ b/apps/server/src/persistence/Migrations/008_ProjectionThreadActivitySequence.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_thread_activities + ADD COLUMN sequence INTEGER + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence + ON projection_thread_activities(thread_id, sequence) + `; +}); diff --git a/apps/server/src/persistence/Migrations/009_ProviderSessionRuntimeMode.ts b/apps/server/src/persistence/Migrations/009_ProviderSessionRuntimeMode.ts new file mode 100644 index 0000000000..3f7249e873 --- /dev/null +++ b/apps/server/src/persistence/Migrations/009_ProviderSessionRuntimeMode.ts @@ -0,0 +1,6 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + yield* SqlClient.SqlClient; +}); diff --git a/apps/server/src/persistence/Migrations/010_ProjectionThreadsRuntimeMode.ts b/apps/server/src/persistence/Migrations/010_ProjectionThreadsRuntimeMode.ts new file mode 100644 index 0000000000..93d1f0a8ec --- /dev/null +++ b/apps/server/src/persistence/Migrations/010_ProjectionThreadsRuntimeMode.ts @@ -0,0 +1,17 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access' + `; + + yield* sql` + UPDATE projection_threads + SET runtime_mode = 'full-access' + WHERE runtime_mode IS NULL + `; +}); diff --git a/apps/server/src/persistence/Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts b/apps/server/src/persistence/Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts new file mode 100644 index 0000000000..a1021a4da9 --- /dev/null +++ b/apps/server/src/persistence/Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts @@ -0,0 +1,13 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + UPDATE orchestration_events + SET payload_json = json_set(payload_json, '$.runtimeMode', 'full-access') + WHERE event_type = 'thread.created' + AND json_type(payload_json, '$.runtimeMode') IS NULL + `; +}); diff --git a/apps/server/src/persistence/Migrations/012_ProjectionThreadsInteractionMode.ts b/apps/server/src/persistence/Migrations/012_ProjectionThreadsInteractionMode.ts new file mode 100644 index 0000000000..60695ac6cc --- /dev/null +++ b/apps/server/src/persistence/Migrations/012_ProjectionThreadsInteractionMode.ts @@ -0,0 +1,11 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN interaction_mode TEXT NOT NULL DEFAULT 'default' + `; +}); diff --git a/apps/server/src/persistence/Migrations/013_ProjectionThreadProposedPlans.ts b/apps/server/src/persistence/Migrations/013_ProjectionThreadProposedPlans.ts new file mode 100644 index 0000000000..2af642c838 --- /dev/null +++ b/apps/server/src/persistence/Migrations/013_ProjectionThreadProposedPlans.ts @@ -0,0 +1,22 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE IF NOT EXISTS projection_thread_proposed_plans ( + plan_id TEXT PRIMARY KEY, + thread_id TEXT NOT NULL, + turn_id TEXT, + plan_markdown TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_thread_proposed_plans_thread_created + ON projection_thread_proposed_plans(thread_id, created_at) + `; +}); diff --git a/apps/server/src/persistence/Migrations/014_ProjectionThreadProposedPlanImplementation.ts b/apps/server/src/persistence/Migrations/014_ProjectionThreadProposedPlanImplementation.ts new file mode 100644 index 0000000000..c7a82bfb33 --- /dev/null +++ b/apps/server/src/persistence/Migrations/014_ProjectionThreadProposedPlanImplementation.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_thread_proposed_plans + ADD COLUMN implemented_at TEXT + `; + + yield* sql` + ALTER TABLE projection_thread_proposed_plans + ADD COLUMN implementation_thread_id TEXT + `; +}); diff --git a/apps/server/src/persistence/Migrations/015_ProjectionTurnsSourceProposedPlan.ts b/apps/server/src/persistence/Migrations/015_ProjectionTurnsSourceProposedPlan.ts new file mode 100644 index 0000000000..57a2661879 --- /dev/null +++ b/apps/server/src/persistence/Migrations/015_ProjectionTurnsSourceProposedPlan.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_turns + ADD COLUMN source_proposed_plan_thread_id TEXT + `; + + yield* sql` + ALTER TABLE projection_turns + ADD COLUMN source_proposed_plan_id TEXT + `; +}); diff --git a/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts b/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts new file mode 100644 index 0000000000..d74e9fe08c --- /dev/null +++ b/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts @@ -0,0 +1,381 @@ +import { assert, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import * as NodeSqliteClient from "../NodeSqliteClient.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); + +layer("016_CanonicalizeModelSelections", (it) => { + it.effect( + "migrates legacy projection rows and event payloads to the canonical model-selection shape", + () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Setup base state + { + yield* runMigrations({ toMigrationInclusive: 15 }); + + yield* sql` + INSERT INTO projection_projects ( + project_id, + title, + workspace_root, + default_model, + scripts_json, + created_at, + updated_at, + deleted_at + ) + VALUES + ('project-codex', 'Codex project', '/tmp/project-codex', 'gpt-5.4', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL), + ('project-claude', 'Claude project', '/tmp/project-claude', 'claude-sonnet-4-6', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL), + ('project-null', 'Null project', '/tmp/project-null', NULL, '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL) + `; + yield* sql` + UPDATE projection_projects + SET default_model = 'claude-opus-4-6' + WHERE project_id = 'project-claude' + `; + yield* sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model, + branch, + worktree_path, + latest_turn_id, + created_at, + updated_at, + deleted_at, + runtime_mode, + interaction_mode + ) + VALUES + ('thread-session', 'project-codex', 'Session thread', 'gpt-5.4', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'), + ('thread-claude', 'project-claude', 'Claude thread', 'claude-opus-4-6', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'), + ('thread-codex', 'project-codex', 'Codex thread', 'gpt-5.4', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'), + ('thread-legacy-options', 'project-claude', 'Legacy options thread', 'claude-opus-4-6', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default') + `; + yield* sql` + INSERT INTO projection_thread_sessions ( + thread_id, + status, + provider_name, + provider_session_id, + provider_thread_id, + active_turn_id, + last_error, + updated_at, + runtime_mode + ) + VALUES ( + 'thread-session', + 'running', + 'claudeAgent', + 'provider-session-1', + 'provider-thread-1', + NULL, + NULL, + '2026-01-01T00:00:00.000Z', + 'full-access' + ) + `; + yield* sql` + INSERT INTO orchestration_events ( + event_id, + aggregate_kind, + stream_id, + stream_version, + event_type, + occurred_at, + command_id, + causation_event_id, + correlation_id, + actor_kind, + payload_json, + metadata_json + ) + VALUES + ( + 'event-project-created', + 'project', + 'project-1', + 1, + 'project.created', + '2026-01-01T00:00:00.000Z', + 'command-project-created', + NULL, + 'correlation-project-created', + 'user', + '{"projectId":"project-1","title":"Project","workspaceRoot":"/tmp/project","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"high"},"claudeAgent":{"effort":"max"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-project-created-fallback', + 'project', + 'project-2', + 1, + 'project.created', + '2026-01-01T00:00:00.000Z', + 'command-project-created-fallback', + NULL, + 'correlation-project-created-fallback', + 'user', + '{"projectId":"project-2","title":"Fallback Project","workspaceRoot":"/tmp/project-2","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"low"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-project-created-null-model', + 'project', + 'project-3', + 1, + 'project.created', + '2026-01-01T00:00:00.000Z', + 'command-project-created-null-model', + NULL, + 'correlation-project-created-null-model', + 'user', + '{"projectId":"project-3","title":"Null Model Project","workspaceRoot":"/tmp/project-3","defaultModel":null,"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-thread-created', + 'thread', + 'thread-1', + 1, + 'thread.created', + '2026-01-01T00:00:00.000Z', + 'command-thread-created', + NULL, + 'correlation-thread-created', + 'user', + '{"threadId":"thread-1","projectId":"project-1","title":"Thread","model":"claude-opus-4-6","modelOptions":{"codex":{"reasoningEffort":"high"},"claudeAgent":{"effort":"max","thinking":false}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-thread-created-fallback', + 'thread', + 'thread-2', + 1, + 'thread.created', + '2026-01-01T00:00:00.000Z', + 'command-thread-created-fallback', + NULL, + 'correlation-thread-created-fallback', + 'user', + '{"threadId":"thread-2","projectId":"project-1","title":"Fallback Thread","model":"gpt-5.4","modelOptions":{"claudeAgent":{"effort":"max"}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-turn-start-requested', + 'thread', + 'thread-1', + 2, + 'thread.turn-start-requested', + '2026-01-01T00:00:00.000Z', + 'command-turn-start-requested', + NULL, + 'correlation-turn-start-requested', + 'user', + '{"threadId":"thread-1","turnId":"turn-1","input":"hi","model":"gpt-5.4","modelOptions":{"codex":{"fastMode":true},"claudeAgent":{"effort":"max"}},"deliveryMode":"buffered"}', + '{}' + ), + ( + 'event-thread-created-no-model', + 'thread', + 'thread-3', + 1, + 'thread.created', + '2026-01-01T00:00:00.000Z', + 'command-thread-created-no-model', + NULL, + 'correlation-thread-created-no-model', + 'user', + '{"threadId":"thread-3","projectId":"project-1","title":"Ancient Thread","runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ) + `; + } + + // Execute migration under test + yield* runMigrations({ toMigrationInclusive: 16 }); + + // Assert expected state + { + const projectRows = yield* sql<{ + readonly projectId: string; + readonly defaultModelSelection: string | null; + }>` + SELECT + project_id AS "projectId", + default_model_selection_json AS "defaultModelSelection" + FROM projection_projects + ORDER BY project_id + `; + assert.deepStrictEqual(projectRows, [ + { + projectId: "project-claude", + defaultModelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}', + }, + { + projectId: "project-codex", + defaultModelSelection: '{"provider":"codex","model":"gpt-5.4"}', + }, + { projectId: "project-null", defaultModelSelection: null }, + ]); + + const threadRows = yield* sql<{ + readonly threadId: string; + readonly modelSelection: string | null; + }>` + SELECT + thread_id AS "threadId", + model_selection_json AS "modelSelection" + FROM projection_threads + ORDER BY thread_id + `; + assert.deepStrictEqual(threadRows, [ + { + threadId: "thread-claude", + modelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}', + }, + { + threadId: "thread-codex", + modelSelection: '{"provider":"codex","model":"gpt-5.4"}', + }, + { + threadId: "thread-legacy-options", + modelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}', + }, + { + threadId: "thread-session", + modelSelection: '{"provider":"claudeAgent","model":"gpt-5.4"}', + }, + ]); + + const eventRows = yield* sql<{ + readonly payloadJson: string; + }>` + SELECT payload_json AS "payloadJson" + FROM orchestration_events + ORDER BY rowid ASC + `; + + assert.deepStrictEqual(JSON.parse(eventRows[0]!.payloadJson), { + projectId: "project-1", + title: "Project", + workspaceRoot: "/tmp/project", + defaultModelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + effort: "max", + }, + }, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + + assert.deepStrictEqual(JSON.parse(eventRows[1]!.payloadJson), { + projectId: "project-2", + title: "Fallback Project", + workspaceRoot: "/tmp/project-2", + defaultModelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + reasoningEffort: "low", + }, + }, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + + assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), { + projectId: "project-3", + title: "Null Model Project", + workspaceRoot: "/tmp/project-3", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + + assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), { + threadId: "thread-1", + projectId: "project-1", + title: "Thread", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + effort: "max", + thinking: false, + }, + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + + assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), { + threadId: "thread-2", + projectId: "project-1", + title: "Fallback Thread", + modelSelection: { + provider: "codex", + model: "gpt-5.4", + options: { + effort: "max", + }, + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + + assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), { + threadId: "thread-1", + turnId: "turn-1", + input: "hi", + modelSelection: { + provider: "codex", + model: "gpt-5.4", + options: { + fastMode: true, + }, + }, + deliveryMode: "buffered", + }); + + assert.deepStrictEqual(JSON.parse(eventRows[6]!.payloadJson), { + threadId: "thread-3", + projectId: "project-1", + title: "Ancient Thread", + modelSelection: { + provider: "codex", + model: "gpt-5.4", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + } + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.ts b/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.ts new file mode 100644 index 0000000000..68d7baf83f --- /dev/null +++ b/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.ts @@ -0,0 +1,235 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE projection_projects + ADD COLUMN default_model_selection_json TEXT + `; + + yield* sql` + UPDATE projection_projects + SET default_model_selection_json = CASE + WHEN default_model IS NULL THEN NULL + ELSE json_object( + 'provider', + CASE + WHEN lower(default_model) LIKE '%claude%' THEN 'claudeAgent' + ELSE 'codex' + END, + 'model', + default_model + ) + END + WHERE default_model_selection_json IS NULL + `; + + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN model_selection_json TEXT + `; + + yield* sql` + UPDATE projection_threads + SET model_selection_json = json_object( + 'provider', + COALESCE( + ( + SELECT provider_name + FROM projection_thread_sessions + WHERE projection_thread_sessions.thread_id = projection_threads.thread_id + ), + CASE + WHEN lower(model) LIKE '%claude%' THEN 'claudeAgent' + ELSE 'codex' + END, + 'codex' + ), + 'model', + model + ) + WHERE model_selection_json IS NULL + `; + + yield* sql` + ALTER TABLE projection_projects + DROP COLUMN default_model + `; + + yield* sql` + ALTER TABLE projection_threads + DROP COLUMN model + `; + + yield* sql` + UPDATE orchestration_events + SET payload_json = CASE + WHEN json_type(payload_json, '$.defaultModel') = 'null' THEN json_remove( + json_set(payload_json, '$.defaultModelSelection', json('null')), + '$.defaultProvider', + '$.defaultModel', + '$.defaultModelOptions' + ) + ELSE json_remove( + json_set( + payload_json, + '$.defaultModelSelection', + json_patch( + json_object( + 'provider', + CASE + WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL + THEN json_extract(payload_json, '$.defaultProvider') + WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%' + THEN 'claudeAgent' + ELSE 'codex' + END, + 'model', + json_extract(payload_json, '$.defaultModel') + ), + CASE + WHEN json_type(payload_json, '$.defaultModelOptions') IS NULL THEN '{}' + WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL + OR json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL + THEN CASE + WHEN ( + CASE + WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL + THEN json_extract(payload_json, '$.defaultProvider') + WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%' + THEN 'claudeAgent' + ELSE 'codex' + END + ) = 'claudeAgent' + THEN CASE + WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL + THEN json_object( + 'options', + json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent')) + ) + WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL + THEN json_object( + 'options', + json(json_extract(payload_json, '$.defaultModelOptions.codex')) + ) + ELSE '{}' + END + ELSE CASE + WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL + THEN json_object( + 'options', + json(json_extract(payload_json, '$.defaultModelOptions.codex')) + ) + WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL + THEN json_object( + 'options', + json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent')) + ) + ELSE '{}' + END + END + ELSE json_object( + 'options', + json(json_extract(payload_json, '$.defaultModelOptions')) + ) + END + ) + ), + '$.defaultProvider', + '$.defaultModel', + '$.defaultModelOptions' + ) + END + WHERE event_type IN ('project.created', 'project.meta-updated') + AND json_type(payload_json, '$.defaultModelSelection') IS NULL + AND json_type(payload_json, '$.defaultModel') IS NOT NULL + `; + + yield* sql` + UPDATE orchestration_events + SET payload_json = json_remove( + json_set( + payload_json, + '$.modelSelection', + json_patch( + json_object( + 'provider', + CASE + WHEN json_extract(payload_json, '$.provider') IS NOT NULL + THEN json_extract(payload_json, '$.provider') + WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%' + THEN 'claudeAgent' + ELSE 'codex' + END, + 'model', + json_extract(payload_json, '$.model') + ), + CASE + WHEN json_type(payload_json, '$.modelOptions') IS NULL THEN '{}' + WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL + OR json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL + THEN CASE + WHEN ( + CASE + WHEN json_extract(payload_json, '$.provider') IS NOT NULL + THEN json_extract(payload_json, '$.provider') + WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%' + THEN 'claudeAgent' + ELSE 'codex' + END + ) = 'claudeAgent' + THEN CASE + WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL + THEN json_object( + 'options', + json(json_extract(payload_json, '$.modelOptions.claudeAgent')) + ) + WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL + THEN json_object( + 'options', + json(json_extract(payload_json, '$.modelOptions.codex')) + ) + ELSE '{}' + END + ELSE CASE + WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL + THEN json_object( + 'options', + json(json_extract(payload_json, '$.modelOptions.codex')) + ) + WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL + THEN json_object( + 'options', + json(json_extract(payload_json, '$.modelOptions.claudeAgent')) + ) + ELSE '{}' + END + END + ELSE json_object('options', json(json_extract(payload_json, '$.modelOptions'))) + END + ) + ), + '$.provider', + '$.model', + '$.modelOptions' + ) + WHERE event_type IN ('thread.created', 'thread.meta-updated', 'thread.turn-start-requested') + AND json_type(payload_json, '$.modelSelection') IS NULL + AND json_type(payload_json, '$.model') IS NOT NULL + `; + + // Backfill thread.created events that predate the model field entirely + yield* sql` + UPDATE orchestration_events + SET payload_json = json_set( + payload_json, + '$.modelSelection', + json(json_object('provider', 'codex', 'model', 'gpt-5.4')) + ) + WHERE event_type = 'thread.created' + AND json_type(payload_json, '$.modelSelection') IS NULL + AND json_type(payload_json, '$.model') IS NULL + `; +}); diff --git a/apps/server/src/persistence/Migrations/017_ProjectionThreadsArchivedAt.ts b/apps/server/src/persistence/Migrations/017_ProjectionThreadsArchivedAt.ts new file mode 100644 index 0000000000..35d05f189b --- /dev/null +++ b/apps/server/src/persistence/Migrations/017_ProjectionThreadsArchivedAt.ts @@ -0,0 +1,18 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const columns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(projection_threads) + `; + + if (columns.some((column) => column.name === "archived_at")) { + return; + } + + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN archived_at TEXT + `; +}); diff --git a/apps/server/src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.ts b/apps/server/src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.ts new file mode 100644 index 0000000000..b12ab1bcfb --- /dev/null +++ b/apps/server/src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.ts @@ -0,0 +1,11 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_threads_project_archived_at + ON projection_threads(project_id, archived_at) + `; +}); diff --git a/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts b/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts new file mode 100644 index 0000000000..6207a9bcb6 --- /dev/null +++ b/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts @@ -0,0 +1,73 @@ +import { assert, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import * as NodeSqliteClient from "../NodeSqliteClient.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); + +layer("019_ProjectionSnapshotLookupIndexes", (it) => { + it.effect("creates indexes for targeted projection lookup filters", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* runMigrations({ toMigrationInclusive: 18 }); + yield* runMigrations({ toMigrationInclusive: 19 }); + + const projectIndexes = yield* sql<{ + readonly seq: number; + readonly name: string; + readonly unique: number; + readonly origin: string; + readonly partial: number; + }>` + PRAGMA index_list(projection_projects) + `; + assert.ok( + projectIndexes.some( + (index) => index.name === "idx_projection_projects_workspace_root_deleted_at", + ), + ); + + const projectIndexColumns = yield* sql<{ + readonly seqno: number; + readonly cid: number; + readonly name: string; + }>` + PRAGMA index_info('idx_projection_projects_workspace_root_deleted_at') + `; + assert.deepStrictEqual( + projectIndexColumns.map((column) => column.name), + ["workspace_root", "deleted_at"], + ); + + const threadIndexes = yield* sql<{ + readonly seq: number; + readonly name: string; + readonly unique: number; + readonly origin: string; + readonly partial: number; + }>` + PRAGMA index_list(projection_threads) + `; + assert.ok( + threadIndexes.some( + (index) => index.name === "idx_projection_threads_project_deleted_created", + ), + ); + + const threadIndexColumns = yield* sql<{ + readonly seqno: number; + readonly cid: number; + readonly name: string; + }>` + PRAGMA index_info('idx_projection_threads_project_deleted_created') + `; + assert.deepStrictEqual( + threadIndexColumns.map((column) => column.name), + ["project_id", "deleted_at", "created_at"], + ); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.ts b/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.ts new file mode 100644 index 0000000000..bf74a5147d --- /dev/null +++ b/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_projects_workspace_root_deleted_at + ON projection_projects(workspace_root, deleted_at) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_threads_project_deleted_created + ON projection_threads(project_id, deleted_at, created_at) + `; +}); diff --git a/apps/server/src/persistence/NodeSqliteClient.test.ts b/apps/server/src/persistence/NodeSqliteClient.test.ts new file mode 100644 index 0000000000..a055d409ba --- /dev/null +++ b/apps/server/src/persistence/NodeSqliteClient.test.ts @@ -0,0 +1,30 @@ +import { assert, it } from "@effect/vitest"; +import { Effect } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import * as SqliteClient from "./NodeSqliteClient.ts"; + +const layer = it.layer(SqliteClient.layerMemory()); + +layer("NodeSqliteClient", (it) => { + it.effect("runs prepared queries and returns positional values", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`; + yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`; + + const rows = yield* sql<{ readonly id: number; readonly name: string }>` + SELECT id, name FROM entries ORDER BY id + `; + assert.equal(rows.length, 2); + assert.equal(rows[0]?.name, "alpha"); + assert.equal(rows[1]?.name, "beta"); + + const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values; + assert.equal(values.length, 2); + assert.equal(values[0]?.[1], "alpha"); + assert.equal(values[1]?.[1], "beta"); + }), + ); +}); diff --git a/apps/server/src/persistence/NodeSqliteClient.ts b/apps/server/src/persistence/NodeSqliteClient.ts new file mode 100644 index 0000000000..77c316e8ca --- /dev/null +++ b/apps/server/src/persistence/NodeSqliteClient.ts @@ -0,0 +1,277 @@ +/** + * Port of `@effect/sql-sqlite-node` that uses the native `node:sqlite` + * bindings instead of `better-sqlite3`. + * + * @module SqliteClient + */ +import { DatabaseSync, type StatementSync } from "node:sqlite"; + +import * as Cache from "effect/Cache"; +import * as Config from "effect/Config"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import { identity } from "effect/Function"; +import * as Layer from "effect/Layer"; +import * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; +import * as ServiceMap from "effect/ServiceMap"; +import * as Stream from "effect/Stream"; +import * as Reactivity from "effect/unstable/reactivity/Reactivity"; +import * as Client from "effect/unstable/sql/SqlClient"; +import type { Connection } from "effect/unstable/sql/SqlConnection"; +import { SqlError, classifySqliteError } from "effect/unstable/sql/SqlError"; +import * as Statement from "effect/unstable/sql/Statement"; + +const ATTR_DB_SYSTEM_NAME = "db.system.name"; + +export const TypeId: TypeId = "~local/sqlite-node/SqliteClient"; + +export type TypeId = "~local/sqlite-node/SqliteClient"; + +/** + * SqliteClient - Effect service tag for the sqlite SQL client. + */ +export const SqliteClient = ServiceMap.Service("t3/persistence/NodeSqliteClient"); + +export interface SqliteClientConfig { + readonly filename: string; + readonly readonly?: boolean | undefined; + readonly allowExtension?: boolean | undefined; + readonly prepareCacheSize?: number | undefined; + readonly prepareCacheTTL?: Duration.Input | undefined; + readonly spanAttributes?: Record | undefined; + readonly transformResultNames?: ((str: string) => string) | undefined; + readonly transformQueryNames?: ((str: string) => string) | undefined; +} + +export interface SqliteMemoryClientConfig extends Omit< + SqliteClientConfig, + "filename" | "readonly" +> {} + +/** + * Verify that the current Node.js version includes the `node:sqlite` APIs + * used by `NodeSqliteClient` — specifically `StatementSync.columns()` (added + * in Node 22.16.0 / 23.11.0). + * + * @see https://github.com/nodejs/node/pull/57490 + */ +const checkNodeSqliteCompat = () => { + const parts = process.versions.node.split(".").map(Number); + const major = parts[0] ?? 0; + const minor = parts[1] ?? 0; + const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24; + + if (!supported) { + return Effect.die( + `Node.js ${process.versions.node} is missing required node:sqlite APIs ` + + `(StatementSync.columns). Upgrade to Node.js >=22.16, >=23.11, or >=24.`, + ); + } + return Effect.void; +}; + +const makeWithDatabase = Effect.fn("makeWithDatabase")(function* ( + options: SqliteClientConfig, + openDatabase: () => DatabaseSync, +): Effect.fn.Return { + yield* checkNodeSqliteCompat(); + + const compiler = Statement.makeCompilerSqlite(options.transformQueryNames); + const transformRows = options.transformResultNames + ? Statement.defaultTransforms(options.transformResultNames).array + : undefined; + + const makeConnection = Effect.gen(function* () { + const scope = yield* Effect.scope; + const db = openDatabase(); + yield* Scope.addFinalizer( + scope, + Effect.sync(() => db.close()), + ); + + const statementReaderCache = new WeakMap(); + const hasRows = (statement: StatementSync): boolean => { + const cached = statementReaderCache.get(statement); + if (cached !== undefined) { + return cached; + } + const value = statement.columns().length > 0; + statementReaderCache.set(statement, value); + return value; + }; + + const prepareCache = yield* Cache.make({ + capacity: options.prepareCacheSize ?? 200, + timeToLive: options.prepareCacheTTL ?? Duration.minutes(10), + lookup: (sql: string) => + Effect.try({ + try: () => db.prepare(sql), + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to prepare statement", + operation: "prepare", + }), + }), + }), + }); + + const runStatement = (statement: StatementSync, params: ReadonlyArray, raw: boolean) => + Effect.withFiber, SqlError>((fiber) => { + statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers))); + try { + if (hasRows(statement)) { + return Effect.succeed(statement.all(...(params as any))); + } + const result = statement.run(...(params as any)); + return Effect.succeed(raw ? (result as unknown as ReadonlyArray) : []); + } catch (cause) { + return Effect.fail( + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to execute statement", + operation: "execute", + }), + }), + ); + } + }); + + const run = (sql: string, params: ReadonlyArray, raw = false) => + Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw)); + + const runValues = (sql: string, params: ReadonlyArray) => + Effect.acquireUseRelease( + Cache.get(prepareCache, sql), + (statement) => + Effect.try({ + try: () => { + if (hasRows(statement)) { + statement.setReturnArrays(true); + // Safe to cast to array after we've setReturnArrays(true) + return statement.all(...(params as any)) as unknown as ReadonlyArray< + ReadonlyArray + >; + } + statement.run(...(params as any)); + return []; + }, + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to execute statement", + operation: "execute", + }), + }), + }), + (statement) => + Effect.sync(() => { + if (hasRows(statement)) { + statement.setReturnArrays(false); + } + }), + ); + + return identity({ + execute(sql, params, rowTransform) { + return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params); + }, + executeRaw(sql, params) { + return run(sql, params, true); + }, + executeValues(sql, params) { + return runValues(sql, params); + }, + executeUnprepared(sql, params, rowTransform) { + const effect = runStatement(db.prepare(sql), params ?? [], false); + return rowTransform ? Effect.map(effect, rowTransform) : effect; + }, + executeStream(_sql, _params) { + return Stream.die("executeStream not implemented"); + }, + }); + }); + + const semaphore = yield* Semaphore.make(1); + const connection = yield* makeConnection; + + const acquirer = semaphore.withPermits(1)(Effect.succeed(connection)); + const transactionAcquirer = Effect.uninterruptibleMask((restore) => { + const fiber = Fiber.getCurrent()!; + const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope); + return Effect.as( + Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))), + connection, + ); + }); + + return yield* Client.make({ + acquirer, + compiler, + transactionAcquirer, + spanAttributes: [ + ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), + [ATTR_DB_SYSTEM_NAME, "sqlite"], + ], + transformRows, + }); +}); + +const make = ( + options: SqliteClientConfig, +): Effect.Effect => + makeWithDatabase( + options, + () => + new DatabaseSync(options.filename, { + readOnly: options.readonly ?? false, + allowExtension: options.allowExtension ?? false, + }), + ); + +const makeMemory = ( + config: SqliteMemoryClientConfig = {}, +): Effect.Effect => + makeWithDatabase( + { + ...config, + filename: ":memory:", + readonly: false, + }, + () => { + const database = new DatabaseSync(":memory:", { + allowExtension: config.allowExtension ?? false, + }); + return database; + }, + ); + +export const layerConfig = ( + config: Config.Wrap, +): Layer.Layer => + Layer.effectServices( + Config.unwrap(config) + .asEffect() + .pipe( + Effect.flatMap(make), + Effect.map((client) => + ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)), + ), + ), + ).pipe(Layer.provide(Reactivity.layer)); + +export const layer = (config: SqliteClientConfig): Layer.Layer => + Layer.effectServices( + Effect.map(make(config), (client) => + ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)), + ), + ).pipe(Layer.provide(Reactivity.layer)); + +export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer => + Layer.effectServices( + Effect.map(makeMemory(config), (client) => + ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)), + ), + ).pipe(Layer.provide(Reactivity.layer)); diff --git a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts new file mode 100644 index 0000000000..0b8f8e9b52 --- /dev/null +++ b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts @@ -0,0 +1,69 @@ +/** + * OrchestrationCommandReceiptRepository - Repository interface for command receipts. + * + * Owns persistence operations for deduplication and status tracking of + * orchestration command handling. + * + * @module OrchestrationCommandReceiptRepository + */ +import { + CommandId, + IsoDateTime, + NonNegativeInt, + OrchestrationAggregateKind, + OrchestrationCommandReceiptStatus, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { Option, Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { OrchestrationCommandReceiptRepositoryError } from "../Errors.ts"; + +export const OrchestrationCommandReceipt = Schema.Struct({ + commandId: CommandId, + aggregateKind: OrchestrationAggregateKind, + aggregateId: Schema.Union([ProjectId, ThreadId]), + acceptedAt: IsoDateTime, + resultSequence: NonNegativeInt, + status: OrchestrationCommandReceiptStatus, + error: Schema.NullOr(Schema.String), +}); +export type OrchestrationCommandReceipt = typeof OrchestrationCommandReceipt.Type; + +export const GetByCommandIdInput = Schema.Struct({ + commandId: CommandId, +}); +export type GetByCommandIdInput = typeof GetByCommandIdInput.Type; + +/** + * OrchestrationCommandReceiptRepositoryShape - Service API for command receipts. + */ +export interface OrchestrationCommandReceiptRepositoryShape { + /** + * Insert or replace a command receipt row. + * + * Upserts by `commandId` for idempotent command-result tracking. + */ + readonly upsert: ( + receipt: OrchestrationCommandReceipt, + ) => Effect.Effect; + + /** + * Read a command receipt by command id. + */ + readonly getByCommandId: ( + input: GetByCommandIdInput, + ) => Effect.Effect< + Option.Option, + OrchestrationCommandReceiptRepositoryError + >; +} + +/** + * OrchestrationCommandReceiptRepository - Service tag for command receipt persistence. + */ +export class OrchestrationCommandReceiptRepository extends ServiceMap.Service< + OrchestrationCommandReceiptRepository, + OrchestrationCommandReceiptRepositoryShape +>()("t3/persistence/Services/OrchestrationCommandReceipts/OrchestrationCommandReceiptRepository") {} diff --git a/apps/server/src/persistence/Services/OrchestrationEventStore.ts b/apps/server/src/persistence/Services/OrchestrationEventStore.ts new file mode 100644 index 0000000000..24febd8fde --- /dev/null +++ b/apps/server/src/persistence/Services/OrchestrationEventStore.ts @@ -0,0 +1,70 @@ +/** + * OrchestrationEventStore - Event store interface for orchestration events. + * + * Owns durable append/replay access to the orchestration event stream. It does + * not reduce events into read models or apply command validation rules. + * + * Uses Effect `ServiceMap.Service` for dependency injection and exposes typed + * persistence/decode errors for event append and replay operations. + * + * @module OrchestrationEventStore + */ +import { OrchestrationEvent } from "@t3tools/contracts"; +import { ServiceMap } from "effect"; +import type { Effect, Stream } from "effect"; + +import type { OrchestrationEventStoreError } from "../Errors.ts"; + +/** + * OrchestrationEventStoreShape - Service API for orchestration event persistence. + */ +export interface OrchestrationEventStoreShape { + /** + * Persist a new orchestration event. + * + * @param event - Event payload without sequence (assigned by storage). + * @returns Effect containing the stored event with assigned sequence. + * + * Actor kind is inferred from command/metadata before persistence. + */ + readonly append: ( + event: Omit, + ) => Effect.Effect; + + /** + * Replay events after the provided sequence. + * + * @param sequenceExclusive - Sequence cursor (exclusive). + * @param limit - Maximum number of events to emit. + * @returns Stream containing ordered events. + * + * Reads in fixed-size pages and normalizes non-integer/negative limits. + */ + readonly readFromSequence: ( + sequenceExclusive: number, + limit?: number, + ) => Stream.Stream; + + /** + * Read all events from the beginning of the stream. + * + * @returns Stream containing all stored events. + */ + readonly readAll: () => Stream.Stream; +} + +/** + * OrchestrationEventStore - Service tag for orchestration event persistence. + * + * @example + * ```ts + * const program = Effect.gen(function* () { + * const events = yield* OrchestrationEventStore + * return yield* Stream.runCollect(events.readAll()) + * }) + * ``` + */ +export class OrchestrationEventStore extends ServiceMap.Service< + OrchestrationEventStore, + OrchestrationEventStoreShape +>()("t3/persistence/Services/OrchestrationEventStore") {} diff --git a/apps/server/src/persistence/Services/ProjectionCheckpoints.ts b/apps/server/src/persistence/Services/ProjectionCheckpoints.ts new file mode 100644 index 0000000000..191d0af968 --- /dev/null +++ b/apps/server/src/persistence/Services/ProjectionCheckpoints.ts @@ -0,0 +1,93 @@ +/** + * ProjectionCheckpointRepository - Projection repository interface for checkpoints. + * + * Owns persistence operations for projected checkpoint summaries in thread + * timelines. + * + * @module ProjectionCheckpointRepository + */ +import { + CheckpointRef, + IsoDateTime, + MessageId, + NonNegativeInt, + OrchestrationCheckpointFile, + OrchestrationCheckpointStatus, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { Option, ServiceMap, Schema } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../Errors.ts"; + +export const ProjectionCheckpoint = Schema.Struct({ + threadId: ThreadId, + turnId: TurnId, + checkpointTurnCount: NonNegativeInt, + checkpointRef: CheckpointRef, + status: OrchestrationCheckpointStatus, + files: Schema.Array(OrchestrationCheckpointFile), + assistantMessageId: Schema.NullOr(MessageId), + completedAt: IsoDateTime, +}); +export type ProjectionCheckpoint = typeof ProjectionCheckpoint.Type; + +export const ListByThreadIdInput = Schema.Struct({ + threadId: ThreadId, +}); +export type ListByThreadIdInput = typeof ListByThreadIdInput.Type; + +export const GetByThreadAndTurnCountInput = Schema.Struct({ + threadId: ThreadId, + checkpointTurnCount: NonNegativeInt, +}); +export type GetByThreadAndTurnCountInput = typeof GetByThreadAndTurnCountInput.Type; + +export const DeleteByThreadIdInput = Schema.Struct({ + threadId: ThreadId, +}); +export type DeleteByThreadIdInput = typeof DeleteByThreadIdInput.Type; + +/** + * ProjectionCheckpointRepositoryShape - Service API for projected checkpoints. + */ +export interface ProjectionCheckpointRepositoryShape { + /** + * Insert or replace a projected checkpoint row. + * + * Upserts by composite key `(threadId, checkpointTurnCount)`. + */ + readonly upsert: (row: ProjectionCheckpoint) => Effect.Effect; + + /** + * List projected checkpoints for a thread. + * + * Returned in ascending checkpoint turn-count order. + */ + readonly listByThreadId: ( + input: ListByThreadIdInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Read a projected checkpoint by thread and turn-count key. + */ + readonly getByThreadAndTurnCount: ( + input: GetByThreadAndTurnCountInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Delete projected checkpoint rows by thread. + */ + readonly deleteByThreadId: ( + input: DeleteByThreadIdInput, + ) => Effect.Effect; +} + +/** + * ProjectionCheckpointRepository - Service tag for checkpoint projection persistence. + */ +export class ProjectionCheckpointRepository extends ServiceMap.Service< + ProjectionCheckpointRepository, + ProjectionCheckpointRepositoryShape +>()("t3/persistence/Services/ProjectionCheckpoints/ProjectionCheckpointRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts b/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts new file mode 100644 index 0000000000..8f4ec5eb4b --- /dev/null +++ b/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts @@ -0,0 +1,91 @@ +/** + * ProjectionPendingApprovalRepository - Repository interface for pending approvals. + * + * Owns persistence operations for projected approval requests awaiting user + * decisions. + * + * @module ProjectionPendingApprovalRepository + */ +import { + ApprovalRequestId, + IsoDateTime, + ProjectionPendingApprovalDecision, + ProjectionPendingApprovalStatus, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { Option, Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../Errors.ts"; + +export const ProjectionPendingApproval = Schema.Struct({ + requestId: ApprovalRequestId, + threadId: ThreadId, + turnId: Schema.NullOr(TurnId), + status: ProjectionPendingApprovalStatus, + decision: ProjectionPendingApprovalDecision, + createdAt: IsoDateTime, + resolvedAt: Schema.NullOr(IsoDateTime), +}); +export type ProjectionPendingApproval = typeof ProjectionPendingApproval.Type; + +export const ListProjectionPendingApprovalsInput = Schema.Struct({ + threadId: ThreadId, +}); +export type ListProjectionPendingApprovalsInput = typeof ListProjectionPendingApprovalsInput.Type; + +export const GetProjectionPendingApprovalInput = Schema.Struct({ + requestId: ApprovalRequestId, +}); +export type GetProjectionPendingApprovalInput = typeof GetProjectionPendingApprovalInput.Type; + +export const DeleteProjectionPendingApprovalInput = Schema.Struct({ + requestId: ApprovalRequestId, +}); +export type DeleteProjectionPendingApprovalInput = typeof DeleteProjectionPendingApprovalInput.Type; + +/** + * ProjectionPendingApprovalRepositoryShape - Service API for pending approvals. + */ +export interface ProjectionPendingApprovalRepositoryShape { + /** + * Insert or replace a projected pending approval row. + * + * Upserts by `requestId`. + */ + readonly upsert: ( + row: ProjectionPendingApproval, + ) => Effect.Effect; + + /** + * List pending approvals for a thread. + * + * Returned in ascending creation order. + */ + readonly listByThreadId: ( + input: ListProjectionPendingApprovalsInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Read a pending approval row by request id. + */ + readonly getByRequestId: ( + input: GetProjectionPendingApprovalInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Delete a pending approval row by request id. + */ + readonly deleteByRequestId: ( + input: DeleteProjectionPendingApprovalInput, + ) => Effect.Effect; +} + +/** + * ProjectionPendingApprovalRepository - Service tag for pending approval persistence. + */ +export class ProjectionPendingApprovalRepository extends ServiceMap.Service< + ProjectionPendingApprovalRepository, + ProjectionPendingApprovalRepositoryShape +>()("t3/persistence/Services/ProjectionPendingApprovals/ProjectionPendingApprovalRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionProjects.ts b/apps/server/src/persistence/Services/ProjectionProjects.ts new file mode 100644 index 0000000000..996ffe6e7b --- /dev/null +++ b/apps/server/src/persistence/Services/ProjectionProjects.ts @@ -0,0 +1,79 @@ +/** + * ProjectionProjectRepository - Projection repository interface for projects. + * + * Owns persistence operations for project rows in the orchestration projection + * read model. + * + * @module ProjectionProjectRepository + */ +import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts"; +import { Option, Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../Errors.ts"; + +export const ProjectionProject = Schema.Struct({ + projectId: ProjectId, + title: Schema.String, + workspaceRoot: Schema.String, + defaultModelSelection: Schema.NullOr(ModelSelection), + scripts: Schema.Array(ProjectScript), + createdAt: IsoDateTime, + updatedAt: IsoDateTime, + deletedAt: Schema.NullOr(IsoDateTime), +}); +export type ProjectionProject = typeof ProjectionProject.Type; + +export const GetProjectionProjectInput = Schema.Struct({ + projectId: ProjectId, +}); +export type GetProjectionProjectInput = typeof GetProjectionProjectInput.Type; + +export const DeleteProjectionProjectInput = Schema.Struct({ + projectId: ProjectId, +}); +export type DeleteProjectionProjectInput = typeof DeleteProjectionProjectInput.Type; + +/** + * ProjectionProjectRepositoryShape - Service API for projected project records. + */ +export interface ProjectionProjectRepositoryShape { + /** + * Insert or replace a projected project row. + * + * Upserts by `projectId` and persists scripts through JSON encoding. + */ + readonly upsert: (row: ProjectionProject) => Effect.Effect; + + /** + * Read a projected project row by id. + */ + readonly getById: ( + input: GetProjectionProjectInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * List all projected project rows. + * + * Returned in deterministic creation order. + */ + readonly listAll: () => Effect.Effect< + ReadonlyArray, + ProjectionRepositoryError + >; + + /** + * Soft-delete a projected project row by id. + */ + readonly deleteById: ( + input: DeleteProjectionProjectInput, + ) => Effect.Effect; +} + +/** + * ProjectionProjectRepository - Service tag for project projection persistence. + */ +export class ProjectionProjectRepository extends ServiceMap.Service< + ProjectionProjectRepository, + ProjectionProjectRepositoryShape +>()("t3/persistence/Services/ProjectionProjects/ProjectionProjectRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionState.ts b/apps/server/src/persistence/Services/ProjectionState.ts new file mode 100644 index 0000000000..e8ef9ceeb0 --- /dev/null +++ b/apps/server/src/persistence/Services/ProjectionState.ts @@ -0,0 +1,64 @@ +/** + * ProjectionStateRepository - Projection repository interface for projector cursors. + * + * Owns persistence operations for projection cursor state used to resume + * incremental event projection. + * + * @module ProjectionStateRepository + */ +import { IsoDateTime, NonNegativeInt } from "@t3tools/contracts"; +import { Option, Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../Errors.ts"; + +export const ProjectionState = Schema.Struct({ + projector: Schema.String, + lastAppliedSequence: NonNegativeInt, + updatedAt: IsoDateTime, +}); +export type ProjectionState = typeof ProjectionState.Type; + +export const GetProjectionStateInput = Schema.Struct({ + projector: Schema.String, +}); +export type GetProjectionStateInput = typeof GetProjectionStateInput.Type; + +/** + * ProjectionStateRepositoryShape - Service API for projector state records. + */ +export interface ProjectionStateRepositoryShape { + /** + * Insert or replace a projection cursor row. + * + * Upserts by projector name. + */ + readonly upsert: (row: ProjectionState) => Effect.Effect; + + /** + * Read projection cursor state for a projector key. + */ + readonly getByProjector: ( + input: GetProjectionStateInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * List all projector cursor rows. + */ + readonly listAll: () => Effect.Effect, ProjectionRepositoryError>; + + /** + * Read the minimum applied sequence across all projectors. + * + * Returns `null` when no projector state rows exist. + */ + readonly minLastAppliedSequence: () => Effect.Effect; +} + +/** + * ProjectionStateRepository - Service tag for projection cursor persistence. + */ +export class ProjectionStateRepository extends ServiceMap.Service< + ProjectionStateRepository, + ProjectionStateRepositoryShape +>()("t3/persistence/Services/ProjectionState/ProjectionStateRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionThreadActivities.ts b/apps/server/src/persistence/Services/ProjectionThreadActivities.ts new file mode 100644 index 0000000000..586ae3eb4a --- /dev/null +++ b/apps/server/src/persistence/Services/ProjectionThreadActivities.ts @@ -0,0 +1,83 @@ +/** + * ProjectionThreadActivityRepository - Projection repository interface for thread activity. + * + * Owns persistence operations for activity timeline entries projected from + * orchestration events. + * + * @module ProjectionThreadActivityRepository + */ +import { + EventId, + IsoDateTime, + NonNegativeInt, + OrchestrationThreadActivityTone, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../Errors.ts"; + +export const ProjectionThreadActivity = Schema.Struct({ + activityId: EventId, + threadId: ThreadId, + turnId: Schema.NullOr(TurnId), + tone: OrchestrationThreadActivityTone, + kind: Schema.String, + summary: Schema.String, + payload: Schema.Unknown, + sequence: Schema.optional(NonNegativeInt), + createdAt: IsoDateTime, +}); +export type ProjectionThreadActivity = typeof ProjectionThreadActivity.Type; + +export const ListProjectionThreadActivitiesInput = Schema.Struct({ + threadId: ThreadId, +}); +export type ListProjectionThreadActivitiesInput = typeof ListProjectionThreadActivitiesInput.Type; + +export const DeleteProjectionThreadActivitiesInput = Schema.Struct({ + threadId: ThreadId, +}); +export type DeleteProjectionThreadActivitiesInput = + typeof DeleteProjectionThreadActivitiesInput.Type; + +/** + * ProjectionThreadActivityRepositoryShape - Service API for projected thread activity. + */ +export interface ProjectionThreadActivityRepositoryShape { + /** + * Insert or replace a projected thread activity row. + * + * Upserts by `activityId` and JSON-encodes payload. + */ + readonly upsert: ( + row: ProjectionThreadActivity, + ) => Effect.Effect; + + /** + * List projected thread activity rows for a thread. + * + * Returned in ascending runtime sequence order (or creation order when + * sequence is unavailable). + */ + readonly listByThreadId: ( + input: ListProjectionThreadActivitiesInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Delete projected thread activity rows by thread. + */ + readonly deleteByThreadId: ( + input: DeleteProjectionThreadActivitiesInput, + ) => Effect.Effect; +} + +/** + * ProjectionThreadActivityRepository - Service tag for thread activity persistence. + */ +export class ProjectionThreadActivityRepository extends ServiceMap.Service< + ProjectionThreadActivityRepository, + ProjectionThreadActivityRepositoryShape +>()("t3/persistence/Services/ProjectionThreadActivities/ProjectionThreadActivityRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts new file mode 100644 index 0000000000..b1a769cd91 --- /dev/null +++ b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts @@ -0,0 +1,94 @@ +/** + * ProjectionThreadMessageRepository - Projection repository interface for messages. + * + * Owns persistence operations for projected thread messages rendered in the + * orchestration read model. + * + * @module ProjectionThreadMessageRepository + */ +import { + ChatAttachment, + MessageId, + OrchestrationMessageRole, + ThreadId, + TurnId, + IsoDateTime, +} from "@t3tools/contracts"; +import { Schema, ServiceMap } from "effect"; +import type { Option } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../Errors.ts"; + +export const ProjectionThreadMessage = Schema.Struct({ + messageId: MessageId, + threadId: ThreadId, + turnId: Schema.NullOr(TurnId), + role: OrchestrationMessageRole, + text: Schema.String, + attachments: Schema.optional(Schema.Array(ChatAttachment)), + isStreaming: Schema.Boolean, + createdAt: IsoDateTime, + updatedAt: IsoDateTime, +}); +export type ProjectionThreadMessage = typeof ProjectionThreadMessage.Type; + +export const ListProjectionThreadMessagesInput = Schema.Struct({ + threadId: ThreadId, +}); +export type ListProjectionThreadMessagesInput = typeof ListProjectionThreadMessagesInput.Type; + +export const GetProjectionThreadMessageInput = Schema.Struct({ + messageId: MessageId, +}); +export type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type; + +export const DeleteProjectionThreadMessagesInput = Schema.Struct({ + threadId: ThreadId, +}); +export type DeleteProjectionThreadMessagesInput = typeof DeleteProjectionThreadMessagesInput.Type; + +/** + * ProjectionThreadMessageRepositoryShape - Service API for projected thread messages. + */ +export interface ProjectionThreadMessageRepositoryShape { + /** + * Insert or replace a projected thread message row. + * + * Upserts by `messageId`. + */ + readonly upsert: ( + message: ProjectionThreadMessage, + ) => Effect.Effect; + + /** + * Read a projected thread message by id. + */ + readonly getByMessageId: ( + input: GetProjectionThreadMessageInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * List projected thread messages for a thread. + * + * Returned in ascending creation order. + */ + readonly listByThreadId: ( + input: ListProjectionThreadMessagesInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Delete projected thread messages by thread. + */ + readonly deleteByThreadId: ( + input: DeleteProjectionThreadMessagesInput, + ) => Effect.Effect; +} + +/** + * ProjectionThreadMessageRepository - Service tag for message projection persistence. + */ +export class ProjectionThreadMessageRepository extends ServiceMap.Service< + ProjectionThreadMessageRepository, + ProjectionThreadMessageRepositoryShape +>()("t3/persistence/Services/ProjectionThreadMessages/ProjectionThreadMessageRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts b/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts new file mode 100644 index 0000000000..d141a11bb9 --- /dev/null +++ b/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts @@ -0,0 +1,54 @@ +import { + IsoDateTime, + OrchestrationProposedPlanId, + ThreadId, + TrimmedNonEmptyString, + TurnId, +} from "@t3tools/contracts"; +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../Errors.ts"; + +export const ProjectionThreadProposedPlan = Schema.Struct({ + planId: OrchestrationProposedPlanId, + threadId: ThreadId, + turnId: Schema.NullOr(TurnId), + planMarkdown: TrimmedNonEmptyString, + implementedAt: Schema.NullOr(IsoDateTime), + implementationThreadId: Schema.NullOr(ThreadId), + createdAt: IsoDateTime, + updatedAt: IsoDateTime, +}); +export type ProjectionThreadProposedPlan = typeof ProjectionThreadProposedPlan.Type; + +export const ListProjectionThreadProposedPlansInput = Schema.Struct({ + threadId: ThreadId, +}); +export type ListProjectionThreadProposedPlansInput = + typeof ListProjectionThreadProposedPlansInput.Type; + +export const DeleteProjectionThreadProposedPlansInput = Schema.Struct({ + threadId: ThreadId, +}); +export type DeleteProjectionThreadProposedPlansInput = + typeof DeleteProjectionThreadProposedPlansInput.Type; + +export interface ProjectionThreadProposedPlanRepositoryShape { + readonly upsert: ( + proposedPlan: ProjectionThreadProposedPlan, + ) => Effect.Effect; + readonly listByThreadId: ( + input: ListProjectionThreadProposedPlansInput, + ) => Effect.Effect, ProjectionRepositoryError>; + readonly deleteByThreadId: ( + input: DeleteProjectionThreadProposedPlansInput, + ) => Effect.Effect; +} + +export class ProjectionThreadProposedPlanRepository extends ServiceMap.Service< + ProjectionThreadProposedPlanRepository, + ProjectionThreadProposedPlanRepositoryShape +>()( + "t3/persistence/Services/ProjectionThreadProposedPlans/ProjectionThreadProposedPlanRepository", +) {} diff --git a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts new file mode 100644 index 0000000000..537ee10bee --- /dev/null +++ b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts @@ -0,0 +1,74 @@ +/** + * ProjectionThreadSessionRepository - Repository interface for thread sessions. + * + * Owns persistence operations for projected provider-session linkage and + * runtime status for each thread. + * + * @module ProjectionThreadSessionRepository + */ +import { + RuntimeMode, + IsoDateTime, + OrchestrationSessionStatus, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { Option, Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../Errors.ts"; + +export const ProjectionThreadSession = Schema.Struct({ + threadId: ThreadId, + status: OrchestrationSessionStatus, + providerName: Schema.NullOr(Schema.String), + runtimeMode: RuntimeMode, + activeTurnId: Schema.NullOr(TurnId), + lastError: Schema.NullOr(Schema.String), + updatedAt: IsoDateTime, +}); +export type ProjectionThreadSession = typeof ProjectionThreadSession.Type; + +export const GetProjectionThreadSessionInput = Schema.Struct({ + threadId: ThreadId, +}); +export type GetProjectionThreadSessionInput = typeof GetProjectionThreadSessionInput.Type; + +export const DeleteProjectionThreadSessionInput = Schema.Struct({ + threadId: ThreadId, +}); +export type DeleteProjectionThreadSessionInput = typeof DeleteProjectionThreadSessionInput.Type; + +/** + * ProjectionThreadSessionRepositoryShape - Service API for projected thread sessions. + */ +export interface ProjectionThreadSessionRepositoryShape { + /** + * Insert or replace a projected thread-session row. + * + * Upserts by `threadId`. + */ + readonly upsert: (row: ProjectionThreadSession) => Effect.Effect; + + /** + * Read projected thread-session state by thread id. + */ + readonly getByThreadId: ( + input: GetProjectionThreadSessionInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Delete projected thread-session state by thread id. + */ + readonly deleteByThreadId: ( + input: DeleteProjectionThreadSessionInput, + ) => Effect.Effect; +} + +/** + * ProjectionThreadSessionRepository - Service tag for thread-session persistence. + */ +export class ProjectionThreadSessionRepository extends ServiceMap.Service< + ProjectionThreadSessionRepository, + ProjectionThreadSessionRepositoryShape +>()("t3/persistence/Services/ProjectionThreadSessions/ProjectionThreadSessionRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts new file mode 100644 index 0000000000..59505c1253 --- /dev/null +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -0,0 +1,96 @@ +/** + * ProjectionThreadRepository - Projection repository interface for threads. + * + * Owns persistence operations for projected thread records in the + * orchestration read model. + * + * @module ProjectionThreadRepository + */ +import { + IsoDateTime, + ModelSelection, + ProjectId, + ProviderInteractionMode, + RuntimeMode, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { Option, Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../Errors.ts"; + +export const ProjectionThread = Schema.Struct({ + threadId: ThreadId, + projectId: ProjectId, + title: Schema.String, + modelSelection: ModelSelection, + runtimeMode: RuntimeMode, + interactionMode: ProviderInteractionMode, + branch: Schema.NullOr(Schema.String), + worktreePath: Schema.NullOr(Schema.String), + latestTurnId: Schema.NullOr(TurnId), + createdAt: IsoDateTime, + updatedAt: IsoDateTime, + archivedAt: Schema.NullOr(IsoDateTime), + deletedAt: Schema.NullOr(IsoDateTime), +}); +export type ProjectionThread = typeof ProjectionThread.Type; + +export const GetProjectionThreadInput = Schema.Struct({ + threadId: ThreadId, +}); +export type GetProjectionThreadInput = typeof GetProjectionThreadInput.Type; + +export const DeleteProjectionThreadInput = Schema.Struct({ + threadId: ThreadId, +}); +export type DeleteProjectionThreadInput = typeof DeleteProjectionThreadInput.Type; + +export const ListProjectionThreadsByProjectInput = Schema.Struct({ + projectId: ProjectId, +}); +export type ListProjectionThreadsByProjectInput = typeof ListProjectionThreadsByProjectInput.Type; + +/** + * ProjectionThreadRepositoryShape - Service API for projected thread records. + */ +export interface ProjectionThreadRepositoryShape { + /** + * Insert or replace a projected thread row. + * + * Upserts by `threadId`. + */ + readonly upsert: (thread: ProjectionThread) => Effect.Effect; + + /** + * Read a projected thread row by id. + */ + readonly getById: ( + input: GetProjectionThreadInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * List projected threads for a project. + * + * Returned in deterministic creation order. + */ + readonly listByProjectId: ( + input: ListProjectionThreadsByProjectInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Soft-delete a projected thread row by id. + */ + readonly deleteById: ( + input: DeleteProjectionThreadInput, + ) => Effect.Effect; +} + +/** + * ProjectionThreadRepository - Service tag for thread projection persistence. + */ +export class ProjectionThreadRepository extends ServiceMap.Service< + ProjectionThreadRepository, + ProjectionThreadRepositoryShape +>()("t3/persistence/Services/ProjectionThreads/ProjectionThreadRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionTurns.ts b/apps/server/src/persistence/Services/ProjectionTurns.ts new file mode 100644 index 0000000000..95dab450bf --- /dev/null +++ b/apps/server/src/persistence/Services/ProjectionTurns.ts @@ -0,0 +1,168 @@ +/** + * ProjectionTurnRepository - Projection repository interface for unified turn state. + * + * Owns persistence operations for pending starts, running/completed turn lifecycle, + * and checkpoint metadata in a single projection table. + * + * @module ProjectionTurnRepository + */ +import { + CheckpointRef, + IsoDateTime, + MessageId, + NonNegativeInt, + OrchestrationProposedPlanId, + OrchestrationCheckpointFile, + OrchestrationCheckpointStatus, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { Option, Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectionRepositoryError } from "../Errors.ts"; + +export const ProjectionTurnState = Schema.Literals([ + "pending", + "running", + "interrupted", + "completed", + "error", +]); +export type ProjectionTurnState = typeof ProjectionTurnState.Type; + +export const ProjectionTurn = Schema.Struct({ + threadId: ThreadId, + turnId: Schema.NullOr(TurnId), + pendingMessageId: Schema.NullOr(MessageId), + sourceProposedPlanThreadId: Schema.NullOr(ThreadId), + sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId), + assistantMessageId: Schema.NullOr(MessageId), + state: ProjectionTurnState, + requestedAt: IsoDateTime, + startedAt: Schema.NullOr(IsoDateTime), + completedAt: Schema.NullOr(IsoDateTime), + checkpointTurnCount: Schema.NullOr(NonNegativeInt), + checkpointRef: Schema.NullOr(CheckpointRef), + checkpointStatus: Schema.NullOr(OrchestrationCheckpointStatus), + checkpointFiles: Schema.Array(OrchestrationCheckpointFile), +}); +export type ProjectionTurn = typeof ProjectionTurn.Type; + +export const ProjectionTurnById = Schema.Struct({ + threadId: ThreadId, + turnId: TurnId, + pendingMessageId: Schema.NullOr(MessageId), + sourceProposedPlanThreadId: Schema.NullOr(ThreadId), + sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId), + assistantMessageId: Schema.NullOr(MessageId), + state: ProjectionTurnState, + requestedAt: IsoDateTime, + startedAt: Schema.NullOr(IsoDateTime), + completedAt: Schema.NullOr(IsoDateTime), + checkpointTurnCount: Schema.NullOr(NonNegativeInt), + checkpointRef: Schema.NullOr(CheckpointRef), + checkpointStatus: Schema.NullOr(OrchestrationCheckpointStatus), + checkpointFiles: Schema.Array(OrchestrationCheckpointFile), +}); +export type ProjectionTurnById = typeof ProjectionTurnById.Type; + +export const ProjectionPendingTurnStart = Schema.Struct({ + threadId: ThreadId, + messageId: MessageId, + sourceProposedPlanThreadId: Schema.NullOr(ThreadId), + sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId), + requestedAt: IsoDateTime, +}); +export type ProjectionPendingTurnStart = typeof ProjectionPendingTurnStart.Type; + +export const ListProjectionTurnsByThreadInput = Schema.Struct({ + threadId: ThreadId, +}); +export type ListProjectionTurnsByThreadInput = typeof ListProjectionTurnsByThreadInput.Type; + +export const GetProjectionTurnByTurnIdInput = Schema.Struct({ + threadId: ThreadId, + turnId: TurnId, +}); +export type GetProjectionTurnByTurnIdInput = typeof GetProjectionTurnByTurnIdInput.Type; + +export const GetProjectionPendingTurnStartInput = Schema.Struct({ + threadId: ThreadId, +}); +export type GetProjectionPendingTurnStartInput = typeof GetProjectionPendingTurnStartInput.Type; + +export const DeleteProjectionTurnsByThreadInput = Schema.Struct({ + threadId: ThreadId, +}); +export type DeleteProjectionTurnsByThreadInput = typeof DeleteProjectionTurnsByThreadInput.Type; + +export const ClearCheckpointTurnConflictInput = Schema.Struct({ + threadId: ThreadId, + turnId: TurnId, + checkpointTurnCount: NonNegativeInt, +}); +export type ClearCheckpointTurnConflictInput = typeof ClearCheckpointTurnConflictInput.Type; + +export interface ProjectionTurnRepositoryShape { + /** + * Inserts or updates the canonical row for a concrete `{threadId, turnId}` turn lifecycle state. + */ + readonly upsertByTurnId: ( + row: ProjectionTurnById, + ) => Effect.Effect; + + /** + * Replaces any existing pending-start placeholder rows for a thread with exactly one latest pending-start row. + */ + readonly replacePendingTurnStart: ( + row: ProjectionPendingTurnStart, + ) => Effect.Effect; + + /** + * Returns the newest pending-start placeholder for a thread; this is expected to be at most one row after replacement writes. + */ + readonly getPendingTurnStartByThreadId: ( + input: GetProjectionPendingTurnStartInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Deletes only pending-start placeholder rows (`turnId = null`) for a thread and leaves concrete turn rows untouched. + */ + readonly deletePendingTurnStartByThreadId: ( + input: GetProjectionPendingTurnStartInput, + ) => Effect.Effect; + + /** + * Lists all projection rows for a thread, including pending placeholders, with checkpoint rows ordered before non-checkpoint rows. + */ + readonly listByThreadId: ( + input: ListProjectionTurnsByThreadInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Looks up a concrete turn row by `{threadId, turnId}` and never returns pending placeholder rows. + */ + readonly getByTurnId: ( + input: GetProjectionTurnByTurnIdInput, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Clears checkpoint fields on conflicting rows that reuse the same checkpoint turn count in a thread, excluding the provided turn. + */ + readonly clearCheckpointTurnConflict: ( + input: ClearCheckpointTurnConflictInput, + ) => Effect.Effect; + + /** + * Hard-deletes all projection rows for a thread, including pending-start placeholders and checkpoint metadata rows. + */ + readonly deleteByThreadId: ( + input: DeleteProjectionTurnsByThreadInput, + ) => Effect.Effect; +} + +export class ProjectionTurnRepository extends ServiceMap.Service< + ProjectionTurnRepository, + ProjectionTurnRepositoryShape +>()("t3/persistence/Services/ProjectionTurns/ProjectionTurnRepository") {} diff --git a/apps/server/src/persistence/Services/ProviderSessionRuntime.ts b/apps/server/src/persistence/Services/ProviderSessionRuntime.ts new file mode 100644 index 0000000000..885a9dd5f1 --- /dev/null +++ b/apps/server/src/persistence/Services/ProviderSessionRuntime.ts @@ -0,0 +1,81 @@ +/** + * ProviderSessionRuntimeRepository - Repository interface for provider runtime sessions. + * + * Owns persistence operations for provider runtime metadata and resume cursors. + * + * @module ProviderSessionRuntimeRepository + */ +import { + IsoDateTime, + ProviderSessionRuntimeStatus, + RuntimeMode, + ThreadId, +} from "@t3tools/contracts"; +import { Option, Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts"; + +export const ProviderSessionRuntime = Schema.Struct({ + threadId: ThreadId, + providerName: Schema.String, + adapterKey: Schema.String, + runtimeMode: RuntimeMode, + status: ProviderSessionRuntimeStatus, + lastSeenAt: IsoDateTime, + resumeCursor: Schema.NullOr(Schema.Unknown), + runtimePayload: Schema.NullOr(Schema.Unknown), +}); +export type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type; + +export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId }); +export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type; + +export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId }); +export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type; + +/** + * ProviderSessionRuntimeRepositoryShape - Service API for provider runtime records. + */ +export interface ProviderSessionRuntimeRepositoryShape { + /** + * Insert or replace a provider runtime row. + * + * Upserts by canonical `threadId`, including JSON payload/cursor fields. + */ + readonly upsert: ( + runtime: ProviderSessionRuntime, + ) => Effect.Effect; + + /** + * Read provider runtime state by canonical thread id. + */ + readonly getByThreadId: ( + input: GetProviderSessionRuntimeInput, + ) => Effect.Effect, ProviderSessionRuntimeRepositoryError>; + + /** + * List all provider runtime rows. + * + * Returned in ascending last-seen order. + */ + readonly list: () => Effect.Effect< + ReadonlyArray, + ProviderSessionRuntimeRepositoryError + >; + + /** + * Delete provider runtime state by canonical thread id. + */ + readonly deleteByThreadId: ( + input: DeleteProviderSessionRuntimeInput, + ) => Effect.Effect; +} + +/** + * ProviderSessionRuntimeRepository - Service tag for provider runtime persistence. + */ +export class ProviderSessionRuntimeRepository extends ServiceMap.Service< + ProviderSessionRuntimeRepository, + ProviderSessionRuntimeRepositoryShape +>()("t3/persistence/Services/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {} diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index 858da5ae3f..5402612887 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -1,4 +1,4 @@ -import { spawn } from "node:child_process"; +import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process"; export interface ProcessRunOptions { cwd?: string | undefined; @@ -37,11 +37,21 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`); } +export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean { + if (process.platform !== "win32") return false; + if (code === 9009) return true; + return /is not recognized as an internal or external command/i.test(stderr); +} + function normalizeExitError( command: string, args: readonly string[], result: ProcessRunResult, ): Error { + if (isWindowsCommandNotFound(result.code, result.stderr)) { + return new Error(`Command not found: ${command}`); + } + const reason = result.timedOut ? "timed out" : `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`; @@ -70,6 +80,23 @@ function normalizeBufferError( const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024; +/** + * On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe` + * wrapper, leaving the actual command running. Use `taskkill /T` to kill the + * entire process tree instead. + */ +function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void { + if (process.platform === "win32" && child.pid !== undefined) { + try { + spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }); + return; + } catch { + // fallback to direct kill + } + } + child.kill(signal); +} + function appendChunkWithinLimit( target: string, currentBytes: number, @@ -112,6 +139,7 @@ export async function runProcess( cwd: options.cwd, env: options.env, stdio: "pipe", + shell: process.platform === "win32", }); let stdout = ""; @@ -126,9 +154,9 @@ export async function runProcess( const timeoutTimer = setTimeout(() => { timedOut = true; - child.kill("SIGTERM"); + killChild(child, "SIGTERM"); forceKillTimer = setTimeout(() => { - child.kill("SIGKILL"); + killChild(child, "SIGKILL"); }, 1_000); }, timeoutMs); @@ -143,7 +171,7 @@ export async function runProcess( }; const fail = (error: Error): void => { - child.kill("SIGTERM"); + killChild(child, "SIGTERM"); finalize(() => { reject(error); }); diff --git a/apps/server/src/project/Layers/ProjectFaviconResolver.test.ts b/apps/server/src/project/Layers/ProjectFaviconResolver.test.ts new file mode 100644 index 0000000000..29b30739b9 --- /dev/null +++ b/apps/server/src/project/Layers/ProjectFaviconResolver.test.ts @@ -0,0 +1,74 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, describe, expect } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { ProjectFaviconResolver } from "../Services/ProjectFaviconResolver.ts"; +import { ProjectFaviconResolverLive } from "./ProjectFaviconResolver.ts"; + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(ProjectFaviconResolverLive), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3code-project-favicon-", + }); +}); + +const writeTextFile = Effect.fn("writeTextFile")(function* ( + cwd: string, + relativePath: string, + contents: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem + .makeDirectory(path.dirname(absolutePath), { recursive: true }) + .pipe(Effect.orDie); + yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); +}); + +it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => { + describe("resolvePath", () => { + it.effect("prefers well-known favicon files", () => + Effect.gen(function* () { + const resolver = yield* ProjectFaviconResolver; + const cwd = yield* makeTempDir; + yield* writeTextFile(cwd, "favicon.svg", "favicon"); + + const resolved = yield* resolver.resolvePath(cwd); + + expect(resolved).not.toBeNull(); + expect(resolved).toContain("favicon.svg"); + }), + ); + + it.effect("resolves icon hrefs from project source files", () => + Effect.gen(function* () { + const resolver = yield* ProjectFaviconResolver; + const cwd = yield* makeTempDir; + yield* writeTextFile(cwd, "index.html", ''); + yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); + + const resolved = yield* resolver.resolvePath(cwd); + + expect(resolved).not.toBeNull(); + expect(resolved).toContain("public/brand/logo.svg"); + }), + ); + + it.effect("returns null when no icon is present", () => + Effect.gen(function* () { + const resolver = yield* ProjectFaviconResolver; + const cwd = yield* makeTempDir; + + const resolved = yield* resolver.resolvePath(cwd); + + expect(resolved).toBeNull(); + }), + ); + }); +}); diff --git a/apps/server/src/project/Layers/ProjectFaviconResolver.ts b/apps/server/src/project/Layers/ProjectFaviconResolver.ts new file mode 100644 index 0000000000..3004a7a45c --- /dev/null +++ b/apps/server/src/project/Layers/ProjectFaviconResolver.ts @@ -0,0 +1,129 @@ +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { + ProjectFaviconResolver, + type ProjectFaviconResolverShape, +} from "../Services/ProjectFaviconResolver.ts"; + +// Well-known favicon paths checked in order. +const FAVICON_CANDIDATES = [ + "favicon.svg", + "favicon.ico", + "favicon.png", + "public/favicon.svg", + "public/favicon.ico", + "public/favicon.png", + "app/favicon.ico", + "app/favicon.png", + "app/icon.svg", + "app/icon.png", + "app/icon.ico", + "src/favicon.ico", + "src/favicon.svg", + "src/app/favicon.ico", + "src/app/icon.svg", + "src/app/icon.png", + "assets/icon.svg", + "assets/icon.png", + "assets/logo.svg", + "assets/logo.png", +] as const; + +// Files that may contain a or icon metadata declaration. +const ICON_SOURCE_FILES = [ + "index.html", + "public/index.html", + "app/routes/__root.tsx", + "src/routes/__root.tsx", + "app/root.tsx", + "src/root.tsx", + "src/index.html", +] as const; + +// Matches tags or object-like icon metadata where rel/href can appear in any order. +const LINK_ICON_HTML_RE = + /]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i; +const LINK_ICON_OBJ_RE = + /(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i; + +function extractIconHref(source: string): string | null { + const htmlMatch = source.match(LINK_ICON_HTML_RE); + if (htmlMatch?.[1]) return htmlMatch[1]; + const objMatch = source.match(LINK_ICON_OBJ_RE); + if (objMatch?.[1]) return objMatch[1]; + return null; +} + +export const makeProjectFaviconResolver = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const resolveIconHref = (projectCwd: string, href: string): string[] => { + const clean = href.replace(/^\//, ""); + return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)]; + }; + + const isPathWithinProject = (projectCwd: string, candidatePath: string): boolean => { + const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath)); + return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); + }; + + const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* ( + projectCwd: string, + candidates: ReadonlyArray, + ): Effect.fn.Return { + for (const candidate of candidates) { + if (!isPathWithinProject(projectCwd, candidate)) { + continue; + } + const stats = yield* fileSystem + .stat(candidate) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (stats?.type === "File") { + return candidate; + } + } + return null; + }); + + const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn( + "ProjectFaviconResolver.resolvePath", + )(function* (cwd: string): Effect.fn.Return { + for (const candidate of FAVICON_CANDIDATES) { + const resolved = path.join(cwd, candidate); + const existing = yield* findExistingFile(cwd, [resolved]); + if (existing) { + return existing; + } + } + + for (const sourceFile of ICON_SOURCE_FILES) { + const sourcePath = path.join(cwd, sourceFile); + const source = yield* fileSystem + .readFileString(sourcePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!source) { + continue; + } + const href = extractIconHref(source); + if (!href) { + continue; + } + const existing = yield* findExistingFile(cwd, resolveIconHref(cwd, href)); + if (existing) { + return existing; + } + } + + return null; + }); + + return { + resolvePath, + } satisfies ProjectFaviconResolverShape; +}); + +export const ProjectFaviconResolverLive = Layer.effect( + ProjectFaviconResolver, + makeProjectFaviconResolver, +); diff --git a/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts new file mode 100644 index 0000000000..6366a768b7 --- /dev/null +++ b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts @@ -0,0 +1,166 @@ +import { Effect, Layer, Stream } from "effect"; +import { describe, expect, it, vi } from "vitest"; +import type { OrchestrationReadModel } from "@t3tools/contracts"; + +import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts"; +import { TerminalManager } from "../../terminal/Services/Manager.ts"; +import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts"; +import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts"; + +const emptySnapshot = ( + scripts: OrchestrationReadModel["projects"][number]["scripts"], +): OrchestrationReadModel => + ({ + snapshotSequence: 1, + updatedAt: "2026-01-01T00:00:00.000Z", + projects: [ + { + id: "project-1", + title: "Project", + workspaceRoot: "/repo/project", + defaultModelSelection: null, + scripts, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + deletedAt: null, + }, + ], + threads: [], + providerSessions: [], + providerStatuses: [], + pendingApprovals: [], + latestTurnByThreadId: {}, + }) as unknown as OrchestrationReadModel; + +describe("ProjectSetupScriptRunner", () => { + it("returns no-script when no setup script exists", async () => { + const open = vi.fn(); + const write = vi.fn(); + const runner = await Effect.runPromise( + Effect.service(ProjectSetupScriptRunner).pipe( + Effect.provide( + ProjectSetupScriptRunnerLive.pipe( + Layer.provideMerge( + Layer.succeed(OrchestrationEngineService, { + getReadModel: () => Effect.succeed(emptySnapshot([])), + readEvents: () => Stream.empty, + dispatch: () => Effect.die(new Error("unused")), + streamDomainEvents: Stream.empty, + }), + ), + Layer.provideMerge( + Layer.succeed(TerminalManager, { + open, + write, + resize: () => Effect.void, + clear: () => Effect.void, + restart: () => Effect.die(new Error("unused")), + close: () => Effect.void, + subscribe: () => Effect.succeed(() => undefined), + }), + ), + ), + ), + ), + ); + + const result = await Effect.runPromise( + runner.runForThread({ + threadId: "thread-1", + projectId: "project-1", + worktreePath: "/repo/worktrees/a", + }), + ); + + expect(result).toEqual({ status: "no-script" }); + expect(open).not.toHaveBeenCalled(); + expect(write).not.toHaveBeenCalled(); + }); + + it("opens the deterministic setup terminal with worktree env and writes the command", async () => { + const open = vi.fn(() => + Effect.succeed({ + threadId: "thread-1", + terminalId: "setup-setup", + cwd: "/repo/worktrees/a", + worktreePath: "/repo/worktrees/a", + status: "running" as const, + pid: 123, + history: "", + exitCode: null, + exitSignal: null, + updatedAt: "2026-01-01T00:00:00.000Z", + }), + ); + const write = vi.fn(() => Effect.void); + const runner = await Effect.runPromise( + Effect.service(ProjectSetupScriptRunner).pipe( + Effect.provide( + ProjectSetupScriptRunnerLive.pipe( + Layer.provideMerge( + Layer.succeed(OrchestrationEngineService, { + getReadModel: () => + Effect.succeed( + emptySnapshot([ + { + id: "setup", + name: "Setup", + command: "bun install", + icon: "configure", + runOnWorktreeCreate: true, + }, + ]), + ), + readEvents: () => Stream.empty, + dispatch: () => Effect.die(new Error("unused")), + streamDomainEvents: Stream.empty, + }), + ), + Layer.provideMerge( + Layer.succeed(TerminalManager, { + open, + write, + resize: () => Effect.void, + clear: () => Effect.void, + restart: () => Effect.die(new Error("unused")), + close: () => Effect.void, + subscribe: () => Effect.succeed(() => undefined), + }), + ), + ), + ), + ), + ); + + const result = await Effect.runPromise( + runner.runForThread({ + threadId: "thread-1", + projectCwd: "/repo/project", + worktreePath: "/repo/worktrees/a", + }), + ); + + expect(result).toEqual({ + status: "started", + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup-setup", + cwd: "/repo/worktrees/a", + }); + expect(open).toHaveBeenCalledWith({ + threadId: "thread-1", + terminalId: "setup-setup", + cwd: "/repo/worktrees/a", + worktreePath: "/repo/worktrees/a", + env: { + T3CODE_PROJECT_ROOT: "/repo/project", + T3CODE_WORKTREE_PATH: "/repo/worktrees/a", + }, + }); + expect(write).toHaveBeenCalledWith({ + threadId: "thread-1", + terminalId: "setup-setup", + data: "bun install\r", + }); + }); +}); diff --git a/apps/server/src/project/Layers/ProjectSetupScriptRunner.ts b/apps/server/src/project/Layers/ProjectSetupScriptRunner.ts new file mode 100644 index 0000000000..3bac8cf0ab --- /dev/null +++ b/apps/server/src/project/Layers/ProjectSetupScriptRunner.ts @@ -0,0 +1,75 @@ +import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts"; +import { Effect, Layer } from "effect"; + +import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts"; +import { TerminalManager } from "../../terminal/Services/Manager.ts"; +import { + type ProjectSetupScriptRunnerShape, + ProjectSetupScriptRunner, +} from "../Services/ProjectSetupScriptRunner.ts"; + +const makeProjectSetupScriptRunner = Effect.gen(function* () { + const orchestrationEngine = yield* OrchestrationEngineService; + const terminalManager = yield* TerminalManager; + + const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) => + Effect.gen(function* () { + const readModel = yield* orchestrationEngine.getReadModel(); + const project = + (input.projectId + ? readModel.projects.find((entry) => entry.id === input.projectId) + : null) ?? + (input.projectCwd + ? readModel.projects.find((entry) => entry.workspaceRoot === input.projectCwd) + : null) ?? + null; + + if (!project) { + return yield* Effect.fail(new Error("Project was not found for setup script execution.")); + } + + const script = setupProjectScript(project.scripts); + if (!script) { + return { + status: "no-script", + } as const; + } + + const terminalId = input.preferredTerminalId ?? `setup-${script.id}`; + const cwd = input.worktreePath; + const env = projectScriptRuntimeEnv({ + project: { cwd: project.workspaceRoot }, + worktreePath: input.worktreePath, + }); + + yield* terminalManager.open({ + threadId: input.threadId, + terminalId, + cwd, + worktreePath: input.worktreePath, + env, + }); + yield* terminalManager.write({ + threadId: input.threadId, + terminalId, + data: `${script.command}\r`, + }); + + return { + status: "started", + scriptId: script.id, + scriptName: script.name, + terminalId, + cwd, + } as const; + }); + + return { + runForThread, + } satisfies ProjectSetupScriptRunnerShape; +}); + +export const ProjectSetupScriptRunnerLive = Layer.effect( + ProjectSetupScriptRunner, + makeProjectSetupScriptRunner, +); diff --git a/apps/server/src/project/Services/ProjectFaviconResolver.ts b/apps/server/src/project/Services/ProjectFaviconResolver.ts new file mode 100644 index 0000000000..f6a8e22c0d --- /dev/null +++ b/apps/server/src/project/Services/ProjectFaviconResolver.ts @@ -0,0 +1,30 @@ +/** + * ProjectFaviconResolver - Effect service contract for project icon discovery. + * + * Resolves a representative favicon or app icon file for a workspace by + * checking common file locations and project source metadata. + * + * @module ProjectFaviconResolver + */ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +/** + * ProjectFaviconResolverShape - Service API for project favicon lookup. + */ +export interface ProjectFaviconResolverShape { + /** + * Resolve a favicon or icon file path for the provided workspace root. + * + * Returns `null` when no candidate icon file can be found. + */ + readonly resolvePath: (cwd: string) => Effect.Effect; +} + +/** + * ProjectFaviconResolver - Service tag for project favicon resolution. + */ +export class ProjectFaviconResolver extends ServiceMap.Service< + ProjectFaviconResolver, + ProjectFaviconResolverShape +>()("t3/project/Services/ProjectFaviconResolver") {} diff --git a/apps/server/src/project/Services/ProjectSetupScriptRunner.ts b/apps/server/src/project/Services/ProjectSetupScriptRunner.ts new file mode 100644 index 0000000000..3828096f85 --- /dev/null +++ b/apps/server/src/project/Services/ProjectSetupScriptRunner.ts @@ -0,0 +1,37 @@ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +export interface ProjectSetupScriptRunnerResultNoScript { + readonly status: "no-script"; +} + +export interface ProjectSetupScriptRunnerResultStarted { + readonly status: "started"; + readonly scriptId: string; + readonly scriptName: string; + readonly terminalId: string; + readonly cwd: string; +} + +export type ProjectSetupScriptRunnerResult = + | ProjectSetupScriptRunnerResultNoScript + | ProjectSetupScriptRunnerResultStarted; + +export interface ProjectSetupScriptRunnerInput { + readonly threadId: string; + readonly projectId?: string; + readonly projectCwd?: string; + readonly worktreePath: string; + readonly preferredTerminalId?: string; +} + +export interface ProjectSetupScriptRunnerShape { + readonly runForThread: ( + input: ProjectSetupScriptRunnerInput, + ) => Effect.Effect; +} + +export class ProjectSetupScriptRunner extends ServiceMap.Service< + ProjectSetupScriptRunner, + ProjectSetupScriptRunnerShape +>()("t3/project/ProjectSetupScriptRunner") {} diff --git a/apps/server/src/projectRegistry.ts b/apps/server/src/projectRegistry.ts deleted file mode 100644 index 5b29fbfed9..0000000000 --- a/apps/server/src/projectRegistry.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { randomUUID } from "node:crypto"; -import fs from "node:fs"; -import path from "node:path"; - -import { - type ProjectAddInput, - type ProjectAddResult, - type ProjectListResult, - type ProjectRecord, - type ProjectRemoveInput, - projectAddInputSchema, - projectRecordSchema, - projectRemoveInputSchema, -} from "@t3tools/contracts"; - -function normalizeCwd(rawCwd: string): string { - const resolved = path.resolve(rawCwd.trim()); - const normalized = path.normalize(resolved); - if (process.platform === "win32") { - return normalized.toLowerCase(); - } - return normalized; -} - -function isDirectory(cwd: string): boolean { - try { - return fs.statSync(cwd).isDirectory(); - } catch { - return false; - } -} - -function inferProjectName(cwd: string): string { - const name = path.basename(cwd); - return name.length > 0 ? name : "project"; -} - -export class ProjectRegistry { - private readonly stateDir: string; - private readonly filePath: string; - private projects: ProjectRecord[]; - - constructor(stateDir: string) { - this.stateDir = stateDir; - this.filePath = path.join(this.stateDir, "projects.json"); - fs.mkdirSync(this.stateDir, { recursive: true }); - this.projects = this.loadFromDisk(); - } - - list(): ProjectListResult { - return this.projects.map((project) => ({ ...project })); - } - - add(raw: ProjectAddInput): ProjectAddResult { - const input = projectAddInputSchema.parse(raw); - const normalizedCwd = normalizeCwd(input.cwd); - if (!isDirectory(normalizedCwd)) { - throw new Error(`Project path does not exist: ${normalizedCwd}`); - } - - const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd); - if (existing) { - return { project: { ...existing }, created: false }; - } - - const now = new Date().toISOString(); - const project: ProjectRecord = { - id: randomUUID(), - cwd: normalizedCwd, - name: inferProjectName(normalizedCwd), - createdAt: now, - updatedAt: now, - }; - - this.projects = [project, ...this.projects]; - this.persist(); - return { project: { ...project }, created: true }; - } - - remove(raw: ProjectRemoveInput): void { - const input = projectRemoveInputSchema.parse(raw); - const next = this.projects.filter((project) => project.id !== input.id); - if (next.length === this.projects.length) { - return; - } - - this.projects = next; - this.persist(); - } - - private loadFromDisk(): ProjectRecord[] { - const loaded = this.readPersistedProjects(); - const deduped = new Map(); - const normalizedProjects: ProjectRecord[] = []; - - for (const project of loaded) { - const normalizedCwd = normalizeCwd(project.cwd); - if (!isDirectory(normalizedCwd)) { - continue; - } - if (deduped.has(normalizedCwd)) { - continue; - } - - const normalizedProject: ProjectRecord = { - ...project, - cwd: normalizedCwd, - name: - project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd), - }; - deduped.set(normalizedCwd, normalizedProject); - normalizedProjects.push(normalizedProject); - } - - const changed = - normalizedProjects.length !== loaded.length || - normalizedProjects.some((project, index) => { - const source = loaded[index]; - if (!source) return true; - return ( - source.id !== project.id || - source.cwd !== project.cwd || - source.name !== project.name || - source.createdAt !== project.createdAt || - source.updatedAt !== project.updatedAt - ); - }); - - if (changed) { - this.projects = normalizedProjects; - this.persist(); - } - - return normalizedProjects; - } - - private readPersistedProjects(): ProjectRecord[] { - try { - const raw = fs.readFileSync(this.filePath, "utf8"); - const parsed = JSON.parse(raw) as { projects?: unknown }; - if (!parsed || !Array.isArray(parsed.projects)) { - return []; - } - - const projects: ProjectRecord[] = []; - for (const candidate of parsed.projects) { - const row = projectRecordSchema.safeParse(candidate); - if (!row.success) { - continue; - } - projects.push(row.data); - } - return projects; - } catch { - return []; - } - } - - private persist(): void { - const payload = JSON.stringify( - { - version: 1, - projects: this.projects, - }, - null, - 2, - ); - const tempFile = `${this.filePath}.tmp-${process.pid}-${Date.now()}`; - fs.writeFileSync(tempFile, payload); - fs.renameSync(tempFile, this.filePath); - } -} diff --git a/apps/server/src/provider/Errors.ts b/apps/server/src/provider/Errors.ts new file mode 100644 index 0000000000..e4e46d3748 --- /dev/null +++ b/apps/server/src/provider/Errors.ts @@ -0,0 +1,163 @@ +import { Schema } from "effect"; + +import type { CheckpointServiceError } from "../checkpointing/Errors.ts"; + +/** + * ProviderAdapterValidationError - Invalid adapter API input. + */ +export class ProviderAdapterValidationError extends Schema.TaggedErrorClass()( + "ProviderAdapterValidationError", + { + provider: Schema.String, + operation: Schema.String, + issue: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Provider adapter validation failed (${this.provider}) in ${this.operation}: ${this.issue}`; + } +} + +/** + * ProviderAdapterSessionNotFoundError - Adapter-owned session id is unknown. + */ +export class ProviderAdapterSessionNotFoundError extends Schema.TaggedErrorClass()( + "ProviderAdapterSessionNotFoundError", + { + provider: Schema.String, + threadId: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Unknown ${this.provider} adapter thread: ${this.threadId}`; + } +} + +/** + * ProviderAdapterSessionClosedError - Adapter session exists but is closed. + */ +export class ProviderAdapterSessionClosedError extends Schema.TaggedErrorClass()( + "ProviderAdapterSessionClosedError", + { + provider: Schema.String, + threadId: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `${this.provider} adapter thread is closed: ${this.threadId}`; + } +} + +/** + * ProviderAdapterRequestError - Provider protocol request failed or timed out. + */ +export class ProviderAdapterRequestError extends Schema.TaggedErrorClass()( + "ProviderAdapterRequestError", + { + provider: Schema.String, + method: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Provider adapter request failed (${this.provider}) for ${this.method}: ${this.detail}`; + } +} + +/** + * ProviderAdapterProcessError - Provider process lifecycle failure. + */ +export class ProviderAdapterProcessError extends Schema.TaggedErrorClass()( + "ProviderAdapterProcessError", + { + provider: Schema.String, + threadId: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Provider adapter process error (${this.provider}) for thread ${this.threadId}: ${this.detail}`; + } +} + +/** + * ProviderValidationError - Invalid provider API input. + */ +export class ProviderValidationError extends Schema.TaggedErrorClass()( + "ProviderValidationError", + { + operation: Schema.String, + issue: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Provider validation failed in ${this.operation}: ${this.issue}`; + } +} + +/** + * ProviderUnsupportedError - Requested provider is not implemented. + */ +export class ProviderUnsupportedError extends Schema.TaggedErrorClass()( + "ProviderUnsupportedError", + { + provider: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Provider '${this.provider}' is not implemented`; + } +} + +/** + * ProviderSessionNotFoundError - Provider-facing session not found. + */ +export class ProviderSessionNotFoundError extends Schema.TaggedErrorClass()( + "ProviderSessionNotFoundError", + { + threadId: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Unknown provider thread: ${this.threadId}`; + } +} + +/** + * ProviderSessionDirectoryPersistenceError - Session directory persistence failure. + */ +export class ProviderSessionDirectoryPersistenceError extends Schema.TaggedErrorClass()( + "ProviderSessionDirectoryPersistenceError", + { + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Provider session directory persistence error in ${this.operation}: ${this.detail}`; + } +} + +export type ProviderAdapterError = + | ProviderAdapterValidationError + | ProviderAdapterSessionNotFoundError + | ProviderAdapterSessionClosedError + | ProviderAdapterRequestError + | ProviderAdapterProcessError; + +export type ProviderServiceError = + | ProviderValidationError + | ProviderUnsupportedError + | ProviderSessionNotFoundError + | ProviderSessionDirectoryPersistenceError + | ProviderAdapterError + | CheckpointServiceError; diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts new file mode 100644 index 0000000000..5a09d8b6ba --- /dev/null +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -0,0 +1,3074 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import type { + Options as ClaudeQueryOptions, + PermissionMode, + PermissionResult, + SDKMessage, + SDKUserMessage, +} from "@anthropic-ai/claude-agent-sdk"; +import { + ApprovalRequestId, + ProviderItemId, + ProviderRuntimeEvent, + ThreadId, +} from "@t3tools/contracts"; +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Fiber, Layer, Random, Stream } from "effect"; + +import { attachmentRelativePath } from "../../attachmentStore.ts"; +import { ServerConfig } from "../../config.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import { ProviderAdapterValidationError } from "../Errors.ts"; +import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts"; +import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts"; + +class FakeClaudeQuery implements AsyncIterable { + private readonly queue: Array = []; + private readonly waiters: Array<{ + readonly resolve: (value: IteratorResult) => void; + readonly reject: (reason: unknown) => void; + }> = []; + private done = false; + private failure: unknown | undefined; + + public readonly interruptCalls: Array = []; + public readonly setModelCalls: Array = []; + public readonly setPermissionModeCalls: Array = []; + public readonly setMaxThinkingTokensCalls: Array = []; + public closeCalls = 0; + + emit(message: SDKMessage): void { + if (this.done) { + return; + } + const waiter = this.waiters.shift(); + if (waiter) { + waiter.resolve({ done: false, value: message }); + return; + } + this.queue.push(message); + } + + fail(cause: unknown): void { + if (this.done) { + return; + } + this.done = true; + this.failure = cause; + for (const waiter of this.waiters.splice(0)) { + waiter.reject(cause); + } + } + + finish(): void { + if (this.done) { + return; + } + this.done = true; + this.failure = undefined; + for (const waiter of this.waiters.splice(0)) { + waiter.resolve({ done: true, value: undefined }); + } + } + + readonly interrupt = async (): Promise => { + this.interruptCalls.push(undefined); + }; + + readonly setModel = async (model?: string): Promise => { + this.setModelCalls.push(model); + }; + + readonly setPermissionMode = async (mode: PermissionMode): Promise => { + this.setPermissionModeCalls.push(mode); + }; + + readonly setMaxThinkingTokens = async (maxThinkingTokens: number | null): Promise => { + this.setMaxThinkingTokensCalls.push(maxThinkingTokens); + }; + + readonly close = (): void => { + this.closeCalls += 1; + this.finish(); + }; + + [Symbol.asyncIterator](): AsyncIterator { + return { + next: () => { + if (this.queue.length > 0) { + const value = this.queue.shift(); + if (value) { + return Promise.resolve({ + done: false, + value, + }); + } + } + if (this.failure !== undefined) { + const failure = this.failure; + this.failure = undefined; + return Promise.reject(failure); + } + if (this.done) { + return Promise.resolve({ + done: true, + value: undefined, + }); + } + return new Promise((resolve, reject) => { + this.waiters.push({ + resolve, + reject, + }); + }); + }, + }; + } +} + +function makeHarness(config?: { + readonly nativeEventLogPath?: string; + readonly nativeEventLogger?: ClaudeAdapterLiveOptions["nativeEventLogger"]; + readonly cwd?: string; + readonly baseDir?: string; +}) { + const query = new FakeClaudeQuery(); + let createInput: + | { + readonly prompt: AsyncIterable; + readonly options: ClaudeQueryOptions; + } + | undefined; + + const adapterOptions: ClaudeAdapterLiveOptions = { + createQuery: (input) => { + createInput = input; + return query; + }, + ...(config?.nativeEventLogger + ? { + nativeEventLogger: config.nativeEventLogger, + } + : {}), + ...(config?.nativeEventLogPath + ? { + nativeEventLogPath: config.nativeEventLogPath, + } + : {}), + }; + + return { + layer: makeClaudeAdapterLive(adapterOptions).pipe( + Layer.provideMerge( + ServerConfig.layerTest( + config?.cwd ?? "/tmp/claude-adapter-test", + config?.baseDir ?? "/tmp", + ), + ), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(NodeServices.layer), + ), + query, + getLastCreateQueryInput: () => createInput, + }; +} + +function makeDeterministicRandomService(seed = 0x1234_5678): { + nextIntUnsafe: () => number; + nextDoubleUnsafe: () => number; +} { + let state = seed >>> 0; + const nextIntUnsafe = (): number => { + state = (Math.imul(1_664_525, state) + 1_013_904_223) >>> 0; + return state; + }; + + return { + nextIntUnsafe, + nextDoubleUnsafe: () => nextIntUnsafe() / 0x1_0000_0000, + }; +} + +async function readFirstPromptText( + input: + | { + readonly prompt: AsyncIterable; + } + | undefined, +): Promise { + const iterator = input?.prompt[Symbol.asyncIterator](); + if (!iterator) { + return undefined; + } + const next = await iterator.next(); + if (next.done) { + return undefined; + } + if (typeof next.value.message.content === "string") { + return next.value.message.content; + } + const content = next.value.message.content[0]; + if (!content || content.type !== "text") { + return undefined; + } + return content.text; +} + +async function readFirstPromptMessage( + input: + | { + readonly prompt: AsyncIterable; + } + | undefined, +): Promise { + const iterator = input?.prompt[Symbol.asyncIterator](); + if (!iterator) { + return undefined; + } + const next = await iterator.next(); + if (next.done) { + return undefined; + } + return next.value; +} + +const THREAD_ID = ThreadId.makeUnsafe("thread-claude-1"); +const RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-claude-resume"); + +describe("ClaudeAdapterLive", () => { + it.effect("returns validation error for non-claude provider on startSession", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + const result = yield* adapter + .startSession({ threadId: THREAD_ID, provider: "codex", runtimeMode: "full-access" }) + .pipe(Effect.result); + + assert.equal(result._tag, "Failure"); + if (result._tag !== "Failure") { + return; + } + assert.deepEqual( + result.failure, + new ProviderAdapterValidationError({ + provider: "claudeAgent", + operation: "startSession", + issue: "Expected provider 'claudeAgent' but received 'codex'.", + }), + ); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("derives bypass permission mode from full-access runtime policy", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.deepEqual(createInput?.options.settingSources, ["user", "project", "local"]); + assert.equal(createInput?.options.permissionMode, "bypassPermissions"); + assert.equal(createInput?.options.allowDangerouslySkipPermissions, true); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("loads Claude filesystem settings sources for SDK sessions", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "approval-required", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.deepEqual(createInput?.options.settingSources, ["user", "project", "local"]); + assert.equal(createInput?.options.permissionMode, undefined); + assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("uses bypass permissions for full-access claude sessions", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.equal(createInput?.options.permissionMode, "bypassPermissions"); + assert.equal(createInput?.options.allowDangerouslySkipPermissions, true); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("forwards claude effort levels into query options", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + effort: "max", + }, + }, + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.equal(createInput?.options.effort, "max"); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "max", + }, + }, + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.equal(createInput?.options.effort, "high"); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("ignores adaptive effort for Haiku 4.5", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection: { + provider: "claudeAgent", + model: "claude-haiku-4-5", + options: { + effort: "high", + }, + }, + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.equal(createInput?.options.effort, undefined); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("forwards Claude thinking toggle into SDK settings for Haiku 4.5", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection: { + provider: "claudeAgent", + model: "claude-haiku-4-5", + options: { + thinking: false, + }, + }, + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.deepEqual(createInput?.options.settings, { + alwaysThinkingEnabled: false, + }); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("ignores Claude thinking toggle for non-Haiku models", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + thinking: false, + }, + }, + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.equal(createInput?.options.settings, undefined); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("forwards claude fast mode into SDK settings", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + fastMode: true, + }, + }, + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.deepEqual(createInput?.options.settings, { + fastMode: true, + }); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("ignores claude fast mode for non-opus models", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + fastMode: true, + }, + }, + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.equal(createInput?.options.settings, undefined); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("treats ultrathink as a prompt keyword instead of a session effort", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "ultrathink", + }, + }, + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "Investigate the edge cases", + attachments: [], + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "ultrathink", + }, + }, + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.equal(createInput?.options.effort, "high"); + const promptText = yield* Effect.promise(() => readFirstPromptText(createInput)); + assert.equal(promptText, "Ultrathink:\nInvestigate the edge cases"); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("embeds image attachments in Claude user messages", () => { + const baseDir = mkdtempSync(path.join(os.tmpdir(), "claude-attachments-")); + const harness = makeHarness({ + cwd: "/tmp/project-claude-attachments", + baseDir, + }); + return Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sync(() => + rmSync(baseDir, { + recursive: true, + force: true, + }), + ), + ); + + const adapter = yield* ClaudeAdapter; + const { attachmentsDir } = yield* ServerConfig; + + const attachment = { + type: "image" as const, + id: "thread-claude-attachment-12345678-1234-1234-1234-123456789abc", + name: "diagram.png", + mimeType: "image/png", + sizeBytes: 4, + }; + const attachmentPath = path.join(attachmentsDir, attachmentRelativePath(attachment)); + mkdirSync(path.dirname(attachmentPath), { recursive: true }); + writeFileSync(attachmentPath, Uint8Array.from([1, 2, 3, 4])); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "What's in this image?", + attachments: [attachment], + }); + + const createInput = harness.getLastCreateQueryInput(); + const promptMessage = yield* Effect.promise(() => readFirstPromptMessage(createInput)); + assert.isDefined(promptMessage); + assert.deepEqual(promptMessage?.message.content, [ + { + type: "text", + text: "What's in this image?", + }, + { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: "AQIDBA==", + }, + }, + ]); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("maps Claude stream/runtime messages to canonical provider runtime events", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 10).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-5", + }, + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-1", + uuid: "stream-0", + parent_tool_use_id: null, + event: { + type: "content_block_start", + index: 0, + content_block: { + type: "text", + text: "", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-1", + uuid: "stream-1", + parent_tool_use_id: null, + event: { + type: "content_block_delta", + index: 0, + delta: { + type: "text_delta", + text: "Hi", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-1", + uuid: "stream-2", + parent_tool_use_id: null, + event: { + type: "content_block_stop", + index: 0, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-1", + uuid: "stream-3", + parent_tool_use_id: null, + event: { + type: "content_block_start", + index: 1, + content_block: { + type: "tool_use", + id: "tool-1", + name: "Bash", + input: { + command: "ls", + }, + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-1", + uuid: "stream-4", + parent_tool_use_id: null, + event: { + type: "content_block_stop", + index: 1, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "assistant", + session_id: "sdk-session-1", + uuid: "assistant-1", + parent_tool_use_id: null, + message: { + id: "assistant-message-1", + content: [{ type: "text", text: "Hi" }], + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-1", + uuid: "result-1", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + assert.deepEqual( + runtimeEvents.map((event) => event.type), + [ + "session.started", + "session.configured", + "session.state.changed", + "turn.started", + "thread.started", + "content.delta", + "item.completed", + "item.started", + "item.completed", + "turn.completed", + ], + ); + + const turnStarted = runtimeEvents[3]; + assert.equal(turnStarted?.type, "turn.started"); + if (turnStarted?.type === "turn.started") { + assert.equal(String(turnStarted.turnId), String(turn.turnId)); + } + + const deltaEvent = runtimeEvents.find((event) => event.type === "content.delta"); + assert.equal(deltaEvent?.type, "content.delta"); + if (deltaEvent?.type === "content.delta") { + assert.equal(deltaEvent.payload.delta, "Hi"); + assert.equal(String(deltaEvent.turnId), String(turn.turnId)); + } + + const toolStarted = runtimeEvents.find((event) => event.type === "item.started"); + assert.equal(toolStarted?.type, "item.started"); + if (toolStarted?.type === "item.started") { + assert.equal(toolStarted.payload.itemType, "command_execution"); + } + + const assistantCompletedIndex = runtimeEvents.findIndex( + (event) => + event.type === "item.completed" && event.payload.itemType === "assistant_message", + ); + const toolStartedIndex = runtimeEvents.findIndex((event) => event.type === "item.started"); + assert.equal( + assistantCompletedIndex >= 0 && + toolStartedIndex >= 0 && + assistantCompletedIndex < toolStartedIndex, + true, + ); + + const turnCompleted = runtimeEvents[runtimeEvents.length - 1]; + assert.equal(turnCompleted?.type, "turn.completed"); + if (turnCompleted?.type === "turn.completed") { + assert.equal(String(turnCompleted.turnId), String(turn.turnId)); + assert.equal(turnCompleted.payload.state, "completed"); + } + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("maps Claude reasoning deltas, streamed tool inputs, and tool results", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 11).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-tool-streams", + uuid: "stream-thinking", + parent_tool_use_id: null, + event: { + type: "content_block_delta", + index: 0, + delta: { + type: "thinking_delta", + thinking: "Let", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-tool-streams", + uuid: "stream-tool-start", + parent_tool_use_id: null, + event: { + type: "content_block_start", + index: 1, + content_block: { + type: "tool_use", + id: "tool-grep-1", + name: "Grep", + input: {}, + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-tool-streams", + uuid: "stream-tool-input-1", + parent_tool_use_id: null, + event: { + type: "content_block_delta", + index: 1, + delta: { + type: "input_json_delta", + partial_json: '{"pattern":"foo","path":"src"}', + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-tool-streams", + uuid: "stream-tool-stop", + parent_tool_use_id: null, + event: { + type: "content_block_stop", + index: 1, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "user", + session_id: "sdk-session-tool-streams", + uuid: "user-tool-result", + parent_tool_use_id: null, + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "tool-grep-1", + content: "src/example.ts:1:foo", + }, + ], + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-tool-streams", + uuid: "result-tool-streams", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + assert.deepEqual( + runtimeEvents.map((event) => event.type), + [ + "session.started", + "session.configured", + "session.state.changed", + "turn.started", + "thread.started", + "content.delta", + "item.started", + "item.updated", + "item.updated", + "item.completed", + "turn.completed", + ], + ); + + const reasoningDelta = runtimeEvents.find( + (event) => event.type === "content.delta" && event.payload.streamKind === "reasoning_text", + ); + assert.equal(reasoningDelta?.type, "content.delta"); + if (reasoningDelta?.type === "content.delta") { + assert.equal(reasoningDelta.payload.delta, "Let"); + assert.equal(String(reasoningDelta.turnId), String(turn.turnId)); + } + + const toolStarted = runtimeEvents.find((event) => event.type === "item.started"); + assert.equal(toolStarted?.type, "item.started"); + if (toolStarted?.type === "item.started") { + assert.equal(toolStarted.payload.itemType, "dynamic_tool_call"); + } + + const toolInputUpdated = runtimeEvents.find( + (event) => + event.type === "item.updated" && + (event.payload.data as { input?: { pattern?: string; path?: string } } | undefined)?.input + ?.pattern === "foo", + ); + assert.equal(toolInputUpdated?.type, "item.updated"); + if (toolInputUpdated?.type === "item.updated") { + assert.deepEqual(toolInputUpdated.payload.data, { + toolName: "Grep", + input: { + pattern: "foo", + path: "src", + }, + }); + } + + const toolResultUpdated = runtimeEvents.find( + (event) => + event.type === "item.updated" && + (event.payload.data as { result?: { tool_use_id?: string } } | undefined)?.result + ?.tool_use_id === "tool-grep-1", + ); + assert.equal(toolResultUpdated?.type, "item.updated"); + if (toolResultUpdated?.type === "item.updated") { + assert.equal( + ( + toolResultUpdated.payload.data as { + result?: { content?: string }; + } + ).result?.content, + "src/example.ts:1:foo", + ); + } + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("classifies Claude Task tool invocations as collaboration agent work", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 8).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "delegate this", + attachments: [], + }); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-task", + uuid: "stream-task-1", + parent_tool_use_id: null, + event: { + type: "content_block_start", + index: 0, + content_block: { + type: "tool_use", + id: "tool-task-1", + name: "Task", + input: { + description: "Review the database layer", + prompt: "Audit the SQL changes", + subagent_type: "code-reviewer", + }, + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "assistant", + session_id: "sdk-session-task", + uuid: "assistant-task-1", + parent_tool_use_id: null, + message: { + id: "assistant-message-task-1", + content: [{ type: "text", text: "Delegated" }], + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-task", + uuid: "result-task-1", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + const toolStarted = runtimeEvents.find((event) => event.type === "item.started"); + assert.equal(toolStarted?.type, "item.started"); + if (toolStarted?.type === "item.started") { + assert.equal(toolStarted.payload.itemType, "collab_agent_tool_call"); + assert.equal(toolStarted.payload.title, "Subagent task"); + } + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("treats user-aborted Claude results as interrupted without a runtime error", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + harness.query.emit({ + type: "result", + subtype: "error_during_execution", + is_error: false, + errors: ["Error: Request was aborted."], + stop_reason: "tool_use", + session_id: "sdk-session-abort", + uuid: "result-abort", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + assert.deepEqual( + runtimeEvents.map((event) => event.type), + [ + "session.started", + "session.configured", + "session.state.changed", + "turn.started", + "thread.started", + "turn.completed", + ], + ); + + const turnCompleted = runtimeEvents[runtimeEvents.length - 1]; + assert.equal(turnCompleted?.type, "turn.completed"); + if (turnCompleted?.type === "turn.completed") { + assert.equal(String(turnCompleted.turnId), String(turn.turnId)); + assert.equal(turnCompleted.payload.state, "interrupted"); + assert.equal(turnCompleted.payload.errorMessage, "Error: Request was aborted."); + assert.equal(turnCompleted.payload.stopReason, "tool_use"); + } + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("closes the session when the Claude stream aborts after a turn starts", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const services = yield* Effect.services(); + const runFork = Effect.runForkWith(services); + + const adapter = yield* ClaudeAdapter; + const runtimeEvents: Array = []; + + const runtimeEventsFiber = runFork( + Stream.runForEach(adapter.streamEvents, (event) => + Effect.sync(() => { + runtimeEvents.push(event); + }), + ), + ); + + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId: THREAD_ID, + input: "hello", + attachments: [], + }); + + harness.query.fail(new Error("All fibers interrupted without error")); + + yield* Effect.yieldNow; + yield* Effect.yieldNow; + yield* Effect.yieldNow; + runtimeEventsFiber.interruptUnsafe(); + assert.deepEqual( + runtimeEvents.map((event) => event.type), + [ + "session.started", + "session.configured", + "session.state.changed", + "turn.started", + "turn.completed", + "session.exited", + ], + ); + + const turnCompleted = runtimeEvents[4]; + assert.equal(turnCompleted?.type, "turn.completed"); + if (turnCompleted?.type === "turn.completed") { + assert.equal(String(turnCompleted.turnId), String(turn.turnId)); + assert.equal(turnCompleted.payload.state, "interrupted"); + assert.equal(turnCompleted.payload.errorMessage, "Claude runtime interrupted."); + } + + const sessionExited = runtimeEvents[5]; + assert.equal(sessionExited?.type, "session.exited"); + + assert.equal(yield* adapter.hasSession(THREAD_ID), false); + const sessions = yield* adapter.listSessions(); + assert.equal(sessions.length, 0); + assert.equal(harness.query.closeCalls, 1); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("stopSession does not throw into the SDK prompt consumer", () => { + // The SDK consumes user messages via `for await (... of prompt)`. + // Stopping a session must end that loop cleanly — not throw an error. + // + // FakeClaudeQuery.close() masks this by resolving pending iterators + // before the shutdown propagates. Override it to match real SDK behavior + // where close() does not resolve the prompt consumer. + const query = new FakeClaudeQuery(); + (query as { close: () => void }).close = () => { + query.closeCalls += 1; + }; + + let promptConsumerError: unknown = undefined; + + const layer = makeClaudeAdapterLive({ + createQuery: (input) => { + // Simulate the SDK consuming the prompt iterable + (async () => { + try { + for await (const _message of input.prompt) { + /* SDK processes user messages */ + } + } catch (error) { + promptConsumerError = error; + } + })(); + return query; + }, + }).pipe( + Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(NodeServices.layer), + ); + + return Effect.gen(function* () { + const services = yield* Effect.services(); + const runFork = Effect.runForkWith(services); + + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = runFork( + Stream.runForEach(adapter.streamEvents, () => Effect.void), + ); + + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* adapter.stopSession(THREAD_ID); + + yield* Effect.yieldNow; + yield* Effect.yieldNow; + yield* Effect.yieldNow; + yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 50))); + + runtimeEventsFiber.interruptUnsafe(); + + assert.equal( + promptConsumerError, + undefined, + `Prompt consumer should not receive a thrown error on session stop, ` + + `but got: "${promptConsumerError instanceof Error ? promptConsumerError.message : String(promptConsumerError)}"`, + ); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(layer), + ); + }); + + it.effect("forwards Claude task progress summaries for subagent updates", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + harness.query.emit({ + type: "system", + subtype: "task_progress", + task_id: "task-subagent-1", + description: "Running background teammate", + summary: "Code reviewer checked the migration edge cases.", + usage: { + total_tokens: 123, + tool_uses: 4, + duration_ms: 987, + }, + session_id: "sdk-session-task-summary", + uuid: "task-progress-1", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + const progressEvent = runtimeEvents.find((event) => event.type === "task.progress"); + assert.equal(progressEvent?.type, "task.progress"); + if (progressEvent?.type === "task.progress") { + assert.equal( + progressEvent.payload.summary, + "Code reviewer checked the migration edge cases.", + ); + assert.equal(progressEvent.payload.description, "Running background teammate"); + } + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("emits thread token usage updates from Claude task progress", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + harness.query.emit({ + type: "system", + subtype: "task_progress", + task_id: "task-usage-1", + description: "Thinking through the patch", + usage: { + total_tokens: 321, + tool_uses: 2, + duration_ms: 654, + }, + session_id: "sdk-session-task-usage", + uuid: "task-usage-progress-1", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated"); + const progressEvent = runtimeEvents.find((event) => event.type === "task.progress"); + assert.equal(usageEvent?.type, "thread.token-usage.updated"); + if (usageEvent?.type === "thread.token-usage.updated") { + assert.deepEqual(usageEvent.payload, { + usage: { + usedTokens: 321, + lastUsedTokens: 321, + toolUses: 2, + durationMs: 654, + }, + }); + } + assert.equal(progressEvent?.type, "task.progress"); + if (usageEvent && progressEvent) { + assert.notStrictEqual(usageEvent.eventId, progressEvent.eventId); + } + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("emits Claude context window on result completion usage snapshots", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: THREAD_ID, + input: "hello", + attachments: [], + }); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + duration_ms: 1234, + duration_api_ms: 1200, + num_turns: 1, + result: "done", + stop_reason: "end_turn", + session_id: "sdk-session-result-usage", + usage: { + input_tokens: 4, + cache_creation_input_tokens: 2715, + cache_read_input_tokens: 21144, + output_tokens: 679, + }, + modelUsage: { + "claude-opus-4-6": { + contextWindow: 200000, + maxOutputTokens: 64000, + }, + }, + } as unknown as SDKMessage); + harness.query.finish(); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated"); + assert.equal(usageEvent?.type, "thread.token-usage.updated"); + if (usageEvent?.type === "thread.token-usage.updated") { + assert.deepEqual(usageEvent.payload, { + usage: { + usedTokens: 24542, + lastUsedTokens: 24542, + inputTokens: 23863, + outputTokens: 679, + maxTokens: 200000, + }, + }); + } + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect( + "emits completion only after turn result when assistant frames arrive before deltas", + () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 8).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + harness.query.emit({ + type: "assistant", + session_id: "sdk-session-early-assistant", + uuid: "assistant-early", + parent_tool_use_id: null, + message: { + id: "assistant-message-early", + content: [ + { type: "tool_use", id: "tool-early", name: "Read", input: { path: "a.ts" } }, + ], + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-early-assistant", + uuid: "stream-early", + parent_tool_use_id: null, + event: { + type: "content_block_delta", + index: 0, + delta: { + type: "text_delta", + text: "Late text", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-early-assistant", + uuid: "result-early", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + assert.deepEqual( + runtimeEvents.map((event) => event.type), + [ + "session.started", + "session.configured", + "session.state.changed", + "turn.started", + "thread.started", + "content.delta", + "item.completed", + "turn.completed", + ], + ); + + const deltaIndex = runtimeEvents.findIndex((event) => event.type === "content.delta"); + const completedIndex = runtimeEvents.findIndex((event) => event.type === "item.completed"); + assert.equal(deltaIndex >= 0 && completedIndex >= 0 && deltaIndex < completedIndex, true); + + const deltaEvent = runtimeEvents[deltaIndex]; + assert.equal(deltaEvent?.type, "content.delta"); + if (deltaEvent?.type === "content.delta") { + assert.equal(deltaEvent.payload.delta, "Late text"); + assert.equal(String(deltaEvent.turnId), String(turn.turnId)); + } + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }, + ); + + it.effect("creates a fresh assistant message when Claude reuses a text block index", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-reused-text-index", + uuid: "stream-reused-start-1", + parent_tool_use_id: null, + event: { + type: "content_block_start", + index: 0, + content_block: { + type: "text", + text: "", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-reused-text-index", + uuid: "stream-reused-delta-1", + parent_tool_use_id: null, + event: { + type: "content_block_delta", + index: 0, + delta: { + type: "text_delta", + text: "First", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-reused-text-index", + uuid: "stream-reused-stop-1", + parent_tool_use_id: null, + event: { + type: "content_block_stop", + index: 0, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-reused-text-index", + uuid: "stream-reused-start-2", + parent_tool_use_id: null, + event: { + type: "content_block_start", + index: 0, + content_block: { + type: "text", + text: "", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-reused-text-index", + uuid: "stream-reused-delta-2", + parent_tool_use_id: null, + event: { + type: "content_block_delta", + index: 0, + delta: { + type: "text_delta", + text: "Second", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-reused-text-index", + uuid: "stream-reused-stop-2", + parent_tool_use_id: null, + event: { + type: "content_block_stop", + index: 0, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-reused-text-index", + uuid: "result-reused-text-index", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + assert.deepEqual( + runtimeEvents.map((event) => event.type), + [ + "session.started", + "session.configured", + "session.state.changed", + "turn.started", + "thread.started", + "content.delta", + "item.completed", + "content.delta", + "item.completed", + ], + ); + + const assistantDeltas = runtimeEvents.filter( + (event) => event.type === "content.delta" && event.payload.streamKind === "assistant_text", + ); + assert.equal(assistantDeltas.length, 2); + if (assistantDeltas.length !== 2) { + return; + } + const [firstAssistantDelta, secondAssistantDelta] = assistantDeltas; + assert.equal(firstAssistantDelta?.type, "content.delta"); + assert.equal(secondAssistantDelta?.type, "content.delta"); + if ( + firstAssistantDelta?.type !== "content.delta" || + secondAssistantDelta?.type !== "content.delta" + ) { + return; + } + assert.equal(firstAssistantDelta.payload.delta, "First"); + assert.equal(secondAssistantDelta.payload.delta, "Second"); + assert.notEqual(firstAssistantDelta.itemId, secondAssistantDelta.itemId); + + const assistantCompletions = runtimeEvents.filter( + (event) => + event.type === "item.completed" && event.payload.itemType === "assistant_message", + ); + assert.equal(assistantCompletions.length, 2); + assert.equal(String(assistantCompletions[0]?.itemId), String(firstAssistantDelta.itemId)); + assert.equal(String(assistantCompletions[1]?.itemId), String(secondAssistantDelta.itemId)); + assert.notEqual( + String(assistantCompletions[0]?.itemId), + String(assistantCompletions[1]?.itemId), + ); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("falls back to assistant payload text when stream deltas are absent", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 8).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + harness.query.emit({ + type: "assistant", + session_id: "sdk-session-fallback-text", + uuid: "assistant-fallback", + parent_tool_use_id: null, + message: { + id: "assistant-message-fallback", + content: [{ type: "text", text: "Fallback hello" }], + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-fallback-text", + uuid: "result-fallback", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + assert.deepEqual( + runtimeEvents.map((event) => event.type), + [ + "session.started", + "session.configured", + "session.state.changed", + "turn.started", + "thread.started", + "content.delta", + "item.completed", + "turn.completed", + ], + ); + + const deltaEvent = runtimeEvents.find((event) => event.type === "content.delta"); + assert.equal(deltaEvent?.type, "content.delta"); + if (deltaEvent?.type === "content.delta") { + assert.equal(deltaEvent.payload.delta, "Fallback hello"); + assert.equal(String(deltaEvent.turnId), String(turn.turnId)); + } + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("segments Claude assistant text blocks around tool calls", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 13).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-interleaved", + uuid: "stream-text-1-start", + parent_tool_use_id: null, + event: { + type: "content_block_start", + index: 0, + content_block: { + type: "text", + text: "", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-interleaved", + uuid: "stream-text-1-delta", + parent_tool_use_id: null, + event: { + type: "content_block_delta", + index: 0, + delta: { + type: "text_delta", + text: "First message.", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-interleaved", + uuid: "stream-text-1-stop", + parent_tool_use_id: null, + event: { + type: "content_block_stop", + index: 0, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-interleaved", + uuid: "stream-tool-start", + parent_tool_use_id: null, + event: { + type: "content_block_start", + index: 1, + content_block: { + type: "tool_use", + id: "tool-interleaved-1", + name: "Grep", + input: { + pattern: "assistant", + path: "src", + }, + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-interleaved", + uuid: "stream-tool-stop", + parent_tool_use_id: null, + event: { + type: "content_block_stop", + index: 1, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "user", + session_id: "sdk-session-interleaved", + uuid: "user-tool-result-interleaved", + parent_tool_use_id: null, + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "tool-interleaved-1", + content: "src/example.ts:1:assistant", + }, + ], + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-interleaved", + uuid: "stream-text-2-start", + parent_tool_use_id: null, + event: { + type: "content_block_start", + index: 2, + content_block: { + type: "text", + text: "", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-interleaved", + uuid: "stream-text-2-delta", + parent_tool_use_id: null, + event: { + type: "content_block_delta", + index: 2, + delta: { + type: "text_delta", + text: "Second message.", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-interleaved", + uuid: "stream-text-2-stop", + parent_tool_use_id: null, + event: { + type: "content_block_stop", + index: 2, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-interleaved", + uuid: "result-interleaved", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + assert.deepEqual( + runtimeEvents.map((event) => event.type), + [ + "session.started", + "session.configured", + "session.state.changed", + "turn.started", + "thread.started", + "content.delta", + "item.completed", + "item.started", + "item.updated", + "item.completed", + "content.delta", + "item.completed", + "turn.completed", + ], + ); + + const assistantTextDeltas = runtimeEvents.filter( + (event) => event.type === "content.delta" && event.payload.streamKind === "assistant_text", + ); + assert.equal(assistantTextDeltas.length, 2); + if (assistantTextDeltas.length !== 2) { + return; + } + const [firstAssistantDelta, secondAssistantDelta] = assistantTextDeltas; + if (!firstAssistantDelta || !secondAssistantDelta) { + return; + } + assert.notEqual(String(firstAssistantDelta.itemId), String(secondAssistantDelta.itemId)); + + const firstAssistantCompletedIndex = runtimeEvents.findIndex( + (event) => + event.type === "item.completed" && + event.payload.itemType === "assistant_message" && + String(event.itemId) === String(firstAssistantDelta.itemId), + ); + const toolStartedIndex = runtimeEvents.findIndex((event) => event.type === "item.started"); + const secondAssistantDeltaIndex = runtimeEvents.findIndex( + (event) => + event.type === "content.delta" && + event.payload.streamKind === "assistant_text" && + String(event.itemId) === String(secondAssistantDelta.itemId), + ); + + assert.equal( + firstAssistantCompletedIndex >= 0 && + toolStartedIndex >= 0 && + secondAssistantDeltaIndex >= 0 && + firstAssistantCompletedIndex < toolStartedIndex && + toolStartedIndex < secondAssistantDeltaIndex, + true, + ); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("does not fabricate provider thread ids before first SDK session_id", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 5).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + assert.equal(session.threadId, THREAD_ID); + + const turn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + assert.equal(turn.threadId, THREAD_ID); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-thread-real", + uuid: "stream-thread-real", + parent_tool_use_id: null, + event: { + type: "message_start", + message: { + id: "msg-thread-real", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-thread-real", + uuid: "result-thread-real", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + assert.deepEqual( + runtimeEvents.map((event) => event.type), + [ + "session.started", + "session.configured", + "session.state.changed", + "turn.started", + "thread.started", + ], + ); + + const sessionStarted = runtimeEvents[0]; + assert.equal(sessionStarted?.type, "session.started"); + if (sessionStarted?.type === "session.started") { + assert.equal(sessionStarted.threadId, THREAD_ID); + } + + const threadStarted = runtimeEvents[4]; + assert.equal(threadStarted?.type, "thread.started"); + if (threadStarted?.type === "thread.started") { + assert.equal(threadStarted.threadId, THREAD_ID); + assert.deepEqual(threadStarted.payload, { + providerThreadId: "sdk-thread-real", + }); + } + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("bridges approval request/response lifecycle through canUseTool", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "approval-required", + }); + + yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "approve this", + attachments: [], + }); + yield* Stream.take(adapter.streamEvents, 1).pipe(Stream.runDrain); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-approval-1", + uuid: "stream-approval-thread", + parent_tool_use_id: null, + event: { + type: "message_start", + message: { + id: "msg-approval-thread", + }, + }, + } as unknown as SDKMessage); + + const threadStarted = yield* Stream.runHead(adapter.streamEvents); + assert.equal(threadStarted._tag, "Some"); + if (threadStarted._tag !== "Some" || threadStarted.value.type !== "thread.started") { + return; + } + + const createInput = harness.getLastCreateQueryInput(); + const canUseTool = createInput?.options.canUseTool; + assert.equal(typeof canUseTool, "function"); + if (!canUseTool) { + return; + } + + const permissionPromise = canUseTool( + "Bash", + { command: "pwd" }, + { + signal: new AbortController().signal, + suggestions: [ + { + type: "setMode", + mode: "default", + destination: "session", + }, + ], + toolUseID: "tool-use-1", + }, + ); + + const requested = yield* Stream.runHead(adapter.streamEvents); + assert.equal(requested._tag, "Some"); + if (requested._tag !== "Some") { + return; + } + assert.equal(requested.value.type, "request.opened"); + if (requested.value.type !== "request.opened") { + return; + } + assert.deepEqual(requested.value.providerRefs, { + providerItemId: ProviderItemId.makeUnsafe("tool-use-1"), + }); + const runtimeRequestId = requested.value.requestId; + assert.equal(typeof runtimeRequestId, "string"); + if (runtimeRequestId === undefined) { + return; + } + + yield* adapter.respondToRequest( + session.threadId, + ApprovalRequestId.makeUnsafe(runtimeRequestId), + "accept", + ); + + 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.requestId, requested.value.requestId); + assert.equal(resolved.value.payload.decision, "accept"); + assert.deepEqual(resolved.value.providerRefs, { + providerItemId: ProviderItemId.makeUnsafe("tool-use-1"), + }); + + const permissionResult = yield* Effect.promise(() => permissionPromise); + assert.equal((permissionResult as PermissionResult).behavior, "allow"); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("classifies Agent tools and read-only Claude tools correctly for approvals", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "approval-required", + }); + + yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain); + + const createInput = harness.getLastCreateQueryInput(); + const canUseTool = createInput?.options.canUseTool; + assert.equal(typeof canUseTool, "function"); + if (!canUseTool) { + return; + } + + const agentPermissionPromise = canUseTool( + "Agent", + {}, + { + signal: new AbortController().signal, + toolUseID: "tool-agent-1", + }, + ); + + const agentRequested = yield* Stream.runHead(adapter.streamEvents); + assert.equal(agentRequested._tag, "Some"); + if (agentRequested._tag !== "Some" || agentRequested.value.type !== "request.opened") { + return; + } + assert.equal(agentRequested.value.payload.requestType, "dynamic_tool_call"); + + yield* adapter.respondToRequest( + session.threadId, + ApprovalRequestId.makeUnsafe(String(agentRequested.value.requestId)), + "accept", + ); + yield* Stream.runHead(adapter.streamEvents); + yield* Effect.promise(() => agentPermissionPromise); + + const grepPermissionPromise = canUseTool( + "Grep", + { pattern: "foo", path: "src" }, + { + signal: new AbortController().signal, + toolUseID: "tool-grep-approval-1", + }, + ); + + const grepRequested = yield* Stream.runHead(adapter.streamEvents); + assert.equal(grepRequested._tag, "Some"); + if (grepRequested._tag !== "Some" || grepRequested.value.type !== "request.opened") { + return; + } + assert.equal(grepRequested.value.payload.requestType, "file_read_approval"); + + yield* adapter.respondToRequest( + session.threadId, + ApprovalRequestId.makeUnsafe(String(grepRequested.value.requestId)), + "accept", + ); + yield* Stream.runHead(adapter.streamEvents); + yield* Effect.promise(() => grepPermissionPromise); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("passes Claude resume ids without pinning a stale assistant checkpoint", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: RESUME_THREAD_ID, + provider: "claudeAgent", + resumeCursor: { + threadId: "resume-thread-1", + resume: "550e8400-e29b-41d4-a716-446655440000", + resumeSessionAt: "assistant-99", + turnCount: 3, + }, + runtimeMode: "full-access", + }); + + assert.equal(session.threadId, RESUME_THREAD_ID); + assert.deepEqual(session.resumeCursor, { + threadId: RESUME_THREAD_ID, + resume: "550e8400-e29b-41d4-a716-446655440000", + resumeSessionAt: "assistant-99", + turnCount: 3, + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.equal(createInput?.options.resume, "550e8400-e29b-41d4-a716-446655440000"); + assert.equal(createInput?.options.sessionId, undefined); + assert.equal(createInput?.options.resumeSessionAt, undefined); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("uses an app-generated Claude session id for fresh sessions", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + const sessionResumeCursor = session.resumeCursor as { + threadId?: string; + resume?: string; + turnCount?: number; + }; + assert.equal(sessionResumeCursor.threadId, THREAD_ID); + assert.equal(typeof sessionResumeCursor.resume, "string"); + assert.equal(sessionResumeCursor.turnCount, 0); + assert.match( + sessionResumeCursor.resume ?? "", + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, + ); + assert.equal(createInput?.options.resume, undefined); + assert.equal(createInput?.options.sessionId, sessionResumeCursor.resume); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect( + "supports rollbackThread by trimming in-memory turns and preserving earlier turns", + () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + const firstTurn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "first", + attachments: [], + }); + + const firstCompletedFiber = yield* Stream.filter( + adapter.streamEvents, + (event) => event.type === "turn.completed", + ).pipe(Stream.runHead, Effect.forkChild); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-rollback", + uuid: "result-first", + } as unknown as SDKMessage); + + const firstCompleted = yield* Fiber.join(firstCompletedFiber); + assert.equal(firstCompleted._tag, "Some"); + if (firstCompleted._tag === "Some" && firstCompleted.value.type === "turn.completed") { + assert.equal(String(firstCompleted.value.turnId), String(firstTurn.turnId)); + } + + const secondTurn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "second", + attachments: [], + }); + + const secondCompletedFiber = yield* Stream.filter( + adapter.streamEvents, + (event) => event.type === "turn.completed", + ).pipe(Stream.runHead, Effect.forkChild); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-rollback", + uuid: "result-second", + } as unknown as SDKMessage); + + const secondCompleted = yield* Fiber.join(secondCompletedFiber); + assert.equal(secondCompleted._tag, "Some"); + if (secondCompleted._tag === "Some" && secondCompleted.value.type === "turn.completed") { + assert.equal(String(secondCompleted.value.turnId), String(secondTurn.turnId)); + } + + const threadBeforeRollback = yield* adapter.readThread(session.threadId); + assert.equal(threadBeforeRollback.turns.length, 2); + + const rolledBack = yield* adapter.rollbackThread(session.threadId, 1); + assert.equal(rolledBack.turns.length, 1); + assert.equal(rolledBack.turns[0]?.id, firstTurn.turnId); + + const threadAfterRollback = yield* adapter.readThread(session.threadId); + assert.equal(threadAfterRollback.turns.length, 1); + assert.equal(threadAfterRollback.turns[0]?.id, firstTurn.turnId); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }, + ); + + it.effect("updates model on sendTurn when model override is provided", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + }, + attachments: [], + }); + + assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect( + "does not re-set the Claude model when the session already uses the same effective API model", + () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + const modelSelection = { + provider: "claudeAgent" as const, + model: "claude-opus-4-6", + }; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection, + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + modelSelection, + attachments: [], + }); + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello again", + modelSelection, + attachments: [], + }); + + assert.deepEqual(harness.query.setModelCalls, []); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }, + ); + + it.effect("re-sets the Claude model when the effective API model changes", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + contextWindow: "1m", + }, + }, + attachments: [], + }); + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello again", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + }, + attachments: [], + }); + + assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]", "claude-opus-4-6"]); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("sets plan permission mode on sendTurn when interactionMode is plan", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "plan this for me", + interactionMode: "plan", + attachments: [], + }); + + assert.deepEqual(harness.query.setPermissionModeCalls, ["plan"]); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("restores base permission mode on sendTurn when interactionMode is default", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + // First turn in plan mode + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "plan this", + interactionMode: "plan", + attachments: [], + }); + + // Complete the turn so we can send another + const turnCompletedFiber = yield* Stream.filter( + adapter.streamEvents, + (event) => event.type === "turn.completed", + ).pipe(Stream.runHead, Effect.forkChild); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-plan-restore", + uuid: "result-plan", + } as unknown as SDKMessage); + + yield* Fiber.join(turnCompletedFiber); + + // Second turn back to default + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "now do it", + interactionMode: "default", + attachments: [], + }); + + // First call sets "plan", second call restores "bypassPermissions" (the base for full-access) + assert.deepEqual(harness.query.setPermissionModeCalls, ["plan", "bypassPermissions"]); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("does not call setPermissionMode when interactionMode is absent", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + assert.deepEqual(harness.query.setPermissionModeCalls, []); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("captures ExitPlanMode as a proposed plan and denies auto-exit", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "plan this", + interactionMode: "plan", + attachments: [], + }); + yield* Stream.take(adapter.streamEvents, 1).pipe(Stream.runDrain); + + const createInput = harness.getLastCreateQueryInput(); + const canUseTool = createInput?.options.canUseTool; + assert.equal(typeof canUseTool, "function"); + if (!canUseTool) { + return; + } + + const permissionPromise = canUseTool( + "ExitPlanMode", + { + plan: "# Ship it\n\n- one\n- two", + allowedPrompts: [{ tool: "Bash", prompt: "run tests" }], + }, + { + signal: new AbortController().signal, + toolUseID: "tool-exit-1", + }, + ); + + const proposedEvent = yield* Stream.runHead(adapter.streamEvents); + assert.equal(proposedEvent._tag, "Some"); + if (proposedEvent._tag !== "Some") { + return; + } + assert.equal(proposedEvent.value.type, "turn.proposed.completed"); + if (proposedEvent.value.type !== "turn.proposed.completed") { + return; + } + assert.equal(proposedEvent.value.payload.planMarkdown, "# Ship it\n\n- one\n- two"); + assert.deepEqual(proposedEvent.value.providerRefs, { + providerItemId: ProviderItemId.makeUnsafe("tool-exit-1"), + }); + + const permissionResult = yield* Effect.promise(() => permissionPromise); + assert.equal((permissionResult as PermissionResult).behavior, "deny"); + const deniedResult = permissionResult as PermissionResult & { + message?: string; + }; + assert.equal(deniedResult.message?.includes("captured your proposed plan"), true); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("extracts proposed plans from assistant ExitPlanMode snapshots", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "plan this", + interactionMode: "plan", + attachments: [], + }); + yield* Stream.take(adapter.streamEvents, 1).pipe(Stream.runDrain); + + const proposedEventFiber = yield* Stream.filter( + adapter.streamEvents, + (event) => event.type === "turn.proposed.completed", + ).pipe(Stream.runHead, Effect.forkChild); + + harness.query.emit({ + type: "assistant", + session_id: "sdk-session-exit-plan", + uuid: "assistant-exit-plan", + parent_tool_use_id: null, + message: { + model: "claude-opus-4-6", + id: "msg-exit-plan", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: "tool-exit-2", + name: "ExitPlanMode", + input: { + plan: "# Final plan\n\n- capture it", + }, + }, + ], + stop_reason: null, + stop_sequence: null, + usage: {}, + }, + } as unknown as SDKMessage); + + const proposedEvent = yield* Fiber.join(proposedEventFiber); + assert.equal(proposedEvent._tag, "Some"); + if (proposedEvent._tag !== "Some") { + return; + } + assert.equal(proposedEvent.value.type, "turn.proposed.completed"); + if (proposedEvent.value.type !== "turn.proposed.completed") { + return; + } + assert.equal(proposedEvent.value.payload.planMarkdown, "# Final plan\n\n- capture it"); + assert.deepEqual(proposedEvent.value.providerRefs, { + providerItemId: ProviderItemId.makeUnsafe("tool-exit-2"), + }); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("handles AskUserQuestion via user-input.requested/resolved lifecycle", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + // Start session in approval-required mode so canUseTool fires. + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "approval-required", + }); + + // Drain the session startup events (started, configured, state.changed). + yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "question turn", + attachments: [], + }); + yield* Stream.take(adapter.streamEvents, 1).pipe(Stream.runDrain); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-user-input-1", + uuid: "stream-user-input-thread", + parent_tool_use_id: null, + event: { + type: "message_start", + message: { + id: "msg-user-input-thread", + }, + }, + } as unknown as SDKMessage); + + const threadStarted = yield* Stream.runHead(adapter.streamEvents); + assert.equal(threadStarted._tag, "Some"); + if (threadStarted._tag !== "Some" || threadStarted.value.type !== "thread.started") { + return; + } + + const createInput = harness.getLastCreateQueryInput(); + const canUseTool = createInput?.options.canUseTool; + assert.equal(typeof canUseTool, "function"); + if (!canUseTool) { + return; + } + + // Simulate Claude calling AskUserQuestion with structured questions. + const askInput = { + questions: [ + { + question: "Which framework?", + header: "Framework", + options: [ + { label: "React", description: "React.js" }, + { label: "Vue", description: "Vue.js" }, + ], + multiSelect: false, + }, + ], + }; + + const permissionPromise = canUseTool("AskUserQuestion", askInput, { + signal: new AbortController().signal, + toolUseID: "tool-ask-1", + }); + + // The adapter should emit a user-input.requested event. + const requestedEvent = yield* Stream.runHead(adapter.streamEvents); + assert.equal(requestedEvent._tag, "Some"); + if (requestedEvent._tag !== "Some") { + return; + } + assert.equal(requestedEvent.value.type, "user-input.requested"); + if (requestedEvent.value.type !== "user-input.requested") { + return; + } + const requestId = requestedEvent.value.requestId; + assert.equal(typeof requestId, "string"); + assert.equal(requestedEvent.value.payload.questions.length, 1); + assert.equal(requestedEvent.value.payload.questions[0]?.question, "Which framework?"); + assert.deepEqual(requestedEvent.value.providerRefs, { + providerItemId: ProviderItemId.makeUnsafe("tool-ask-1"), + }); + + // Respond with the user's answers. + yield* adapter.respondToUserInput( + session.threadId, + ApprovalRequestId.makeUnsafe(requestId!), + { "Which framework?": "React" }, + ); + + // The adapter should emit a user-input.resolved event. + const resolvedEvent = yield* Stream.runHead(adapter.streamEvents); + assert.equal(resolvedEvent._tag, "Some"); + if (resolvedEvent._tag !== "Some") { + return; + } + assert.equal(resolvedEvent.value.type, "user-input.resolved"); + if (resolvedEvent.value.type !== "user-input.resolved") { + return; + } + assert.deepEqual(resolvedEvent.value.payload.answers, { + "Which framework?": "React", + }); + assert.deepEqual(resolvedEvent.value.providerRefs, { + providerItemId: ProviderItemId.makeUnsafe("tool-ask-1"), + }); + + // The canUseTool promise should resolve with the answers in SDK format. + const permissionResult = yield* Effect.promise(() => permissionPromise); + assert.equal((permissionResult as PermissionResult).behavior, "allow"); + const updatedInput = (permissionResult as { updatedInput: Record }) + .updatedInput; + assert.deepEqual(updatedInput.answers, { "Which framework?": "React" }); + // Original questions should be passed through. + assert.deepEqual(updatedInput.questions, askInput.questions); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("routes AskUserQuestion through user-input flow even in full-access mode", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + // In full-access mode, regular tools are auto-approved. + // AskUserQuestion should still go through the user-input flow. + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain); + + const createInput = harness.getLastCreateQueryInput(); + const canUseTool = createInput?.options.canUseTool; + assert.equal(typeof canUseTool, "function"); + if (!canUseTool) { + return; + } + + const askInput = { + questions: [ + { + question: "Deploy to which env?", + header: "Env", + options: [ + { label: "Staging", description: "Staging environment" }, + { label: "Production", description: "Production environment" }, + ], + multiSelect: false, + }, + ], + }; + + const permissionPromise = canUseTool("AskUserQuestion", askInput, { + signal: new AbortController().signal, + toolUseID: "tool-ask-2", + }); + + // Should still get user-input.requested even in full-access mode. + const requestedEvent = yield* Stream.runHead(adapter.streamEvents); + assert.equal(requestedEvent._tag, "Some"); + if (requestedEvent._tag !== "Some" || requestedEvent.value.type !== "user-input.requested") { + assert.fail("Expected user-input.requested event"); + return; + } + const requestId = requestedEvent.value.requestId; + + yield* adapter.respondToUserInput( + session.threadId, + ApprovalRequestId.makeUnsafe(requestId!), + { "Deploy to which env?": "Staging" }, + ); + + // Drain the resolved event. + yield* Stream.runHead(adapter.streamEvents); + + const permissionResult = yield* Effect.promise(() => permissionPromise); + assert.equal((permissionResult as PermissionResult).behavior, "allow"); + const updatedInput = (permissionResult as { updatedInput: Record }) + .updatedInput; + assert.deepEqual(updatedInput.answers, { "Deploy to which env?": "Staging" }); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("denies AskUserQuestion when the waiting turn is aborted", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "approval-required", + }); + + yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain); + + const createInput = harness.getLastCreateQueryInput(); + const canUseTool = createInput?.options.canUseTool; + assert.equal(typeof canUseTool, "function"); + if (!canUseTool) { + return; + } + + const controller = new AbortController(); + const permissionPromise = canUseTool( + "AskUserQuestion", + { + questions: [ + { + question: "Continue?", + header: "Continue", + options: [{ label: "Yes", description: "Proceed" }], + multiSelect: false, + }, + ], + }, + { + signal: controller.signal, + toolUseID: "tool-ask-abort", + }, + ); + + const requestedEvent = yield* Stream.runHead(adapter.streamEvents); + assert.equal(requestedEvent._tag, "Some"); + if (requestedEvent._tag !== "Some" || requestedEvent.value.type !== "user-input.requested") { + assert.fail("Expected user-input.requested event"); + return; + } + assert.equal(requestedEvent.value.threadId, session.threadId); + + controller.abort(); + + const resolvedEvent = yield* Stream.runHead(adapter.streamEvents); + assert.equal(resolvedEvent._tag, "Some"); + if (resolvedEvent._tag !== "Some" || resolvedEvent.value.type !== "user-input.resolved") { + assert.fail("Expected user-input.resolved event"); + return; + } + assert.deepEqual(resolvedEvent.value.payload.answers, {}); + + const permissionResult = yield* Effect.promise(() => permissionPromise); + assert.deepEqual(permissionResult, { + behavior: "deny", + message: "User cancelled tool execution.", + } satisfies PermissionResult); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + + it.effect("writes provider-native observability records when enabled", () => { + const nativeEvents: Array<{ + event?: { + provider?: string; + method?: string; + threadId?: string; + turnId?: string; + }; + }> = []; + const nativeThreadIds: Array = []; + const harness = makeHarness({ + nativeEventLogger: { + filePath: "memory://claude-native-events", + write: (event, threadId) => { + nativeEvents.push(event as (typeof nativeEvents)[number]); + nativeThreadIds.push(threadId ?? null); + return Effect.void; + }, + close: () => Effect.void, + }, + }); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + const turn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + const turnCompletedFiber = yield* Stream.filter( + adapter.streamEvents, + (event) => event.type === "turn.completed", + ).pipe(Stream.runHead, Effect.forkChild); + + harness.query.emit({ + type: "stream_event", + session_id: "sdk-session-native-log", + uuid: "stream-native-log", + parent_tool_use_id: null, + event: { + type: "content_block_delta", + index: 0, + delta: { + type: "text_delta", + text: "hi", + }, + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-native-log", + uuid: "result-native-log", + } as unknown as SDKMessage); + + const turnCompleted = yield* Fiber.join(turnCompletedFiber); + assert.equal(turnCompleted._tag, "Some"); + + assert.equal(nativeEvents.length > 0, true); + assert.equal( + nativeEvents.some((record) => record.event?.provider === "claudeAgent"), + true, + ); + assert.equal( + nativeEvents.some( + (record) => + String( + (record.event as { readonly providerThreadId?: string } | undefined) + ?.providerThreadId, + ) === "sdk-session-native-log", + ), + true, + ); + assert.equal( + nativeEvents.some((record) => String(record.event?.turnId) === String(turn.turnId)), + true, + ); + assert.equal( + nativeEvents.some( + (record) => record.event?.method === "claude/stream_event/content_block_delta/text_delta", + ), + true, + ); + assert.equal( + nativeThreadIds.every((threadId) => threadId === String(THREAD_ID)), + true, + ); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); +}); diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts new file mode 100644 index 0000000000..d99e2ad203 --- /dev/null +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -0,0 +1,3065 @@ +/** + * ClaudeAdapterLive - Scoped live implementation for the Claude Agent provider adapter. + * + * Wraps `@anthropic-ai/claude-agent-sdk` query sessions behind the generic + * provider adapter contract and emits canonical runtime events. + * + * @module ClaudeAdapterLive + */ +import { + type CanUseTool, + query, + type Options as ClaudeQueryOptions, + type PermissionMode, + type PermissionResult, + type PermissionUpdate, + type SDKMessage, + type SDKResultMessage, + type SettingSource, + type SDKUserMessage, +} from "@anthropic-ai/claude-agent-sdk"; +import { + ApprovalRequestId, + type CanonicalItemType, + type CanonicalRequestType, + EventId, + type ProviderApprovalDecision, + ProviderItemId, + type ProviderRuntimeEvent, + type ProviderRuntimeTurnStatus, + type ProviderSendTurnInput, + type ProviderSession, + type ThreadTokenUsageSnapshot, + type ProviderUserInputAnswers, + type RuntimeContentStreamKind, + RuntimeItemId, + RuntimeRequestId, + RuntimeTaskId, + ThreadId, + TurnId, + type UserInputQuestion, + ClaudeCodeEffort, +} from "@t3tools/contracts"; +import { + applyClaudePromptEffortPrefix, + resolveApiModelId, + resolveEffort, + trimOrNull, +} from "@t3tools/shared/model"; +import { + Cause, + DateTime, + Deferred, + Effect, + Exit, + FileSystem, + Fiber, + Layer, + Queue, + Random, + Ref, + Stream, +} from "effect"; + +import { resolveAttachmentPath } from "../../attachmentStore.ts"; +import { ServerConfig } from "../../config.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import { getClaudeModelCapabilities } from "./ClaudeProvider.ts"; +import { + ProviderAdapterProcessError, + ProviderAdapterRequestError, + ProviderAdapterSessionClosedError, + ProviderAdapterSessionNotFoundError, + ProviderAdapterValidationError, + type ProviderAdapterError, +} from "../Errors.ts"; +import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts"; +import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; + +const PROVIDER = "claudeAgent" as const; +type ClaudeTextStreamKind = Extract; +type ClaudeToolResultStreamKind = Extract< + RuntimeContentStreamKind, + "command_output" | "file_change_output" +>; + +type PromptQueueItem = + | { + readonly type: "message"; + readonly message: SDKUserMessage; + } + | { + readonly type: "terminate"; + }; + +interface ClaudeResumeState { + readonly threadId?: ThreadId; + readonly resume?: string; + readonly resumeSessionAt?: string; + readonly turnCount?: number; +} + +interface ClaudeTurnState { + readonly turnId: TurnId; + readonly startedAt: string; + readonly items: Array; + readonly assistantTextBlocks: Map; + readonly assistantTextBlockOrder: Array; + readonly capturedProposedPlanKeys: Set; + nextSyntheticAssistantBlockIndex: number; +} + +interface AssistantTextBlockState { + readonly itemId: string; + readonly blockIndex: number; + emittedTextDelta: boolean; + fallbackText: string; + streamClosed: boolean; + completionEmitted: boolean; +} + +interface PendingApproval { + readonly requestType: CanonicalRequestType; + readonly detail?: string; + readonly suggestions?: ReadonlyArray; + readonly decision: Deferred.Deferred; +} + +interface PendingUserInput { + readonly questions: ReadonlyArray; + readonly answers: Deferred.Deferred; +} + +interface ToolInFlight { + readonly itemId: string; + readonly itemType: CanonicalItemType; + readonly toolName: string; + readonly title: string; + readonly detail?: string; + readonly input: Record; + readonly partialInputJson: string; + readonly lastEmittedInputFingerprint?: string; +} + +interface ClaudeSessionContext { + session: ProviderSession; + readonly promptQueue: Queue.Queue; + readonly query: ClaudeQueryRuntime; + streamFiber: Fiber.Fiber | undefined; + readonly startedAt: string; + readonly basePermissionMode: PermissionMode | undefined; + currentApiModelId: string | undefined; + resumeSessionId: string | undefined; + readonly pendingApprovals: Map; + readonly pendingUserInputs: Map; + readonly turns: Array<{ + id: TurnId; + items: Array; + }>; + readonly inFlightTools: Map; + turnState: ClaudeTurnState | undefined; + lastKnownContextWindow: number | undefined; + lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined; + lastAssistantUuid: string | undefined; + lastThreadStartedId: string | undefined; + stopped: boolean; +} + +interface ClaudeQueryRuntime extends AsyncIterable { + readonly interrupt: () => Promise; + readonly setModel: (model?: string) => Promise; + readonly setPermissionMode: (mode: PermissionMode) => Promise; + readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise; + readonly close: () => void; +} + +export interface ClaudeAdapterLiveOptions { + readonly createQuery?: (input: { + readonly prompt: AsyncIterable; + readonly options: ClaudeQueryOptions; + }) => ClaudeQueryRuntime; + readonly nativeEventLogPath?: string; + readonly nativeEventLogger?: EventNdjsonLogger; +} + +function isUuid(value: string): boolean { + return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value); +} + +function isSyntheticClaudeThreadId(value: string): boolean { + return value.startsWith("claude-thread-"); +} + +function toMessage(cause: unknown, fallback: string): string { + if (cause instanceof Error && cause.message.length > 0) { + return cause.message; + } + return fallback; +} + +function toError(cause: unknown, fallback: string): Error { + return cause instanceof Error ? cause : new Error(toMessage(cause, fallback)); +} + +function normalizeClaudeStreamMessages(cause: Cause.Cause): ReadonlyArray { + const errors = Cause.prettyErrors(cause) + .map((error) => error.message.trim()) + .filter((message) => message.length > 0); + if (errors.length > 0) { + return errors; + } + + const squashed = toMessage(Cause.squash(cause), "").trim(); + return squashed.length > 0 ? [squashed] : []; +} + +function getEffectiveClaudeCodeEffort( + effort: ClaudeCodeEffort | null | undefined, +): Exclude | null { + if (!effort) { + return null; + } + return effort === "ultrathink" ? null : effort; +} + +function isClaudeInterruptedMessage(message: string): boolean { + const normalized = message.toLowerCase(); + return ( + normalized.includes("all fibers interrupted without error") || + normalized.includes("request was aborted") || + normalized.includes("interrupted by user") + ); +} + +function isClaudeInterruptedCause(cause: Cause.Cause): boolean { + return ( + Cause.hasInterruptsOnly(cause) || + normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage) + ); +} + +function messageFromClaudeStreamCause(cause: Cause.Cause, fallback: string): string { + return normalizeClaudeStreamMessages(cause)[0] ?? fallback; +} + +function interruptionMessageFromClaudeCause(cause: Cause.Cause): string { + const message = messageFromClaudeStreamCause(cause, "Claude runtime interrupted."); + return isClaudeInterruptedMessage(message) ? "Claude runtime interrupted." : message; +} + +function resultErrorsText(result: SDKResultMessage): string { + return "errors" in result && Array.isArray(result.errors) + ? result.errors.join(" ").toLowerCase() + : ""; +} + +function isInterruptedResult(result: SDKResultMessage): boolean { + const errors = resultErrorsText(result); + if (errors.includes("interrupt")) { + return true; + } + + return ( + result.subtype === "error_during_execution" && + result.is_error === false && + (errors.includes("request was aborted") || + errors.includes("interrupted by user") || + errors.includes("aborted")) + ); +} + +function asRuntimeItemId(value: string): RuntimeItemId { + return RuntimeItemId.makeUnsafe(value); +} + +function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | undefined { + if (!modelUsage || typeof modelUsage !== "object") { + return undefined; + } + + let maxContextWindow: number | undefined; + for (const value of Object.values(modelUsage as Record)) { + if (!value || typeof value !== "object") { + continue; + } + const contextWindow = (value as { contextWindow?: unknown }).contextWindow; + if ( + typeof contextWindow !== "number" || + !Number.isFinite(contextWindow) || + contextWindow <= 0 + ) { + continue; + } + maxContextWindow = Math.max(maxContextWindow ?? 0, contextWindow); + } + + return maxContextWindow; +} + +function normalizeClaudeTokenUsage( + usage: unknown, + contextWindow?: number, +): ThreadTokenUsageSnapshot | undefined { + if (!usage || typeof usage !== "object") { + return undefined; + } + + const record = usage as Record; + const directUsedTokens = + typeof record.total_tokens === "number" && Number.isFinite(record.total_tokens) + ? record.total_tokens + : undefined; + const inputTokens = + (typeof record.input_tokens === "number" && Number.isFinite(record.input_tokens) + ? record.input_tokens + : 0) + + (typeof record.cache_creation_input_tokens === "number" && + Number.isFinite(record.cache_creation_input_tokens) + ? record.cache_creation_input_tokens + : 0) + + (typeof record.cache_read_input_tokens === "number" && + Number.isFinite(record.cache_read_input_tokens) + ? record.cache_read_input_tokens + : 0); + const outputTokens = + typeof record.output_tokens === "number" && Number.isFinite(record.output_tokens) + ? record.output_tokens + : 0; + const derivedUsedTokens = inputTokens + outputTokens; + const usedTokens = directUsedTokens ?? (derivedUsedTokens > 0 ? derivedUsedTokens : undefined); + if (usedTokens === undefined || usedTokens <= 0) { + return undefined; + } + + return { + usedTokens, + lastUsedTokens: usedTokens, + ...(inputTokens > 0 ? { inputTokens } : {}), + ...(outputTokens > 0 ? { outputTokens } : {}), + ...(typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0 + ? { maxTokens: contextWindow } + : {}), + ...(typeof record.tool_uses === "number" && Number.isFinite(record.tool_uses) + ? { toolUses: record.tool_uses } + : {}), + ...(typeof record.duration_ms === "number" && Number.isFinite(record.duration_ms) + ? { durationMs: record.duration_ms } + : {}), + }; +} + +function asCanonicalTurnId(value: TurnId): TurnId { + return value; +} + +function asRuntimeRequestId(value: ApprovalRequestId): RuntimeRequestId { + return RuntimeRequestId.makeUnsafe(value); +} + +function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undefined { + if (!resumeCursor || typeof resumeCursor !== "object") { + return undefined; + } + const cursor = resumeCursor as { + threadId?: unknown; + resume?: unknown; + sessionId?: unknown; + resumeSessionAt?: unknown; + turnCount?: unknown; + }; + + const threadIdCandidate = typeof cursor.threadId === "string" ? cursor.threadId : undefined; + const threadId = + threadIdCandidate && !isSyntheticClaudeThreadId(threadIdCandidate) + ? ThreadId.makeUnsafe(threadIdCandidate) + : undefined; + const resumeCandidate = + typeof cursor.resume === "string" + ? cursor.resume + : typeof cursor.sessionId === "string" + ? cursor.sessionId + : undefined; + const resume = resumeCandidate && isUuid(resumeCandidate) ? resumeCandidate : undefined; + const resumeSessionAt = + typeof cursor.resumeSessionAt === "string" ? cursor.resumeSessionAt : undefined; + const turnCountValue = typeof cursor.turnCount === "number" ? cursor.turnCount : undefined; + + return { + ...(threadId ? { threadId } : {}), + ...(resume ? { resume } : {}), + ...(resumeSessionAt ? { resumeSessionAt } : {}), + ...(turnCountValue !== undefined && Number.isInteger(turnCountValue) && turnCountValue >= 0 + ? { turnCount: turnCountValue } + : {}), + }; +} + +function classifyToolItemType(toolName: string): CanonicalItemType { + const normalized = toolName.toLowerCase(); + if (normalized.includes("agent")) { + return "collab_agent_tool_call"; + } + if ( + normalized === "task" || + normalized === "agent" || + normalized.includes("subagent") || + normalized.includes("sub-agent") + ) { + return "collab_agent_tool_call"; + } + if ( + normalized.includes("bash") || + normalized.includes("command") || + normalized.includes("shell") || + normalized.includes("terminal") + ) { + return "command_execution"; + } + if ( + normalized.includes("edit") || + normalized.includes("write") || + normalized.includes("file") || + normalized.includes("patch") || + normalized.includes("replace") || + normalized.includes("create") || + normalized.includes("delete") + ) { + return "file_change"; + } + if (normalized.includes("mcp")) { + return "mcp_tool_call"; + } + if (normalized.includes("websearch") || normalized.includes("web search")) { + return "web_search"; + } + if (normalized.includes("image")) { + return "image_view"; + } + return "dynamic_tool_call"; +} + +function isReadOnlyToolName(toolName: string): boolean { + const normalized = toolName.toLowerCase(); + return ( + normalized === "read" || + normalized.includes("read file") || + normalized.includes("view") || + normalized.includes("grep") || + normalized.includes("glob") || + normalized.includes("search") + ); +} + +function classifyRequestType(toolName: string): CanonicalRequestType { + if (isReadOnlyToolName(toolName)) { + return "file_read_approval"; + } + const itemType = classifyToolItemType(toolName); + return itemType === "command_execution" + ? "command_execution_approval" + : itemType === "file_change" + ? "file_change_approval" + : "dynamic_tool_call"; +} + +function summarizeToolRequest(toolName: string, input: Record): string { + const commandValue = input.command ?? input.cmd; + const command = typeof commandValue === "string" ? commandValue : undefined; + if (command && command.trim().length > 0) { + return `${toolName}: ${command.trim().slice(0, 400)}`; + } + + const serialized = JSON.stringify(input); + if (serialized.length <= 400) { + return `${toolName}: ${serialized}`; + } + return `${toolName}: ${serialized.slice(0, 397)}...`; +} + +function titleForTool(itemType: CanonicalItemType): string { + switch (itemType) { + case "command_execution": + return "Command run"; + case "file_change": + return "File change"; + case "mcp_tool_call": + return "MCP tool call"; + case "collab_agent_tool_call": + return "Subagent task"; + case "web_search": + return "Web search"; + case "image_view": + return "Image view"; + case "dynamic_tool_call": + return "Tool call"; + default: + return "Item"; + } +} + +const SUPPORTED_CLAUDE_IMAGE_MIME_TYPES = new Set([ + "image/gif", + "image/jpeg", + "image/png", + "image/webp", +]); +const CLAUDE_SETTING_SOURCES = [ + "user", + "project", + "local", +] as const satisfies ReadonlyArray; + +function buildPromptText(input: ProviderSendTurnInput): string { + const rawEffort = + input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null; + const claudeModel = + input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined; + const caps = getClaudeModelCapabilities(claudeModel); + + // For prompt injection, we check if the raw effort is a prompt-injected level (e.g. "ultrathink"). + // resolveEffort strips prompt-injected values (returning the default instead), so we check the raw value directly. + const trimmedEffort = trimOrNull(rawEffort); + const promptEffort = + trimmedEffort && caps.promptInjectedEffortLevels.includes(trimmedEffort) ? trimmedEffort : null; + return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort); +} + +function buildUserMessage(input: { + readonly sdkContent: Array>; +}): SDKUserMessage { + return { + type: "user", + session_id: "", + parent_tool_use_id: null, + message: { + role: "user", + content: input.sdkContent as unknown as SDKUserMessage["message"]["content"], + }, + } as SDKUserMessage; +} + +function buildClaudeImageContentBlock(input: { + readonly mimeType: string; + readonly bytes: Uint8Array; +}): Record { + return { + type: "image", + source: { + type: "base64", + media_type: input.mimeType, + data: Buffer.from(input.bytes).toString("base64"), + }, + }; +} + +const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* ( + input: ProviderSendTurnInput, + dependencies: { + readonly fileSystem: FileSystem.FileSystem; + readonly attachmentsDir: string; + }, +) { + const text = buildPromptText(input); + const sdkContent: Array> = []; + + if (text.length > 0) { + sdkContent.push({ type: "text", text }); + } + + for (const attachment of input.attachments ?? []) { + if (attachment.type !== "image") { + continue; + } + + if (!SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType)) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`, + }); + } + + const attachmentPath = resolveAttachmentPath({ + attachmentsDir: dependencies.attachmentsDir, + attachment, + }); + if (!attachmentPath) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: `Invalid attachment id '${attachment.id}'.`, + }); + } + + const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: toMessage(cause, "Failed to read attachment file."), + cause, + }), + ), + ); + + sdkContent.push( + buildClaudeImageContentBlock({ + mimeType: attachment.mimeType, + bytes, + }), + ); + } + + return buildUserMessage({ sdkContent }); +}); + +function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStatus { + if (result.subtype === "success") { + return "completed"; + } + + const errors = resultErrorsText(result); + if (isInterruptedResult(result)) { + return "interrupted"; + } + if (errors.includes("cancel")) { + return "cancelled"; + } + return "failed"; +} + +function streamKindFromDeltaType(deltaType: string): ClaudeTextStreamKind { + return deltaType.includes("thinking") ? "reasoning_text" : "assistant_text"; +} + +function nativeProviderRefs( + _context: ClaudeSessionContext, + options?: { + readonly providerItemId?: string | undefined; + }, +): NonNullable { + if (options?.providerItemId) { + return { + providerItemId: ProviderItemId.makeUnsafe(options.providerItemId), + }; + } + return {}; +} + +function extractAssistantTextBlocks(message: SDKMessage): Array { + if (message.type !== "assistant") { + return []; + } + + const content = (message.message as { content?: unknown } | undefined)?.content; + if (!Array.isArray(content)) { + return []; + } + + const fragments: string[] = []; + for (const block of content) { + if (!block || typeof block !== "object") { + continue; + } + const candidate = block as { type?: unknown; text?: unknown }; + if ( + candidate.type === "text" && + typeof candidate.text === "string" && + candidate.text.length > 0 + ) { + fragments.push(candidate.text); + } + } + + return fragments; +} + +function extractContentBlockText(block: unknown): string { + if (!block || typeof block !== "object") { + return ""; + } + + const candidate = block as { type?: unknown; text?: unknown }; + return candidate.type === "text" && typeof candidate.text === "string" ? candidate.text : ""; +} + +function extractTextContent(value: unknown): string { + if (typeof value === "string") { + return value; + } + + if (Array.isArray(value)) { + return value.map((entry) => extractTextContent(entry)).join(""); + } + + if (!value || typeof value !== "object") { + return ""; + } + + const record = value as { + text?: unknown; + content?: unknown; + }; + + if (typeof record.text === "string") { + return record.text; + } + + return extractTextContent(record.content); +} + +function extractExitPlanModePlan(value: unknown): string | undefined { + if (!value || typeof value !== "object") { + return undefined; + } + + const record = value as { + plan?: unknown; + }; + return typeof record.plan === "string" && record.plan.trim().length > 0 + ? record.plan.trim() + : undefined; +} + +function exitPlanCaptureKey(input: { + readonly toolUseId?: string | undefined; + readonly planMarkdown: string; +}): string { + return input.toolUseId && input.toolUseId.length > 0 + ? `tool:${input.toolUseId}` + : `plan:${input.planMarkdown}`; +} + +function tryParseJsonRecord(value: string): Record | undefined { + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) + ? (parsed as Record) + : undefined; + } catch { + return undefined; + } +} + +function toolInputFingerprint(input: Record): string | undefined { + try { + return JSON.stringify(input); + } catch { + return undefined; + } +} + +function toolResultStreamKind(itemType: CanonicalItemType): ClaudeToolResultStreamKind | undefined { + switch (itemType) { + case "command_execution": + return "command_output"; + case "file_change": + return "file_change_output"; + default: + return undefined; + } +} + +function toolResultBlocksFromUserMessage(message: SDKMessage): Array<{ + readonly toolUseId: string; + readonly block: Record; + readonly text: string; + readonly isError: boolean; +}> { + if (message.type !== "user") { + return []; + } + + const content = (message.message as { content?: unknown } | undefined)?.content; + if (!Array.isArray(content)) { + return []; + } + + const blocks: Array<{ + readonly toolUseId: string; + readonly block: Record; + readonly text: string; + readonly isError: boolean; + }> = []; + + for (const entry of content) { + if (!entry || typeof entry !== "object") { + continue; + } + + const block = entry as Record; + if (block.type !== "tool_result") { + continue; + } + + const toolUseId = typeof block.tool_use_id === "string" ? block.tool_use_id : undefined; + if (!toolUseId) { + continue; + } + + blocks.push({ + toolUseId, + block, + text: extractTextContent(block.content), + isError: block.is_error === true, + }); + } + + return blocks; +} + +function toSessionError( + threadId: ThreadId, + cause: unknown, +): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined { + const normalized = toMessage(cause, "").toLowerCase(); + if (normalized.includes("unknown session") || normalized.includes("not found")) { + return new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId, + cause, + }); + } + if (normalized.includes("closed")) { + return new ProviderAdapterSessionClosedError({ + provider: PROVIDER, + threadId, + cause, + }); + } + return undefined; +} + +function toRequestError(threadId: ThreadId, method: string, cause: unknown): ProviderAdapterError { + const sessionError = toSessionError(threadId, cause); + if (sessionError) { + return sessionError; + } + return new ProviderAdapterRequestError({ + provider: PROVIDER, + method, + detail: toMessage(cause, `${method} failed`), + cause, + }); +} + +function sdkMessageType(value: unknown): string | undefined { + if (!value || typeof value !== "object") { + return undefined; + } + const record = value as { type?: unknown }; + return typeof record.type === "string" ? record.type : undefined; +} + +function sdkMessageSubtype(value: unknown): string | undefined { + if (!value || typeof value !== "object") { + return undefined; + } + const record = value as { subtype?: unknown }; + return typeof record.subtype === "string" ? record.subtype : undefined; +} + +function sdkNativeMethod(message: SDKMessage): string { + const subtype = sdkMessageSubtype(message); + if (subtype) { + return `claude/${message.type}/${subtype}`; + } + + if (message.type === "stream_event") { + const streamType = sdkMessageType(message.event); + if (streamType) { + const deltaType = + streamType === "content_block_delta" + ? sdkMessageType((message.event as { delta?: unknown }).delta) + : undefined; + if (deltaType) { + return `claude/${message.type}/${streamType}/${deltaType}`; + } + return `claude/${message.type}/${streamType}`; + } + } + + return `claude/${message.type}`; +} + +function sdkNativeItemId(message: SDKMessage): string | undefined { + if (message.type === "assistant") { + const maybeId = (message.message as { id?: unknown }).id; + if (typeof maybeId === "string") { + return maybeId; + } + return undefined; + } + + if (message.type === "user") { + return toolResultBlocksFromUserMessage(message)[0]?.toolUseId; + } + + if (message.type === "stream_event") { + const event = message.event as { + type?: unknown; + content_block?: { id?: unknown }; + }; + if (event.type === "content_block_start" && typeof event.content_block?.id === "string") { + return event.content_block.id; + } + } + + return undefined; +} + +const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( + options?: ClaudeAdapterLiveOptions, +) { + const fileSystem = yield* FileSystem.FileSystem; + const serverConfig = yield* ServerConfig; + const nativeEventLogger = + options?.nativeEventLogger ?? + (options?.nativeEventLogPath !== undefined + ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { + stream: "native", + }) + : undefined); + + const createQuery = + options?.createQuery ?? + ((input: { + readonly prompt: AsyncIterable; + readonly options: ClaudeQueryOptions; + }) => query({ prompt: input.prompt, options: input.options }) as ClaudeQueryRuntime); + + const sessions = new Map(); + const runtimeEventQueue = yield* Queue.unbounded(); + const serverSettingsService = yield* ServerSettingsService; + + const nowIso = Effect.map(DateTime.now, DateTime.formatIso); + const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.makeUnsafe(id)); + const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso }); + + const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => + Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid); + + const logNativeSdkMessage = Effect.fn("logNativeSdkMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (!nativeEventLogger) { + return; + } + + const observedAt = new Date().toISOString(); + const itemId = sdkNativeItemId(message); + + yield* nativeEventLogger.write( + { + observedAt, + event: { + id: + "uuid" in message && typeof message.uuid === "string" + ? message.uuid + : crypto.randomUUID(), + kind: "notification", + provider: PROVIDER, + createdAt: observedAt, + method: sdkNativeMethod(message), + ...(typeof message.session_id === "string" + ? { providerThreadId: message.session_id } + : {}), + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + ...(itemId ? { itemId: ProviderItemId.makeUnsafe(itemId) } : {}), + payload: message, + }, + }, + context.session.threadId, + ); + }); + + const snapshotThread = Effect.fn("snapshotThread")(function* (context: ClaudeSessionContext) { + const threadId = context.session.threadId; + if (!threadId) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "readThread", + issue: "Session thread id is not initialized yet.", + }); + } + return { + threadId, + turns: context.turns.map((turn) => ({ + id: turn.id, + items: [...turn.items], + })), + }; + }); + + const updateResumeCursor = Effect.fn("updateResumeCursor")(function* ( + context: ClaudeSessionContext, + ) { + const threadId = context.session.threadId; + if (!threadId) return; + + const resumeCursor = { + threadId, + ...(context.resumeSessionId ? { resume: context.resumeSessionId } : {}), + ...(context.lastAssistantUuid ? { resumeSessionAt: context.lastAssistantUuid } : {}), + turnCount: context.turns.length, + }; + + context.session = { + ...context.session, + resumeCursor, + updatedAt: yield* nowIso, + }; + }); + + const ensureAssistantTextBlock = Effect.fn("ensureAssistantTextBlock")(function* ( + context: ClaudeSessionContext, + blockIndex: number, + options?: { + readonly fallbackText?: string; + readonly streamClosed?: boolean; + }, + ) { + const turnState = context.turnState; + if (!turnState) { + return undefined; + } + + const existing = turnState.assistantTextBlocks.get(blockIndex); + if (existing && !existing.completionEmitted) { + if (existing.fallbackText.length === 0 && options?.fallbackText) { + existing.fallbackText = options.fallbackText; + } + if (options?.streamClosed) { + existing.streamClosed = true; + } + return { blockIndex, block: existing }; + } + + const block: AssistantTextBlockState = { + itemId: yield* Random.nextUUIDv4, + blockIndex, + emittedTextDelta: false, + fallbackText: options?.fallbackText ?? "", + streamClosed: options?.streamClosed ?? false, + completionEmitted: false, + }; + turnState.assistantTextBlocks.set(blockIndex, block); + turnState.assistantTextBlockOrder.push(block); + return { blockIndex, block }; + }); + + const createSyntheticAssistantTextBlock = Effect.fn("createSyntheticAssistantTextBlock")( + function* (context: ClaudeSessionContext, fallbackText: string) { + const turnState = context.turnState; + if (!turnState) { + return undefined; + } + + const blockIndex = turnState.nextSyntheticAssistantBlockIndex; + turnState.nextSyntheticAssistantBlockIndex -= 1; + return yield* ensureAssistantTextBlock(context, blockIndex, { + fallbackText, + streamClosed: true, + }); + }, + ); + + const completeAssistantTextBlock = Effect.fn("completeAssistantTextBlock")(function* ( + context: ClaudeSessionContext, + block: AssistantTextBlockState, + options?: { + readonly force?: boolean; + readonly rawMethod?: string; + readonly rawPayload?: unknown; + }, + ) { + const turnState = context.turnState; + if (!turnState || block.completionEmitted) { + return; + } + + if (!options?.force && !block.streamClosed) { + return; + } + + if (!block.emittedTextDelta && block.fallbackText.length > 0) { + const deltaStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "content.delta", + eventId: deltaStamp.eventId, + provider: PROVIDER, + createdAt: deltaStamp.createdAt, + threadId: context.session.threadId, + turnId: turnState.turnId, + itemId: asRuntimeItemId(block.itemId), + payload: { + streamKind: "assistant_text", + delta: block.fallbackText, + }, + providerRefs: nativeProviderRefs(context), + ...(options?.rawMethod || options?.rawPayload + ? { + raw: { + source: "claude.sdk.message" as const, + ...(options.rawMethod ? { method: options.rawMethod } : {}), + payload: options?.rawPayload, + }, + } + : {}), + }); + } + + block.completionEmitted = true; + if (turnState.assistantTextBlocks.get(block.blockIndex) === block) { + turnState.assistantTextBlocks.delete(block.blockIndex); + } + + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.completed", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + itemId: asRuntimeItemId(block.itemId), + threadId: context.session.threadId, + turnId: turnState.turnId, + payload: { + itemType: "assistant_message", + status: "completed", + title: "Assistant message", + ...(block.fallbackText.length > 0 ? { detail: block.fallbackText } : {}), + }, + providerRefs: nativeProviderRefs(context), + ...(options?.rawMethod || options?.rawPayload + ? { + raw: { + source: "claude.sdk.message" as const, + ...(options.rawMethod ? { method: options.rawMethod } : {}), + payload: options?.rawPayload, + }, + } + : {}), + }); + }); + + const backfillAssistantTextBlocksFromSnapshot = Effect.fn( + "backfillAssistantTextBlocksFromSnapshot", + )(function* (context: ClaudeSessionContext, message: SDKMessage) { + const turnState = context.turnState; + if (!turnState) { + return; + } + + const snapshotTextBlocks = extractAssistantTextBlocks(message); + if (snapshotTextBlocks.length === 0) { + return; + } + + const orderedBlocks = turnState.assistantTextBlockOrder.map((block) => ({ + blockIndex: block.blockIndex, + block, + })); + + for (const [position, text] of snapshotTextBlocks.entries()) { + const existingEntry = orderedBlocks[position]; + const entry = + existingEntry ?? + (yield* createSyntheticAssistantTextBlock(context, text).pipe( + Effect.map((created) => { + if (!created) { + return undefined; + } + orderedBlocks.push(created); + return created; + }), + )); + if (!entry) { + continue; + } + + if (entry.block.fallbackText.length === 0) { + entry.block.fallbackText = text; + } + + if (entry.block.streamClosed && !entry.block.completionEmitted) { + yield* completeAssistantTextBlock(context, entry.block, { + rawMethod: "claude/assistant", + rawPayload: message, + }); + } + } + }); + + const ensureThreadId = Effect.fn("ensureThreadId")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (typeof message.session_id !== "string" || message.session_id.length === 0) { + return; + } + const nextThreadId = message.session_id; + context.resumeSessionId = message.session_id; + yield* updateResumeCursor(context); + + if (context.lastThreadStartedId !== nextThreadId) { + context.lastThreadStartedId = nextThreadId; + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "thread.started", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + payload: { + providerThreadId: nextThreadId, + }, + providerRefs: {}, + raw: { + source: "claude.sdk.message", + method: "claude/thread/started", + payload: { + session_id: message.session_id, + }, + }, + }); + } + }); + + const emitRuntimeError = Effect.fn("emitRuntimeError")(function* ( + context: ClaudeSessionContext, + message: string, + cause?: unknown, + ) { + if (cause !== undefined) { + void cause; + } + const turnState = context.turnState; + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "runtime.error", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}), + payload: { + message, + class: "provider_error", + ...(cause !== undefined ? { detail: cause } : {}), + }, + providerRefs: nativeProviderRefs(context), + }); + }); + + const emitRuntimeWarning = Effect.fn("emitRuntimeWarning")(function* ( + context: ClaudeSessionContext, + message: string, + detail?: unknown, + ) { + const turnState = context.turnState; + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "runtime.warning", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}), + payload: { + message, + ...(detail !== undefined ? { detail } : {}), + }, + providerRefs: nativeProviderRefs(context), + }); + }); + + const emitProposedPlanCompleted = Effect.fn("emitProposedPlanCompleted")(function* ( + context: ClaudeSessionContext, + input: { + readonly planMarkdown: string; + readonly toolUseId?: string | undefined; + readonly rawSource: "claude.sdk.message" | "claude.sdk.permission"; + readonly rawMethod: string; + readonly rawPayload: unknown; + }, + ) { + const turnState = context.turnState; + const planMarkdown = input.planMarkdown.trim(); + if (!turnState || planMarkdown.length === 0) { + return; + } + + const captureKey = exitPlanCaptureKey({ + toolUseId: input.toolUseId, + planMarkdown, + }); + if (turnState.capturedProposedPlanKeys.has(captureKey)) { + return; + } + turnState.capturedProposedPlanKeys.add(captureKey); + + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.proposed.completed", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + turnId: turnState.turnId, + payload: { + planMarkdown, + }, + providerRefs: nativeProviderRefs(context, { + providerItemId: input.toolUseId, + }), + raw: { + source: input.rawSource, + method: input.rawMethod, + payload: input.rawPayload, + }, + }); + }); + + const completeTurn = Effect.fn("completeTurn")(function* ( + context: ClaudeSessionContext, + status: ProviderRuntimeTurnStatus, + errorMessage?: string, + result?: SDKResultMessage, + ) { + const resultUsage = + result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined; + const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage); + if (resultContextWindow !== undefined) { + context.lastKnownContextWindow = resultContextWindow; + } + + // The SDK result.usage contains *accumulated* totals across all API calls + // (input_tokens, cache_read_input_tokens, etc. summed over every request). + // This does NOT represent the current context window size. + // Instead, use the last known context-window-accurate usage from task_progress + // events and treat the accumulated total as totalProcessedTokens. + const accumulatedSnapshot = normalizeClaudeTokenUsage( + resultUsage, + resultContextWindow ?? context.lastKnownContextWindow, + ); + const lastGoodUsage = context.lastKnownTokenUsage; + const maxTokens = resultContextWindow ?? context.lastKnownContextWindow; + const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage + ? { + ...lastGoodUsage, + ...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0 + ? { maxTokens } + : {}), + ...(accumulatedSnapshot && accumulatedSnapshot.usedTokens > lastGoodUsage.usedTokens + ? { totalProcessedTokens: accumulatedSnapshot.usedTokens } + : {}), + } + : accumulatedSnapshot; + + const turnState = context.turnState; + if (!turnState) { + if (usageSnapshot) { + const usageStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "thread.token-usage.updated", + eventId: usageStamp.eventId, + provider: PROVIDER, + createdAt: usageStamp.createdAt, + threadId: context.session.threadId, + payload: { + usage: usageSnapshot, + }, + providerRefs: {}, + }); + } + + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.completed", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + payload: { + state: status, + ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}), + ...(result?.usage ? { usage: result.usage } : {}), + ...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}), + ...(typeof result?.total_cost_usd === "number" + ? { totalCostUsd: result.total_cost_usd } + : {}), + ...(errorMessage ? { errorMessage } : {}), + }, + providerRefs: {}, + }); + return; + } + + for (const [index, tool] of context.inFlightTools.entries()) { + const toolStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.completed", + eventId: toolStamp.eventId, + provider: PROVIDER, + createdAt: toolStamp.createdAt, + threadId: context.session.threadId, + turnId: turnState.turnId, + itemId: asRuntimeItemId(tool.itemId), + payload: { + itemType: tool.itemType, + status: status === "completed" ? "completed" : "failed", + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + data: { + toolName: tool.toolName, + input: tool.input, + }, + }, + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/result", + payload: result ?? { status }, + }, + }); + context.inFlightTools.delete(index); + } + // Clear any remaining stale entries (e.g. from interrupted content blocks) + context.inFlightTools.clear(); + + for (const block of turnState.assistantTextBlockOrder) { + yield* completeAssistantTextBlock(context, block, { + force: true, + rawMethod: "claude/result", + rawPayload: result ?? { status }, + }); + } + + context.turns.push({ + id: turnState.turnId, + items: [...turnState.items], + }); + + if (usageSnapshot) { + const usageStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "thread.token-usage.updated", + eventId: usageStamp.eventId, + provider: PROVIDER, + createdAt: usageStamp.createdAt, + threadId: context.session.threadId, + turnId: turnState.turnId, + payload: { + usage: usageSnapshot, + }, + providerRefs: nativeProviderRefs(context), + }); + } + + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.completed", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + turnId: turnState.turnId, + payload: { + state: status, + ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}), + ...(result?.usage ? { usage: result.usage } : {}), + ...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}), + ...(typeof result?.total_cost_usd === "number" + ? { totalCostUsd: result.total_cost_usd } + : {}), + ...(errorMessage ? { errorMessage } : {}), + }, + providerRefs: nativeProviderRefs(context), + }); + + const updatedAt = yield* nowIso; + context.turnState = undefined; + context.session = { + ...context.session, + status: "ready", + activeTurnId: undefined, + updatedAt, + ...(status === "failed" && errorMessage ? { lastError: errorMessage } : {}), + }; + yield* updateResumeCursor(context); + }); + + const handleStreamEvent = Effect.fn("handleStreamEvent")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (message.type !== "stream_event") { + return; + } + + const { event } = message; + + if (event.type === "content_block_delta") { + if ( + (event.delta.type === "text_delta" || event.delta.type === "thinking_delta") && + context.turnState + ) { + const deltaText = + event.delta.type === "text_delta" + ? event.delta.text + : typeof event.delta.thinking === "string" + ? event.delta.thinking + : ""; + if (deltaText.length === 0) { + return; + } + const streamKind = streamKindFromDeltaType(event.delta.type); + const assistantBlockEntry = + event.delta.type === "text_delta" + ? yield* ensureAssistantTextBlock(context, event.index) + : context.turnState.assistantTextBlocks.get(event.index) + ? { + blockIndex: event.index, + block: context.turnState.assistantTextBlocks.get( + event.index, + ) as AssistantTextBlockState, + } + : undefined; + if (assistantBlockEntry?.block && event.delta.type === "text_delta") { + assistantBlockEntry.block.emittedTextDelta = true; + } + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "content.delta", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + turnId: context.turnState.turnId, + ...(assistantBlockEntry?.block + ? { itemId: asRuntimeItemId(assistantBlockEntry.block.itemId) } + : {}), + payload: { + streamKind, + delta: deltaText, + }, + providerRefs: nativeProviderRefs(context), + raw: { + source: "claude.sdk.message", + method: "claude/stream_event/content_block_delta", + payload: message, + }, + }); + return; + } + + if (event.delta.type === "input_json_delta") { + const tool = context.inFlightTools.get(event.index); + if (!tool || typeof event.delta.partial_json !== "string") { + return; + } + + const partialInputJson = tool.partialInputJson + event.delta.partial_json; + const parsedInput = tryParseJsonRecord(partialInputJson); + const detail = parsedInput ? summarizeToolRequest(tool.toolName, parsedInput) : tool.detail; + let nextTool: ToolInFlight = { + ...tool, + partialInputJson, + ...(parsedInput ? { input: parsedInput } : {}), + ...(detail ? { detail } : {}), + }; + + const nextFingerprint = + parsedInput && Object.keys(parsedInput).length > 0 + ? toolInputFingerprint(parsedInput) + : undefined; + context.inFlightTools.set(event.index, nextTool); + + if ( + !parsedInput || + !nextFingerprint || + tool.lastEmittedInputFingerprint === nextFingerprint + ) { + return; + } + + nextTool = { + ...nextTool, + lastEmittedInputFingerprint: nextFingerprint, + }; + context.inFlightTools.set(event.index, nextTool); + + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.updated", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + itemId: asRuntimeItemId(nextTool.itemId), + payload: { + itemType: nextTool.itemType, + status: "inProgress", + title: nextTool.title, + ...(nextTool.detail ? { detail: nextTool.detail } : {}), + data: { + toolName: nextTool.toolName, + input: nextTool.input, + }, + }, + providerRefs: nativeProviderRefs(context, { providerItemId: nextTool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/stream_event/content_block_delta/input_json_delta", + payload: message, + }, + }); + } + return; + } + + if (event.type === "content_block_start") { + const { index, content_block: block } = event; + if (block.type === "text") { + yield* ensureAssistantTextBlock(context, index, { + fallbackText: extractContentBlockText(block), + }); + return; + } + if ( + block.type !== "tool_use" && + block.type !== "server_tool_use" && + block.type !== "mcp_tool_use" + ) { + return; + } + + const toolName = block.name; + const itemType = classifyToolItemType(toolName); + const toolInput = + typeof block.input === "object" && block.input !== null + ? (block.input as Record) + : {}; + const itemId = block.id; + const detail = summarizeToolRequest(toolName, toolInput); + const inputFingerprint = + Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined; + + const tool: ToolInFlight = { + itemId, + itemType, + toolName, + title: titleForTool(itemType), + detail, + input: toolInput, + partialInputJson: "", + ...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}), + }; + context.inFlightTools.set(index, tool); + + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.started", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + itemId: asRuntimeItemId(tool.itemId), + payload: { + itemType: tool.itemType, + status: "inProgress", + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + data: { + toolName: tool.toolName, + input: toolInput, + }, + }, + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/stream_event/content_block_start", + payload: message, + }, + }); + return; + } + + if (event.type === "content_block_stop") { + const { index } = event; + const assistantBlock = context.turnState?.assistantTextBlocks.get(index); + if (assistantBlock) { + assistantBlock.streamClosed = true; + yield* completeAssistantTextBlock(context, assistantBlock, { + rawMethod: "claude/stream_event/content_block_stop", + rawPayload: message, + }); + return; + } + const tool = context.inFlightTools.get(index); + if (!tool) { + return; + } + } + }); + + const handleUserMessage = Effect.fn("handleUserMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (message.type !== "user") { + return; + } + + if (context.turnState) { + context.turnState.items.push(message.message); + } + + for (const toolResult of toolResultBlocksFromUserMessage(message)) { + const toolEntry = Array.from(context.inFlightTools.entries()).find( + ([, tool]) => tool.itemId === toolResult.toolUseId, + ); + if (!toolEntry) { + continue; + } + + const [index, tool] = toolEntry; + const itemStatus = toolResult.isError ? "failed" : "completed"; + const toolData = { + toolName: tool.toolName, + input: tool.input, + result: toolResult.block, + }; + + const updatedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.updated", + eventId: updatedStamp.eventId, + provider: PROVIDER, + createdAt: updatedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + itemId: asRuntimeItemId(tool.itemId), + payload: { + itemType: tool.itemType, + status: toolResult.isError ? "failed" : "inProgress", + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + data: toolData, + }, + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/user", + payload: message, + }, + }); + + const streamKind = toolResultStreamKind(tool.itemType); + if (streamKind && toolResult.text.length > 0 && context.turnState) { + const deltaStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "content.delta", + eventId: deltaStamp.eventId, + provider: PROVIDER, + createdAt: deltaStamp.createdAt, + threadId: context.session.threadId, + turnId: context.turnState.turnId, + itemId: asRuntimeItemId(tool.itemId), + payload: { + streamKind, + delta: toolResult.text, + }, + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/user", + payload: message, + }, + }); + } + + const completedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.completed", + eventId: completedStamp.eventId, + provider: PROVIDER, + createdAt: completedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + itemId: asRuntimeItemId(tool.itemId), + payload: { + itemType: tool.itemType, + status: itemStatus, + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + data: toolData, + }, + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/user", + payload: message, + }, + }); + + context.inFlightTools.delete(index); + } + }); + + const handleAssistantMessage = Effect.fn("handleAssistantMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (message.type !== "assistant") { + return; + } + + // Auto-start a synthetic turn for assistant messages that arrive without + // an active turn (e.g., background agent/subagent responses between user prompts). + if (!context.turnState) { + const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4); + const startedAt = yield* nowIso; + context.turnState = { + turnId, + startedAt, + items: [], + assistantTextBlocks: new Map(), + assistantTextBlockOrder: [], + capturedProposedPlanKeys: new Set(), + nextSyntheticAssistantBlockIndex: -1, + }; + context.session = { + ...context.session, + status: "running", + activeTurnId: turnId, + updatedAt: startedAt, + }; + const turnStartedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.started", + eventId: turnStartedStamp.eventId, + provider: PROVIDER, + createdAt: turnStartedStamp.createdAt, + threadId: context.session.threadId, + turnId, + payload: {}, + providerRefs: { + ...nativeProviderRefs(context), + providerTurnId: turnId, + }, + raw: { + source: "claude.sdk.message", + method: "claude/synthetic-turn-start", + payload: {}, + }, + }); + } + + const content = message.message?.content; + if (Array.isArray(content)) { + for (const block of content) { + if (!block || typeof block !== "object") { + continue; + } + const toolUse = block as { + type?: unknown; + id?: unknown; + name?: unknown; + input?: unknown; + }; + if (toolUse.type !== "tool_use" || toolUse.name !== "ExitPlanMode") { + continue; + } + const planMarkdown = extractExitPlanModePlan(toolUse.input); + if (!planMarkdown) { + continue; + } + yield* emitProposedPlanCompleted(context, { + planMarkdown, + toolUseId: typeof toolUse.id === "string" ? toolUse.id : undefined, + rawSource: "claude.sdk.message", + rawMethod: "claude/assistant", + rawPayload: message, + }); + } + } + + if (context.turnState) { + context.turnState.items.push(message.message); + yield* backfillAssistantTextBlocksFromSnapshot(context, message); + } + + context.lastAssistantUuid = message.uuid; + yield* updateResumeCursor(context); + }); + + const handleResultMessage = Effect.fn("handleResultMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (message.type !== "result") { + return; + } + + const status = turnStatusFromResult(message); + const errorMessage = message.subtype === "success" ? undefined : message.errors[0]; + + if (status === "failed") { + yield* emitRuntimeError(context, errorMessage ?? "Claude turn failed."); + } + + yield* completeTurn(context, status, errorMessage, message); + }); + + const handleSystemMessage = Effect.fn("handleSystemMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (message.type !== "system") { + return; + } + + const stamp = yield* makeEventStamp(); + const base = { + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + providerRefs: nativeProviderRefs(context), + raw: { + source: "claude.sdk.message" as const, + method: sdkNativeMethod(message), + messageType: `${message.type}:${message.subtype}`, + payload: message, + }, + }; + + switch (message.subtype) { + case "init": + yield* offerRuntimeEvent({ + ...base, + type: "session.configured", + payload: { + config: message as Record, + }, + }); + return; + case "status": + yield* offerRuntimeEvent({ + ...base, + type: "session.state.changed", + payload: { + state: message.status === "compacting" ? "waiting" : "running", + reason: `status:${message.status ?? "active"}`, + detail: message, + }, + }); + return; + case "compact_boundary": + yield* offerRuntimeEvent({ + ...base, + type: "thread.state.changed", + payload: { + state: "compacted", + detail: message, + }, + }); + return; + case "hook_started": + yield* offerRuntimeEvent({ + ...base, + type: "hook.started", + payload: { + hookId: message.hook_id, + hookName: message.hook_name, + hookEvent: message.hook_event, + }, + }); + return; + case "hook_progress": + yield* offerRuntimeEvent({ + ...base, + type: "hook.progress", + payload: { + hookId: message.hook_id, + output: message.output, + stdout: message.stdout, + stderr: message.stderr, + }, + }); + return; + case "hook_response": + yield* offerRuntimeEvent({ + ...base, + type: "hook.completed", + payload: { + hookId: message.hook_id, + outcome: message.outcome, + output: message.output, + stdout: message.stdout, + stderr: message.stderr, + ...(typeof message.exit_code === "number" ? { exitCode: message.exit_code } : {}), + }, + }); + return; + case "task_started": + yield* offerRuntimeEvent({ + ...base, + type: "task.started", + payload: { + taskId: RuntimeTaskId.makeUnsafe(message.task_id), + description: message.description, + ...(message.task_type ? { taskType: message.task_type } : {}), + }, + }); + return; + case "task_progress": + if (message.usage) { + const normalizedUsage = normalizeClaudeTokenUsage( + message.usage, + context.lastKnownContextWindow, + ); + if (normalizedUsage) { + context.lastKnownTokenUsage = normalizedUsage; + const usageStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + ...base, + eventId: usageStamp.eventId, + createdAt: usageStamp.createdAt, + type: "thread.token-usage.updated", + payload: { + usage: normalizedUsage, + }, + }); + } + } + yield* offerRuntimeEvent({ + ...base, + type: "task.progress", + payload: { + taskId: RuntimeTaskId.makeUnsafe(message.task_id), + description: message.description, + ...(message.summary ? { summary: message.summary } : {}), + ...(message.usage ? { usage: message.usage } : {}), + ...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}), + }, + }); + return; + case "task_notification": + if (message.usage) { + const normalizedUsage = normalizeClaudeTokenUsage( + message.usage, + context.lastKnownContextWindow, + ); + if (normalizedUsage) { + context.lastKnownTokenUsage = normalizedUsage; + const usageStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + ...base, + eventId: usageStamp.eventId, + createdAt: usageStamp.createdAt, + type: "thread.token-usage.updated", + payload: { + usage: normalizedUsage, + }, + }); + } + } + yield* offerRuntimeEvent({ + ...base, + type: "task.completed", + payload: { + taskId: RuntimeTaskId.makeUnsafe(message.task_id), + status: message.status, + ...(message.summary ? { summary: message.summary } : {}), + ...(message.usage ? { usage: message.usage } : {}), + }, + }); + return; + case "files_persisted": + yield* offerRuntimeEvent({ + ...base, + type: "files.persisted", + payload: { + files: Array.isArray(message.files) + ? message.files.map((file: { filename: string; file_id: string }) => ({ + filename: file.filename, + fileId: file.file_id, + })) + : [], + ...(Array.isArray(message.failed) + ? { + failed: message.failed.map((entry: { filename: string; error: string }) => ({ + filename: entry.filename, + error: entry.error, + })), + } + : {}), + }, + }); + return; + default: + yield* emitRuntimeWarning( + context, + `Unhandled Claude system message subtype '${message.subtype}'.`, + message, + ); + return; + } + }); + + const handleSdkTelemetryMessage = Effect.fn("handleSdkTelemetryMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + const stamp = yield* makeEventStamp(); + const base = { + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + providerRefs: nativeProviderRefs(context), + raw: { + source: "claude.sdk.message" as const, + method: sdkNativeMethod(message), + messageType: message.type, + payload: message, + }, + }; + + if (message.type === "tool_progress") { + yield* offerRuntimeEvent({ + ...base, + type: "tool.progress", + payload: { + toolUseId: message.tool_use_id, + toolName: message.tool_name, + elapsedSeconds: message.elapsed_time_seconds, + ...(message.task_id ? { summary: `task:${message.task_id}` } : {}), + }, + }); + return; + } + + if (message.type === "tool_use_summary") { + yield* offerRuntimeEvent({ + ...base, + type: "tool.summary", + payload: { + summary: message.summary, + ...(message.preceding_tool_use_ids.length > 0 + ? { precedingToolUseIds: message.preceding_tool_use_ids } + : {}), + }, + }); + return; + } + + if (message.type === "auth_status") { + yield* offerRuntimeEvent({ + ...base, + type: "auth.status", + payload: { + isAuthenticating: message.isAuthenticating, + output: message.output, + ...(message.error ? { error: message.error } : {}), + }, + }); + return; + } + + if (message.type === "rate_limit_event") { + yield* offerRuntimeEvent({ + ...base, + type: "account.rate-limits.updated", + payload: { + rateLimits: message, + }, + }); + return; + } + }); + + const handleSdkMessage = Effect.fn("handleSdkMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + yield* logNativeSdkMessage(context, message); + yield* ensureThreadId(context, message); + + switch (message.type) { + case "stream_event": + yield* handleStreamEvent(context, message); + return; + case "user": + yield* handleUserMessage(context, message); + return; + case "assistant": + yield* handleAssistantMessage(context, message); + return; + case "result": + yield* handleResultMessage(context, message); + return; + case "system": + yield* handleSystemMessage(context, message); + return; + case "tool_progress": + case "tool_use_summary": + case "auth_status": + case "rate_limit_event": + yield* handleSdkTelemetryMessage(context, message); + return; + default: + yield* emitRuntimeWarning( + context, + `Unhandled Claude SDK message type '${message.type}'.`, + message, + ); + return; + } + }); + + const runSdkStream = (context: ClaudeSessionContext): Effect.Effect => + Stream.fromAsyncIterable(context.query, (cause) => + toError(cause, "Claude runtime stream failed."), + ).pipe( + Stream.takeWhile(() => !context.stopped), + Stream.runForEach((message) => handleSdkMessage(context, message)), + ); + + const handleStreamExit = Effect.fn("handleStreamExit")(function* ( + context: ClaudeSessionContext, + exit: Exit.Exit, + ) { + if (context.stopped) { + return; + } + + if (Exit.isFailure(exit)) { + if (isClaudeInterruptedCause(exit.cause)) { + if (context.turnState) { + yield* completeTurn( + context, + "interrupted", + interruptionMessageFromClaudeCause(exit.cause), + ); + } + } else { + const message = messageFromClaudeStreamCause(exit.cause, "Claude runtime stream failed."); + yield* emitRuntimeError(context, message, Cause.pretty(exit.cause)); + yield* completeTurn(context, "failed", message); + } + } else if (context.turnState) { + yield* completeTurn(context, "interrupted", "Claude runtime stream ended."); + } + + yield* stopSessionInternal(context, { + emitExitEvent: true, + }); + }); + + const stopSessionInternal = Effect.fn("stopSessionInternal")(function* ( + context: ClaudeSessionContext, + options?: { readonly emitExitEvent?: boolean }, + ) { + if (context.stopped) return; + + context.stopped = true; + + for (const [requestId, pending] of context.pendingApprovals) { + yield* Deferred.succeed(pending.decision, "cancel"); + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "request.resolved", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + requestId: asRuntimeRequestId(requestId), + payload: { + requestType: pending.requestType, + decision: "cancel", + }, + providerRefs: nativeProviderRefs(context), + }); + } + context.pendingApprovals.clear(); + + if (context.turnState) { + yield* completeTurn(context, "interrupted", "Session stopped."); + } + + yield* Queue.shutdown(context.promptQueue); + + const streamFiber = context.streamFiber; + context.streamFiber = undefined; + if (streamFiber && streamFiber.pollUnsafe() === undefined) { + yield* Fiber.interrupt(streamFiber); + } + + // @effect-diagnostics-next-line tryCatchInEffectGen:off + try { + context.query.close(); + } catch (cause) { + yield* emitRuntimeError(context, "Failed to close Claude runtime query.", cause); + } + + const updatedAt = yield* nowIso; + context.session = { + ...context.session, + status: "closed", + activeTurnId: undefined, + updatedAt, + }; + + if (options?.emitExitEvent !== false) { + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "session.exited", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + payload: { + reason: "Session stopped", + exitKind: "graceful", + }, + providerRefs: {}, + }); + } + + sessions.delete(context.session.threadId); + }); + + const requireSession = ( + threadId: ThreadId, + ): Effect.Effect => { + const context = sessions.get(threadId); + if (!context) { + return Effect.fail( + new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId, + }), + ); + } + if (context.stopped || context.session.status === "closed") { + return Effect.fail( + new ProviderAdapterSessionClosedError({ + provider: PROVIDER, + threadId, + }), + ); + } + return Effect.succeed(context); + }; + + const startSession: ClaudeAdapterShape["startSession"] = Effect.fn("startSession")( + function* (input) { + if (input.provider !== undefined && input.provider !== PROVIDER) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "startSession", + issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, + }); + } + + const startedAt = yield* nowIso; + const resumeState = readClaudeResumeState(input.resumeCursor); + const threadId = input.threadId; + const existingResumeSessionId = resumeState?.resume; + const newSessionId = + existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined; + const sessionId = existingResumeSessionId ?? newSessionId; + + const services = yield* Effect.services(); + const runFork = Effect.runForkWith(services); + const runPromise = Effect.runPromiseWith(services); + + const promptQueue = yield* Queue.unbounded(); + const prompt = Stream.fromQueue(promptQueue).pipe( + Stream.filter((item) => item.type === "message"), + Stream.map((item) => item.message), + Stream.catchCause((cause) => + Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause), + ), + Stream.toAsyncIterable, + ); + + const pendingApprovals = new Map(); + const pendingUserInputs = new Map(); + const inFlightTools = new Map(); + + const contextRef = yield* Ref.make(undefined); + + /** + * Handle AskUserQuestion tool calls by emitting a `user-input.requested` + * runtime event and waiting for the user to respond via `respondToUserInput`. + */ + const handleAskUserQuestion = Effect.fn("handleAskUserQuestion")(function* ( + context: ClaudeSessionContext, + toolInput: Record, + callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string }, + ) { + const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4); + + // Parse questions from the SDK's AskUserQuestion input. + const rawQuestions = Array.isArray(toolInput.questions) ? toolInput.questions : []; + const questions: Array = rawQuestions.map( + (q: Record, idx: number) => ({ + id: typeof q.header === "string" ? q.header : `q-${idx}`, + header: typeof q.header === "string" ? q.header : `Question ${idx + 1}`, + question: typeof q.question === "string" ? q.question : "", + options: Array.isArray(q.options) + ? q.options.map((opt: Record) => ({ + label: typeof opt.label === "string" ? opt.label : "", + description: typeof opt.description === "string" ? opt.description : "", + })) + : [], + multiSelect: typeof q.multiSelect === "boolean" ? q.multiSelect : false, + }), + ); + + const answersDeferred = yield* Deferred.make(); + let aborted = false; + const pendingInput: PendingUserInput = { + questions, + answers: answersDeferred, + }; + + // Emit user-input.requested so the UI can present the questions. + const requestedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "user-input.requested", + eventId: requestedStamp.eventId, + provider: PROVIDER, + createdAt: requestedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + requestId: asRuntimeRequestId(requestId), + payload: { questions }, + providerRefs: nativeProviderRefs(context, { + providerItemId: callbackOptions.toolUseID, + }), + raw: { + source: "claude.sdk.permission", + method: "canUseTool/AskUserQuestion", + payload: { toolName: "AskUserQuestion", input: toolInput }, + }, + }); + + pendingUserInputs.set(requestId, pendingInput); + + // Handle abort (e.g. turn interrupted while waiting for user input). + const onAbort = () => { + if (!pendingUserInputs.has(requestId)) { + return; + } + aborted = true; + pendingUserInputs.delete(requestId); + runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers)); + }; + callbackOptions.signal.addEventListener("abort", onAbort, { once: true }); + + // Block until the user provides answers. + const answers = yield* Deferred.await(answersDeferred); + pendingUserInputs.delete(requestId); + + // Emit user-input.resolved so the UI knows the interaction completed. + const resolvedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "user-input.resolved", + eventId: resolvedStamp.eventId, + provider: PROVIDER, + createdAt: resolvedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + requestId: asRuntimeRequestId(requestId), + payload: { answers }, + providerRefs: nativeProviderRefs(context, { + providerItemId: callbackOptions.toolUseID, + }), + raw: { + source: "claude.sdk.permission", + method: "canUseTool/AskUserQuestion/resolved", + payload: { answers }, + }, + }); + + if (aborted) { + return { + behavior: "deny", + message: "User cancelled tool execution.", + } satisfies PermissionResult; + } + + // Return the answers to the SDK in the expected format: + // { questions: [...], answers: { questionText: selectedLabel } } + return { + behavior: "allow", + updatedInput: { + questions: toolInput.questions, + answers, + }, + } satisfies PermissionResult; + }); + + const canUseToolEffect = Effect.fn("canUseTool")(function* ( + toolName: Parameters[0], + toolInput: Parameters[1], + callbackOptions: Parameters[2], + ) { + const context = yield* Ref.get(contextRef); + if (!context) { + return { + behavior: "deny", + message: "Claude session context is unavailable.", + } satisfies PermissionResult; + } + + // Handle AskUserQuestion: surface clarifying questions to the + // user via the user-input runtime event channel, regardless of + // runtime mode (plan mode relies on this heavily). + if (toolName === "AskUserQuestion") { + return yield* handleAskUserQuestion(context, toolInput, callbackOptions); + } + + if (toolName === "ExitPlanMode") { + const planMarkdown = extractExitPlanModePlan(toolInput); + if (planMarkdown) { + yield* emitProposedPlanCompleted(context, { + planMarkdown, + toolUseId: callbackOptions.toolUseID, + rawSource: "claude.sdk.permission", + rawMethod: "canUseTool/ExitPlanMode", + rawPayload: { + toolName, + input: toolInput, + }, + }); + } + + return { + behavior: "deny", + message: + "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.", + } satisfies PermissionResult; + } + + const runtimeMode = input.runtimeMode ?? "full-access"; + if (runtimeMode === "full-access") { + return { + behavior: "allow", + updatedInput: toolInput, + } satisfies PermissionResult; + } + + const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4); + const requestType = classifyRequestType(toolName); + const detail = summarizeToolRequest(toolName, toolInput); + const decisionDeferred = yield* Deferred.make(); + const pendingApproval: PendingApproval = { + requestType, + detail, + decision: decisionDeferred, + ...(callbackOptions.suggestions ? { suggestions: callbackOptions.suggestions } : {}), + }; + + const requestedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "request.opened", + eventId: requestedStamp.eventId, + provider: PROVIDER, + createdAt: requestedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + requestId: asRuntimeRequestId(requestId), + payload: { + requestType, + detail, + args: { + toolName, + input: toolInput, + ...(callbackOptions.toolUseID ? { toolUseId: callbackOptions.toolUseID } : {}), + }, + }, + providerRefs: nativeProviderRefs(context, { + providerItemId: callbackOptions.toolUseID, + }), + raw: { + source: "claude.sdk.permission", + method: "canUseTool/request", + payload: { + toolName, + input: toolInput, + }, + }, + }); + + pendingApprovals.set(requestId, pendingApproval); + + const onAbort = () => { + if (!pendingApprovals.has(requestId)) { + return; + } + pendingApprovals.delete(requestId); + runFork(Deferred.succeed(decisionDeferred, "cancel")); + }; + + callbackOptions.signal.addEventListener("abort", onAbort, { + once: true, + }); + + const decision = yield* Deferred.await(decisionDeferred); + pendingApprovals.delete(requestId); + + const resolvedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "request.resolved", + eventId: resolvedStamp.eventId, + provider: PROVIDER, + createdAt: resolvedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + requestId: asRuntimeRequestId(requestId), + payload: { + requestType, + decision, + }, + providerRefs: nativeProviderRefs(context, { + providerItemId: callbackOptions.toolUseID, + }), + raw: { + source: "claude.sdk.permission", + method: "canUseTool/decision", + payload: { + decision, + }, + }, + }); + + if (decision === "accept" || decision === "acceptForSession") { + return { + behavior: "allow", + updatedInput: toolInput, + ...(decision === "acceptForSession" && pendingApproval.suggestions + ? { updatedPermissions: [...pendingApproval.suggestions] } + : {}), + } satisfies PermissionResult; + } + + return { + behavior: "deny", + message: + decision === "cancel" + ? "User cancelled tool execution." + : "User declined tool execution.", + } satisfies PermissionResult; + }); + + const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) => + runPromise(canUseToolEffect(toolName, toolInput, callbackOptions)); + + const claudeSettings = yield* serverSettingsService.getSettings.pipe( + Effect.map((settings) => settings.providers.claudeAgent), + Effect.mapError( + (error) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId: input.threadId, + detail: error.message, + cause: error, + }), + ), + ); + const claudeBinaryPath = claudeSettings.binaryPath; + const modelSelection = + input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined; + const caps = getClaudeModelCapabilities(modelSelection?.model); + const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined; + const effort = (resolveEffort(caps, modelSelection?.options?.effort) ?? + null) as ClaudeCodeEffort | null; + const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode; + const thinking = + typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle + ? modelSelection.options.thinking + : undefined; + const effectiveEffort = getEffectiveClaudeCodeEffort(effort); + const permissionMode = input.runtimeMode === "full-access" ? "bypassPermissions" : undefined; + const settings = { + ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}), + ...(fastMode ? { fastMode: true } : {}), + }; + + const queryOptions: ClaudeQueryOptions = { + ...(input.cwd ? { cwd: input.cwd } : {}), + ...(apiModelId ? { model: apiModelId } : {}), + pathToClaudeCodeExecutable: claudeBinaryPath, + settingSources: [...CLAUDE_SETTING_SOURCES], + ...(effectiveEffort ? { effort: effectiveEffort } : {}), + ...(permissionMode ? { permissionMode } : {}), + ...(permissionMode === "bypassPermissions" + ? { allowDangerouslySkipPermissions: true } + : {}), + ...(Object.keys(settings).length > 0 ? { settings } : {}), + ...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}), + ...(newSessionId ? { sessionId: newSessionId } : {}), + includePartialMessages: true, + canUseTool, + env: process.env, + ...(input.cwd ? { additionalDirectories: [input.cwd] } : {}), + }; + + const queryRuntime = yield* Effect.try({ + try: () => + createQuery({ + prompt, + options: queryOptions, + }), + catch: (cause) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId, + detail: toMessage(cause, "Failed to start Claude runtime session."), + cause, + }), + }); + + const session: ProviderSession = { + threadId, + provider: PROVIDER, + status: "ready", + runtimeMode: input.runtimeMode, + ...(input.cwd ? { cwd: input.cwd } : {}), + ...(modelSelection?.model ? { model: modelSelection.model } : {}), + ...(threadId ? { threadId } : {}), + resumeCursor: { + ...(threadId ? { threadId } : {}), + ...(sessionId ? { resume: sessionId } : {}), + ...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}), + turnCount: resumeState?.turnCount ?? 0, + }, + createdAt: startedAt, + updatedAt: startedAt, + }; + + const context: ClaudeSessionContext = { + session, + promptQueue, + query: queryRuntime, + streamFiber: undefined, + startedAt, + basePermissionMode: permissionMode, + currentApiModelId: apiModelId, + resumeSessionId: sessionId, + pendingApprovals, + pendingUserInputs, + turns: [], + inFlightTools, + turnState: undefined, + lastKnownContextWindow: undefined, + lastKnownTokenUsage: undefined, + lastAssistantUuid: resumeState?.resumeSessionAt, + lastThreadStartedId: undefined, + stopped: false, + }; + yield* Ref.set(contextRef, context); + sessions.set(threadId, context); + + const sessionStartedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "session.started", + eventId: sessionStartedStamp.eventId, + provider: PROVIDER, + createdAt: sessionStartedStamp.createdAt, + threadId, + payload: input.resumeCursor !== undefined ? { resume: input.resumeCursor } : {}, + providerRefs: {}, + }); + + const configuredStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "session.configured", + eventId: configuredStamp.eventId, + provider: PROVIDER, + createdAt: configuredStamp.createdAt, + threadId, + payload: { + config: { + ...(apiModelId ? { model: apiModelId } : {}), + ...(input.cwd ? { cwd: input.cwd } : {}), + ...(effectiveEffort ? { effort: effectiveEffort } : {}), + ...(permissionMode ? { permissionMode } : {}), + ...(fastMode ? { fastMode: true } : {}), + }, + }, + providerRefs: {}, + }); + + const readyStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "session.state.changed", + eventId: readyStamp.eventId, + provider: PROVIDER, + createdAt: readyStamp.createdAt, + threadId, + payload: { + state: "ready", + }, + providerRefs: {}, + }); + + let streamFiber: Fiber.Fiber; + streamFiber = runFork( + Effect.exit(runSdkStream(context)).pipe( + Effect.flatMap((exit) => { + if (context.stopped) { + return Effect.void; + } + if (context.streamFiber === streamFiber) { + context.streamFiber = undefined; + } + return handleStreamExit(context, exit); + }), + ), + ); + context.streamFiber = streamFiber; + streamFiber.addObserver(() => { + if (context.streamFiber === streamFiber) { + context.streamFiber = undefined; + } + }); + + return { + ...session, + }; + }, + ); + + const sendTurn: ClaudeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) { + const context = yield* requireSession(input.threadId); + const modelSelection = + input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined; + + if (context.turnState) { + // Auto-close a stale synthetic turn (from background agent responses + // between user prompts) to prevent blocking the user's next turn. + yield* completeTurn(context, "completed"); + } + + if (modelSelection?.model) { + const apiModelId = resolveApiModelId(modelSelection); + if (context.currentApiModelId !== apiModelId) { + yield* Effect.tryPromise({ + try: () => context.query.setModel(apiModelId), + catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause), + }); + context.currentApiModelId = apiModelId; + } + context.session = { + ...context.session, + model: modelSelection.model, + }; + } + + // Apply interaction mode by switching the SDK's permission mode. + // "plan" maps directly to the SDK's "plan" permission mode; + // "default" restores the session's original permission mode. + // When interactionMode is absent we leave the current mode unchanged. + if (input.interactionMode === "plan") { + yield* Effect.tryPromise({ + try: () => context.query.setPermissionMode("plan"), + catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause), + }); + } else if (input.interactionMode === "default") { + yield* Effect.tryPromise({ + try: () => + context.query.setPermissionMode(context.basePermissionMode ?? "bypassPermissions"), + catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause), + }); + } + + const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4); + const turnState: ClaudeTurnState = { + turnId, + startedAt: yield* nowIso, + items: [], + assistantTextBlocks: new Map(), + assistantTextBlockOrder: [], + capturedProposedPlanKeys: new Set(), + nextSyntheticAssistantBlockIndex: -1, + }; + + const updatedAt = yield* nowIso; + context.turnState = turnState; + context.session = { + ...context.session, + status: "running", + activeTurnId: turnId, + updatedAt, + }; + + const turnStartedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.started", + eventId: turnStartedStamp.eventId, + provider: PROVIDER, + createdAt: turnStartedStamp.createdAt, + threadId: context.session.threadId, + turnId, + payload: modelSelection?.model ? { model: modelSelection.model } : {}, + providerRefs: {}, + }); + + const message = yield* buildUserMessageEffect(input, { + fileSystem, + attachmentsDir: serverConfig.attachmentsDir, + }); + + yield* Queue.offer(context.promptQueue, { + type: "message", + message, + }).pipe(Effect.mapError((cause) => toRequestError(input.threadId, "turn/start", cause))); + + return { + threadId: context.session.threadId, + turnId, + ...(context.session.resumeCursor !== undefined + ? { resumeCursor: context.session.resumeCursor } + : {}), + }; + }); + + const interruptTurn: ClaudeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")( + function* (threadId, _turnId) { + const context = yield* requireSession(threadId); + yield* Effect.tryPromise({ + try: () => context.query.interrupt(), + catch: (cause) => toRequestError(threadId, "turn/interrupt", cause), + }); + }, + ); + + const readThread: ClaudeAdapterShape["readThread"] = Effect.fn("readThread")( + function* (threadId) { + const context = yield* requireSession(threadId); + return yield* snapshotThread(context); + }, + ); + + const rollbackThread: ClaudeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")( + function* (threadId, numTurns) { + const context = yield* requireSession(threadId); + const nextLength = Math.max(0, context.turns.length - numTurns); + context.turns.splice(nextLength); + yield* updateResumeCursor(context); + return yield* snapshotThread(context); + }, + ); + + const respondToRequest: ClaudeAdapterShape["respondToRequest"] = Effect.fn("respondToRequest")( + function* (threadId, requestId, decision) { + const context = yield* requireSession(threadId); + const pending = context.pendingApprovals.get(requestId); + if (!pending) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "item/requestApproval/decision", + detail: `Unknown pending approval request: ${requestId}`, + }); + } + + context.pendingApprovals.delete(requestId); + yield* Deferred.succeed(pending.decision, decision); + }, + ); + + const respondToUserInput: ClaudeAdapterShape["respondToUserInput"] = Effect.fn( + "respondToUserInput", + )(function* (threadId, requestId, answers) { + const context = yield* requireSession(threadId); + const pending = context.pendingUserInputs.get(requestId); + if (!pending) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "item/tool/respondToUserInput", + detail: `Unknown pending user-input request: ${requestId}`, + }); + } + + context.pendingUserInputs.delete(requestId); + yield* Deferred.succeed(pending.answers, answers); + }); + + const stopSession: ClaudeAdapterShape["stopSession"] = Effect.fn("stopSession")( + function* (threadId) { + const context = yield* requireSession(threadId); + yield* stopSessionInternal(context, { + emitExitEvent: true, + }); + }, + ); + + const listSessions: ClaudeAdapterShape["listSessions"] = () => + Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session }))); + + const hasSession: ClaudeAdapterShape["hasSession"] = (threadId) => + Effect.sync(() => { + const context = sessions.get(threadId); + return context !== undefined && !context.stopped; + }); + + const stopAll: ClaudeAdapterShape["stopAll"] = () => + Effect.forEach( + sessions, + ([, context]) => + stopSessionInternal(context, { + emitExitEvent: true, + }), + { discard: true }, + ); + + yield* Effect.addFinalizer(() => + Effect.forEach( + sessions, + ([, context]) => + stopSessionInternal(context, { + emitExitEvent: false, + }), + { discard: true }, + ).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))), + ); + + return { + provider: PROVIDER, + capabilities: { + sessionModelSwitch: "in-session", + }, + startSession, + sendTurn, + interruptTurn, + readThread, + rollbackThread, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + hasSession, + stopAll, + streamEvents: Stream.fromQueue(runtimeEventQueue), + } satisfies ClaudeAdapterShape; +}); + +export const ClaudeAdapterLive = Layer.effect(ClaudeAdapter, makeClaudeAdapter()); + +export function makeClaudeAdapterLive(options?: ClaudeAdapterLiveOptions) { + return Layer.effect(ClaudeAdapter, makeClaudeAdapter(options)); +} diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts new file mode 100644 index 0000000000..761b795fe5 --- /dev/null +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -0,0 +1,650 @@ +import type { + ClaudeSettings, + ModelCapabilities, + ServerProvider, + ServerProviderModel, + ServerProviderAuth, + ServerProviderState, +} from "@t3tools/contracts"; +import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; +import { decodeJsonResult } from "@t3tools/shared/schemaJson"; +import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk"; + +import { + buildServerProvider, + DEFAULT_TIMEOUT_MS, + detailFromResult, + extractAuthBoolean, + isCommandMissingCause, + parseGenericCliVersion, + providerModelsFromSettings, + spawnAndCollect, + type CommandResult, +} from "../providerSnapshot"; +import { makeManagedServerProvider } from "../makeManagedServerProvider"; +import { ClaudeProvider } from "../Services/ClaudeProvider"; +import { ServerSettingsService } from "../../serverSettings"; +import { ServerSettingsError } from "@t3tools/contracts"; + +const PROVIDER = "claudeAgent" as const; +const BUILT_IN_MODELS: ReadonlyArray = [ + { + slug: "claude-opus-4-6", + name: "Claude Opus 4.6", + isCustom: false, + capabilities: { + reasoningEffortLevels: [ + { value: "low", label: "Low" }, + { value: "medium", label: "Medium" }, + { value: "high", label: "High", isDefault: true }, + { value: "max", label: "Max" }, + { value: "ultrathink", label: "Ultrathink" }, + ], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [ + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, + ], + promptInjectedEffortLevels: ["ultrathink"], + } satisfies ModelCapabilities, + }, + { + slug: "claude-sonnet-4-6", + name: "Claude Sonnet 4.6", + isCustom: false, + capabilities: { + reasoningEffortLevels: [ + { value: "low", label: "Low" }, + { value: "medium", label: "Medium" }, + { value: "high", label: "High", isDefault: true }, + { value: "ultrathink", label: "Ultrathink" }, + ], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [ + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, + ], + promptInjectedEffortLevels: ["ultrathink"], + } satisfies ModelCapabilities, + }, + { + slug: "claude-haiku-4-5", + name: "Claude Haiku 4.5", + isCustom: false, + capabilities: { + reasoningEffortLevels: [], + supportsFastMode: false, + supportsThinkingToggle: true, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + } satisfies ModelCapabilities, + }, +]; + +export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities { + const slug = model?.trim(); + return ( + BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? { + reasoningEffortLevels: [], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + } + ); +} + +export function parseClaudeAuthStatusFromOutput(result: CommandResult): { + readonly status: Exclude; + readonly auth: Pick; + readonly message?: string; +} { + const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase(); + + if ( + lowerOutput.includes("unknown command") || + lowerOutput.includes("unrecognized command") || + lowerOutput.includes("unexpected argument") + ) { + return { + status: "warning", + auth: { status: "unknown" }, + message: + "Claude Agent authentication status command is unavailable in this version of Claude.", + }; + } + + if ( + lowerOutput.includes("not logged in") || + lowerOutput.includes("login required") || + lowerOutput.includes("authentication required") || + lowerOutput.includes("run `claude login`") || + lowerOutput.includes("run claude login") + ) { + return { + status: "error", + auth: { status: "unauthenticated" }, + message: "Claude is not authenticated. Run `claude auth login` and try again.", + }; + } + + const parsedAuth = (() => { + const trimmed = result.stdout.trim(); + if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) { + return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined }; + } + try { + return { + attemptedJsonParse: true as const, + auth: extractAuthBoolean(JSON.parse(trimmed)), + }; + } catch { + return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined }; + } + })(); + + if (parsedAuth.auth === true) { + return { status: "ready", auth: { status: "authenticated" } }; + } + if (parsedAuth.auth === false) { + return { + status: "error", + auth: { status: "unauthenticated" }, + message: "Claude is not authenticated. Run `claude auth login` and try again.", + }; + } + if (parsedAuth.attemptedJsonParse) { + return { + status: "warning", + auth: { status: "unknown" }, + message: + "Could not verify Claude authentication status from JSON output (missing auth marker).", + }; + } + if (result.code === 0) { + return { status: "ready", auth: { status: "authenticated" } }; + } + + const detail = detailFromResult(result); + return { + status: "warning", + auth: { status: "unknown" }, + message: detail + ? `Could not verify Claude authentication status. ${detail}` + : "Could not verify Claude authentication status.", + }; +} + +// ── Subscription type detection ───────────────────────────────────── +// +// The SDK probe returns typed `AccountInfo.subscriptionType` directly. +// This walker is a best-effort fallback for the `claude auth status` +// JSON output whose shape is not guaranteed. + +/** Keys that directly hold a subscription/plan identifier. */ +const SUBSCRIPTION_TYPE_KEYS = [ + "subscriptionType", + "subscription_type", + "plan", + "tier", + "planType", + "plan_type", +] as const; + +/** Keys whose value may be a nested object containing subscription info. */ +const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const; +const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const; +const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const; + +/** Lift an unknown value into `Option` if it is a non-empty string. */ +const asNonEmptyString = (v: unknown): Option.Option => + typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none(); + +/** Lift an unknown value into `Option` if it is a plain object. */ +const asRecord = (v: unknown): Option.Option> => + typeof v === "object" && v !== null && !globalThis.Array.isArray(v) + ? Option.some(v as Record) + : Option.none(); + +/** + * Walk an unknown parsed JSON value looking for a subscription/plan + * identifier, returning the first match as an `Option`. + */ +function findSubscriptionType(value: unknown): Option.Option { + if (globalThis.Array.isArray(value)) { + return Option.firstSomeOf(value.map(findSubscriptionType)); + } + + return asRecord(value).pipe( + Option.flatMap((record) => { + const direct = Option.firstSomeOf( + SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])), + ); + if (Option.isSome(direct)) return direct; + + return Option.firstSomeOf( + SUBSCRIPTION_CONTAINER_KEYS.map((key) => + asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)), + ), + ); + }), + ); +} + +function findAuthMethod(value: unknown): Option.Option { + if (globalThis.Array.isArray(value)) { + return Option.firstSomeOf(value.map(findAuthMethod)); + } + + return asRecord(value).pipe( + Option.flatMap((record) => { + const direct = Option.firstSomeOf( + AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])), + ); + if (Option.isSome(direct)) return direct; + + return Option.firstSomeOf( + AUTH_METHOD_CONTAINER_KEYS.map((key) => + asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)), + ), + ); + }), + ); +} + +/** + * Try to extract a subscription type from the `claude auth status` JSON + * output. This is a zero-cost operation on data we already have. + */ +const decodeUnknownJson = decodeJsonResult(Schema.Unknown); + +function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined { + const parsed = decodeUnknownJson(result.stdout.trim()); + if (Result.isFailure(parsed)) return undefined; + return Option.getOrUndefined(findSubscriptionType(parsed.success)); +} + +function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined { + const parsed = decodeUnknownJson(result.stdout.trim()); + if (Result.isFailure(parsed)) return undefined; + return Option.getOrUndefined(findAuthMethod(parsed.success)); +} + +// ── Dynamic model capability adjustment ───────────────────────────── + +/** Subscription types where the 1M context window is included in the plan. */ +const PREMIUM_SUBSCRIPTION_TYPES = new Set([ + "max", + "maxplan", + "max5", + "max20", + "enterprise", + "team", +]); + +function toTitleCaseWords(value: string): string { + return value + .split(/[\s_-]+/g) + .filter(Boolean) + .map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase()) + .join(" "); +} + +function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined { + const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, ""); + if (!normalized) return undefined; + + switch (normalized) { + case "max": + case "maxplan": + case "max5": + case "max20": + return "Max"; + case "enterprise": + return "Enterprise"; + case "team": + return "Team"; + case "pro": + return "Pro"; + case "free": + return "Free"; + default: + return toTitleCaseWords(subscriptionType!); + } +} + +function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined { + const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, ""); + if (!normalized) return undefined; + if (normalized === "apikey") return "apiKey"; + return undefined; +} + +function claudeAuthMetadata(input: { + readonly subscriptionType: string | undefined; + readonly authMethod: string | undefined; +}): { readonly type: string; readonly label: string } | undefined { + if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") { + return { + type: "apiKey", + label: "Claude API Key", + }; + } + + if (input.subscriptionType) { + const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType); + return { + type: input.subscriptionType, + label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`, + }; + } + + return undefined; +} + +/** + * Adjust the built-in model list based on the user's detected subscription. + * + * - Premium tiers (Max, Enterprise, Team): 1M context becomes the default. + * - Other tiers (Pro, free, unknown): 200k context stays the default; + * 1M remains available as a manual option so users can still enable it. + */ +export function adjustModelsForSubscription( + baseModels: ReadonlyArray, + subscriptionType: string | undefined, +): ReadonlyArray { + const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, ""); + if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) { + return baseModels; + } + + // Flip 1M to be the default for premium users + return baseModels.map((model) => { + const caps = model.capabilities; + if (!caps || caps.contextWindowOptions.length === 0) return model; + + return { + ...model, + capabilities: { + ...caps, + contextWindowOptions: caps.contextWindowOptions.map((opt) => + opt.value === "1m" + ? { value: opt.value, label: opt.label, isDefault: true as const } + : { value: opt.value, label: opt.label }, + ), + }, + }; + }); +} + +// ── SDK capability probe ──────────────────────────────────────────── + +const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000; + +/** + * Probe account information by spawning a lightweight Claude Agent SDK + * session and reading the initialization result. + * + * The prompt is never sent to the Anthropic API — we abort immediately + * after the local initialization phase completes. This gives us the + * user's subscription type without incurring any token cost. + * + * This is used as a fallback when `claude auth status` does not include + * subscription type information. + */ +const probeClaudeCapabilities = (binaryPath: string) => { + const abort = new AbortController(); + return Effect.tryPromise(async () => { + const q = claudeQuery({ + prompt: ".", + options: { + persistSession: false, + pathToClaudeCodeExecutable: binaryPath, + abortController: abort, + maxTurns: 0, + settingSources: [], + allowedTools: [], + stderr: () => {}, + }, + }); + const init = await q.initializationResult(); + return { subscriptionType: init.account?.subscriptionType }; + }).pipe( + Effect.ensuring( + Effect.sync(() => { + if (!abort.signal.aborted) abort.abort(); + }), + ), + Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS), + Effect.result, + Effect.map((result) => { + if (Result.isFailure(result)) return undefined; + return Option.isSome(result.success) ? result.success.value : undefined; + }), + ); +}; + +const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray) { + const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( + Effect.flatMap((service) => service.getSettings), + Effect.map((settings) => settings.providers.claudeAgent), + ); + const command = ChildProcess.make(claudeSettings.binaryPath, [...args], { + shell: process.platform === "win32", + }); + return yield* spawnAndCollect(claudeSettings.binaryPath, command); +}); + +export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* ( + resolveSubscriptionType?: (binaryPath: string) => Effect.Effect, +): Effect.fn.Return< + ServerProvider, + ServerSettingsError, + ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService +> { + const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( + Effect.flatMap((service) => service.getSettings), + Effect.map((settings) => settings.providers.claudeAgent), + ); + const checkedAt = new Date().toISOString(); + const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels); + + if (!claudeSettings.enabled) { + return buildServerProvider({ + provider: PROVIDER, + enabled: false, + checkedAt, + models, + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Claude is disabled in T3 Code settings.", + }, + }); + } + + const versionProbe = yield* runClaudeCommand(["--version"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); + + if (Result.isFailure(versionProbe)) { + const error = versionProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models, + probe: { + installed: !isCommandMissingCause(error), + version: null, + status: "error", + auth: { status: "unknown" }, + message: isCommandMissingCause(error) + ? "Claude Agent CLI (`claude`) is not installed or not on PATH." + : `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`, + }, + }); + } + + if (Option.isNone(versionProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: + "Claude Agent CLI is installed but failed to run. Timed out while running command.", + }, + }); + } + + const version = versionProbe.success.value; + const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); + if (version.code !== 0) { + const detail = detailFromResult(version); + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: parsedVersion, + status: "error", + auth: { status: "unknown" }, + message: detail + ? `Claude Agent CLI is installed but failed to run. ${detail}` + : "Claude Agent CLI is installed but failed to run.", + }, + }); + } + + // ── Auth check + subscription detection ──────────────────────────── + + const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); + + // Determine subscription type from multiple sources (cheapest first): + // 1. `claude auth status` JSON output (may or may not contain it) + // 2. Cached SDK probe (spawns a Claude process on miss, reads + // `initializationResult()` for account metadata, then aborts + // immediately — no API tokens are consumed) + + let subscriptionType: string | undefined; + let authMethod: string | undefined; + + if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) { + subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value); + authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value); + } + + if (!subscriptionType && resolveSubscriptionType) { + subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath); + } + + const resolvedModels = adjustModelsForSubscription(models, subscriptionType); + + // ── Handle auth results (same logic as before, adjusted models) ── + + if (Result.isFailure(authProbe)) { + const error = authProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: + error instanceof Error + ? `Could not verify Claude authentication status: ${error.message}.` + : "Could not verify Claude authentication status.", + }, + }); + } + + if (Option.isNone(authProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: "Could not verify Claude authentication status. Timed out while running command.", + }, + }); + } + + const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value); + const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod }); + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: parsed.status, + auth: { + ...parsed.auth, + ...(authMetadata ? authMetadata : {}), + }, + ...(parsed.message ? { message: parsed.message } : {}), + }, + }); +}); + +export const ClaudeProviderLive = Layer.effect( + ClaudeProvider, + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + + const subscriptionProbeCache = yield* Cache.make({ + capacity: 1, + timeToLive: Duration.minutes(5), + lookup: (binaryPath: string) => + probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)), + }); + + const checkProvider = checkClaudeProviderStatus((binaryPath) => + Cache.get(subscriptionProbeCache, binaryPath), + ).pipe( + Effect.provideService(ServerSettingsService, serverSettings), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + return yield* makeManagedServerProvider({ + getSettings: serverSettings.getSettings.pipe( + Effect.map((settings) => settings.providers.claudeAgent), + Effect.orDie, + ), + streamSettings: serverSettings.streamChanges.pipe( + Stream.map((settings) => settings.providers.claudeAgent), + ), + haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), + checkProvider, + }); + }), +); diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts new file mode 100644 index 0000000000..b5eb873e85 --- /dev/null +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -0,0 +1,990 @@ +import assert from "node:assert/strict"; +import { + ApprovalRequestId, + EventId, + ProviderItemId, + type ProviderApprovalDecision, + type ProviderEvent, + type ProviderSession, + type ProviderTurnStartResult, + type ProviderUserInputAnswers, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { afterAll, it, vi } from "@effect/vitest"; + +import { Effect, Fiber, Layer, Option, Stream } from "effect"; + +import { + CodexAppServerManager, + type CodexAppServerStartSessionInput, + type CodexAppServerSendTurnInput, +} from "../../codexAppServerManager.ts"; +import { ServerConfig } from "../../config.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import { ProviderAdapterValidationError } from "../Errors.ts"; +import { CodexAdapter } from "../Services/CodexAdapter.ts"; +import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; +import { makeCodexAdapterLive } from "./CodexAdapter.ts"; + +const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value); +const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); +const asEventId = (value: string): EventId => EventId.makeUnsafe(value); +const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value); + +class FakeCodexManager extends CodexAppServerManager { + public startSessionImpl = vi.fn( + async (input: CodexAppServerStartSessionInput): Promise => { + const now = new Date().toISOString(); + return { + provider: "codex", + status: "ready", + runtimeMode: input.runtimeMode, + threadId: input.threadId, + cwd: input.cwd, + createdAt: now, + updatedAt: now, + }; + }, + ); + + public sendTurnImpl = vi.fn( + async (_input: CodexAppServerSendTurnInput): Promise => ({ + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-1"), + }), + ); + + public interruptTurnImpl = vi.fn( + async (_threadId: ThreadId, _turnId?: TurnId): Promise => undefined, + ); + + public readThreadImpl = vi.fn(async (_threadId: ThreadId) => ({ + threadId: asThreadId("thread-1"), + turns: [], + })); + + public rollbackThreadImpl = vi.fn(async (_threadId: ThreadId, _numTurns: number) => ({ + threadId: asThreadId("thread-1"), + turns: [], + })); + + public respondToRequestImpl = vi.fn( + async ( + _threadId: ThreadId, + _requestId: ApprovalRequestId, + _decision: ProviderApprovalDecision, + ): Promise => undefined, + ); + + public respondToUserInputImpl = vi.fn( + async ( + _threadId: ThreadId, + _requestId: ApprovalRequestId, + _answers: ProviderUserInputAnswers, + ): Promise => undefined, + ); + + public stopAllImpl = vi.fn(() => undefined); + + override startSession(input: CodexAppServerStartSessionInput): Promise { + return this.startSessionImpl(input); + } + + override sendTurn(input: CodexAppServerSendTurnInput): Promise { + return this.sendTurnImpl(input); + } + + override interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise { + return this.interruptTurnImpl(threadId, turnId); + } + + override readThread(threadId: ThreadId) { + return this.readThreadImpl(threadId); + } + + override rollbackThread(threadId: ThreadId, numTurns: number) { + return this.rollbackThreadImpl(threadId, numTurns); + } + + override respondToRequest( + threadId: ThreadId, + requestId: ApprovalRequestId, + decision: ProviderApprovalDecision, + ): Promise { + return this.respondToRequestImpl(threadId, requestId, decision); + } + + override respondToUserInput( + threadId: ThreadId, + requestId: ApprovalRequestId, + answers: ProviderUserInputAnswers, + ): Promise { + return this.respondToUserInputImpl(threadId, requestId, answers); + } + + override stopSession(_threadId: ThreadId): void {} + + override listSessions(): ProviderSession[] { + return []; + } + + override hasSession(_threadId: ThreadId): boolean { + return false; + } + + override stopAll(): void { + this.stopAllImpl(); + } +} + +const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, { + upsert: () => Effect.void, + getProvider: () => + Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")), + getBinding: () => Effect.succeed(Option.none()), + remove: () => Effect.void, + listThreadIds: () => Effect.succeed([]), +}); + +const validationManager = new FakeCodexManager(); +const validationLayer = it.layer( + makeCodexAdapterLive({ manager: validationManager }).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ), +); + +validationLayer("CodexAdapterLive validation", (it) => { + it.effect("returns validation error for non-codex provider on startSession", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const result = yield* adapter + .startSession({ + provider: "claudeAgent", + threadId: asThreadId("thread-1"), + runtimeMode: "full-access", + }) + .pipe(Effect.result); + + assert.equal(result._tag, "Failure"); + assert.deepStrictEqual( + result.failure, + new ProviderAdapterValidationError({ + provider: "codex", + operation: "startSession", + issue: "Expected provider 'codex' but received 'claudeAgent'.", + }), + ); + assert.equal(validationManager.startSessionImpl.mock.calls.length, 0); + }), + ); + it.effect("maps codex model options before starting a session", () => + Effect.gen(function* () { + validationManager.startSessionImpl.mockClear(); + const adapter = yield* CodexAdapter; + + yield* adapter.startSession({ + provider: "codex", + threadId: asThreadId("thread-1"), + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + fastMode: true, + }, + }, + runtimeMode: "full-access", + }); + + assert.deepStrictEqual(validationManager.startSessionImpl.mock.calls[0]?.[0], { + provider: "codex", + threadId: asThreadId("thread-1"), + binaryPath: "codex", + model: "gpt-5.3-codex", + serviceTier: "fast", + runtimeMode: "full-access", + }); + }), + ); +}); + +const sessionErrorManager = new FakeCodexManager(); +sessionErrorManager.sendTurnImpl.mockImplementation(async () => { + throw new Error("Unknown session: sess-missing"); +}); +const sessionErrorLayer = it.layer( + makeCodexAdapterLive({ manager: sessionErrorManager }).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ), +); + +sessionErrorLayer("CodexAdapterLive session errors", (it) => { + it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const result = yield* adapter + .sendTurn({ + threadId: asThreadId("sess-missing"), + input: "hello", + attachments: [], + }) + .pipe(Effect.result); + + assert.equal(result._tag, "Failure"); + if (result._tag !== "Failure") { + return; + } + + assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError"); + if (result.failure._tag !== "ProviderAdapterSessionNotFoundError") { + return; + } + assert.equal(result.failure.provider, "codex"); + assert.equal(result.failure.threadId, "sess-missing"); + assert.equal(result.failure.cause instanceof Error, true); + }), + ); + + it.effect("maps codex model options before sending a turn", () => + Effect.gen(function* () { + sessionErrorManager.sendTurnImpl.mockClear(); + const adapter = yield* CodexAdapter; + + yield* Effect.ignore( + adapter.sendTurn({ + threadId: asThreadId("sess-missing"), + input: "hello", + modelSelection: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + reasoningEffort: "high", + fastMode: true, + }, + }, + attachments: [], + }), + ); + + assert.deepStrictEqual(sessionErrorManager.sendTurnImpl.mock.calls[0]?.[0], { + threadId: asThreadId("sess-missing"), + input: "hello", + model: "gpt-5.3-codex", + effort: "high", + serviceTier: "fast", + }); + }), + ); +}); + +const lifecycleManager = new FakeCodexManager(); +const lifecycleLayer = it.layer( + makeCodexAdapterLive({ manager: lifecycleManager }).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ), +); + +lifecycleLayer("CodexAdapterLive lifecycle", (it) => { + it.effect("maps completed agent message items to canonical item.completed events", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + const event: ProviderEvent = { + id: asEventId("evt-msg-complete"), + kind: "notification", + provider: "codex", + createdAt: new Date().toISOString(), + method: "item/completed", + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-1"), + itemId: asItemId("msg_1"), + payload: { + item: { + type: "agentMessage", + id: "msg_1", + }, + }, + }; + + 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, "item.completed"); + if (firstEvent.value.type !== "item.completed") { + return; + } + assert.equal(firstEvent.value.itemId, "msg_1"); + assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal(firstEvent.value.payload.itemType, "assistant_message"); + }), + ); + + it.effect("maps completed plan items to canonical proposed-plan completion events", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + const event: ProviderEvent = { + id: asEventId("evt-plan-complete"), + kind: "notification", + provider: "codex", + createdAt: new Date().toISOString(), + method: "item/completed", + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-1"), + itemId: asItemId("plan_1"), + payload: { + item: { + type: "Plan", + id: "plan_1", + text: "## Final plan\n\n- one\n- two", + }, + }, + }; + + 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, "turn.proposed.completed"); + if (firstEvent.value.type !== "turn.proposed.completed") { + return; + } + assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal(firstEvent.value.payload.planMarkdown, "## Final plan\n\n- one\n- two"); + }), + ); + + it.effect("maps plan deltas to canonical proposed-plan delta events", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + lifecycleManager.emit("event", { + id: asEventId("evt-plan-delta"), + kind: "notification", + provider: "codex", + createdAt: new Date().toISOString(), + method: "item/plan/delta", + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-1"), + itemId: asItemId("plan_1"), + payload: { + delta: "## Final plan", + }, + } satisfies ProviderEvent); + + const firstEvent = yield* Fiber.join(firstEventFiber); + + assert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + assert.equal(firstEvent.value.type, "turn.proposed.delta"); + if (firstEvent.value.type !== "turn.proposed.delta") { + return; + } + assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal(firstEvent.value.payload.delta, "## Final plan"); + }), + ); + + it.effect("maps session/closed lifecycle events to canonical session.exited runtime events", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + const event: ProviderEvent = { + id: asEventId("evt-session-closed"), + kind: "session", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "session/closed", + message: "Session stopped", + }; + + 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, "session.exited"); + if (firstEvent.value.type !== "session.exited") { + return; + } + assert.equal(firstEvent.value.threadId, "thread-1"); + assert.equal(firstEvent.value.payload.reason, "Session stopped"); + }), + ); + + it.effect("maps retryable Codex error notifications to runtime.warning", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + lifecycleManager.emit("event", { + id: asEventId("evt-retryable-error"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "error", + turnId: asTurnId("turn-1"), + payload: { + error: { + message: "Reconnecting... 2/5", + }, + willRetry: true, + }, + } satisfies ProviderEvent); + + const firstEvent = yield* Fiber.join(firstEventFiber); + + assert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + assert.equal(firstEvent.value.type, "runtime.warning"); + if (firstEvent.value.type !== "runtime.warning") { + return; + } + assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal(firstEvent.value.payload.message, "Reconnecting... 2/5"); + }), + ); + + it.effect("maps process stderr notifications to runtime.warning", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + lifecycleManager.emit("event", { + id: asEventId("evt-process-stderr"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "process/stderr", + turnId: asTurnId("turn-1"), + message: "The filename or extension is too long. (os error 206)", + } satisfies ProviderEvent); + + const firstEvent = yield* Fiber.join(firstEventFiber); + + assert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + assert.equal(firstEvent.value.type, "runtime.warning"); + if (firstEvent.value.type !== "runtime.warning") { + return; + } + assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal( + firstEvent.value.payload.message, + "The filename or extension is too long. (os error 206)", + ); + }), + ); + + it.effect("maps fatal websocket stderr notifications to runtime.error", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + lifecycleManager.emit("event", { + id: asEventId("evt-process-stderr-websocket"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "process/stderr", + turnId: asTurnId("turn-1"), + message: + "2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses", + } satisfies ProviderEvent); + + const firstEvent = yield* Fiber.join(firstEventFiber); + + assert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + assert.equal(firstEvent.value.type, "runtime.error"); + if (firstEvent.value.type !== "runtime.error") { + return; + } + assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal(firstEvent.value.payload.class, "provider_error"); + assert.equal( + firstEvent.value.payload.message, + "2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses", + ); + }), + ); + + it.effect("preserves 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-request-resolved"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "serverRequest/resolved", + requestId: ApprovalRequestId.makeUnsafe("req-1"), + payload: { + request: { + method: "item/commandExecution/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, "command_execution_approval"); + }), + ); + + 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; + const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe( + Effect.forkChild, + ); + + const event: ProviderEvent = { + id: asEventId("evt-windows-sandbox-failed"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "windowsSandbox/setupCompleted", + message: "Sandbox setup failed", + payload: { + success: false, + detail: "unsupported environment", + }, + }; + + lifecycleManager.emit("event", event); + const events = Array.from(yield* Fiber.join(eventsFiber)); + + assert.equal(events.length, 2); + + const firstEvent = events[0]; + const secondEvent = events[1]; + + assert.equal(firstEvent?.type, "session.state.changed"); + if (firstEvent?.type === "session.state.changed") { + assert.equal(firstEvent.payload.state, "error"); + assert.equal(firstEvent.payload.reason, "Sandbox setup failed"); + } + + assert.equal(secondEvent?.type, "runtime.warning"); + if (secondEvent?.type === "runtime.warning") { + assert.equal(secondEvent.payload.message, "Sandbox setup failed"); + } + }), + ); + + it.effect( + "maps requestUserInput requests and answered notifications to canonical user-input events", + () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe( + Effect.forkChild, + ); + + lifecycleManager.emit("event", { + id: asEventId("evt-user-input-requested"), + kind: "request", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "item/tool/requestUserInput", + requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"), + payload: { + questions: [ + { + id: "sandbox_mode", + header: "Sandbox", + question: "Which mode should be used?", + options: [ + { + label: "workspace-write", + description: "Allow workspace writes only", + }, + ], + }, + ], + }, + } satisfies ProviderEvent); + lifecycleManager.emit("event", { + id: asEventId("evt-user-input-resolved"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "item/tool/requestUserInput/answered", + requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"), + payload: { + answers: { + sandbox_mode: { + answers: ["workspace-write"], + }, + }, + }, + } satisfies ProviderEvent); + + const events = Array.from(yield* Fiber.join(eventsFiber)); + assert.equal(events[0]?.type, "user-input.requested"); + if (events[0]?.type === "user-input.requested") { + assert.equal(events[0].requestId, "req-user-input-1"); + assert.equal(events[0].payload.questions[0]?.id, "sandbox_mode"); + } + + assert.equal(events[1]?.type, "user-input.resolved"); + if (events[1]?.type === "user-input.resolved") { + assert.equal(events[1].requestId, "req-user-input-1"); + assert.deepEqual(events[1].payload.answers, { + sandbox_mode: "workspace-write", + }); + } + }), + ); + + it.effect("maps Codex task and reasoning event chunks into canonical runtime events", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 5)).pipe( + Effect.forkChild, + ); + + lifecycleManager.emit("event", { + id: asEventId("evt-codex-task-started"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "codex/event/task_started", + payload: { + id: "turn-structured-1", + msg: { + type: "task_started", + turn_id: "turn-structured-1", + collaboration_mode_kind: "plan", + }, + }, + } satisfies ProviderEvent); + + lifecycleManager.emit("event", { + id: asEventId("evt-codex-agent-reasoning"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "codex/event/agent_reasoning", + payload: { + id: "turn-structured-1", + msg: { + type: "agent_reasoning", + text: "Need to compare both transport layers before finalizing the plan.", + }, + }, + } satisfies ProviderEvent); + + lifecycleManager.emit("event", { + id: asEventId("evt-codex-reasoning-delta"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "codex/event/reasoning_content_delta", + payload: { + id: "turn-structured-1", + msg: { + type: "reasoning_content_delta", + turn_id: "turn-structured-1", + item_id: "rs_reasoning_1", + delta: "**Compare** transport boundaries", + summary_index: 0, + }, + }, + } satisfies ProviderEvent); + + lifecycleManager.emit("event", { + id: asEventId("evt-codex-task-complete"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "codex/event/task_complete", + payload: { + id: "turn-structured-1", + msg: { + type: "task_complete", + turn_id: "turn-structured-1", + last_agent_message: "\n# Ship it\n", + }, + }, + } satisfies ProviderEvent); + + const events = Array.from(yield* Fiber.join(eventsFiber)); + + assert.equal(events[0]?.type, "task.started"); + if (events[0]?.type === "task.started") { + assert.equal(events[0].turnId, "turn-structured-1"); + assert.equal(events[0].payload.taskId, "turn-structured-1"); + assert.equal(events[0].payload.taskType, "plan"); + } + + assert.equal(events[1]?.type, "task.progress"); + if (events[1]?.type === "task.progress") { + assert.equal(events[1].payload.taskId, "turn-structured-1"); + assert.equal( + events[1].payload.description, + "Need to compare both transport layers before finalizing the plan.", + ); + } + + assert.equal(events[2]?.type, "content.delta"); + if (events[2]?.type === "content.delta") { + assert.equal(events[2].turnId, "turn-structured-1"); + assert.equal(events[2].itemId, "rs_reasoning_1"); + assert.equal(events[2].payload.streamKind, "reasoning_summary_text"); + assert.equal(events[2].payload.summaryIndex, 0); + } + + assert.equal(events[3]?.type, "task.completed"); + if (events[3]?.type === "task.completed") { + assert.equal(events[3].turnId, "turn-structured-1"); + assert.equal(events[3].payload.taskId, "turn-structured-1"); + assert.equal(events[3].payload.summary, "\n# Ship it\n"); + } + + assert.equal(events[4]?.type, "turn.proposed.completed"); + if (events[4]?.type === "turn.proposed.completed") { + assert.equal(events[4].turnId, "turn-structured-1"); + assert.equal(events[4].payload.planMarkdown, "# Ship it"); + } + }), + ); + + it.effect("prefers manager-assigned turn ids for Codex task events", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + lifecycleManager.emit("event", { + id: asEventId("evt-codex-task-started-parent-turn"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-parent"), + createdAt: new Date().toISOString(), + method: "codex/event/task_started", + payload: { + id: "turn-child", + msg: { + type: "task_started", + turn_id: "turn-child", + collaboration_mode_kind: "default", + }, + conversationId: "child-provider-thread", + }, + } satisfies ProviderEvent); + + const firstEvent = yield* Fiber.join(firstEventFiber); + assert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + assert.equal(firstEvent.value.type, "task.started"); + if (firstEvent.value.type !== "task.started") { + return; + } + assert.equal(firstEvent.value.turnId, "turn-parent"); + assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent"); + assert.equal(firstEvent.value.payload.taskId, "turn-child"); + }), + ); + + it.effect("unwraps Codex token usage payloads for context window events", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + lifecycleManager.emit("event", { + id: asEventId("evt-codex-thread-token-usage-updated"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-1"), + createdAt: new Date().toISOString(), + method: "thread/tokenUsage/updated", + payload: { + threadId: "thread-1", + turnId: "turn-1", + tokenUsage: { + total: { + inputTokens: 11_833, + cachedInputTokens: 3456, + outputTokens: 6, + reasoningOutputTokens: 0, + totalTokens: 11_839, + }, + last: { + inputTokens: 120, + cachedInputTokens: 0, + outputTokens: 6, + reasoningOutputTokens: 0, + totalTokens: 126, + }, + modelContextWindow: 258_400, + }, + }, + } satisfies ProviderEvent); + + const firstEvent = yield* Fiber.join(firstEventFiber); + assert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + assert.equal(firstEvent.value.type, "thread.token-usage.updated"); + if (firstEvent.value.type !== "thread.token-usage.updated") { + return; + } + + assert.deepEqual(firstEvent.value.payload.usage, { + usedTokens: 126, + totalProcessedTokens: 11_839, + maxTokens: 258_400, + inputTokens: 120, + cachedInputTokens: 0, + outputTokens: 6, + reasoningOutputTokens: 0, + lastUsedTokens: 126, + lastInputTokens: 120, + lastCachedInputTokens: 0, + lastOutputTokens: 6, + lastReasoningOutputTokens: 0, + compactsAutomatically: true, + }); + }), + ); +}); + +afterAll(() => { + if (lifecycleManager.stopAllImpl.mock.calls.length === 0) { + lifecycleManager.stopAll(); + } + assert.ok(lifecycleManager.stopAllImpl.mock.calls.length >= 1); +}); diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts new file mode 100644 index 0000000000..cee6bca6ed --- /dev/null +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -0,0 +1,1642 @@ +/** + * CodexAdapterLive - Scoped live implementation for the Codex provider adapter. + * + * Wraps `CodexAppServerManager` behind the `CodexAdapter` service contract and + * maps manager failures into the shared `ProviderAdapterError` algebra. + * + * @module CodexAdapterLive + */ +import { + type CanonicalItemType, + type CanonicalRequestType, + type ProviderEvent, + type ProviderRuntimeEvent, + type ThreadTokenUsageSnapshot, + type ProviderUserInputAnswers, + RuntimeItemId, + RuntimeRequestId, + RuntimeTaskId, + ProviderApprovalDecision, + ProviderItemId, + ThreadId, + TurnId, + ProviderSendTurnInput, +} from "@t3tools/contracts"; +import { Effect, FileSystem, Layer, Queue, Schema, ServiceMap, Stream } from "effect"; + +import { + ProviderAdapterProcessError, + ProviderAdapterRequestError, + ProviderAdapterSessionClosedError, + ProviderAdapterSessionNotFoundError, + ProviderAdapterValidationError, + type ProviderAdapterError, +} from "../Errors.ts"; +import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts"; +import { + CodexAppServerManager, + type CodexAppServerStartSessionInput, +} from "../../codexAppServerManager.ts"; +import { resolveAttachmentPath } from "../../attachmentStore.ts"; +import { ServerConfig } from "../../config.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; + +const PROVIDER = "codex" as const; + +export interface CodexAdapterLiveOptions { + readonly manager?: CodexAppServerManager; + readonly makeManager?: (services?: ServiceMap.ServiceMap) => CodexAppServerManager; + readonly nativeEventLogPath?: string; + readonly nativeEventLogger?: EventNdjsonLogger; +} + +function toMessage(cause: unknown, fallback: string): string { + if (cause instanceof Error && cause.message.length > 0) { + return cause.message; + } + return fallback; +} + +function toSessionError( + threadId: ThreadId, + cause: unknown, +): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined { + const normalized = toMessage(cause, "").toLowerCase(); + if (normalized.includes("unknown session") || normalized.includes("unknown provider session")) { + return new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId, + cause, + }); + } + if (normalized.includes("session is closed")) { + return new ProviderAdapterSessionClosedError({ + provider: PROVIDER, + threadId, + cause, + }); + } + return undefined; +} + +function toRequestError(threadId: ThreadId, method: string, cause: unknown): ProviderAdapterError { + const sessionError = toSessionError(threadId, cause); + if (sessionError) { + return sessionError; + } + return new ProviderAdapterRequestError({ + provider: PROVIDER, + method, + detail: toMessage(cause, `${method} failed`), + cause, + }); +} + +function asObject(value: unknown): Record | undefined { + if (!value || typeof value !== "object") { + return undefined; + } + return value as Record; +} + +function asString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function asArray(value: unknown): unknown[] | undefined { + return Array.isArray(value) ? value : undefined; +} + +function asNumber(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"]; + +function isFatalCodexProcessStderrMessage(message: string): boolean { + const normalized = message.toLowerCase(); + return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet)); +} + +function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined { + const usage = asObject(value); + const totalUsage = asObject(usage?.total_token_usage ?? usage?.total); + const lastUsage = asObject(usage?.last_token_usage ?? usage?.last); + + const totalProcessedTokens = + asNumber(totalUsage?.total_tokens) ?? asNumber(totalUsage?.totalTokens); + const usedTokens = + asNumber(lastUsage?.total_tokens) ?? asNumber(lastUsage?.totalTokens) ?? totalProcessedTokens; + if (usedTokens === undefined || usedTokens <= 0) { + return undefined; + } + + const maxTokens = asNumber(usage?.model_context_window) ?? asNumber(usage?.modelContextWindow); + const inputTokens = asNumber(lastUsage?.input_tokens) ?? asNumber(lastUsage?.inputTokens); + const cachedInputTokens = + asNumber(lastUsage?.cached_input_tokens) ?? asNumber(lastUsage?.cachedInputTokens); + const outputTokens = asNumber(lastUsage?.output_tokens) ?? asNumber(lastUsage?.outputTokens); + const reasoningOutputTokens = + asNumber(lastUsage?.reasoning_output_tokens) ?? asNumber(lastUsage?.reasoningOutputTokens); + + return { + usedTokens, + ...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens + ? { totalProcessedTokens } + : {}), + ...(maxTokens !== undefined ? { maxTokens } : {}), + ...(inputTokens !== undefined ? { inputTokens } : {}), + ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}), + ...(outputTokens !== undefined ? { outputTokens } : {}), + ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}), + ...(usedTokens !== undefined ? { lastUsedTokens: usedTokens } : {}), + ...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}), + ...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}), + ...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}), + ...(reasoningOutputTokens !== undefined + ? { lastReasoningOutputTokens: reasoningOutputTokens } + : {}), + compactsAutomatically: true, + }; +} + +function toTurnId(value: string | undefined): TurnId | undefined { + return value?.trim() ? TurnId.makeUnsafe(value) : undefined; +} + +function toProviderItemId(value: string | undefined): ProviderItemId | undefined { + return value?.trim() ? ProviderItemId.makeUnsafe(value) : undefined; +} + +function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" { + switch (value) { + case "completed": + case "failed": + case "cancelled": + case "interrupted": + return value; + default: + return "completed"; + } +} + +function normalizeItemType(raw: unknown): string { + const type = asString(raw); + if (!type) return "item"; + return type + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/[._/-]/g, " ") + .replace(/\s+/g, " ") + .trim() + .toLowerCase(); +} + +function toCanonicalItemType(raw: unknown): CanonicalItemType { + const type = normalizeItemType(raw); + if (type.includes("user")) return "user_message"; + if (type.includes("agent message") || type.includes("assistant")) return "assistant_message"; + if (type.includes("reasoning") || type.includes("thought")) return "reasoning"; + if (type.includes("plan") || type.includes("todo")) return "plan"; + if (type.includes("command")) return "command_execution"; + if (type.includes("file change") || type.includes("patch") || type.includes("edit")) + return "file_change"; + if (type.includes("mcp")) return "mcp_tool_call"; + if (type.includes("dynamic tool")) return "dynamic_tool_call"; + if (type.includes("collab")) return "collab_agent_tool_call"; + if (type.includes("web search")) return "web_search"; + if (type.includes("image")) return "image_view"; + if (type.includes("review entered")) return "review_entered"; + if (type.includes("review exited")) return "review_exited"; + if (type.includes("compact")) return "context_compaction"; + if (type.includes("error")) return "error"; + return "unknown"; +} + +function itemTitle(itemType: CanonicalItemType): string | undefined { + switch (itemType) { + case "assistant_message": + return "Assistant message"; + case "user_message": + return "User message"; + case "reasoning": + return "Reasoning"; + case "plan": + return "Plan"; + case "command_execution": + return "Ran command"; + case "file_change": + return "File change"; + case "mcp_tool_call": + return "MCP tool call"; + case "dynamic_tool_call": + return "Tool call"; + case "web_search": + return "Web search"; + case "image_view": + return "Image view"; + case "error": + return "Error"; + default: + return undefined; + } +} + +function itemDetail( + item: Record, + payload: Record, +): string | undefined { + const nestedResult = asObject(item.result); + const candidates = [ + asString(item.command), + asString(item.title), + asString(item.summary), + asString(item.text), + asString(item.path), + asString(item.prompt), + asString(nestedResult?.command), + asString(payload.command), + asString(payload.message), + asString(payload.prompt), + ]; + for (const candidate of candidates) { + if (!candidate) continue; + const trimmed = candidate.trim(); + if (trimmed.length === 0) continue; + return trimmed; + } + return undefined; +} + +function toRequestTypeFromMethod(method: string): CanonicalRequestType { + switch (method) { + case "item/commandExecution/requestApproval": + return "command_execution_approval"; + case "item/fileRead/requestApproval": + return "file_read_approval"; + case "item/fileChange/requestApproval": + return "file_change_approval"; + case "applyPatchApproval": + return "apply_patch_approval"; + case "execCommandApproval": + return "exec_command_approval"; + case "item/tool/requestUserInput": + return "tool_user_input"; + case "item/tool/call": + return "dynamic_tool_call"; + case "account/chatgptAuthTokens/refresh": + return "auth_tokens_refresh"; + default: + return "unknown"; + } +} + +function toRequestTypeFromKind(kind: unknown): CanonicalRequestType { + switch (kind) { + case "command": + return "command_execution_approval"; + case "file-read": + return "file_read_approval"; + case "file-change": + return "file_change_approval"; + default: + return "unknown"; + } +} + +function toRequestTypeFromResolvedPayload( + payload: Record | undefined, +): CanonicalRequestType { + const request = asObject(payload?.request); + const method = asString(request?.method) ?? asString(payload?.method); + if (method) { + return toRequestTypeFromMethod(method); + } + const requestKind = asString(request?.kind) ?? asString(payload?.requestKind); + if (requestKind) { + return toRequestTypeFromKind(requestKind); + } + return "unknown"; +} + +function toCanonicalUserInputAnswers( + answers: ProviderUserInputAnswers | undefined, +): ProviderUserInputAnswers { + if (!answers) { + return {}; + } + + return Object.fromEntries( + Object.entries(answers).flatMap(([questionId, value]) => { + if (typeof value === "string") { + return [[questionId, value] as const]; + } + + if (Array.isArray(value)) { + const normalized = value.filter((entry): entry is string => typeof entry === "string"); + return [[questionId, normalized.length === 1 ? normalized[0] : normalized] as const]; + } + + const answerObject = asObject(value); + const answerList = asArray(answerObject?.answers)?.filter( + (entry): entry is string => typeof entry === "string", + ); + if (!answerList) { + return []; + } + return [[questionId, answerList.length === 1 ? answerList[0] : answerList] as const]; + }), + ); +} + +function toUserInputQuestions(payload: Record | undefined) { + const questions = asArray(payload?.questions); + if (!questions) { + return undefined; + } + + const parsedQuestions = questions + .map((entry) => { + const question = asObject(entry); + if (!question) return undefined; + const options = asArray(question.options) + ?.map((option) => { + const optionRecord = asObject(option); + if (!optionRecord) return undefined; + const label = asString(optionRecord.label)?.trim(); + const description = asString(optionRecord.description)?.trim(); + if (!label || !description) { + return undefined; + } + return { label, description }; + }) + .filter((option): option is { label: string; description: string } => option !== undefined); + const id = asString(question.id)?.trim(); + const header = asString(question.header)?.trim(); + const prompt = asString(question.question)?.trim(); + if (!id || !header || !prompt || !options || options.length === 0) { + return undefined; + } + return { + id, + header, + question: prompt, + options, + }; + }) + .filter( + ( + question, + ): question is { + id: string; + header: string; + question: string; + options: Array<{ label: string; description: string }>; + } => question !== undefined, + ); + + return parsedQuestions.length > 0 ? parsedQuestions : undefined; +} + +function toThreadState( + value: unknown, +): "active" | "idle" | "archived" | "closed" | "compacted" | "error" { + switch (value) { + case "idle": + return "idle"; + case "archived": + return "archived"; + case "closed": + return "closed"; + case "compacted": + return "compacted"; + case "error": + case "failed": + return "error"; + default: + return "active"; + } +} + +function contentStreamKindFromMethod( + method: string, +): + | "assistant_text" + | "reasoning_text" + | "reasoning_summary_text" + | "plan_text" + | "command_output" + | "file_change_output" { + switch (method) { + case "item/agentMessage/delta": + return "assistant_text"; + case "item/reasoning/textDelta": + return "reasoning_text"; + case "item/reasoning/summaryTextDelta": + return "reasoning_summary_text"; + case "item/commandExecution/outputDelta": + return "command_output"; + case "item/fileChange/outputDelta": + return "file_change_output"; + default: + return "assistant_text"; + } +} + +const PROPOSED_PLAN_BLOCK_REGEX = /\s*([\s\S]*?)\s*<\/proposed_plan>/i; + +function extractProposedPlanMarkdown(text: string | undefined): string | undefined { + const match = text ? PROPOSED_PLAN_BLOCK_REGEX.exec(text) : null; + const planMarkdown = match?.[1]?.trim(); + return planMarkdown && planMarkdown.length > 0 ? planMarkdown : undefined; +} + +function asRuntimeItemId(itemId: ProviderItemId): RuntimeItemId { + return RuntimeItemId.makeUnsafe(itemId); +} + +function asRuntimeRequestId(requestId: string): RuntimeRequestId { + return RuntimeRequestId.makeUnsafe(requestId); +} + +function asRuntimeTaskId(taskId: string): RuntimeTaskId { + return RuntimeTaskId.makeUnsafe(taskId); +} + +function codexEventMessage( + payload: Record | undefined, +): Record | undefined { + return asObject(payload?.msg); +} + +function codexEventBase( + event: ProviderEvent, + canonicalThreadId: ThreadId, +): Omit { + const payload = asObject(event.payload); + const msg = codexEventMessage(payload); + const turnId = event.turnId ?? toTurnId(asString(msg?.turn_id) ?? asString(msg?.turnId)); + const itemId = event.itemId ?? toProviderItemId(asString(msg?.item_id) ?? asString(msg?.itemId)); + const requestId = asString(msg?.request_id) ?? asString(msg?.requestId); + const base = runtimeEventBase(event, canonicalThreadId); + const providerRefs = base.providerRefs + ? { + ...base.providerRefs, + ...(turnId ? { providerTurnId: turnId } : {}), + ...(itemId ? { providerItemId: itemId } : {}), + ...(requestId ? { providerRequestId: requestId } : {}), + } + : { + ...(turnId ? { providerTurnId: turnId } : {}), + ...(itemId ? { providerItemId: itemId } : {}), + ...(requestId ? { providerRequestId: requestId } : {}), + }; + + return { + ...base, + ...(turnId ? { turnId } : {}), + ...(itemId ? { itemId: asRuntimeItemId(itemId) } : {}), + ...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}), + ...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}), + }; +} + +function eventRawSource(event: ProviderEvent): NonNullable["source"] { + return event.kind === "request" ? "codex.app-server.request" : "codex.app-server.notification"; +} + +function providerRefsFromEvent( + event: ProviderEvent, +): ProviderRuntimeEvent["providerRefs"] | undefined { + const refs: Record = {}; + if (event.turnId) refs.providerTurnId = event.turnId; + if (event.itemId) refs.providerItemId = event.itemId; + if (event.requestId) refs.providerRequestId = event.requestId; + + return Object.keys(refs).length > 0 ? (refs as ProviderRuntimeEvent["providerRefs"]) : undefined; +} + +function runtimeEventBase( + event: ProviderEvent, + canonicalThreadId: ThreadId, +): Omit { + const refs = providerRefsFromEvent(event); + return { + eventId: event.id, + provider: event.provider, + threadId: canonicalThreadId, + createdAt: event.createdAt, + ...(event.turnId ? { turnId: event.turnId } : {}), + ...(event.itemId ? { itemId: asRuntimeItemId(event.itemId) } : {}), + ...(event.requestId ? { requestId: asRuntimeRequestId(event.requestId) } : {}), + ...(refs ? { providerRefs: refs } : {}), + raw: { + source: eventRawSource(event), + method: event.method, + payload: event.payload ?? {}, + }, + }; +} + +function mapItemLifecycle( + event: ProviderEvent, + canonicalThreadId: ThreadId, + lifecycle: "item.started" | "item.updated" | "item.completed", +): ProviderRuntimeEvent | undefined { + const payload = asObject(event.payload); + const item = asObject(payload?.item); + const source = item ?? payload; + if (!source) { + return undefined; + } + + const itemType = toCanonicalItemType(source.type ?? source.kind); + if (itemType === "unknown" && lifecycle !== "item.updated") { + return undefined; + } + + const detail = itemDetail(source, payload ?? {}); + const status = + lifecycle === "item.started" + ? "inProgress" + : lifecycle === "item.completed" + ? "completed" + : undefined; + + return { + ...runtimeEventBase(event, canonicalThreadId), + type: lifecycle, + payload: { + itemType, + ...(status ? { status } : {}), + ...(itemTitle(itemType) ? { title: itemTitle(itemType) } : {}), + ...(detail ? { detail } : {}), + ...(event.payload !== undefined ? { data: event.payload } : {}), + }, + }; +} + +function mapToRuntimeEvents( + event: ProviderEvent, + canonicalThreadId: ThreadId, +): ReadonlyArray { + const payload = asObject(event.payload); + const turn = asObject(payload?.turn); + + if (event.kind === "error") { + if (!event.message) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "runtime.error", + payload: { + message: event.message, + class: "provider_error", + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + }, + ]; + } + + if (event.kind === "request") { + if (event.method === "item/tool/requestUserInput") { + const questions = toUserInputQuestions(payload); + if (!questions) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "user-input.requested", + payload: { + questions, + }, + }, + ]; + } + + const detail = + asString(payload?.command) ?? asString(payload?.reason) ?? asString(payload?.prompt); + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "request.opened", + payload: { + requestType: toRequestTypeFromMethod(event.method), + ...(detail ? { detail } : {}), + ...(event.payload !== undefined ? { args: event.payload } : {}), + }, + }, + ]; + } + + if (event.method === "item/requestApproval/decision" && event.requestId) { + const decision = Schema.decodeUnknownSync(ProviderApprovalDecision)(payload?.decision); + const requestType = + event.requestKind !== undefined + ? toRequestTypeFromKind(event.requestKind) + : toRequestTypeFromMethod(event.method); + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "request.resolved", + payload: { + requestType, + ...(decision ? { decision } : {}), + ...(event.payload !== undefined ? { resolution: event.payload } : {}), + }, + }, + ]; + } + + if (event.method === "session/connecting") { + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "session.state.changed", + payload: { + state: "starting", + ...(event.message ? { reason: event.message } : {}), + }, + }, + ]; + } + + if (event.method === "session/ready") { + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "session.state.changed", + payload: { + state: "ready", + ...(event.message ? { reason: event.message } : {}), + }, + }, + ]; + } + + if (event.method === "session/started") { + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "session.started", + payload: { + ...(event.message ? { message: event.message } : {}), + ...(event.payload !== undefined ? { resume: event.payload } : {}), + }, + }, + ]; + } + + if (event.method === "session/exited" || event.method === "session/closed") { + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "session.exited", + payload: { + ...(event.message ? { reason: event.message } : {}), + ...(event.method === "session/closed" ? { exitKind: "graceful" } : {}), + }, + }, + ]; + } + + if (event.method === "thread/started") { + const payloadThreadId = asString(asObject(payload?.thread)?.id); + const providerThreadId = payloadThreadId ?? asString(payload?.threadId); + if (!providerThreadId) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "thread.started", + payload: { + providerThreadId, + }, + }, + ]; + } + + if ( + event.method === "thread/status/changed" || + event.method === "thread/archived" || + event.method === "thread/unarchived" || + event.method === "thread/closed" || + event.method === "thread/compacted" + ) { + return [ + { + type: "thread.state.changed", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + state: + event.method === "thread/archived" + ? "archived" + : event.method === "thread/closed" + ? "closed" + : event.method === "thread/compacted" + ? "compacted" + : toThreadState(asObject(payload?.thread)?.state ?? payload?.state), + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + }, + ]; + } + + if (event.method === "thread/name/updated") { + return [ + { + type: "thread.metadata.updated", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + ...(asString(payload?.threadName) ? { name: asString(payload?.threadName) } : {}), + ...(event.payload !== undefined ? { metadata: asObject(event.payload) } : {}), + }, + }, + ]; + } + + if (event.method === "thread/tokenUsage/updated") { + const tokenUsage = asObject(payload?.tokenUsage); + const normalizedUsage = normalizeCodexTokenUsage(tokenUsage ?? event.payload); + if (!normalizedUsage) { + return []; + } + return [ + { + type: "thread.token-usage.updated", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + usage: normalizedUsage, + }, + }, + ]; + } + + if (event.method === "turn/started") { + const turnId = event.turnId; + if (!turnId) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + turnId, + type: "turn.started", + payload: { + ...(asString(turn?.model) ? { model: asString(turn?.model) } : {}), + ...(asString(turn?.effort) ? { effort: asString(turn?.effort) } : {}), + }, + }, + ]; + } + + if (event.method === "turn/completed") { + const errorMessage = asString(asObject(turn?.error)?.message); + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "turn.completed", + payload: { + state: toTurnStatus(turn?.status), + ...(asString(turn?.stopReason) ? { stopReason: asString(turn?.stopReason) } : {}), + ...(turn?.usage !== undefined ? { usage: turn.usage } : {}), + ...(asObject(turn?.modelUsage) ? { modelUsage: asObject(turn?.modelUsage) } : {}), + ...(asNumber(turn?.totalCostUsd) !== undefined + ? { totalCostUsd: asNumber(turn?.totalCostUsd) } + : {}), + ...(errorMessage ? { errorMessage } : {}), + }, + }, + ]; + } + + if (event.method === "turn/aborted") { + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "turn.aborted", + payload: { + reason: event.message ?? "Turn aborted", + }, + }, + ]; + } + + if (event.method === "turn/plan/updated") { + const steps = Array.isArray(payload?.plan) ? payload.plan : []; + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "turn.plan.updated", + payload: { + ...(asString(payload?.explanation) + ? { explanation: asString(payload?.explanation) } + : {}), + plan: steps + .map((entry) => asObject(entry)) + .filter((entry): entry is Record => entry !== undefined) + .map((entry) => ({ + step: asString(entry.step) ?? "step", + status: + entry.status === "completed" || entry.status === "inProgress" + ? entry.status + : "pending", + })), + }, + }, + ]; + } + + if (event.method === "turn/diff/updated") { + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "turn.diff.updated", + payload: { + unifiedDiff: + asString(payload?.unifiedDiff) ?? + asString(payload?.diff) ?? + asString(payload?.patch) ?? + "", + }, + }, + ]; + } + + if (event.method === "item/started") { + const started = mapItemLifecycle(event, canonicalThreadId, "item.started"); + return started ? [started] : []; + } + + if (event.method === "item/completed") { + const payload = asObject(event.payload); + const item = asObject(payload?.item); + const source = item ?? payload; + if (!source) { + return []; + } + const itemType = source ? toCanonicalItemType(source.type ?? source.kind) : "unknown"; + if (itemType === "plan") { + const detail = itemDetail(source, payload ?? {}); + if (!detail) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "turn.proposed.completed", + payload: { + planMarkdown: detail, + }, + }, + ]; + } + const completed = mapItemLifecycle(event, canonicalThreadId, "item.completed"); + return completed ? [completed] : []; + } + + if ( + event.method === "item/reasoning/summaryPartAdded" || + event.method === "item/commandExecution/terminalInteraction" + ) { + const updated = mapItemLifecycle(event, canonicalThreadId, "item.updated"); + return updated ? [updated] : []; + } + + if (event.method === "item/plan/delta") { + const delta = + event.textDelta ?? + asString(payload?.delta) ?? + asString(payload?.text) ?? + asString(asObject(payload?.content)?.text); + if (!delta || delta.length === 0) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "turn.proposed.delta", + payload: { + delta, + }, + }, + ]; + } + + if ( + event.method === "item/agentMessage/delta" || + event.method === "item/commandExecution/outputDelta" || + event.method === "item/fileChange/outputDelta" || + event.method === "item/reasoning/summaryTextDelta" || + event.method === "item/reasoning/textDelta" + ) { + const delta = + event.textDelta ?? + asString(payload?.delta) ?? + asString(payload?.text) ?? + asString(asObject(payload?.content)?.text); + if (!delta || delta.length === 0) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "content.delta", + payload: { + streamKind: contentStreamKindFromMethod(event.method), + delta, + ...(typeof payload?.contentIndex === "number" + ? { contentIndex: payload.contentIndex } + : {}), + ...(typeof payload?.summaryIndex === "number" + ? { summaryIndex: payload.summaryIndex } + : {}), + }, + }, + ]; + } + + if (event.method === "item/mcpToolCall/progress") { + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "tool.progress", + payload: { + ...(asString(payload?.toolUseId) ? { toolUseId: asString(payload?.toolUseId) } : {}), + ...(asString(payload?.toolName) ? { toolName: asString(payload?.toolName) } : {}), + ...(asString(payload?.summary) ? { summary: asString(payload?.summary) } : {}), + ...(asNumber(payload?.elapsedSeconds) !== undefined + ? { elapsedSeconds: asNumber(payload?.elapsedSeconds) } + : {}), + }, + }, + ]; + } + + if (event.method === "serverRequest/resolved") { + const requestType = + toRequestTypeFromResolvedPayload(payload) !== "unknown" + ? toRequestTypeFromResolvedPayload(payload) + : event.requestId && event.requestKind !== undefined + ? toRequestTypeFromKind(event.requestKind) + : "unknown"; + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "request.resolved", + payload: { + requestType, + ...(event.payload !== undefined ? { resolution: event.payload } : {}), + }, + }, + ]; + } + + if (event.method === "item/tool/requestUserInput/answered") { + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "user-input.resolved", + payload: { + answers: toCanonicalUserInputAnswers( + asObject(event.payload)?.answers as ProviderUserInputAnswers | undefined, + ), + }, + }, + ]; + } + + if (event.method === "codex/event/task_started") { + const msg = codexEventMessage(payload); + const taskId = asString(payload?.id) ?? asString(msg?.turn_id); + if (!taskId) { + return []; + } + return [ + { + ...codexEventBase(event, canonicalThreadId), + type: "task.started", + payload: { + taskId: asRuntimeTaskId(taskId), + ...(asString(msg?.collaboration_mode_kind) + ? { taskType: asString(msg?.collaboration_mode_kind) } + : {}), + }, + }, + ]; + } + + if (event.method === "codex/event/task_complete") { + const msg = codexEventMessage(payload); + const taskId = asString(payload?.id) ?? asString(msg?.turn_id); + const proposedPlanMarkdown = extractProposedPlanMarkdown(asString(msg?.last_agent_message)); + if (!taskId) { + if (!proposedPlanMarkdown) { + return []; + } + return [ + { + ...codexEventBase(event, canonicalThreadId), + type: "turn.proposed.completed", + payload: { + planMarkdown: proposedPlanMarkdown, + }, + }, + ]; + } + const events: ProviderRuntimeEvent[] = [ + { + ...codexEventBase(event, canonicalThreadId), + type: "task.completed", + payload: { + taskId: asRuntimeTaskId(taskId), + status: "completed", + ...(asString(msg?.last_agent_message) + ? { summary: asString(msg?.last_agent_message) } + : {}), + }, + }, + ]; + if (proposedPlanMarkdown) { + events.push({ + ...codexEventBase(event, canonicalThreadId), + type: "turn.proposed.completed", + payload: { + planMarkdown: proposedPlanMarkdown, + }, + }); + } + return events; + } + + if (event.method === "codex/event/agent_reasoning") { + const msg = codexEventMessage(payload); + const taskId = asString(payload?.id); + const description = asString(msg?.text); + if (!taskId || !description) { + return []; + } + return [ + { + ...codexEventBase(event, canonicalThreadId), + type: "task.progress", + payload: { + taskId: asRuntimeTaskId(taskId), + description, + }, + }, + ]; + } + + if (event.method === "codex/event/reasoning_content_delta") { + const msg = codexEventMessage(payload); + const delta = asString(msg?.delta); + if (!delta) { + return []; + } + return [ + { + ...codexEventBase(event, canonicalThreadId), + type: "content.delta", + payload: { + streamKind: + asNumber(msg?.summary_index) !== undefined + ? "reasoning_summary_text" + : "reasoning_text", + delta, + ...(asNumber(msg?.summary_index) !== undefined + ? { summaryIndex: asNumber(msg?.summary_index) } + : {}), + }, + }, + ]; + } + + if (event.method === "model/rerouted") { + return [ + { + type: "model.rerouted", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + fromModel: asString(payload?.fromModel) ?? "unknown", + toModel: asString(payload?.toModel) ?? "unknown", + reason: asString(payload?.reason) ?? "unknown", + }, + }, + ]; + } + + if (event.method === "deprecationNotice") { + return [ + { + type: "deprecation.notice", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + summary: asString(payload?.summary) ?? "Deprecation notice", + ...(asString(payload?.details) ? { details: asString(payload?.details) } : {}), + }, + }, + ]; + } + + if (event.method === "configWarning") { + return [ + { + type: "config.warning", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + summary: asString(payload?.summary) ?? "Configuration warning", + ...(asString(payload?.details) ? { details: asString(payload?.details) } : {}), + ...(asString(payload?.path) ? { path: asString(payload?.path) } : {}), + ...(payload?.range !== undefined ? { range: payload.range } : {}), + }, + }, + ]; + } + + if (event.method === "account/updated") { + return [ + { + type: "account.updated", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + account: event.payload ?? {}, + }, + }, + ]; + } + + if (event.method === "account/rateLimits/updated") { + return [ + { + type: "account.rate-limits.updated", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + rateLimits: event.payload ?? {}, + }, + }, + ]; + } + + if (event.method === "mcpServer/oauthLogin/completed") { + return [ + { + type: "mcp.oauth.completed", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + success: payload?.success === true, + ...(asString(payload?.name) ? { name: asString(payload?.name) } : {}), + ...(asString(payload?.error) ? { error: asString(payload?.error) } : {}), + }, + }, + ]; + } + + if (event.method === "thread/realtime/started") { + const realtimeSessionId = asString(payload?.realtimeSessionId); + return [ + { + type: "thread.realtime.started", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + realtimeSessionId, + }, + }, + ]; + } + + if (event.method === "thread/realtime/itemAdded") { + return [ + { + type: "thread.realtime.item-added", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + item: event.payload ?? {}, + }, + }, + ]; + } + + if (event.method === "thread/realtime/outputAudio/delta") { + return [ + { + type: "thread.realtime.audio.delta", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + audio: event.payload ?? {}, + }, + }, + ]; + } + + if (event.method === "thread/realtime/error") { + const message = asString(payload?.message) ?? event.message ?? "Realtime error"; + return [ + { + type: "thread.realtime.error", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message, + }, + }, + ]; + } + + if (event.method === "thread/realtime/closed") { + return [ + { + type: "thread.realtime.closed", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + reason: event.message, + }, + }, + ]; + } + + if (event.method === "error") { + const message = + asString(asObject(payload?.error)?.message) ?? event.message ?? "Provider runtime error"; + const willRetry = payload?.willRetry === true; + return [ + { + type: willRetry ? "runtime.warning" : "runtime.error", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message, + ...(!willRetry ? { class: "provider_error" as const } : {}), + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + }, + ]; + } + + if (event.method === "process/stderr") { + const message = event.message ?? "Codex process stderr"; + const isFatal = isFatalCodexProcessStderrMessage(message); + return [ + isFatal + ? { + type: "runtime.error", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message, + class: "provider_error" as const, + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + } + : { + type: "runtime.warning", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message, + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + }, + ]; + } + + if (event.method === "windows/worldWritableWarning") { + return [ + { + type: "runtime.warning", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message: event.message ?? "Windows world-writable warning", + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + }, + ]; + } + + if (event.method === "windowsSandbox/setupCompleted") { + const payloadRecord = asObject(event.payload); + const success = payloadRecord?.success; + const successMessage = event.message ?? "Windows sandbox setup completed"; + const failureMessage = event.message ?? "Windows sandbox setup failed"; + + return [ + { + type: "session.state.changed", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + state: success === false ? "error" : "ready", + reason: success === false ? failureMessage : successMessage, + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + }, + ...(success === false + ? [ + { + type: "runtime.warning" as const, + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message: failureMessage, + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + }, + ] + : []), + ]; + } + + return []; +} + +const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( + options?: CodexAdapterLiveOptions, +) { + const fileSystem = yield* FileSystem.FileSystem; + const serverConfig = yield* Effect.service(ServerConfig); + const nativeEventLogger = + options?.nativeEventLogger ?? + (options?.nativeEventLogPath !== undefined + ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { + stream: "native", + }) + : undefined); + + const acquireManager = Effect.fn("acquireManager")(function* () { + if (options?.manager) { + return options.manager; + } + const services = yield* Effect.services(); + return options?.makeManager?.(services) ?? new CodexAppServerManager(services); + }); + + const manager = yield* Effect.acquireRelease(acquireManager(), (manager) => + Effect.sync(() => { + try { + manager.stopAll(); + } catch { + // Finalizers should never fail and block shutdown. + } + }), + ); + const serverSettingsService = yield* ServerSettingsService; + + const startSession: CodexAdapterShape["startSession"] = Effect.fn("startSession")( + function* (input) { + if (input.provider !== undefined && input.provider !== PROVIDER) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "startSession", + issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, + }); + } + + const codexSettings = yield* serverSettingsService.getSettings.pipe( + Effect.map((settings) => settings.providers.codex), + Effect.mapError( + (error) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId: input.threadId, + detail: error.message, + cause: error, + }), + ), + ); + const binaryPath = codexSettings.binaryPath; + const homePath = codexSettings.homePath; + const managerInput: CodexAppServerStartSessionInput = { + threadId: input.threadId, + provider: "codex", + ...(input.cwd !== undefined ? { cwd: input.cwd } : {}), + ...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}), + runtimeMode: input.runtimeMode, + binaryPath, + ...(homePath ? { homePath } : {}), + ...(input.modelSelection?.provider === "codex" + ? { model: input.modelSelection.model } + : {}), + ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode + ? { serviceTier: "fast" } + : {}), + }; + + return yield* Effect.tryPromise({ + try: () => manager.startSession(managerInput), + catch: (cause) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId: input.threadId, + detail: toMessage(cause, "Failed to start Codex adapter session."), + cause, + }), + }); + }, + ); + + const resolveAttachment = Effect.fn("resolveAttachment")(function* ( + input: ProviderSendTurnInput, + attachment: NonNullable[number], + ) { + const attachmentPath = resolveAttachmentPath({ + attachmentsDir: serverConfig.attachmentsDir, + attachment, + }); + if (!attachmentPath) { + return yield* toRequestError( + input.threadId, + "turn/start", + new Error(`Invalid attachment id '${attachment.id}'.`), + ); + } + const bytes = yield* fileSystem.readFile(attachmentPath).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: toMessage(cause, "Failed to read attachment file."), + cause, + }), + ), + ); + return { + type: "image" as const, + url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`, + }; + }); + + const sendTurn: CodexAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) { + const codexAttachments = yield* Effect.forEach( + input.attachments ?? [], + (attachment) => resolveAttachment(input, attachment), + { concurrency: 1 }, + ); + + return yield* Effect.tryPromise({ + try: () => { + const managerInput = { + threadId: input.threadId, + ...(input.input !== undefined ? { input: input.input } : {}), + ...(input.modelSelection?.provider === "codex" + ? { model: input.modelSelection.model } + : {}), + ...(input.modelSelection?.provider === "codex" && + input.modelSelection.options?.reasoningEffort !== undefined + ? { effort: input.modelSelection.options.reasoningEffort } + : {}), + ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode + ? { serviceTier: "fast" } + : {}), + ...(input.interactionMode !== undefined + ? { interactionMode: input.interactionMode } + : {}), + ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}), + }; + return manager.sendTurn(managerInput); + }, + catch: (cause) => toRequestError(input.threadId, "turn/start", cause), + }).pipe( + Effect.map((result) => ({ + ...result, + threadId: input.threadId, + })), + ); + }); + + const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) => + Effect.tryPromise({ + try: () => manager.interruptTurn(threadId, turnId), + catch: (cause) => toRequestError(threadId, "turn/interrupt", cause), + }); + + const readThread: CodexAdapterShape["readThread"] = (threadId) => + Effect.tryPromise({ + try: () => manager.readThread(threadId), + catch: (cause) => toRequestError(threadId, "thread/read", cause), + }).pipe( + Effect.map((snapshot) => ({ + threadId, + turns: snapshot.turns, + })), + ); + + const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => { + if (!Number.isInteger(numTurns) || numTurns < 1) { + return Effect.fail( + new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "rollbackThread", + issue: "numTurns must be an integer >= 1.", + }), + ); + } + + return Effect.tryPromise({ + try: () => manager.rollbackThread(threadId, numTurns), + catch: (cause) => toRequestError(threadId, "thread/rollback", cause), + }).pipe( + Effect.map((snapshot) => ({ + threadId, + turns: snapshot.turns, + })), + ); + }; + + const respondToRequest: CodexAdapterShape["respondToRequest"] = (threadId, requestId, decision) => + Effect.tryPromise({ + try: () => manager.respondToRequest(threadId, requestId, decision), + catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause), + }); + + const respondToUserInput: CodexAdapterShape["respondToUserInput"] = ( + threadId, + requestId, + answers, + ) => + Effect.tryPromise({ + try: () => manager.respondToUserInput(threadId, requestId, answers), + catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause), + }); + + const stopSession: CodexAdapterShape["stopSession"] = (threadId) => + Effect.sync(() => { + manager.stopSession(threadId); + }); + + const listSessions: CodexAdapterShape["listSessions"] = () => + Effect.sync(() => manager.listSessions()); + + const hasSession: CodexAdapterShape["hasSession"] = (threadId) => + Effect.sync(() => manager.hasSession(threadId)); + + const stopAll: CodexAdapterShape["stopAll"] = () => + Effect.sync(() => { + manager.stopAll(); + }); + + const runtimeEventQueue = yield* Queue.unbounded(); + + const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) { + if (!nativeEventLogger) { + return; + } + yield* nativeEventLogger.write(event, event.threadId); + }); + + const registerListener = Effect.fn("registerListener")(function* () { + const services = yield* Effect.services(); + const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) { + yield* writeNativeEvent(event); + const runtimeEvents = mapToRuntimeEvents(event, event.threadId); + if (runtimeEvents.length === 0) { + yield* Effect.logDebug("ignoring unhandled Codex provider event", { + method: event.method, + threadId: event.threadId, + turnId: event.turnId, + itemId: event.itemId, + }); + return; + } + yield* Queue.offerAll(runtimeEventQueue, runtimeEvents); + }); + const listener = (event: ProviderEvent) => + listenerEffect(event).pipe(Effect.runPromiseWith(services)); + manager.on("event", listener); + return listener; + }); + + const unregisterListener = Effect.fn("unregisterListener")(function* ( + listener: (event: ProviderEvent) => Promise, + ) { + yield* Effect.sync(() => { + manager.off("event", listener); + }); + yield* Queue.shutdown(runtimeEventQueue); + }); + + yield* Effect.acquireRelease(registerListener(), unregisterListener); + + return { + provider: PROVIDER, + capabilities: { + sessionModelSwitch: "in-session", + }, + startSession, + sendTurn, + interruptTurn, + readThread, + rollbackThread, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + hasSession, + stopAll, + streamEvents: Stream.fromQueue(runtimeEventQueue), + } satisfies CodexAdapterShape; +}); + +export const CodexAdapterLive = Layer.effect(CodexAdapter, makeCodexAdapter()); + +export function makeCodexAdapterLive(options?: CodexAdapterLiveOptions) { + return Layer.effect(CodexAdapter, makeCodexAdapter(options)); +} diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts new file mode 100644 index 0000000000..667bdf048b --- /dev/null +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -0,0 +1,565 @@ +import * as OS from "node:os"; +import type { + ModelCapabilities, + CodexSettings, + ServerProvider, + ServerProviderModel, + ServerProviderAuth, + ServerProviderState, +} from "@t3tools/contracts"; +import { + Cache, + Duration, + Effect, + Equal, + FileSystem, + Layer, + Option, + Path, + Result, + Stream, +} from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { + buildServerProvider, + DEFAULT_TIMEOUT_MS, + detailFromResult, + extractAuthBoolean, + isCommandMissingCause, + parseGenericCliVersion, + providerModelsFromSettings, + spawnAndCollect, + type CommandResult, +} from "../providerSnapshot"; +import { makeManagedServerProvider } from "../makeManagedServerProvider"; +import { + formatCodexCliUpgradeMessage, + isCodexCliVersionSupported, + parseCodexCliVersion, +} from "../codexCliVersion"; +import { + adjustCodexModelsForAccount, + codexAuthSubLabel, + codexAuthSubType, + type CodexAccountSnapshot, +} from "../codexAccount"; +import { probeCodexAccount } from "../codexAppServer"; +import { CodexProvider } from "../Services/CodexProvider"; +import { ServerSettingsService } from "../../serverSettings"; +import { ServerSettingsError } from "@t3tools/contracts"; + +const PROVIDER = "codex" as const; +const OPENAI_AUTH_PROVIDERS = new Set(["openai"]); +const BUILT_IN_MODELS: ReadonlyArray = [ + { + slug: "gpt-5.4", + name: "GPT-5.4", + isCustom: false, + capabilities: { + reasoningEffortLevels: [ + { value: "xhigh", label: "Extra High" }, + { value: "high", label: "High", isDefault: true }, + { value: "medium", label: "Medium" }, + { value: "low", label: "Low" }, + ], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + { + slug: "gpt-5.4-mini", + name: "GPT-5.4 Mini", + isCustom: false, + capabilities: { + reasoningEffortLevels: [ + { value: "xhigh", label: "Extra High" }, + { value: "high", label: "High", isDefault: true }, + { value: "medium", label: "Medium" }, + { value: "low", label: "Low" }, + ], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + { + slug: "gpt-5.3-codex", + name: "GPT-5.3 Codex", + isCustom: false, + capabilities: { + reasoningEffortLevels: [ + { value: "xhigh", label: "Extra High" }, + { value: "high", label: "High", isDefault: true }, + { value: "medium", label: "Medium" }, + { value: "low", label: "Low" }, + ], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + { + slug: "gpt-5.3-codex-spark", + name: "GPT-5.3 Codex Spark", + isCustom: false, + capabilities: { + reasoningEffortLevels: [ + { value: "xhigh", label: "Extra High" }, + { value: "high", label: "High", isDefault: true }, + { value: "medium", label: "Medium" }, + { value: "low", label: "Low" }, + ], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + { + slug: "gpt-5.2-codex", + name: "GPT-5.2 Codex", + isCustom: false, + capabilities: { + reasoningEffortLevels: [ + { value: "xhigh", label: "Extra High" }, + { value: "high", label: "High", isDefault: true }, + { value: "medium", label: "Medium" }, + { value: "low", label: "Low" }, + ], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + { + slug: "gpt-5.2", + name: "GPT-5.2", + isCustom: false, + capabilities: { + reasoningEffortLevels: [ + { value: "xhigh", label: "Extra High" }, + { value: "high", label: "High", isDefault: true }, + { value: "medium", label: "Medium" }, + { value: "low", label: "Low" }, + ], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, +]; + +export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities { + const slug = model?.trim(); + return ( + BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? { + reasoningEffortLevels: [], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + } + ); +} + +export function parseAuthStatusFromOutput(result: CommandResult): { + readonly status: Exclude; + readonly auth: Pick; + readonly message?: string; +} { + const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase(); + + if ( + lowerOutput.includes("unknown command") || + lowerOutput.includes("unrecognized command") || + lowerOutput.includes("unexpected argument") + ) { + return { + status: "warning", + auth: { status: "unknown" }, + message: "Codex CLI authentication status command is unavailable in this Codex version.", + }; + } + + if ( + lowerOutput.includes("not logged in") || + lowerOutput.includes("login required") || + lowerOutput.includes("authentication required") || + lowerOutput.includes("run `codex login`") || + lowerOutput.includes("run codex login") + ) { + return { + status: "error", + auth: { status: "unauthenticated" }, + message: "Codex CLI is not authenticated. Run `codex login` and try again.", + }; + } + + const parsedAuth = (() => { + const trimmed = result.stdout.trim(); + if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) { + return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined }; + } + try { + return { + attemptedJsonParse: true as const, + auth: extractAuthBoolean(JSON.parse(trimmed)), + }; + } catch { + return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined }; + } + })(); + + if (parsedAuth.auth === true) { + return { status: "ready", auth: { status: "authenticated" } }; + } + if (parsedAuth.auth === false) { + return { + status: "error", + auth: { status: "unauthenticated" }, + message: "Codex CLI is not authenticated. Run `codex login` and try again.", + }; + } + if (parsedAuth.attemptedJsonParse) { + return { + status: "warning", + auth: { status: "unknown" }, + message: + "Could not verify Codex authentication status from JSON output (missing auth marker).", + }; + } + if (result.code === 0) { + return { status: "ready", auth: { status: "authenticated" } }; + } + + const detail = detailFromResult(result); + return { + status: "warning", + auth: { status: "unknown" }, + message: detail + ? `Could not verify Codex authentication status. ${detail}` + : "Could not verify Codex authentication status.", + }; +} + +export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const settingsService = yield* ServerSettingsService; + const codexHome = yield* settingsService.getSettings.pipe( + Effect.map( + (settings) => + settings.providers.codex.homePath || + process.env.CODEX_HOME || + path.join(OS.homedir(), ".codex"), + ), + ); + const configPath = path.join(codexHome, "config.toml"); + + const content = yield* fileSystem + .readFileString(configPath) + .pipe(Effect.orElseSucceed(() => undefined)); + if (content === undefined) { + return undefined; + } + + let inTopLevel = true; + for (const line of content.split("\n")) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + if (trimmed.startsWith("[")) { + inTopLevel = false; + continue; + } + if (!inTopLevel) continue; + + const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/); + if (match) return match[1]; + } + return undefined; +}); + +export const hasCustomModelProvider = readCodexConfigModelProvider().pipe( + Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)), + Effect.orElseSucceed(() => false), +); + +const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000; + +const probeCodexCapabilities = (input: { + readonly binaryPath: string; + readonly homePath?: string; +}) => + Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe( + Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS), + Effect.result, + Effect.map((result) => { + if (Result.isFailure(result)) return undefined; + return Option.isSome(result.success) ? result.success.value : undefined; + }), + ); + +const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray) { + const settingsService = yield* ServerSettingsService; + const codexSettings = yield* settingsService.getSettings.pipe( + Effect.map((settings) => settings.providers.codex), + ); + const command = ChildProcess.make(codexSettings.binaryPath, [...args], { + shell: process.platform === "win32", + env: { + ...process.env, + ...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}), + }, + }); + return yield* spawnAndCollect(codexSettings.binaryPath, command); +}); + +export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* ( + resolveAccount?: (input: { + readonly binaryPath: string; + readonly homePath?: string; + }) => Effect.Effect, +): Effect.fn.Return< + ServerProvider, + ServerSettingsError, + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | Path.Path + | ServerSettingsService +> { + const codexSettings = yield* Effect.service(ServerSettingsService).pipe( + Effect.flatMap((service) => service.getSettings), + Effect.map((settings) => settings.providers.codex), + ); + const checkedAt = new Date().toISOString(); + const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels); + + if (!codexSettings.enabled) { + return buildServerProvider({ + provider: PROVIDER, + enabled: false, + checkedAt, + models, + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Codex is disabled in T3 Code settings.", + }, + }); + } + + const versionProbe = yield* runCodexCommand(["--version"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); + + if (Result.isFailure(versionProbe)) { + const error = versionProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: !isCommandMissingCause(error), + version: null, + status: "error", + auth: { status: "unknown" }, + message: isCommandMissingCause(error) + ? "Codex CLI (`codex`) is not installed or not on PATH." + : `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`, + }, + }); + } + + if (Option.isNone(versionProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: "Codex CLI is installed but failed to run. Timed out while running command.", + }, + }); + } + + const version = versionProbe.success.value; + const parsedVersion = + parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ?? + parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); + if (version.code !== 0) { + const detail = detailFromResult(version); + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: parsedVersion, + status: "error", + auth: { status: "unknown" }, + message: detail + ? `Codex CLI is installed but failed to run. ${detail}` + : "Codex CLI is installed but failed to run.", + }, + }); + } + + if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: parsedVersion, + status: "error", + auth: { status: "unknown" }, + message: formatCodexCliUpgradeMessage(parsedVersion), + }, + }); + } + + if (yield* hasCustomModelProvider) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: parsedVersion, + status: "ready", + auth: { status: "unknown" }, + message: "Using a custom Codex model provider; OpenAI login check skipped.", + }, + }); + } + + const authProbe = yield* runCodexCommand(["login", "status"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); + const account = resolveAccount + ? yield* resolveAccount({ + binaryPath: codexSettings.binaryPath, + homePath: codexSettings.homePath, + }) + : undefined; + const resolvedModels = adjustCodexModelsForAccount(models, account); + + if (Result.isFailure(authProbe)) { + const error = authProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: + error instanceof Error + ? `Could not verify Codex authentication status: ${error.message}.` + : "Could not verify Codex authentication status.", + }, + }); + } + + if (Option.isNone(authProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: "Could not verify Codex authentication status. Timed out while running command.", + }, + }); + } + + const parsed = parseAuthStatusFromOutput(authProbe.success.value); + const authType = codexAuthSubType(account); + const authLabel = codexAuthSubLabel(account); + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: parsed.status, + auth: { + ...parsed.auth, + ...(authType ? { type: authType } : {}), + ...(authLabel ? { label: authLabel } : {}), + }, + ...(parsed.message ? { message: parsed.message } : {}), + }, + }); +}); + +export const CodexProviderLive = Layer.effect( + CodexProvider, + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const accountProbeCache = yield* Cache.make({ + capacity: 4, + timeToLive: Duration.minutes(5), + lookup: (key: string) => { + const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined]; + return probeCodexCapabilities({ + binaryPath, + ...(homePath ? { homePath } : {}), + }); + }, + }); + + const checkProvider = checkCodexProviderStatus((input) => + Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])), + ).pipe( + Effect.provideService(ServerSettingsService, serverSettings), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + return yield* makeManagedServerProvider({ + getSettings: serverSettings.getSettings.pipe( + Effect.map((settings) => settings.providers.codex), + Effect.orDie, + ), + streamSettings: serverSettings.streamChanges.pipe( + Stream.map((settings) => settings.providers.codex), + ), + haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), + checkProvider, + }); + }), +); diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts new file mode 100644 index 0000000000..258b50d6f2 --- /dev/null +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts @@ -0,0 +1,166 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { ThreadId } from "@t3tools/contracts"; +import { assert, describe, it } from "@effect/vitest"; +import { Effect } from "effect"; + +import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; + +function parseLogLine(line: string) { + const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line); + assert.notEqual(match, null); + if (!match) { + throw new Error(`invalid log line: ${line}`); + } + const observedAt = match[1]; + const stream = match[2]; + const payload = match[3]; + if (!observedAt || !stream || payload === undefined) { + throw new Error(`invalid log line: ${line}`); + } + return { + observedAt, + stream, + payload, + }; +} + +describe("EventNdjsonLogger", () => { + it.effect("writes effect-style lines to thread-scoped files", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-")); + const basePath = path.join(tempDir, "provider-native.ndjson"); + + try { + const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" }); + assert.notEqual(logger, undefined); + if (!logger) { + return; + } + + yield* logger.write( + { threadId: "provider-thread-1", id: "evt-1" }, + ThreadId.makeUnsafe("thread-1"), + ); + yield* logger.write( + { type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" }, + ThreadId.makeUnsafe("thread-2"), + ); + yield* logger.close(); + + const threadOnePath = path.join(tempDir, "thread-1.log"); + const threadTwoPath = path.join(tempDir, "thread-2.log"); + assert.equal(fs.existsSync(threadOnePath), true); + assert.equal(fs.existsSync(threadTwoPath), true); + + const first = parseLogLine(fs.readFileSync(threadOnePath, "utf8").trim()); + const second = parseLogLine(fs.readFileSync(threadTwoPath, "utf8").trim()); + + assert.equal(Number.isNaN(Date.parse(first.observedAt)), false); + assert.equal(first.stream, "NTIVE"); + assert.equal(first.payload, '{"threadId":"provider-thread-1","id":"evt-1"}'); + + assert.equal(Number.isNaN(Date.parse(second.observedAt)), false); + assert.equal(second.stream, "NTIVE"); + assert.equal( + second.payload, + '{"type":"turn.completed","threadId":"provider-thread-2","id":"evt-2"}', + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + + it.effect( + "falls back to a global segment when orchestration thread id is missing or invalid", + () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-")); + const basePath = path.join(tempDir, "provider-canonical.ndjson"); + + try { + const logger = yield* makeEventNdjsonLogger(basePath, { stream: "orchestration" }); + assert.notEqual(logger, undefined); + if (!logger) { + return; + } + + yield* logger.write({ id: "evt-no-thread" }, null); + yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId); + yield* logger.close(); + + const globalPath = path.join(tempDir, "_global.log"); + assert.equal(fs.existsSync(globalPath), true); + const lines = fs + .readFileSync(globalPath, "utf8") + .trim() + .split("\n") + .map((line) => parseLogLine(line)); + assert.equal(lines.length, 2); + assert.equal(Number.isNaN(Date.parse(lines[0]?.observedAt ?? "")), false); + assert.equal(Number.isNaN(Date.parse(lines[1]?.observedAt ?? "")), false); + assert.equal(lines[0]?.stream, "CANON"); + assert.equal(lines[0]?.payload, '{"id":"evt-no-thread"}'); + assert.equal(lines[1]?.stream, "CANON"); + assert.equal(lines[1]?.payload, '{"id":"evt-invalid-thread"}'); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + + it.effect("rotates per-thread files when max size is exceeded", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-")); + const basePath = path.join(tempDir, "provider-native.ndjson"); + + try { + const logger = yield* makeEventNdjsonLogger(basePath, { + stream: "native", + maxBytes: 120, + maxFiles: 2, + }); + assert.notEqual(logger, undefined); + if (!logger) { + return; + } + + for (let index = 0; index < 10; index += 1) { + yield* logger.write( + { + threadId: "provider-thread-rotate", + id: `evt-${index}`, + payload: "x".repeat(40), + }, + ThreadId.makeUnsafe("thread-rotate"), + ); + } + yield* logger.close(); + + const fileStem = "thread-rotate.log"; + const matchingFiles = fs + .readdirSync(tempDir) + .filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`)) + .toSorted(); + + assert.equal( + matchingFiles.some((entry) => entry === `${fileStem}.1`), + true, + ); + assert.equal( + matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`), + true, + ); + assert.equal( + matchingFiles.some((entry) => entry === `${fileStem}.3`), + false, + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); +}); diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.ts new file mode 100644 index 0000000000..a4fd6f235d --- /dev/null +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.ts @@ -0,0 +1,253 @@ +/** + * Provider event logger helper. + * + * Best-effort writer for observability logs. Each record is formatted as a + * single effect-style text line in a thread-scoped file. Failures are + * downgraded to warnings so provider runtime behavior is unaffected. + */ +import fs from "node:fs"; +import path from "node:path"; + +import type { ThreadId } from "@t3tools/contracts"; +import { RotatingFileSink } from "@t3tools/shared/logging"; +import { Effect, Exit, Logger, Scope } from "effect"; + +import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts"; + +const DEFAULT_MAX_BYTES = 10 * 1024 * 1024; +const DEFAULT_MAX_FILES = 10; +const DEFAULT_BATCH_WINDOW_MS = 200; +const GLOBAL_THREAD_SEGMENT = "_global"; +const LOG_SCOPE = "provider-observability"; + +export type EventNdjsonStream = "native" | "canonical" | "orchestration"; + +export interface EventNdjsonLogger { + readonly filePath: string; + write: (event: unknown, threadId: ThreadId | null) => Effect.Effect; + close: () => Effect.Effect; +} + +export interface EventNdjsonLoggerOptions { + readonly stream: EventNdjsonStream; + readonly maxBytes?: number; + readonly maxFiles?: number; + readonly batchWindowMs?: number; +} + +interface ThreadWriter { + writeMessage: (message: string) => Effect.Effect; + close: () => Effect.Effect; +} + +function logWarning(message: string, context: Record): Effect.Effect { + return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE })); +} + +function resolveThreadSegment(raw: string | null | undefined): string { + const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null; + return normalized ?? GLOBAL_THREAD_SEGMENT; +} + +function formatLoggerMessage(message: unknown): string { + if (Array.isArray(message)) { + return message.map((part) => (typeof part === "string" ? part : String(part))).join(" "); + } + return typeof message === "string" ? message : String(message); +} + +function makeLineLogger(streamLabel: string): Logger.Logger { + return Logger.make( + ({ date, message }) => + `[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`, + ); +} + +function resolveStreamLabel(stream: EventNdjsonStream): string { + switch (stream) { + case "native": + return "NTIVE"; + case "canonical": + case "orchestration": + default: + return "CANON"; + } +} + +const toLogMessage = Effect.fn("toLogMessage")(function* ( + event: unknown, +): Effect.fn.Return { + const serialized = yield* Effect.sync(() => { + try { + return { ok: true as const, value: JSON.stringify(event) }; + } catch (error) { + return { ok: false as const, error }; + } + }); + + if (!serialized.ok) { + yield* logWarning("failed to serialize provider event log record", { + error: serialized.error, + }); + return undefined; + } + + if (typeof serialized.value !== "string") { + return undefined; + } + + return serialized.value; +}); + +const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: { + readonly filePath: string; + readonly maxBytes: number; + readonly maxFiles: number; + readonly batchWindowMs: number; + readonly streamLabel: string; +}): Effect.fn.Return { + const sinkResult = yield* Effect.sync(() => { + try { + return { + ok: true as const, + sink: new RotatingFileSink({ + filePath: input.filePath, + maxBytes: input.maxBytes, + maxFiles: input.maxFiles, + throwOnError: true, + }), + }; + } catch (error) { + return { ok: false as const, error }; + } + }); + + if (!sinkResult.ok) { + yield* logWarning("failed to initialize provider thread log file", { + filePath: input.filePath, + error: sinkResult.error, + }); + return undefined; + } + + const sink = sinkResult.sink; + const scope = yield* Scope.make(); + const lineLogger = makeLineLogger(input.streamLabel); + const batchedLogger = yield* Logger.batched(lineLogger, { + window: input.batchWindowMs, + flush: Effect.fn("makeThreadWriter.flush")(function* (messages) { + const flushResult = yield* Effect.sync(() => { + try { + for (const message of messages) { + sink.write(message); + } + return { ok: true as const }; + } catch (error) { + return { ok: false as const, error }; + } + }); + + if (!flushResult.ok) { + yield* logWarning("provider event log batch flush failed", { + filePath: input.filePath, + error: flushResult.error, + }); + } + }), + }).pipe(Effect.provideService(Scope.Scope, scope)); + + const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false }); + + return { + writeMessage(message: string) { + return Effect.log(message).pipe(Effect.provide(loggerLayer)); + }, + close() { + return Scope.close(scope, Exit.void); + }, + } satisfies ThreadWriter; +}); + +export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* ( + filePath: string, + options: EventNdjsonLoggerOptions, +): Effect.fn.Return { + const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES; + const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES; + const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS; + const streamLabel = resolveStreamLabel(options.stream); + + const directoryReady = yield* Effect.sync(() => { + try { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + return true; + } catch (error) { + return { ok: false as const, error }; + } + }); + if (directoryReady !== true) { + yield* logWarning("failed to create provider event log directory", { + filePath, + error: directoryReady.error, + }); + return undefined; + } + + const threadWriters = new Map(); + const failedSegments = new Set(); + + const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* ( + threadSegment: string, + ): Effect.fn.Return { + if (failedSegments.has(threadSegment)) { + return undefined; + } + const existing = threadWriters.get(threadSegment); + if (existing) { + return existing; + } + + const writer = yield* makeThreadWriter({ + filePath: path.join(path.dirname(filePath), `${threadSegment}.log`), + maxBytes, + maxFiles, + batchWindowMs, + streamLabel, + }); + if (!writer) { + failedSegments.add(threadSegment); + return undefined; + } + + threadWriters.set(threadSegment, writer); + return writer; + }); + + const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) { + const threadSegment = resolveThreadSegment(threadId); + const message = yield* toLogMessage(event); + if (!message) { + return; + } + + const writer = yield* resolveThreadWriter(threadSegment); + if (!writer) { + return; + } + + yield* writer.writeMessage(message); + }); + + const close = Effect.fn("close")(function* () { + for (const writer of threadWriters.values()) { + yield* writer.close(); + } + threadWriters.clear(); + }); + + return { + filePath, + write, + close, + } satisfies EventNdjsonLogger; +}); diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts new file mode 100644 index 0000000000..db0293f0fe --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts @@ -0,0 +1,82 @@ +import type { ProviderKind } from "@t3tools/contracts"; +import { it, assert, vi } from "@effect/vitest"; +import { assertFailure } from "@effect/vitest/utils"; + +import { Effect, Layer, Stream } from "effect"; + +import { ClaudeAdapter, ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts"; +import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts"; +import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; +import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts"; +import { ProviderUnsupportedError } from "../Errors.ts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; + +const fakeCodexAdapter: CodexAdapterShape = { + provider: "codex", + capabilities: { sessionModelSwitch: "in-session" }, + 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 fakeClaudeAdapter: ClaudeAdapterShape = { + provider: "claudeAgent", + capabilities: { sessionModelSwitch: "in-session" }, + 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(ClaudeAdapter, fakeClaudeAdapter), + ), + ), + NodeServices.layer, + ), +); + +layer("ProviderAdapterRegistryLive", (it) => { + it.effect("resolves a registered provider adapter", () => + Effect.gen(function* () { + const registry = yield* ProviderAdapterRegistry; + const codex = yield* registry.getByProvider("codex"); + const claude = yield* registry.getByProvider("claudeAgent"); + assert.equal(codex, fakeCodexAdapter); + assert.equal(claude, fakeClaudeAdapter); + + const providers = yield* registry.listProviders(); + assert.deepEqual(providers, ["codex", "claudeAgent"]); + }), + ); + + it.effect("fails with ProviderUnsupportedError for unknown providers", () => + Effect.gen(function* () { + const registry = yield* ProviderAdapterRegistry; + const adapter = yield* registry.getByProvider("unknown" as ProviderKind).pipe(Effect.result); + assertFailure(adapter, new ProviderUnsupportedError({ provider: "unknown" })); + }), + ); +}); diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts new file mode 100644 index 0000000000..b6c987c64c --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts @@ -0,0 +1,54 @@ +/** + * ProviderAdapterRegistryLive - In-memory provider adapter lookup layer. + * + * Binds provider kinds (codex/claudeAgent/...) to concrete adapter services. + * This layer only performs adapter lookup; it does not route session-scoped + * calls or own provider lifecycle workflows. + * + * @module ProviderAdapterRegistryLive + */ +import { Effect, Layer } from "effect"; + +import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts"; +import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; +import { + ProviderAdapterRegistry, + type ProviderAdapterRegistryShape, +} from "../Services/ProviderAdapterRegistry.ts"; +import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts"; +import { CodexAdapter } from "../Services/CodexAdapter.ts"; + +export interface ProviderAdapterRegistryLiveOptions { + readonly adapters?: ReadonlyArray>; +} + +const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* ( + options?: ProviderAdapterRegistryLiveOptions, +) { + const adapters = + options?.adapters !== undefined + ? options.adapters + : [yield* CodexAdapter, yield* ClaudeAdapter]; + const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter])); + + const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => { + const adapter = byProvider.get(provider); + if (!adapter) { + return Effect.fail(new ProviderUnsupportedError({ provider })); + } + return Effect.succeed(adapter); + }; + + const listProviders: ProviderAdapterRegistryShape["listProviders"] = () => + Effect.sync(() => Array.from(byProvider.keys())); + + return { + getByProvider, + listProviders, + } satisfies ProviderAdapterRegistryShape; +}); + +export const ProviderAdapterRegistryLive = Layer.effect( + ProviderAdapterRegistry, + makeProviderAdapterRegistry(), +); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts new file mode 100644 index 0000000000..116c008d67 --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -0,0 +1,1057 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, it, assert } from "@effect/vitest"; +import { + Effect, + Exit, + FileSystem, + Layer, + Path, + PubSub, + Ref, + Schema, + Scope, + Sink, + Stream, +} from "effect"; +import { + DEFAULT_SERVER_SETTINGS, + ServerSettings, + type ServerProvider, + type ServerSettings as ContractServerSettings, +} from "@t3tools/contracts"; +import * as PlatformError from "effect/PlatformError"; +import { ChildProcessSpawner } from "effect/unstable/process"; +import { deepMerge } from "@t3tools/shared/Struct"; + +import { + checkCodexProviderStatus, + hasCustomModelProvider, + parseAuthStatusFromOutput, + readCodexConfigModelProvider, +} from "./CodexProvider"; +import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider"; +import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry"; +import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings"; +import { ProviderRegistry } from "../Services/ProviderRegistry"; + +// ── Test helpers ──────────────────────────────────────────────────── + +const encoder = new TextEncoder(); + +function mockHandle(result: { stdout: string; stderr: string; code: number }) { + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + stdout: Stream.make(encoder.encode(result.stdout)), + stderr: Stream.make(encoder.encode(result.stderr)), + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); +} + +function mockSpawnerLayer( + handler: (args: ReadonlyArray) => { stdout: string; stderr: string; code: number }, +) { + return Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => { + const cmd = command as unknown as { args: ReadonlyArray }; + return Effect.succeed(mockHandle(handler(cmd.args))); + }), + ); +} + +function mockCommandSpawnerLayer( + handler: ( + command: string, + args: ReadonlyArray, + ) => { stdout: string; stderr: string; code: number }, +) { + return Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => { + const cmd = command as unknown as { command: string; args: ReadonlyArray }; + return Effect.succeed(mockHandle(handler(cmd.command, cmd.args))); + }), + ); +} + +function failingSpawnerLayer(description: string) { + return Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "ChildProcess", + method: "spawn", + description, + }), + ), + ), + ); +} + +function makeMutableServerSettingsService( + initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS, +) { + return Effect.gen(function* () { + const settingsRef = yield* Ref.make(initial); + const changes = yield* PubSub.unbounded(); + + return { + start: Effect.void, + ready: Effect.void, + getSettings: Ref.get(settingsRef), + updateSettings: (patch) => + Effect.gen(function* () { + const current = yield* Ref.get(settingsRef); + const next = Schema.decodeSync(ServerSettings)(deepMerge(current, patch)); + yield* Ref.set(settingsRef, next); + yield* PubSub.publish(changes, next); + return next; + }), + streamChanges: Stream.fromPubSub(changes), + } satisfies ServerSettingsShape; + }); +} + +/** + * Create a temporary CODEX_HOME scoped to the current Effect test. + * Cleanup is registered in the test scope rather than via Vitest hooks. + */ +function withTempCodexHome(configContent?: string) { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" }); + + yield* Effect.acquireRelease( + Effect.sync(() => { + const originalCodexHome = process.env.CODEX_HOME; + process.env.CODEX_HOME = tmpDir; + return originalCodexHome; + }), + (originalCodexHome) => + Effect.sync(() => { + if (originalCodexHome !== undefined) { + process.env.CODEX_HOME = originalCodexHome; + } else { + delete process.env.CODEX_HOME; + } + }), + ); + + if (configContent !== undefined) { + yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent); + } + + return { tmpDir } as const; + }); +} + +it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( + "ProviderRegistry", + (it) => { + // ── checkCodexProviderStatus tests ──────────────────────────────── + // + // These tests control CODEX_HOME to ensure the custom-provider detection + // in hasCustomModelProvider() does not interfere with the auth-probe + // path being tested. + + describe("checkCodexProviderStatus", () => { + it.effect("returns ready when codex is installed and authenticated", () => + Effect.gen(function* () { + // Point CODEX_HOME at an empty tmp dir (no config.toml) so the + // default code path (OpenAI provider, auth probe runs) is exercised. + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(); + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "authenticated"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns the codex plan type in auth and keeps spark for supported plans", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "chatgpt" as const, + planType: "pro" as const, + sparkEnabled: true, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "pro"); + assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + true, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("hides spark from codex models for unsupported chatgpt plans", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "chatgpt" as const, + planType: "plus" as const, + sparkEnabled: false, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "plus"); + assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + false, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "chatgpt" as const, + planType: "team" as const, + sparkEnabled: false, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.auth.type, "team"); + assert.strictEqual(status.auth.label, "ChatGPT Team Subscription"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + false, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns an api key label for codex api key auth", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "apiKey" as const, + planType: null, + sparkEnabled: false, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "apiKey"); + assert.strictEqual(status.auth.label, "OpenAI API Key"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + false, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect.skipIf(process.platform === "win32")( + "inherits PATH when launching the codex probe with a CODEX_HOME override", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-test-codex-bin-", + }); + const codexPath = path.join(binDir, "codex"); + yield* fileSystem.writeFileString( + codexPath, + [ + "#!/bin/sh", + 'if [ "$1" = "--version" ]; then', + ' echo "codex-cli 1.0.0"', + " exit 0", + "fi", + 'if [ "$1" = "login" ] && [ "$2" = "status" ]; then', + ' echo "Logged in using ChatGPT"', + " exit 0", + "fi", + 'echo "unexpected args: $*" >&2', + "exit 1", + "", + ].join("\n"), + ); + yield* fileSystem.chmod(codexPath, 0o755); + const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-test-codex-home-", + }); + const previousPath = process.env.PATH; + process.env.PATH = binDir; + + try { + const serverSettingsLayer = ServerSettingsService.layerTest({ + providers: { + codex: { + homePath: customCodexHome, + }, + }, + }); + + const status = yield* checkCodexProviderStatus().pipe( + Effect.provide(serverSettingsLayer), + ); + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + } finally { + process.env.PATH = previousPath; + } + }), + ); + + it.effect("returns unavailable when codex is missing", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(); + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.installed, false); + assert.strictEqual(status.auth.status, "unknown"); + assert.strictEqual( + status.message, + "Codex CLI (`codex`) is not installed or not on PATH.", + ); + }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))), + ); + + it.effect("returns unavailable when codex is below the minimum supported version", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(); + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "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* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(); + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "unauthenticated"); + assert.strictEqual( + status.message, + "Codex CLI is not authenticated. Run `codex login` and try again.", + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") { + return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 }; + } + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns unauthenticated when login status output includes 'not logged in'", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(); + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "unauthenticated"); + assert.strictEqual( + status.message, + "Codex CLI is not authenticated. Run `codex login` and try again.", + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") + return { stdout: "Not logged in\n", stderr: "", code: 1 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns warning when login status command is unsupported", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(); + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "warning"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "unknown"); + assert.strictEqual( + status.message, + "Codex CLI authentication status command is unavailable in this Codex version.", + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") { + return { stdout: "", stderr: "error: unknown command 'login'", code: 2 }; + } + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + }); + + describe("ProviderRegistryLive", () => { + it("treats equal provider snapshots as unchanged", () => { + const providers = [ + { + provider: "codex", + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-03-25T00:00:00.000Z", + version: "1.0.0", + models: [], + }, + { + provider: "claudeAgent", + status: "warning", + enabled: true, + installed: true, + auth: { status: "unknown" }, + checkedAt: "2026-03-25T00:00:00.000Z", + version: "1.0.0", + models: [], + }, + ] as const satisfies ReadonlyArray; + + assert.strictEqual(haveProvidersChanged(providers, [...providers]), false); + }); + + it.effect("reruns codex health when codex provider settings change", () => + Effect.gen(function* () { + const serverSettings = yield* makeMutableServerSettingsService(); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const providerRegistryLayer = ProviderRegistryLive.pipe( + Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), + Layer.provideMerge( + mockCommandSpawnerLayer((command, args) => { + const joined = args.join(" "); + if (joined === "--version") { + if (command === "codex") { + return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + } + return { stdout: "", stderr: "spawn ENOENT", code: 1 }; + } + if (joined === "login status") { + return { stdout: "Logged in\n", stderr: "", code: 0 }; + } + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ); + const runtimeServices = yield* Layer.build( + Layer.mergeAll( + Layer.succeed(ServerSettingsService, serverSettings), + providerRegistryLayer, + ), + ).pipe(Scope.provide(scope)); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + + const initial = yield* registry.getProviders; + assert.strictEqual( + initial.find((status) => status.provider === "codex")?.status, + "ready", + ); + + yield* serverSettings.updateSettings({ + providers: { + codex: { + binaryPath: "/custom/codex", + }, + }, + }); + + for (let attempt = 0; attempt < 20; attempt += 1) { + const updated = yield* registry.getProviders; + if (updated.find((status) => status.provider === "codex")?.status === "error") { + return; + } + yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 0))); + } + + const updated = yield* registry.getProviders; + assert.strictEqual( + updated.find((status) => status.provider === "codex")?.status, + "error", + ); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + it.effect("skips codex probes entirely when the provider is disabled", () => + Effect.gen(function* () { + const serverSettingsLayer = ServerSettingsService.layerTest({ + providers: { + codex: { + enabled: false, + }, + }, + }); + + const status = yield* checkCodexProviderStatus().pipe( + Effect.provide( + Layer.mergeAll(serverSettingsLayer, failingSpawnerLayer("spawn codex ENOENT")), + ), + ); + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.enabled, false); + assert.strictEqual(status.status, "disabled"); + assert.strictEqual(status.installed, false); + assert.strictEqual(status.message, "Codex is disabled in T3 Code settings."); + }), + ); + }); + + // ── Custom model provider: checkCodexProviderStatus integration ─── + + describe("checkCodexProviderStatus with custom model provider", () => { + it.effect( + "skips auth probe and returns ready when a custom model provider is configured", + () => + Effect.gen(function* () { + yield* withTempCodexHome( + [ + 'model_provider = "portkey"', + "", + "[model_providers.portkey]", + 'base_url = "https://api.portkey.ai/v1"', + 'env_key = "PORTKEY_API_KEY"', + ].join("\n"), + ); + const status = yield* checkCodexProviderStatus(); + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "unknown"); + assert.strictEqual( + status.message, + "Using a custom Codex model provider; OpenAI login check skipped.", + ); + }).pipe( + Effect.provide( + // The spawner only handles --version; if the test attempts + // "login status" the throw proves the auth probe was NOT skipped. + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + throw new Error(`Auth probe should have been skipped but got args: ${joined}`); + }), + ), + ), + ); + + it.effect("still reports error when codex CLI is missing even with custom provider", () => + Effect.gen(function* () { + yield* withTempCodexHome( + [ + 'model_provider = "portkey"', + "", + "[model_providers.portkey]", + 'base_url = "https://api.portkey.ai/v1"', + 'env_key = "PORTKEY_API_KEY"', + ].join("\n"), + ); + const status = yield* checkCodexProviderStatus(); + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.installed, false); + }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))), + ); + }); + + describe("checkCodexProviderStatus with openai model provider", () => { + it.effect("still runs auth probe when model_provider is openai", () => + Effect.gen(function* () { + yield* withTempCodexHome('model_provider = "openai"\n'); + const status = yield* checkCodexProviderStatus(); + // The auth probe runs and sees "not logged in" → error + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.auth.status, "unauthenticated"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") + return { stdout: "Not logged in\n", stderr: "", code: 1 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + }); + + // ── parseAuthStatusFromOutput pure tests ────────────────────────── + + describe("parseAuthStatusFromOutput", () => { + it("exit code 0 with no auth markers is ready", () => { + const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 }); + assert.strictEqual(parsed.status, "ready"); + assert.strictEqual(parsed.auth.status, "authenticated"); + }); + + it("JSON with authenticated=false is unauthenticated", () => { + const parsed = parseAuthStatusFromOutput({ + stdout: '[{"authenticated":false}]\n', + stderr: "", + code: 0, + }); + assert.strictEqual(parsed.status, "error"); + assert.strictEqual(parsed.auth.status, "unauthenticated"); + }); + + it("JSON without auth marker is warning", () => { + const parsed = parseAuthStatusFromOutput({ + stdout: '[{"ok":true}]\n', + stderr: "", + code: 0, + }); + assert.strictEqual(parsed.status, "warning"); + assert.strictEqual(parsed.auth.status, "unknown"); + }); + }); + + // ── readCodexConfigModelProvider tests ───────────────────────────── + + describe("readCodexConfigModelProvider", () => { + it.effect("returns undefined when config file does not exist", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + assert.strictEqual(yield* readCodexConfigModelProvider(), undefined); + }), + ); + + it.effect("returns undefined when config has no model_provider key", () => + Effect.gen(function* () { + yield* withTempCodexHome('model = "gpt-5-codex"\n'); + assert.strictEqual(yield* readCodexConfigModelProvider(), undefined); + }), + ); + + it.effect("returns the provider when model_provider is set at top level", () => + Effect.gen(function* () { + yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n'); + assert.strictEqual(yield* readCodexConfigModelProvider(), "portkey"); + }), + ); + + it.effect("returns openai when model_provider is openai", () => + Effect.gen(function* () { + yield* withTempCodexHome('model_provider = "openai"\n'); + assert.strictEqual(yield* readCodexConfigModelProvider(), "openai"); + }), + ); + + it.effect("ignores model_provider inside section headers", () => + Effect.gen(function* () { + yield* withTempCodexHome( + [ + 'model = "gpt-5-codex"', + "", + "[model_providers.portkey]", + 'base_url = "https://api.portkey.ai/v1"', + 'model_provider = "should-be-ignored"', + "", + ].join("\n"), + ); + assert.strictEqual(yield* readCodexConfigModelProvider(), undefined); + }), + ); + + it.effect("handles comments and whitespace", () => + Effect.gen(function* () { + yield* withTempCodexHome( + [ + "# This is a comment", + "", + ' model_provider = "azure" ', + "", + "[profiles.deep-review]", + 'model = "gpt-5-pro"', + ].join("\n"), + ); + assert.strictEqual(yield* readCodexConfigModelProvider(), "azure"); + }), + ); + + it.effect("handles single-quoted values in TOML", () => + Effect.gen(function* () { + yield* withTempCodexHome("model_provider = 'mistral'\n"); + assert.strictEqual(yield* readCodexConfigModelProvider(), "mistral"); + }), + ); + }); + + // ── hasCustomModelProvider tests ─────────────────────────────────── + + describe("hasCustomModelProvider", () => { + it.effect("returns false when no config file exists", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + assert.strictEqual(yield* hasCustomModelProvider, false); + }), + ); + + it.effect("returns false when model_provider is not set", () => + Effect.gen(function* () { + yield* withTempCodexHome('model = "gpt-5-codex"\n'); + assert.strictEqual(yield* hasCustomModelProvider, false); + }), + ); + + it.effect("returns false when model_provider is openai", () => + Effect.gen(function* () { + yield* withTempCodexHome('model_provider = "openai"\n'); + assert.strictEqual(yield* hasCustomModelProvider, false); + }), + ); + + it.effect("returns true when model_provider is portkey", () => + Effect.gen(function* () { + yield* withTempCodexHome('model_provider = "portkey"\n'); + assert.strictEqual(yield* hasCustomModelProvider, true); + }), + ); + + it.effect("returns true when model_provider is azure", () => + Effect.gen(function* () { + yield* withTempCodexHome('model_provider = "azure"\n'); + assert.strictEqual(yield* hasCustomModelProvider, true); + }), + ); + + it.effect("returns true when model_provider is ollama", () => + Effect.gen(function* () { + yield* withTempCodexHome('model_provider = "ollama"\n'); + assert.strictEqual(yield* hasCustomModelProvider, true); + }), + ); + + it.effect("returns true when model_provider is a custom proxy", () => + Effect.gen(function* () { + yield* withTempCodexHome('model_provider = "my-company-proxy"\n'); + assert.strictEqual(yield* hasCustomModelProvider, true); + }), + ); + }); + + // ── checkClaudeProviderStatus tests ────────────────────────── + + describe("checkClaudeProviderStatus", () => { + it.effect("returns ready when claude is installed and authenticated", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "authenticated"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { + stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', + stderr: "", + code: 0, + }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns a display label for claude subscription types", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan")); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "maxplan"); + assert.strictEqual(status.auth.label, "Claude Max Subscription"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { + stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', + stderr: "", + code: 0, + }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns an api key label for claude api key auth", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "apiKey"); + assert.strictEqual(status.auth.label, "Claude API Key"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { + stdout: '{"loggedIn":true,"authMethod":"api-key"}\n', + stderr: "", + code: 0, + }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns unavailable when claude is missing", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.installed, false); + assert.strictEqual(status.auth.status, "unknown"); + assert.strictEqual( + status.message, + "Claude Agent CLI (`claude`) is not installed or not on PATH.", + ); + }).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))), + ); + + it.effect("returns error when version check fails with non-zero exit code", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.installed, true); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") + return { stdout: "", stderr: "Something went wrong", code: 1 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns unauthenticated when auth status reports not logged in", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "unauthenticated"); + assert.strictEqual( + status.message, + "Claude is not authenticated. Run `claude auth login` and try again.", + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { + stdout: '{"loggedIn":false}\n', + stderr: "", + code: 1, + }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns unauthenticated when output includes 'not logged in'", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "unauthenticated"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { stdout: "Not logged in\n", stderr: "", code: 1 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns warning when auth status command is unsupported", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "warning"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.auth.status, "unknown"); + assert.strictEqual( + status.message, + "Claude Agent authentication status command is unavailable in this version of Claude.", + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + }); + + // ── parseClaudeAuthStatusFromOutput pure tests ──────────────────── + + describe("parseClaudeAuthStatusFromOutput", () => { + it("exit code 0 with no auth markers is ready", () => { + const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 }); + assert.strictEqual(parsed.status, "ready"); + assert.strictEqual(parsed.auth.status, "authenticated"); + }); + + it("JSON with loggedIn=true is authenticated", () => { + const parsed = parseClaudeAuthStatusFromOutput({ + stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', + stderr: "", + code: 0, + }); + assert.strictEqual(parsed.status, "ready"); + assert.strictEqual(parsed.auth.status, "authenticated"); + }); + + it("JSON with loggedIn=false is unauthenticated", () => { + const parsed = parseClaudeAuthStatusFromOutput({ + stdout: '{"loggedIn":false}\n', + stderr: "", + code: 0, + }); + assert.strictEqual(parsed.status, "error"); + assert.strictEqual(parsed.auth.status, "unauthenticated"); + }); + + it("JSON without auth marker is warning", () => { + const parsed = parseClaudeAuthStatusFromOutput({ + stdout: '{"ok":true}\n', + stderr: "", + code: 0, + }); + assert.strictEqual(parsed.status, "warning"); + assert.strictEqual(parsed.auth.status, "unknown"); + }); + }); + }, +); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts new file mode 100644 index 0000000000..fb2f33c293 --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderRegistry.ts @@ -0,0 +1,96 @@ +/** + * ProviderRegistryLive - Aggregates provider-specific snapshot services. + * + * @module ProviderRegistryLive + */ +import type { ProviderKind, ServerProvider } from "@t3tools/contracts"; +import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect"; + +import { ClaudeProviderLive } from "./ClaudeProvider"; +import { CodexProviderLive } from "./CodexProvider"; +import type { ClaudeProviderShape } from "../Services/ClaudeProvider"; +import { ClaudeProvider } from "../Services/ClaudeProvider"; +import type { CodexProviderShape } from "../Services/CodexProvider"; +import { CodexProvider } from "../Services/CodexProvider"; +import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry"; + +const loadProviders = ( + codexProvider: CodexProviderShape, + claudeProvider: ClaudeProviderShape, +): Effect.Effect => + Effect.all([codexProvider.getSnapshot, claudeProvider.getSnapshot], { + concurrency: "unbounded", + }); + +export const haveProvidersChanged = ( + previousProviders: ReadonlyArray, + nextProviders: ReadonlyArray, +): boolean => !Equal.equals(previousProviders, nextProviders); + +export const ProviderRegistryLive = Layer.effect( + ProviderRegistry, + Effect.gen(function* () { + const codexProvider = yield* CodexProvider; + const claudeProvider = yield* ClaudeProvider; + const changesPubSub = yield* Effect.acquireRelease( + PubSub.unbounded>(), + PubSub.shutdown, + ); + const providersRef = yield* Ref.make>( + yield* loadProviders(codexProvider, claudeProvider), + ); + + const syncProviders = Effect.fn("syncProviders")(function* (options?: { + readonly publish?: boolean; + }) { + const previousProviders = yield* Ref.get(providersRef); + const providers = yield* loadProviders(codexProvider, claudeProvider); + yield* Ref.set(providersRef, providers); + + if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) { + yield* PubSub.publish(changesPubSub, providers); + } + + return providers; + }); + + yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe( + Effect.forkScoped, + ); + yield* Stream.runForEach(claudeProvider.streamChanges, () => syncProviders()).pipe( + Effect.forkScoped, + ); + + const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) { + switch (provider) { + case "codex": + yield* codexProvider.refresh; + break; + case "claudeAgent": + yield* claudeProvider.refresh; + break; + default: + yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], { + concurrency: "unbounded", + }); + break; + } + return yield* syncProviders(); + }); + + return { + getProviders: syncProviders({ publish: false }).pipe( + Effect.tapError(Effect.logError), + Effect.orElseSucceed(() => []), + ), + refresh: (provider?: ProviderKind) => + refresh(provider).pipe( + Effect.tapError(Effect.logError), + Effect.orElseSucceed(() => []), + ), + get streamChanges() { + return Stream.fromPubSub(changesPubSub); + }, + } satisfies ProviderRegistryShape; + }), +).pipe(Layer.provideMerge(CodexProviderLive), Layer.provideMerge(ClaudeProviderLive)); diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts new file mode 100644 index 0000000000..cd6c81405b --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -0,0 +1,1255 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import type { + ProviderApprovalDecision, + ProviderRuntimeEvent, + ProviderSendTurnInput, + ProviderSession, + ProviderTurnStartResult, +} from "@t3tools/contracts"; +import { + ApprovalRequestId, + EventId, + type ProviderKind, + ProviderSessionStartInput, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { it, assert, vi } from "@effect/vitest"; +import { assertFailure } from "@effect/vitest/utils"; + +import { Effect, Fiber, Layer, Metric, Option, PubSub, Ref, Stream } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { + ProviderAdapterSessionNotFoundError, + ProviderUnsupportedError, + ProviderValidationError, + type ProviderAdapterError, +} from "../Errors.ts"; +import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; +import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; +import { ProviderService } from "../Services/ProviderService.ts"; +import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; +import { makeProviderServiceLive } from "./ProviderService.ts"; +import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts"; +import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts"; +import { + makeSqlitePersistenceLive, + SqlitePersistenceMemory, +} from "../../persistence/Layers/Sqlite.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts"; + +const defaultServerSettingsLayer = ServerSettingsService.layerTest(); + +const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value); +const asEventId = (value: string): EventId => EventId.makeUnsafe(value); +const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value); +const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); + +type LegacyProviderRuntimeEvent = { + readonly type: string; + readonly eventId: EventId; + readonly provider: ProviderKind; + readonly createdAt: string; + readonly threadId: ThreadId; + readonly turnId?: string | undefined; + readonly itemId?: string | undefined; + readonly requestId?: string | undefined; + readonly payload?: unknown | undefined; + readonly [key: string]: unknown; +}; + +function makeFakeCodexAdapter(provider: ProviderKind = "codex") { + const sessions = new Map(); + const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); + + const startSession = vi.fn((input: ProviderSessionStartInput) => + Effect.sync(() => { + const now = new Date().toISOString(); + const session: ProviderSession = { + provider, + status: "ready", + runtimeMode: input.runtimeMode, + threadId: input.threadId, + resumeCursor: input.resumeCursor ?? { opaque: `resume-${String(input.threadId)}` }, + cwd: input.cwd ?? process.cwd(), + createdAt: now, + updatedAt: now, + }; + sessions.set(session.threadId, session); + return session; + }), + ); + + const sendTurn = vi.fn( + ( + input: ProviderSendTurnInput, + ): Effect.Effect => { + if (!sessions.has(input.threadId)) { + return Effect.fail( + new ProviderAdapterSessionNotFoundError({ + provider, + threadId: input.threadId, + }), + ); + } + + return Effect.succeed({ + threadId: input.threadId, + turnId: TurnId.makeUnsafe(`turn-${String(input.threadId)}`), + }); + }, + ); + + const interruptTurn = vi.fn( + (_threadId: ThreadId, _turnId?: TurnId): Effect.Effect => + Effect.void, + ); + + const respondToRequest = vi.fn( + ( + _threadId: ThreadId, + _requestId: string, + _decision: ProviderApprovalDecision, + ): Effect.Effect => Effect.void, + ); + + const respondToUserInput = vi.fn( + ( + _threadId: ThreadId, + _requestId: string, + _answers: Record, + ): Effect.Effect => Effect.void, + ); + + const stopSession = vi.fn( + (threadId: ThreadId): Effect.Effect => + Effect.sync(() => { + sessions.delete(threadId); + }), + ); + + const listSessions = vi.fn( + (): Effect.Effect> => + Effect.sync(() => Array.from(sessions.values())), + ); + + const hasSession = vi.fn( + (threadId: ThreadId): Effect.Effect => Effect.succeed(sessions.has(threadId)), + ); + + const readThread = vi.fn( + ( + threadId: ThreadId, + ): Effect.Effect< + { + threadId: ThreadId; + turns: ReadonlyArray<{ id: TurnId; items: readonly [] }>; + }, + ProviderAdapterError + > => + Effect.succeed({ + threadId, + turns: [{ id: asTurnId("turn-1"), items: [] }], + }), + ); + + const rollbackThread = vi.fn( + ( + threadId: ThreadId, + _numTurns: number, + ): Effect.Effect<{ threadId: ThreadId; turns: readonly [] }, ProviderAdapterError> => + Effect.succeed({ threadId, turns: [] }), + ); + + const stopAll = vi.fn( + (): Effect.Effect => + Effect.sync(() => { + sessions.clear(); + }), + ); + + const adapter: ProviderAdapterShape = { + provider, + capabilities: { + sessionModelSwitch: "in-session", + }, + startSession, + sendTurn, + interruptTurn, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + hasSession, + readThread, + rollbackThread, + stopAll, + streamEvents: Stream.fromPubSub(runtimeEventPubSub), + }; + + const emit = (event: LegacyProviderRuntimeEvent): void => { + Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent)); + }; + + const updateSession = ( + threadId: ThreadId, + update: (session: ProviderSession) => ProviderSession, + ): void => { + const existing = sessions.get(threadId); + if (!existing) { + return; + } + sessions.set(threadId, update(existing)); + }; + + return { + adapter, + emit, + updateSession, + startSession, + sendTurn, + interruptTurn, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + hasSession, + readThread, + rollbackThread, + stopAll, + }; +} + +const sleep = (ms: number) => + Effect.promise(() => new Promise((resolve) => setTimeout(resolve, ms))); + +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + +function makeProviderServiceLayer() { + const codex = makeFakeCodexAdapter(); + const claude = makeFakeCodexAdapter("claudeAgent"); + const registry: typeof ProviderAdapterRegistry.Service = { + getByProvider: (provider) => + provider === "codex" + ? Effect.succeed(codex.adapter) + : provider === "claudeAgent" + ? Effect.succeed(claude.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed(["codex", "claudeAgent"]), + }; + + const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry); + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(SqlitePersistenceMemory), + ); + const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); + + const layer = it.layer( + Layer.mergeAll( + makeProviderServiceLive().pipe( + Layer.provide(providerAdapterLayer), + Layer.provide(directoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provideMerge(AnalyticsService.layerTest), + ), + directoryLayer, + + runtimeRepositoryLayer, + NodeServices.layer, + ), + ); + + return { + codex, + claude, + layer, + }; +} + +it.effect("ProviderServiceLive rejects new sessions for disabled providers", () => + Effect.gen(function* () { + const codex = makeFakeCodexAdapter(); + const claude = makeFakeCodexAdapter("claudeAgent"); + const registry: typeof ProviderAdapterRegistry.Service = { + getByProvider: (provider) => + provider === "codex" + ? Effect.succeed(codex.adapter) + : provider === "claudeAgent" + ? Effect.succeed(claude.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed(["codex", "claudeAgent"]), + }; + const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry); + const serverSettingsLayer = ServerSettingsService.layerTest({ + providers: { + claudeAgent: { + enabled: false, + }, + }, + }); + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(SqlitePersistenceMemory), + ); + const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); + const providerLayer = makeProviderServiceLive().pipe( + Layer.provide(providerAdapterLayer), + Layer.provide(directoryLayer), + Layer.provide(serverSettingsLayer), + Layer.provide(AnalyticsService.layerTest), + ); + + const failure = yield* Effect.flip( + Effect.gen(function* () { + const provider = yield* ProviderService; + return yield* provider.startSession(asThreadId("thread-disabled"), { + provider: "claudeAgent", + threadId: asThreadId("thread-disabled"), + runtimeMode: "full-access", + }); + }).pipe(Effect.provide(providerLayer)), + ); + + assert.instanceOf(failure, ProviderValidationError); + assert.include(failure.issue, "Provider 'claudeAgent' is disabled in T3 Code settings."); + assert.equal(claude.startSession.mock.calls.length, 0); + }).pipe(Effect.provide(NodeServices.layer)), +); + +const routing = makeProviderServiceLayer(); +it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-")); + const dbPath = path.join(tempDir, "orchestration.sqlite"); + + const codex = makeFakeCodexAdapter(); + const registry: typeof ProviderAdapterRegistry.Service = { + getByProvider: (provider) => + provider === "codex" + ? Effect.succeed(codex.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed(["codex"]), + }; + + const persistenceLayer = makeSqlitePersistenceLive(dbPath); + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(persistenceLayer), + ); + const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); + + yield* Effect.gen(function* () { + const directory = yield* ProviderSessionDirectory; + yield* directory.upsert({ + provider: "codex", + threadId: ThreadId.makeUnsafe("thread-stale"), + }); + }).pipe(Effect.provide(directoryLayer)); + + const providerLayer = makeProviderServiceLive().pipe( + Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)), + Layer.provide(directoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provide(AnalyticsService.layerTest), + ); + + yield* Effect.gen(function* () { + yield* ProviderService; + }).pipe(Effect.provide(providerLayer)); + + const persistedProvider = yield* Effect.gen(function* () { + const directory = yield* ProviderSessionDirectory; + return yield* directory.getProvider(asThreadId("thread-stale")); + }).pipe(Effect.provide(directoryLayer)); + assert.equal(persistedProvider, "codex"); + + const runtime = yield* Effect.gen(function* () { + const repository = yield* ProviderSessionRuntimeRepository; + return yield* repository.getByThreadId({ threadId: asThreadId("thread-stale") }); + }).pipe(Effect.provide(runtimeRepositoryLayer)); + assert.equal(Option.isSome(runtime), true); + + const legacyTableRows = yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return yield* sql<{ readonly name: string }>` + SELECT name + FROM sqlite_master + WHERE type = 'table' AND name = 'provider_sessions' + `; + }).pipe(Effect.provide(persistenceLayer)); + assert.equal(legacyTableRows.length, 0); + + fs.rmSync(tempDir, { recursive: true, force: true }); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect( + "ProviderServiceLive restores rollback routing after restart using persisted thread mapping", + () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-restart-")); + const dbPath = path.join(tempDir, "orchestration.sqlite"); + const persistenceLayer = makeSqlitePersistenceLive(dbPath); + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(persistenceLayer), + ); + + const firstCodex = makeFakeCodexAdapter(); + const firstRegistry: typeof ProviderAdapterRegistry.Service = { + getByProvider: (provider) => + provider === "codex" + ? Effect.succeed(firstCodex.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed(["codex"]), + }; + + const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(runtimeRepositoryLayer), + ); + const firstProviderLayer = makeProviderServiceLive().pipe( + Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)), + Layer.provide(firstDirectoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provide(AnalyticsService.layerTest), + ); + const updatedResumeCursor = { + threadId: asThreadId("thread-1"), + resume: "resume-session-1", + resumeSessionAt: "assistant-message-1", + turnCount: 1, + }; + + const startedSession = yield* Effect.gen(function* () { + const provider = yield* ProviderService; + const threadId = asThreadId("thread-1"); + const session = yield* provider.startSession(threadId, { + provider: "codex", + cwd: "/tmp/project", + runtimeMode: "full-access", + threadId, + }); + firstCodex.updateSession(threadId, (existing) => ({ + ...existing, + status: "ready", + resumeCursor: updatedResumeCursor, + updatedAt: new Date(Date.now() + 1_000).toISOString(), + })); + return session; + }).pipe(Effect.provide(firstProviderLayer)); + + const persistedAfterStopAll = yield* Effect.gen(function* () { + const repository = yield* ProviderSessionRuntimeRepository; + return yield* repository.getByThreadId({ threadId: startedSession.threadId }); + }).pipe(Effect.provide(runtimeRepositoryLayer)); + assert.equal(Option.isSome(persistedAfterStopAll), true); + if (Option.isSome(persistedAfterStopAll)) { + assert.equal(persistedAfterStopAll.value.status, "stopped"); + assert.deepEqual(persistedAfterStopAll.value.resumeCursor, updatedResumeCursor); + } + + const secondCodex = makeFakeCodexAdapter(); + const secondRegistry: typeof ProviderAdapterRegistry.Service = { + getByProvider: (provider) => + provider === "codex" + ? Effect.succeed(secondCodex.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed(["codex"]), + }; + const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(runtimeRepositoryLayer), + ); + const secondProviderLayer = makeProviderServiceLive().pipe( + Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)), + Layer.provide(secondDirectoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provide(AnalyticsService.layerTest), + ); + + secondCodex.startSession.mockClear(); + secondCodex.rollbackThread.mockClear(); + + yield* Effect.gen(function* () { + const provider = yield* ProviderService; + yield* provider.rollbackConversation({ + threadId: startedSession.threadId, + numTurns: 1, + }); + }).pipe(Effect.provide(secondProviderLayer)); + + assert.equal(secondCodex.startSession.mock.calls.length, 1); + const resumedStartInput = secondCodex.startSession.mock.calls[0]?.[0]; + assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); + if (resumedStartInput && typeof resumedStartInput === "object") { + const startPayload = resumedStartInput as { + provider?: string; + cwd?: string; + resumeCursor?: unknown; + threadId?: string; + }; + assert.equal(startPayload.provider, "codex"); + assert.equal(startPayload.cwd, "/tmp/project"); + assert.deepEqual(startPayload.resumeCursor, updatedResumeCursor); + assert.equal(startPayload.threadId, startedSession.threadId); + } + assert.equal(secondCodex.rollbackThread.mock.calls.length, 1); + const rollbackCall = secondCodex.rollbackThread.mock.calls[0]; + assert.equal(typeof rollbackCall?.[0], "string"); + assert.equal(rollbackCall?.[1], 1); + + fs.rmSync(tempDir, { recursive: true, force: true }); + }).pipe(Effect.provide(NodeServices.layer)), +); + +routing.layer("ProviderServiceLive routing", (it) => { + it.effect("routes provider operations and rollback conversation", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const session = yield* provider.startSession(asThreadId("thread-1"), { + provider: "codex", + threadId: asThreadId("thread-1"), + cwd: "/tmp/project", + runtimeMode: "full-access", + }); + assert.equal(session.provider, "codex"); + + const sessions = yield* provider.listSessions(); + assert.equal(sessions.length, 1); + + yield* provider.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + assert.equal(routing.codex.sendTurn.mock.calls.length, 1); + + yield* provider.interruptTurn({ threadId: session.threadId }); + assert.deepEqual(routing.codex.interruptTurn.mock.calls, [[session.threadId, undefined]]); + + yield* provider.respondToRequest({ + threadId: session.threadId, + requestId: asRequestId("req-1"), + decision: "accept", + }); + assert.deepEqual(routing.codex.respondToRequest.mock.calls, [ + [session.threadId, asRequestId("req-1"), "accept"], + ]); + + yield* provider.respondToUserInput({ + threadId: session.threadId, + requestId: asRequestId("req-user-input-1"), + answers: { + sandbox_mode: "workspace-write", + }, + }); + assert.deepEqual(routing.codex.respondToUserInput.mock.calls, [ + [ + session.threadId, + asRequestId("req-user-input-1"), + { + sandbox_mode: "workspace-write", + }, + ], + ]); + + yield* provider.rollbackConversation({ + threadId: session.threadId, + numTurns: 0, + }); + + yield* provider.stopSession({ threadId: session.threadId }); + const sendAfterStop = yield* Effect.result( + provider.sendTurn({ + threadId: session.threadId, + input: "after-stop", + attachments: [], + }), + ); + assertFailure( + sendAfterStop, + new ProviderValidationError({ + operation: "ProviderService.sendTurn", + issue: `Cannot route thread '${session.threadId}' because no persisted provider binding exists.`, + }), + ); + }), + ); + + it.effect("recovers stale persisted sessions for rollback by resuming thread identity", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const initial = yield* provider.startSession(asThreadId("thread-1"), { + provider: "codex", + threadId: asThreadId("thread-1"), + cwd: "/tmp/project", + runtimeMode: "full-access", + }); + yield* routing.codex.stopSession(initial.threadId); + routing.codex.startSession.mockClear(); + routing.codex.rollbackThread.mockClear(); + + yield* provider.rollbackConversation({ + threadId: initial.threadId, + numTurns: 1, + }); + + assert.equal(routing.codex.startSession.mock.calls.length, 1); + const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0]; + assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); + if (resumedStartInput && typeof resumedStartInput === "object") { + const startPayload = resumedStartInput as { + provider?: string; + cwd?: string; + resumeCursor?: unknown; + threadId?: string; + }; + assert.equal(startPayload.provider, "codex"); + assert.equal(startPayload.cwd, "/tmp/project"); + assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); + assert.equal(startPayload.threadId, initial.threadId); + } + assert.equal(routing.codex.rollbackThread.mock.calls.length, 1); + const rollbackCall = routing.codex.rollbackThread.mock.calls[0]; + assert.equal(rollbackCall?.[1], 1); + }), + ); + + it.effect("routes explicit claudeAgent provider session starts to the claude adapter", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const session = yield* provider.startSession(asThreadId("thread-claude"), { + provider: "claudeAgent", + threadId: asThreadId("thread-claude"), + cwd: "/tmp/project-claude", + runtimeMode: "full-access", + }); + + assert.equal(session.provider, "claudeAgent"); + 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, "claudeAgent"); + assert.equal(startPayload.cwd, "/tmp/project-claude"); + } + }), + ); + + it.effect("recovers stale sessions for sendTurn using persisted cwd", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const initial = yield* provider.startSession(asThreadId("thread-1"), { + provider: "codex", + threadId: asThreadId("thread-1"), + cwd: "/tmp/project-send-turn", + runtimeMode: "full-access", + }); + + yield* routing.codex.stopAll(); + routing.codex.startSession.mockClear(); + routing.codex.sendTurn.mockClear(); + + yield* provider.sendTurn({ + threadId: initial.threadId, + input: "resume", + attachments: [], + }); + + assert.equal(routing.codex.startSession.mock.calls.length, 1); + const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0]; + assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); + if (resumedStartInput && typeof resumedStartInput === "object") { + const startPayload = resumedStartInput as { + provider?: string; + cwd?: string; + resumeCursor?: unknown; + threadId?: string; + }; + assert.equal(startPayload.provider, "codex"); + assert.equal(startPayload.cwd, "/tmp/project-send-turn"); + assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); + assert.equal(startPayload.threadId, initial.threadId); + } + assert.equal(routing.codex.sendTurn.mock.calls.length, 1); + }), + ); + + it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const initial = yield* provider.startSession(asThreadId("thread-claude-send-turn"), { + provider: "claudeAgent", + threadId: asThreadId("thread-claude-send-turn"), + cwd: "/tmp/project-claude-send-turn", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + effort: "max", + }, + }, + runtimeMode: "full-access", + }); + + yield* routing.claude.stopAll(); + routing.claude.startSession.mockClear(); + routing.claude.sendTurn.mockClear(); + + yield* provider.sendTurn({ + threadId: initial.threadId, + input: "resume with claude", + attachments: [], + }); + + assert.equal(routing.claude.startSession.mock.calls.length, 1); + const resumedStartInput = routing.claude.startSession.mock.calls[0]?.[0]; + assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); + if (resumedStartInput && typeof resumedStartInput === "object") { + const startPayload = resumedStartInput as { + provider?: string; + cwd?: string; + modelSelection?: unknown; + resumeCursor?: unknown; + threadId?: string; + }; + assert.equal(startPayload.provider, "claudeAgent"); + assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn"); + assert.deepEqual(startPayload.modelSelection, { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + effort: "max", + }, + }); + assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); + assert.equal(startPayload.threadId, initial.threadId); + } + assert.equal(routing.claude.sendTurn.mock.calls.length, 1); + }), + ); + + it.effect("lists no sessions after adapter runtime clears", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + yield* provider.startSession(asThreadId("thread-1"), { + provider: "codex", + threadId: asThreadId("thread-1"), + runtimeMode: "full-access", + }); + yield* provider.startSession(asThreadId("thread-2"), { + provider: "codex", + threadId: asThreadId("thread-2"), + runtimeMode: "full-access", + }); + + yield* routing.codex.stopAll(); + yield* routing.claude.stopAll(); + + const remaining = yield* provider.listSessions(); + assert.equal(remaining.length, 0); + }), + ); + + it.effect("persists runtime status transitions in provider_session_runtime", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const runtimeRepository = yield* ProviderSessionRuntimeRepository; + + const session = yield* provider.startSession(asThreadId("thread-1"), { + provider: "codex", + threadId: asThreadId("thread-1"), + runtimeMode: "full-access", + }); + yield* provider.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + const runningRuntime = yield* runtimeRepository.getByThreadId({ + threadId: session.threadId, + }); + assert.equal(Option.isSome(runningRuntime), true); + if (Option.isSome(runningRuntime)) { + assert.equal(runningRuntime.value.status, "running"); + assert.deepEqual(runningRuntime.value.resumeCursor, session.resumeCursor); + const payload = runningRuntime.value.runtimePayload; + assert.equal(payload !== null && typeof payload === "object", true); + if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) { + const runtimePayload = payload as { + cwd: string; + model: string | null; + activeTurnId: string | null; + lastError: string | null; + lastRuntimeEvent: string | null; + }; + assert.equal(runtimePayload.cwd, process.cwd()); + assert.equal(runtimePayload.model, null); + assert.equal(runtimePayload.activeTurnId, `turn-${String(session.threadId)}`); + assert.equal(runtimePayload.lastError, null); + assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn"); + } + } + }), + ); + + it.effect("reuses persisted resume cursor when startSession is called after a restart", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-start-")); + const dbPath = path.join(tempDir, "orchestration.sqlite"); + const persistenceLayer = makeSqlitePersistenceLive(dbPath); + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(persistenceLayer), + ); + + const firstClaude = makeFakeCodexAdapter("claudeAgent"); + const firstRegistry: typeof ProviderAdapterRegistry.Service = { + getByProvider: (provider) => + provider === "claudeAgent" + ? Effect.succeed(firstClaude.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed(["claudeAgent"]), + }; + const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(runtimeRepositoryLayer), + ); + const firstProviderLayer = makeProviderServiceLive().pipe( + Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)), + Layer.provide(firstDirectoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provide(AnalyticsService.layerTest), + ); + + const initial = yield* Effect.gen(function* () { + const provider = yield* ProviderService; + return yield* provider.startSession(asThreadId("thread-claude-start"), { + provider: "claudeAgent", + threadId: asThreadId("thread-claude-start"), + cwd: "/tmp/project-claude-start", + runtimeMode: "full-access", + }); + }).pipe(Effect.provide(firstProviderLayer)); + + yield* Effect.gen(function* () { + const provider = yield* ProviderService; + yield* provider.listSessions(); + }).pipe(Effect.provide(firstProviderLayer)); + + const secondClaude = makeFakeCodexAdapter("claudeAgent"); + const secondRegistry: typeof ProviderAdapterRegistry.Service = { + getByProvider: (provider) => + provider === "claudeAgent" + ? Effect.succeed(secondClaude.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed(["claudeAgent"]), + }; + const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(runtimeRepositoryLayer), + ); + const secondProviderLayer = makeProviderServiceLive().pipe( + Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)), + Layer.provide(secondDirectoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provide(AnalyticsService.layerTest), + ); + + secondClaude.startSession.mockClear(); + + yield* Effect.gen(function* () { + const provider = yield* ProviderService; + yield* provider.startSession(initial.threadId, { + provider: "claudeAgent", + threadId: initial.threadId, + cwd: "/tmp/project-claude-start", + runtimeMode: "full-access", + }); + }).pipe(Effect.provide(secondProviderLayer)); + + assert.equal(secondClaude.startSession.mock.calls.length, 1); + const resumedStartInput = secondClaude.startSession.mock.calls[0]?.[0]; + assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); + if (resumedStartInput && typeof resumedStartInput === "object") { + const startPayload = resumedStartInput as { + provider?: string; + cwd?: string; + resumeCursor?: unknown; + threadId?: string; + }; + assert.equal(startPayload.provider, "claudeAgent"); + assert.equal(startPayload.cwd, "/tmp/project-claude-start"); + assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); + assert.equal(startPayload.threadId, initial.threadId); + } + + fs.rmSync(tempDir, { recursive: true, force: true }); + }).pipe(Effect.provide(NodeServices.layer)), + ); +}); + +const fanout = makeProviderServiceLayer(); +fanout.layer("ProviderServiceLive fanout", (it) => { + it.effect("fans out adapter turn completion events", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const session = yield* provider.startSession(asThreadId("thread-1"), { + provider: "codex", + threadId: asThreadId("thread-1"), + runtimeMode: "full-access", + }); + + const eventsRef = yield* Ref.make>([]); + const consumer = yield* Stream.runForEach(provider.streamEvents, (event) => + Ref.update(eventsRef, (current) => [...current, event]), + ).pipe(Effect.forkChild); + yield* sleep(50); + + const completedEvent: LegacyProviderRuntimeEvent = { + type: "turn.completed", + eventId: asEventId("evt-1"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: session.threadId, + turnId: asTurnId("turn-1"), + status: "completed", + }; + + fanout.codex.emit(completedEvent); + yield* sleep(50); + + const events = yield* Ref.get(eventsRef); + yield* Fiber.interrupt(consumer); + + assert.equal( + events.some((entry) => entry.type === "turn.completed"), + true, + ); + }), + ); + + it.effect("fans out canonical runtime events in emission order", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const session = yield* provider.startSession(asThreadId("thread-seq"), { + provider: "codex", + threadId: asThreadId("thread-seq"), + runtimeMode: "full-access", + }); + + const receivedRef = yield* Ref.make>([]); + const consumer = yield* Stream.take(provider.streamEvents, 3).pipe( + Stream.runForEach((event) => Ref.update(receivedRef, (current) => [...current, event])), + Effect.forkChild, + ); + yield* sleep(50); + + fanout.codex.emit({ + type: "tool.started", + eventId: asEventId("evt-seq-1"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: session.threadId, + turnId: asTurnId("turn-1"), + toolKind: "command", + title: "Ran command", + }); + fanout.codex.emit({ + type: "tool.completed", + eventId: asEventId("evt-seq-2"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: session.threadId, + turnId: asTurnId("turn-1"), + toolKind: "command", + title: "Ran command", + }); + fanout.codex.emit({ + type: "turn.completed", + eventId: asEventId("evt-seq-3"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: session.threadId, + turnId: asTurnId("turn-1"), + status: "completed", + }); + + yield* Fiber.join(consumer); + const received = yield* Ref.get(receivedRef); + assert.deepEqual( + received.map((event) => event.eventId), + [asEventId("evt-seq-1"), asEventId("evt-seq-2"), asEventId("evt-seq-3")], + ); + }), + ); + + it.effect("keeps subscriber delivery ordered and isolates failing subscribers", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const session = yield* provider.startSession(asThreadId("thread-1"), { + provider: "codex", + threadId: asThreadId("thread-1"), + runtimeMode: "full-access", + }); + + const receivedByHealthy: string[] = []; + const expectedEventIds = new Set(["evt-ordered-1", "evt-ordered-2", "evt-ordered-3"]); + const healthyFiber = yield* Stream.take(provider.streamEvents, 3).pipe( + Stream.runForEach((event) => + Effect.sync(() => { + receivedByHealthy.push(event.eventId); + }), + ), + Effect.forkChild, + ); + const failingFiber = yield* Stream.take(provider.streamEvents, 1).pipe( + Stream.runForEach(() => Effect.fail("listener crash")), + Effect.forkChild, + ); + yield* sleep(50); + + const events: ReadonlyArray = [ + { + type: "tool.completed", + eventId: asEventId("evt-ordered-1"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: session.threadId, + turnId: asTurnId("turn-1"), + toolKind: "command", + title: "Ran command", + detail: "echo one", + }, + { + type: "message.delta", + eventId: asEventId("evt-ordered-2"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: session.threadId, + turnId: asTurnId("turn-1"), + delta: "hello", + }, + { + type: "turn.completed", + eventId: asEventId("evt-ordered-3"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: session.threadId, + turnId: asTurnId("turn-1"), + status: "completed", + }, + ]; + + for (const event of events) { + fanout.codex.emit(event); + } + const failingResult = yield* Effect.result(Fiber.join(failingFiber)); + assert.equal(failingResult._tag, "Failure"); + yield* Fiber.join(healthyFiber); + + assert.deepEqual( + receivedByHealthy.filter((eventId) => expectedEventIds.has(eventId)).slice(0, 3), + ["evt-ordered-1", "evt-ordered-2", "evt-ordered-3"], + ); + }), + ); + + it.effect("records provider metrics with the routed provider label", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const session = yield* provider.startSession(asThreadId("thread-metrics"), { + provider: "claudeAgent", + threadId: asThreadId("thread-metrics"), + cwd: "/tmp/project", + runtimeMode: "full-access", + }); + + yield* provider.interruptTurn({ threadId: session.threadId }); + yield* provider.respondToRequest({ + threadId: session.threadId, + requestId: asRequestId("req-metrics-1"), + decision: "accept", + }); + yield* provider.respondToUserInput({ + threadId: session.threadId, + requestId: asRequestId("req-metrics-2"), + answers: { + sandbox_mode: "workspace-write", + }, + }); + yield* provider.rollbackConversation({ + threadId: session.threadId, + numTurns: 1, + }); + yield* provider.stopSession({ threadId: session.threadId }); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "interrupt", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "approval-response", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "user-input-response", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "rollback", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_sessions_total", { + provider: "claudeAgent", + operation: "stop", + outcome: "success", + }), + true, + ); + }), + ); + + it.effect( + "records sendTurn metrics with the resolved provider when modelSelection is omitted", + () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const session = yield* provider.startSession(asThreadId("thread-send-metrics"), { + provider: "claudeAgent", + threadId: asThreadId("thread-send-metrics"), + cwd: "/tmp/project-send-metrics", + runtimeMode: "full-access", + }); + + yield* provider.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "send", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turn_duration", { + provider: "claudeAgent", + operation: "send", + }), + true, + ); + }), + ); +}); + +const validation = makeProviderServiceLayer(); +validation.layer("ProviderServiceLive validation", (it) => { + it.effect("returns ProviderValidationError for invalid input payloads", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const failure = yield* Effect.result( + provider.startSession(asThreadId("thread-validation"), { + threadId: asThreadId("thread-validation"), + provider: "invalid-provider", + runtimeMode: "full-access", + } as never), + ); + + assert.equal(failure._tag, "Failure"); + if (failure._tag !== "Failure") { + return; + } + assert.equal(failure.failure._tag, "ProviderValidationError"); + if (failure.failure._tag !== "ProviderValidationError") { + return; + } + assert.equal(failure.failure.operation, "ProviderService.startSession"); + assert.equal(failure.failure.issue.includes("invalid-provider"), true); + }), + ); + + it.effect("accepts startSession when adapter has not emitted provider thread id yet", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const runtimeRepository = yield* ProviderSessionRuntimeRepository; + + validation.codex.startSession.mockImplementationOnce((input: ProviderSessionStartInput) => + Effect.sync(() => { + const now = new Date().toISOString(); + return { + provider: "codex", + status: "ready", + threadId: input.threadId, + runtimeMode: input.runtimeMode, + cwd: input.cwd ?? process.cwd(), + createdAt: now, + updatedAt: now, + } satisfies ProviderSession; + }), + ); + + const session = yield* provider.startSession(asThreadId("thread-missing"), { + provider: "codex", + threadId: asThreadId("thread-missing"), + cwd: "/tmp/project", + runtimeMode: "full-access", + }); + + assert.equal(session.threadId, asThreadId("thread-missing")); + + const runtime = yield* runtimeRepository.getByThreadId({ + threadId: session.threadId, + }); + assert.equal(Option.isSome(runtime), true); + if (Option.isSome(runtime)) { + assert.equal(runtime.value.threadId, session.threadId); + } + }), + ); +}); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts new file mode 100644 index 0000000000..da2c293fac --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -0,0 +1,764 @@ +/** + * ProviderServiceLive - Cross-provider orchestration layer. + * + * Routes validated transport/API calls to provider adapters through + * `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a + * unified provider event stream for subscribers. + * + * It does not implement provider protocol details (adapter concern). + * + * @module ProviderServiceLive + */ +import { + ModelSelection, + NonNegativeInt, + ThreadId, + ProviderInterruptTurnInput, + ProviderRespondToRequestInput, + ProviderRespondToUserInputInput, + ProviderSendTurnInput, + ProviderSessionStartInput, + ProviderStopSessionInput, + type ProviderRuntimeEvent, + type ProviderSession, +} from "@t3tools/contracts"; +import { Effect, Layer, Option, PubSub, Queue, Schema, SchemaIssue, Stream } from "effect"; + +import { + increment, + providerMetricAttributes, + providerRuntimeEventsTotal, + providerSessionsTotal, + providerTurnDuration, + providerTurnsTotal, + providerTurnMetricAttributes, + withMetrics, +} from "../../observability/Metrics.ts"; +import { ProviderValidationError } from "../Errors.ts"; +import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; +import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts"; +import { + ProviderSessionDirectory, + type ProviderRuntimeBinding, +} from "../Services/ProviderSessionDirectory.ts"; +import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; +import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; + +export interface ProviderServiceLiveOptions { + readonly canonicalEventLogPath?: string; + readonly canonicalEventLogger?: EventNdjsonLogger; +} + +const ProviderRollbackConversationInput = Schema.Struct({ + threadId: ThreadId, + numTurns: NonNegativeInt, +}); + +function toValidationError( + operation: string, + issue: string, + cause?: unknown, +): ProviderValidationError { + return new ProviderValidationError({ + operation, + issue, + ...(cause !== undefined ? { cause } : {}), + }); +} + +const decodeInputOrValidationError = (input: { + readonly operation: string; + readonly schema: S; + readonly payload: unknown; +}) => + Schema.decodeUnknownEffect(input.schema)(input.payload).pipe( + Effect.mapError( + (schemaError) => + new ProviderValidationError({ + operation: input.operation, + issue: SchemaIssue.makeFormatterDefault()(schemaError.issue), + cause: schemaError, + }), + ), + ); + +function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "stopped" | "error" { + switch (session.status) { + case "connecting": + return "starting"; + case "error": + return "error"; + case "closed": + return "stopped"; + case "ready": + case "running": + default: + return "running"; + } +} + +function toRuntimePayloadFromSession( + session: ProviderSession, + extra?: { + readonly modelSelection?: unknown; + readonly lastRuntimeEvent?: string; + readonly lastRuntimeEventAt?: string; + }, +): Record { + return { + cwd: session.cwd ?? null, + model: session.model ?? null, + activeTurnId: session.activeTurnId ?? null, + lastError: session.lastError ?? null, + ...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}), + ...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}), + ...(extra?.lastRuntimeEventAt !== undefined + ? { lastRuntimeEventAt: extra.lastRuntimeEventAt } + : {}), + }; +} + +function readPersistedModelSelection( + runtimePayload: ProviderRuntimeBinding["runtimePayload"], +): ModelSelection | undefined { + if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) { + return undefined; + } + const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined; + return Schema.is(ModelSelection)(raw) ? raw : undefined; +} + +function readPersistedCwd( + runtimePayload: ProviderRuntimeBinding["runtimePayload"], +): string | undefined { + if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) { + return undefined; + } + const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined; + if (typeof rawCwd !== "string") return undefined; + const trimmed = rawCwd.trim(); + return trimmed.length > 0 ? trimmed : undefined; +} + +const makeProviderService = Effect.fn("makeProviderService")(function* ( + options?: ProviderServiceLiveOptions, +) { + const analytics = yield* Effect.service(AnalyticsService); + const serverSettings = yield* ServerSettingsService; + const canonicalEventLogger = + options?.canonicalEventLogger ?? + (options?.canonicalEventLogPath !== undefined + ? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, { + stream: "canonical", + }) + : undefined); + + const registry = yield* ProviderAdapterRegistry; + const directory = yield* ProviderSessionDirectory; + const runtimeEventQueue = yield* Queue.unbounded(); + const runtimeEventPubSub = yield* PubSub.unbounded(); + + const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => + Effect.succeed(event).pipe( + Effect.tap((canonicalEvent) => + canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void, + ), + Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)), + Effect.asVoid, + ); + + const upsertSessionBinding = ( + session: ProviderSession, + threadId: ThreadId, + extra?: { + readonly modelSelection?: unknown; + readonly lastRuntimeEvent?: string; + readonly lastRuntimeEventAt?: string; + }, + ) => + directory.upsert({ + threadId, + provider: session.provider, + runtimeMode: session.runtimeMode, + status: toRuntimeStatus(session), + ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}), + runtimePayload: toRuntimePayloadFromSession(session, extra), + }); + + const providers = yield* registry.listProviders(); + const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider)); + const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => + increment(providerRuntimeEventsTotal, { + provider: event.provider, + eventType: event.type, + }).pipe(Effect.andThen(publishRuntimeEvent(event))); + + const worker = Effect.forever( + Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)), + ); + yield* Effect.forkScoped(worker); + + yield* Effect.forEach(adapters, (adapter) => + Stream.runForEach(adapter.streamEvents, (event) => + Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid), + ).pipe(Effect.forkScoped), + ).pipe(Effect.asVoid); + + const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: { + readonly binding: ProviderRuntimeBinding; + readonly operation: string; + }) { + yield* Effect.annotateCurrentSpan({ + "provider.operation": "recover-session", + "provider.kind": input.binding.provider, + "provider.thread_id": input.binding.threadId, + }); + return yield* Effect.gen(function* () { + const adapter = yield* registry.getByProvider(input.binding.provider); + const hasResumeCursor = + input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined; + const hasActiveSession = yield* adapter.hasSession(input.binding.threadId); + if (hasActiveSession) { + const activeSessions = yield* adapter.listSessions(); + 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; + } + } + + if (!hasResumeCursor) { + return yield* toValidationError( + input.operation, + `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`, + ); + } + + const persistedCwd = readPersistedCwd(input.binding.runtimePayload); + const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload); + + const resumed = yield* adapter.startSession({ + threadId: input.binding.threadId, + provider: input.binding.provider, + ...(persistedCwd ? { cwd: persistedCwd } : {}), + ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}), + ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), + runtimeMode: input.binding.runtimeMode ?? "full-access", + }); + if (resumed.provider !== adapter.provider) { + return yield* toValidationError( + input.operation, + `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`, + ); + } + + 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; + }).pipe( + withMetrics({ + counter: providerSessionsTotal, + attributes: providerMetricAttributes(input.binding.provider, { + operation: "recover", + }), + }), + ); + }); + + const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: { + readonly threadId: ThreadId; + readonly operation: string; + readonly allowRecovery: boolean; + }) { + const bindingOption = yield* directory.getBinding(input.threadId); + const binding = Option.getOrUndefined(bindingOption); + if (!binding) { + return yield* toValidationError( + input.operation, + `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`, + ); + } + const adapter = yield* registry.getByProvider(binding.provider); + + const hasRequestedSession = yield* adapter.hasSession(input.threadId); + if (hasRequestedSession) { + return { adapter, threadId: input.threadId, isActive: true } as const; + } + + if (!input.allowRecovery) { + return { adapter, threadId: input.threadId, isActive: false } as const; + } + + const recovered = yield* recoverSessionForThread({ binding, operation: input.operation }); + return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const; + }); + + const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")( + function* (threadId, rawInput) { + const parsed = yield* decodeInputOrValidationError({ + operation: "ProviderService.startSession", + schema: ProviderSessionStartInput, + payload: rawInput, + }); + + const input = { + ...parsed, + threadId, + provider: parsed.provider ?? "codex", + }; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "start-session", + "provider.kind": input.provider, + "provider.thread_id": threadId, + "provider.runtime_mode": input.runtimeMode, + }); + return yield* Effect.gen(function* () { + const settings = yield* serverSettings.getSettings.pipe( + Effect.mapError((error) => + toValidationError( + "ProviderService.startSession", + `Failed to load provider settings: ${error.message}`, + error, + ), + ), + ); + if (!settings.providers[input.provider].enabled) { + return yield* toValidationError( + "ProviderService.startSession", + `Provider '${input.provider}' is disabled in T3 Code settings.`, + ); + } + const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId)); + const effectiveResumeCursor = + input.resumeCursor ?? + (persistedBinding?.provider === input.provider + ? persistedBinding.resumeCursor + : undefined); + const adapter = yield* registry.getByProvider(input.provider); + const session = yield* adapter.startSession({ + ...input, + ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), + }); + + if (session.provider !== adapter.provider) { + return yield* toValidationError( + "ProviderService.startSession", + `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`, + ); + } + + yield* upsertSessionBinding(session, threadId, { + modelSelection: input.modelSelection, + }); + 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.modelSelection?.model === "string" && + input.modelSelection.model.trim().length > 0, + }); + + return session; + }).pipe( + withMetrics({ + counter: providerSessionsTotal, + attributes: providerMetricAttributes(input.provider, { + operation: "start", + }), + }), + ); + }, + ); + + const sendTurn: ProviderServiceShape["sendTurn"] = Effect.fn("sendTurn")(function* (rawInput) { + const parsed = yield* decodeInputOrValidationError({ + operation: "ProviderService.sendTurn", + schema: ProviderSendTurnInput, + payload: rawInput, + }); + + const input = { + ...parsed, + attachments: parsed.attachments ?? [], + }; + if (!input.input && input.attachments.length === 0) { + return yield* toValidationError( + "ProviderService.sendTurn", + "Either input text or at least one attachment is required", + ); + } + yield* Effect.annotateCurrentSpan({ + "provider.operation": "send-turn", + "provider.thread_id": input.threadId, + "provider.interaction_mode": input.interactionMode, + "provider.attachment_count": input.attachments.length, + }); + let metricProvider = "unknown"; + let metricModel = input.modelSelection?.model; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.sendTurn", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + metricModel = input.modelSelection?.model; + yield* Effect.annotateCurrentSpan({ + "provider.kind": routed.adapter.provider, + ...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}), + }); + const turn = yield* routed.adapter.sendTurn(input); + yield* directory.upsert({ + threadId: input.threadId, + provider: routed.adapter.provider, + status: "running", + ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}), + runtimePayload: { + ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), + activeTurnId: turn.turnId, + lastRuntimeEvent: "provider.sendTurn", + lastRuntimeEventAt: new Date().toISOString(), + }, + }); + yield* analytics.record("provider.turn.sent", { + provider: routed.adapter.provider, + model: input.modelSelection?.model, + interactionMode: input.interactionMode, + attachmentCount: input.attachments.length, + hasInput: typeof input.input === "string" && input.input.trim().length > 0, + }); + return turn; + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + timer: providerTurnDuration, + attributes: () => + providerTurnMetricAttributes({ + provider: metricProvider, + model: metricModel, + extra: { + operation: "send", + }, + }), + }), + ); + }); + + const interruptTurn: ProviderServiceShape["interruptTurn"] = Effect.fn("interruptTurn")( + function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.interruptTurn", + schema: ProviderInterruptTurnInput, + payload: rawInput, + }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.interruptTurn", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "interrupt-turn", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.turn_id": input.turnId, + }); + yield* routed.adapter.interruptTurn(routed.threadId, input.turnId); + yield* analytics.record("provider.turn.interrupted", { + provider: routed.adapter.provider, + }); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "interrupt", + }), + }), + ); + }, + ); + + const respondToRequest: ProviderServiceShape["respondToRequest"] = Effect.fn("respondToRequest")( + function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.respondToRequest", + schema: ProviderRespondToRequestInput, + payload: rawInput, + }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.respondToRequest", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "respond-to-request", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.request_id": input.requestId, + }); + yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision); + yield* analytics.record("provider.request.responded", { + provider: routed.adapter.provider, + decision: input.decision, + }); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "approval-response", + }), + }), + ); + }, + ); + + const respondToUserInput: ProviderServiceShape["respondToUserInput"] = Effect.fn( + "respondToUserInput", + )(function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.respondToUserInput", + schema: ProviderRespondToUserInputInput, + payload: rawInput, + }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.respondToUserInput", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "respond-to-user-input", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.request_id": input.requestId, + }); + yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "user-input-response", + }), + }), + ); + }); + + const stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")( + function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.stopSession", + schema: ProviderStopSessionInput, + payload: rawInput, + }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.stopSession", + allowRecovery: false, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "stop-session", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + }); + if (routed.isActive) { + yield* routed.adapter.stopSession(routed.threadId); + } + yield* directory.remove(input.threadId); + yield* analytics.record("provider.session.stopped", { + provider: routed.adapter.provider, + }); + }).pipe( + withMetrics({ + counter: providerSessionsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "stop", + }), + }), + ); + }, + ); + + const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")( + function* () { + const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) => + adapter.listSessions(), + ); + const activeSessions = sessionsByProvider.flatMap((sessions) => sessions); + const persistedBindings = yield* directory.listThreadIds().pipe( + Effect.flatMap((threadIds) => + Effect.forEach( + threadIds, + (threadId) => + directory + .getBinding(threadId) + .pipe(Effect.orElseSucceed(() => Option.none())), + { concurrency: "unbounded" }, + ), + ), + Effect.orElseSucceed(() => [] as Array>), + ); + const bindingsByThreadId = new Map(); + for (const bindingOption of persistedBindings) { + const binding = Option.getOrUndefined(bindingOption); + if (binding) { + bindingsByThreadId.set(binding.threadId, binding); + } + } + + return activeSessions.map((session) => { + const binding = bindingsByThreadId.get(session.threadId); + if (!binding) { + return session; + } + + 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); + }); + }, + ); + + const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) => + registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities)); + + const rollbackConversation: ProviderServiceShape["rollbackConversation"] = Effect.fn( + "rollbackConversation", + )(function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.rollbackConversation", + schema: ProviderRollbackConversationInput, + payload: rawInput, + }); + if (input.numTurns === 0) { + return; + } + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.rollbackConversation", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "rollback-conversation", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.rollback_turns": input.numTurns, + }); + yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns); + yield* analytics.record("provider.conversation.rolled_back", { + provider: routed.adapter.provider, + turns: input.numTurns, + }); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "rollback", + }), + }), + ); + }); + + const runStopAll = Effect.fn("runStopAll")(function* () { + const threadIds = yield* directory.listThreadIds(); + const activeSessions = yield* Effect.forEach(adapters, (adapter) => + adapter.listSessions(), + ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions))); + yield* Effect.forEach(activeSessions, (session) => + upsertSessionBinding(session, session.threadId, { + lastRuntimeEvent: "provider.stopAll", + lastRuntimeEventAt: new Date().toISOString(), + }), + ).pipe(Effect.asVoid); + yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid); + yield* Effect.forEach(threadIds, (threadId) => + directory.getProvider(threadId).pipe( + Effect.flatMap((provider) => + directory.upsert({ + threadId, + provider, + status: "stopped", + runtimePayload: { + activeTurnId: null, + lastRuntimeEvent: "provider.stopAll", + lastRuntimeEventAt: new Date().toISOString(), + }, + }), + ), + ), + ).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, + interruptTurn, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + getCapabilities, + rollbackConversation, + // Each access creates a fresh PubSub subscription so that multiple + // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each + // independently receive all runtime events. + get streamEvents(): ProviderServiceShape["streamEvents"] { + return Stream.fromPubSub(runtimeEventPubSub); + }, + } satisfies ProviderServiceShape; +}); + +export const ProviderServiceLive = Layer.effect(ProviderService, makeProviderService()); + +export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) { + return Layer.effect(ProviderService, makeProviderService(options)); +} diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts new file mode 100644 index 0000000000..d23b247f21 --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts @@ -0,0 +1,207 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { ThreadId } from "@t3tools/contracts"; +import { it, assert } from "@effect/vitest"; +import { assertFailure, assertSome } from "@effect/vitest/utils"; +import { Effect, Layer, Option } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { + makeSqlitePersistenceLive, + SqlitePersistenceMemory, +} from "../../persistence/Layers/Sqlite.ts"; +import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts"; +import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts"; +import { ProviderSessionDirectoryPersistenceError } from "../Errors.ts"; +import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; +import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts"; + +function makeDirectoryLayer(persistenceLayer: Layer.Layer) { + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(persistenceLayer), + ); + return Layer.mergeAll( + runtimeRepositoryLayer, + ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)), + NodeServices.layer, + ); +} + +it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => { + it("upserts, reads, and removes thread bindings", () => + Effect.gen(function* () { + const directory = yield* ProviderSessionDirectory; + const runtimeRepository = yield* ProviderSessionRuntimeRepository; + + const initialThreadId = ThreadId.makeUnsafe("thread-1"); + + yield* directory.upsert({ + provider: "codex", + threadId: initialThreadId, + }); + + const provider = yield* directory.getProvider(initialThreadId); + assert.equal(provider, "codex"); + const resolvedBinding = yield* directory.getBinding(initialThreadId); + assertSome(resolvedBinding, { + threadId: initialThreadId, + provider: "codex", + }); + if (Option.isSome(resolvedBinding)) { + assert.equal(resolvedBinding.value.threadId, initialThreadId); + } + + const nextThreadId = ThreadId.makeUnsafe("thread-2"); + + yield* directory.upsert({ + provider: "codex", + threadId: nextThreadId, + }); + const updatedBinding = yield* directory.getBinding(nextThreadId); + assert.equal(Option.isSome(updatedBinding), true); + if (Option.isSome(updatedBinding)) { + assert.equal(updatedBinding.value.threadId, nextThreadId); + } + + const runtime = yield* runtimeRepository.getByThreadId({ threadId: nextThreadId }); + assert.equal(Option.isSome(runtime), true); + if (Option.isSome(runtime)) { + assert.equal(runtime.value.threadId, nextThreadId); + assert.equal(runtime.value.status, "running"); + assert.equal(runtime.value.providerName, "codex"); + } + + const threadIds = yield* directory.listThreadIds(); + assert.deepEqual(threadIds, [nextThreadId]); + + yield* directory.remove(nextThreadId); + const missingProvider = yield* directory.getProvider(nextThreadId).pipe(Effect.result); + assertFailure( + missingProvider, + new ProviderSessionDirectoryPersistenceError({ + operation: "ProviderSessionDirectory.getProvider", + detail: `No persisted provider binding found for thread '${nextThreadId}'.`, + }), + ); + })); + + it("persists runtime fields and merges payload updates", () => + Effect.gen(function* () { + const directory = yield* ProviderSessionDirectory; + const runtimeRepository = yield* ProviderSessionRuntimeRepository; + + const threadId = ThreadId.makeUnsafe("thread-runtime"); + + yield* directory.upsert({ + provider: "codex", + threadId, + status: "starting", + resumeCursor: { + threadId: "provider-thread-runtime", + }, + runtimePayload: { + cwd: "/tmp/project", + model: "gpt-5-codex", + }, + }); + + yield* directory.upsert({ + provider: "codex", + threadId, + status: "running", + runtimePayload: { + activeTurnId: "turn-1", + }, + }); + + const runtime = yield* runtimeRepository.getByThreadId({ threadId }); + assert.equal(Option.isSome(runtime), true); + if (Option.isSome(runtime)) { + assert.equal(runtime.value.threadId, threadId); + assert.equal(runtime.value.status, "running"); + assert.deepEqual(runtime.value.resumeCursor, { + threadId: "provider-thread-runtime", + }); + assert.deepEqual(runtime.value.runtimePayload, { + cwd: "/tmp/project", + model: "gpt-5-codex", + activeTurnId: "turn-1", + }); + } + })); + + 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: "claudeAgent", + adapterKey: "claudeAgent", + 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-")); + const dbPath = path.join(tempDir, "orchestration.sqlite"); + const directoryLayer = makeDirectoryLayer(makeSqlitePersistenceLive(dbPath)); + + const threadId = ThreadId.makeUnsafe("thread-restart"); + + yield* Effect.gen(function* () { + const directory = yield* ProviderSessionDirectory; + yield* directory.upsert({ + provider: "codex", + threadId, + }); + }).pipe(Effect.provide(directoryLayer)); + + yield* Effect.gen(function* () { + const directory = yield* ProviderSessionDirectory; + const sql = yield* SqlClient.SqlClient; + const provider = yield* directory.getProvider(threadId); + assert.equal(provider, "codex"); + + const resolvedBinding = yield* directory.getBinding(threadId); + assertSome(resolvedBinding, { + threadId, + provider: "codex", + }); + if (Option.isSome(resolvedBinding)) { + assert.equal(resolvedBinding.value.threadId, threadId); + } + + const legacyTableRows = yield* sql<{ readonly name: string }>` + SELECT name + FROM sqlite_master + WHERE type = 'table' AND name = 'provider_sessions' + `; + assert.equal(legacyTableRows.length, 0); + }).pipe(Effect.provide(directoryLayer)); + + fs.rmSync(tempDir, { recursive: true, force: true }); + })); +}); diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts new file mode 100644 index 0000000000..961c63d696 --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts @@ -0,0 +1,164 @@ +import { type ProviderKind, type ThreadId } from "@t3tools/contracts"; +import { Effect, Layer, Option } from "effect"; + +import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts"; +import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts"; +import { + ProviderSessionDirectory, + type ProviderRuntimeBinding, + type ProviderSessionDirectoryShape, +} from "../Services/ProviderSessionDirectory.ts"; + +function toPersistenceError(operation: string) { + return (cause: unknown) => + new ProviderSessionDirectoryPersistenceError({ + operation, + detail: `Failed to execute ${operation}.`, + cause, + }); +} + +function decodeProviderKind( + providerName: string, + operation: string, +): Effect.Effect { + if (providerName === "codex" || providerName === "claudeAgent") { + return Effect.succeed(providerName); + } + return Effect.fail( + new ProviderSessionDirectoryPersistenceError({ + operation, + detail: `Unknown persisted provider '${providerName}'.`, + }), + ); +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function mergeRuntimePayload( + existing: unknown | null, + next: unknown | null | undefined, +): unknown | null { + if (next === undefined) { + return existing ?? null; + } + if (isRecord(existing) && isRecord(next)) { + return { ...existing, ...next }; + } + return next; +} + +const makeProviderSessionDirectory = Effect.gen(function* () { + const repository = yield* ProviderSessionRuntimeRepository; + + const getBinding = (threadId: ThreadId) => + repository.getByThreadId({ threadId }).pipe( + Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")), + Effect.flatMap((runtime) => + Option.match(runtime, { + onNone: () => Effect.succeed(Option.none()), + onSome: (value) => + decodeProviderKind(value.providerName, "ProviderSessionDirectory.getBinding").pipe( + Effect.map((provider) => + Option.some({ + threadId: value.threadId, + provider, + adapterKey: value.adapterKey, + runtimeMode: value.runtimeMode, + status: value.status, + resumeCursor: value.resumeCursor, + runtimePayload: value.runtimePayload, + }), + ), + ), + }), + ), + ); + + const upsert: ProviderSessionDirectoryShape["upsert"] = Effect.fn(function* (binding) { + const existing = yield* repository + .getByThreadId({ threadId: binding.threadId }) + .pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId"))); + + const existingRuntime = Option.getOrUndefined(existing); + const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId; + if (!resolvedThreadId) { + return yield* new ProviderValidationError({ + operation: "ProviderSessionDirectory.upsert", + issue: "threadId must be a non-empty string.", + }); + } + + const now = new Date().toISOString(); + const providerChanged = + existingRuntime !== undefined && existingRuntime.providerName !== binding.provider; + yield* repository + .upsert({ + threadId: resolvedThreadId, + providerName: binding.provider, + adapterKey: + binding.adapterKey ?? + (providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)), + runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access", + status: binding.status ?? existingRuntime?.status ?? "running", + lastSeenAt: now, + resumeCursor: + binding.resumeCursor !== undefined + ? binding.resumeCursor + : (existingRuntime?.resumeCursor ?? null), + runtimePayload: mergeRuntimePayload( + existingRuntime?.runtimePayload ?? null, + binding.runtimePayload, + ), + }) + .pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert"))); + }); + + const getProvider: ProviderSessionDirectoryShape["getProvider"] = (threadId) => + getBinding(threadId).pipe( + Effect.flatMap((binding) => + Option.match(binding, { + onSome: (value) => Effect.succeed(value.provider), + onNone: () => + Effect.fail( + new ProviderSessionDirectoryPersistenceError({ + operation: "ProviderSessionDirectory.getProvider", + detail: `No persisted provider binding found for thread '${threadId}'.`, + }), + ), + }), + ), + ); + + const remove: ProviderSessionDirectoryShape["remove"] = (threadId) => + repository + .deleteByThreadId({ threadId }) + .pipe( + Effect.mapError(toPersistenceError("ProviderSessionDirectory.remove:deleteByThreadId")), + ); + + const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () => + repository.list().pipe( + Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")), + Effect.map((rows) => rows.map((row) => row.threadId)), + ); + + return { + upsert, + getProvider, + getBinding, + remove, + listThreadIds, + } satisfies ProviderSessionDirectoryShape; +}); + +export const ProviderSessionDirectoryLive = Layer.effect( + ProviderSessionDirectory, + makeProviderSessionDirectory, +); + +export function makeProviderSessionDirectoryLive() { + return Layer.effect(ProviderSessionDirectory, makeProviderSessionDirectory); +} diff --git a/apps/server/src/provider/Services/ClaudeAdapter.ts b/apps/server/src/provider/Services/ClaudeAdapter.ts new file mode 100644 index 0000000000..3a3f616ea5 --- /dev/null +++ b/apps/server/src/provider/Services/ClaudeAdapter.ts @@ -0,0 +1,30 @@ +/** + * ClaudeAdapter - Claude Agent implementation of the generic provider adapter contract. + * + * This service owns Claude runtime/session semantics and emits canonical + * provider runtime events. It does not perform cross-provider routing, shared + * event fan-out, or checkpoint orchestration. + * + * Uses Effect `ServiceMap.Service` for dependency injection and returns the + * shared provider-adapter error channel with `provider: "claudeAgent"` context. + * + * @module ClaudeAdapter + */ +import { ServiceMap } from "effect"; + +import type { ProviderAdapterError } from "../Errors.ts"; +import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; + +/** + * ClaudeAdapterShape - Service API for the Claude Agent provider adapter. + */ +export interface ClaudeAdapterShape extends ProviderAdapterShape { + readonly provider: "claudeAgent"; +} + +/** + * ClaudeAdapter - Service tag for Claude Agent provider adapter operations. + */ +export class ClaudeAdapter extends ServiceMap.Service()( + "t3/provider/Services/ClaudeAdapter", +) {} diff --git a/apps/server/src/provider/Services/ClaudeProvider.ts b/apps/server/src/provider/Services/ClaudeProvider.ts new file mode 100644 index 0000000000..18ee8a4f6d --- /dev/null +++ b/apps/server/src/provider/Services/ClaudeProvider.ts @@ -0,0 +1,9 @@ +import { ServiceMap } from "effect"; + +import type { ServerProviderShape } from "./ServerProvider"; + +export interface ClaudeProviderShape extends ServerProviderShape {} + +export class ClaudeProvider extends ServiceMap.Service()( + "t3/provider/Services/ClaudeProvider", +) {} diff --git a/apps/server/src/provider/Services/CodexAdapter.ts b/apps/server/src/provider/Services/CodexAdapter.ts new file mode 100644 index 0000000000..c9f944bb96 --- /dev/null +++ b/apps/server/src/provider/Services/CodexAdapter.ts @@ -0,0 +1,30 @@ +/** + * CodexAdapter - Codex implementation of the generic provider adapter contract. + * + * This service owns Codex app-server process / JSON-RPC semantics and emits + * Codex provider events. It does not perform cross-provider routing, shared + * event fan-out, or checkpoint orchestration. + * + * Uses Effect `ServiceMap.Service` for dependency injection and returns the + * shared provider-adapter error channel with `provider: "codex"` context. + * + * @module CodexAdapter + */ +import { ServiceMap } from "effect"; + +import type { ProviderAdapterError } from "../Errors.ts"; +import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; + +/** + * CodexAdapterShape - Service API for the Codex provider adapter. + */ +export interface CodexAdapterShape extends ProviderAdapterShape { + readonly provider: "codex"; +} + +/** + * CodexAdapter - Service tag for Codex provider adapter operations. + */ +export class CodexAdapter extends ServiceMap.Service()( + "t3/provider/Services/CodexAdapter", +) {} diff --git a/apps/server/src/provider/Services/CodexProvider.ts b/apps/server/src/provider/Services/CodexProvider.ts new file mode 100644 index 0000000000..2e9b57c89b --- /dev/null +++ b/apps/server/src/provider/Services/CodexProvider.ts @@ -0,0 +1,9 @@ +import { ServiceMap } from "effect"; + +import type { ServerProviderShape } from "./ServerProvider"; + +export interface CodexProviderShape extends ServerProviderShape {} + +export class CodexProvider extends ServiceMap.Service()( + "t3/provider/Services/CodexProvider", +) {} diff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts new file mode 100644 index 0000000000..38a05f7574 --- /dev/null +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -0,0 +1,126 @@ +/** + * ProviderAdapter - Provider-specific runtime adapter contract. + * + * Defines the provider-native session/protocol operations that `ProviderService` + * routes to after resolving the target provider. Implementations should focus + * on provider behavior only and avoid cross-provider orchestration concerns. + * + * @module ProviderAdapter + */ +import type { + ApprovalRequestId, + ProviderApprovalDecision, + ProviderKind, + ProviderUserInputAnswers, + ProviderRuntimeEvent, + ProviderSendTurnInput, + ProviderSession, + ProviderSessionStartInput, + ThreadId, + ProviderTurnStartResult, + TurnId, +} from "@t3tools/contracts"; +import type { Effect } from "effect"; +import type { Stream } from "effect"; + +export type ProviderSessionModelSwitchMode = "in-session" | "restart-session" | "unsupported"; + +export interface ProviderAdapterCapabilities { + /** + * Declares whether changing the model on an existing session is supported. + */ + readonly sessionModelSwitch: ProviderSessionModelSwitchMode; +} + +export interface ProviderThreadTurnSnapshot { + readonly id: TurnId; + readonly items: ReadonlyArray; +} + +export interface ProviderThreadSnapshot { + readonly threadId: ThreadId; + readonly turns: ReadonlyArray; +} + +export interface ProviderAdapterShape { + /** + * Provider kind implemented by this adapter. + */ + readonly provider: ProviderKind; + readonly capabilities: ProviderAdapterCapabilities; + + /** + * Start a provider-backed session. + */ + readonly startSession: ( + input: ProviderSessionStartInput, + ) => Effect.Effect; + + /** + * Send a turn to an active provider session. + */ + readonly sendTurn: ( + input: ProviderSendTurnInput, + ) => Effect.Effect; + + /** + * Interrupt an active turn. + */ + readonly interruptTurn: (threadId: ThreadId, turnId?: TurnId) => Effect.Effect; + + /** + * Respond to an interactive approval request. + */ + readonly respondToRequest: ( + threadId: ThreadId, + requestId: ApprovalRequestId, + decision: ProviderApprovalDecision, + ) => Effect.Effect; + + /** + * Respond to a structured user-input request. + */ + readonly respondToUserInput: ( + threadId: ThreadId, + requestId: ApprovalRequestId, + answers: ProviderUserInputAnswers, + ) => Effect.Effect; + + /** + * Stop one provider session. + */ + readonly stopSession: (threadId: ThreadId) => Effect.Effect; + + /** + * List currently active provider sessions for this adapter. + */ + readonly listSessions: () => Effect.Effect>; + + /** + * Check whether this adapter owns an active session id. + */ + readonly hasSession: (threadId: ThreadId) => Effect.Effect; + + /** + * Read a provider thread snapshot. + */ + readonly readThread: (threadId: ThreadId) => Effect.Effect; + + /** + * Roll back a provider thread by N turns. + */ + readonly rollbackThread: ( + threadId: ThreadId, + numTurns: number, + ) => Effect.Effect; + + /** + * Stop all sessions owned by this adapter. + */ + readonly stopAll: () => Effect.Effect; + + /** + * Canonical runtime event stream emitted by this adapter. + */ + readonly streamEvents: Stream.Stream; +} diff --git a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts new file mode 100644 index 0000000000..490c4d3d14 --- /dev/null +++ b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts @@ -0,0 +1,42 @@ +/** + * ProviderAdapterRegistry - Lookup boundary for provider adapter implementations. + * + * Maps a provider kind to the concrete adapter service (Codex, Claude, etc). + * It does not own session lifecycle or routing rules; `ProviderService` uses + * this registry together with `ProviderSessionDirectory`. + * + * @module ProviderAdapterRegistry + */ +import type { ProviderKind } from "@t3tools/contracts"; +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProviderAdapterError, ProviderUnsupportedError } from "../Errors.ts"; +import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; + +/** + * ProviderAdapterRegistryShape - Service API for adapter lookup by provider kind. + */ +export interface ProviderAdapterRegistryShape { + /** + * Resolve the adapter for a provider kind. + */ + readonly getByProvider: ( + provider: ProviderKind, + ) => Effect.Effect, ProviderUnsupportedError>; + + /** + * List provider kinds currently registered. + */ + readonly listProviders: () => Effect.Effect>; +} + +/** + * ProviderAdapterRegistry - Service tag for provider adapter lookup. + */ +export class ProviderAdapterRegistry extends ServiceMap.Service< + ProviderAdapterRegistry, + ProviderAdapterRegistryShape +>()("t3/provider/Services/ProviderAdapterRegistry") {} + +// Dummy comment for workflow testing. diff --git a/apps/server/src/provider/Services/ProviderRegistry.ts b/apps/server/src/provider/Services/ProviderRegistry.ts new file mode 100644 index 0000000000..80710691c1 --- /dev/null +++ b/apps/server/src/provider/Services/ProviderRegistry.ts @@ -0,0 +1,32 @@ +/** + * ProviderRegistry - Provider snapshot service. + * + * Owns provider install/auth/version/model snapshots and exposes the latest + * provider state to transport layers. + * + * @module ProviderRegistry + */ +import type { ProviderKind, ServerProvider } from "@t3tools/contracts"; +import { ServiceMap } from "effect"; +import type { Effect, Stream } from "effect"; + +export interface ProviderRegistryShape { + /** + * Read the latest provider snapshots. + */ + readonly getProviders: Effect.Effect>; + + /** + * Refresh all providers, or a single provider when specified. + */ + readonly refresh: (provider?: ProviderKind) => Effect.Effect>; + + /** + * Stream of provider snapshot updates. + */ + readonly streamChanges: Stream.Stream>; +} + +export class ProviderRegistry extends ServiceMap.Service()( + "t3/provider/Services/ProviderRegistry", +) {} diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts new file mode 100644 index 0000000000..ebfe8c8ab1 --- /dev/null +++ b/apps/server/src/provider/Services/ProviderService.ts @@ -0,0 +1,115 @@ +/** + * ProviderService - Service interface for provider sessions, turns, and checkpoints. + * + * Acts as the cross-provider facade used by transports (WebSocket/RPC). It + * resolves provider adapters through `ProviderAdapterRegistry`, routes + * session-scoped calls via `ProviderSessionDirectory`, and exposes one unified + * provider event stream to callers. + * + * Uses Effect `ServiceMap.Service` for dependency injection and returns typed + * domain errors for validation, session, codex, and checkpoint workflows. + * + * @module ProviderService + */ +import type { + ProviderInterruptTurnInput, + ProviderKind, + ProviderRespondToRequestInput, + ProviderRespondToUserInputInput, + ProviderRuntimeEvent, + ProviderSendTurnInput, + ProviderSession, + ProviderSessionStartInput, + ProviderStopSessionInput, + ThreadId, + ProviderTurnStartResult, +} from "@t3tools/contracts"; +import { ServiceMap } from "effect"; +import type { Effect, Stream } from "effect"; + +import type { ProviderServiceError } from "../Errors.ts"; +import type { ProviderAdapterCapabilities } from "./ProviderAdapter.ts"; + +/** + * ProviderServiceShape - Service API for provider session and turn orchestration. + */ +export interface ProviderServiceShape { + /** + * Start a provider session. + */ + readonly startSession: ( + threadId: ThreadId, + input: ProviderSessionStartInput, + ) => Effect.Effect; + + /** + * Send a provider turn. + */ + readonly sendTurn: ( + input: ProviderSendTurnInput, + ) => Effect.Effect; + + /** + * Interrupt a running provider turn. + */ + readonly interruptTurn: ( + input: ProviderInterruptTurnInput, + ) => Effect.Effect; + + /** + * Respond to a provider approval request. + */ + readonly respondToRequest: ( + input: ProviderRespondToRequestInput, + ) => Effect.Effect; + + /** + * Respond to a provider structured user-input request. + */ + readonly respondToUserInput: ( + input: ProviderRespondToUserInputInput, + ) => Effect.Effect; + + /** + * Stop a provider session. + */ + readonly stopSession: ( + input: ProviderStopSessionInput, + ) => Effect.Effect; + + /** + * List active provider sessions. + * + * Aggregates runtime session lists from all registered adapters. + */ + readonly listSessions: () => Effect.Effect>; + + /** + * Read static capabilities for a provider adapter. + */ + readonly getCapabilities: ( + provider: ProviderKind, + ) => Effect.Effect; + + /** + * Roll back provider conversation state by a number of turns. + */ + readonly rollbackConversation: (input: { + readonly threadId: ThreadId; + readonly numTurns: number; + }) => Effect.Effect; + + /** + * Canonical provider runtime event stream. + * + * Fan-out is owned by ProviderService (not by a standalone event-bus service). + */ + readonly streamEvents: Stream.Stream; +} + +/** + * ProviderService - Service tag for provider orchestration. + */ +export class ProviderService extends ServiceMap.Service()( + "t3/provider/Services/ProviderService", +) {} diff --git a/apps/server/src/provider/Services/ProviderSessionDirectory.ts b/apps/server/src/provider/Services/ProviderSessionDirectory.ts new file mode 100644 index 0000000000..3a374976b0 --- /dev/null +++ b/apps/server/src/provider/Services/ProviderSessionDirectory.ts @@ -0,0 +1,57 @@ +import type { + ProviderKind, + ProviderSessionRuntimeStatus, + RuntimeMode, + ThreadId, +} from "@t3tools/contracts"; +import { Option, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { + ProviderSessionDirectoryPersistenceError, + ProviderValidationError, +} from "../Errors.ts"; + +export interface ProviderRuntimeBinding { + readonly threadId: ThreadId; + readonly provider: ProviderKind; + readonly adapterKey?: string; + readonly status?: ProviderSessionRuntimeStatus; + readonly resumeCursor?: unknown | null; + readonly runtimePayload?: unknown | null; + readonly runtimeMode?: RuntimeMode; +} + +export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError; + +export type ProviderSessionDirectoryWriteError = + | ProviderValidationError + | ProviderSessionDirectoryPersistenceError; + +export interface ProviderSessionDirectoryShape { + readonly upsert: ( + binding: ProviderRuntimeBinding, + ) => Effect.Effect; + + readonly getProvider: ( + threadId: ThreadId, + ) => Effect.Effect; + + readonly getBinding: ( + threadId: ThreadId, + ) => Effect.Effect, ProviderSessionDirectoryReadError>; + + readonly remove: ( + threadId: ThreadId, + ) => Effect.Effect; + + readonly listThreadIds: () => Effect.Effect< + ReadonlyArray, + ProviderSessionDirectoryPersistenceError + >; +} + +export class ProviderSessionDirectory extends ServiceMap.Service< + ProviderSessionDirectory, + ProviderSessionDirectoryShape +>()("t3/provider/Services/ProviderSessionDirectory") {} diff --git a/apps/server/src/provider/Services/ServerProvider.ts b/apps/server/src/provider/Services/ServerProvider.ts new file mode 100644 index 0000000000..4df0bc8fc2 --- /dev/null +++ b/apps/server/src/provider/Services/ServerProvider.ts @@ -0,0 +1,8 @@ +import type { ServerProvider } from "@t3tools/contracts"; +import type { Effect, Stream } from "effect"; + +export interface ServerProviderShape { + readonly getSnapshot: Effect.Effect; + readonly refresh: Effect.Effect; + readonly streamChanges: Stream.Stream; +} diff --git a/apps/server/src/provider/codexAccount.ts b/apps/server/src/provider/codexAccount.ts new file mode 100644 index 0000000000..1db00250f6 --- /dev/null +++ b/apps/server/src/provider/codexAccount.ts @@ -0,0 +1,123 @@ +import type { ServerProviderModel } from "@t3tools/contracts"; + +export type CodexPlanType = + | "free" + | "go" + | "plus" + | "pro" + | "team" + | "business" + | "enterprise" + | "edu" + | "unknown"; + +export interface CodexAccountSnapshot { + readonly type: "apiKey" | "chatgpt" | "unknown"; + readonly planType: CodexPlanType | null; + readonly sparkEnabled: boolean; +} + +export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex"; +export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark"; +const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set(["pro"]); + +function asObject(value: unknown): Record | undefined { + if (!value || typeof value !== "object") { + return undefined; + } + return value as Record; +} + +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: false, + }; + } + + if (accountType === "chatgpt") { + const planType = (account?.planType as CodexPlanType | null) ?? "unknown"; + return { + type: "chatgpt", + planType, + sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType), + }; + } + + return { + type: "unknown", + planType: null, + sparkEnabled: false, + }; +} + +export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined { + if (account?.type === "apiKey") { + return "apiKey"; + } + + if (account?.type !== "chatgpt") { + return undefined; + } + + return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt"; +} + +export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined { + switch (codexAuthSubType(account)) { + case "apiKey": + return "OpenAI API Key"; + case "chatgpt": + return "ChatGPT Subscription"; + case "free": + return "ChatGPT Free Subscription"; + case "go": + return "ChatGPT Go Subscription"; + case "plus": + return "ChatGPT Plus Subscription"; + case "pro": + return "ChatGPT Pro Subscription"; + case "team": + return "ChatGPT Team Subscription"; + case "business": + return "ChatGPT Business Subscription"; + case "enterprise": + return "ChatGPT Enterprise Subscription"; + case "edu": + return "ChatGPT Edu Subscription"; + default: + return undefined; + } +} + +export function adjustCodexModelsForAccount( + baseModels: ReadonlyArray, + account: CodexAccountSnapshot | undefined, +): ReadonlyArray { + if (account?.sparkEnabled !== false) { + return baseModels; + } + + return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL); +} + +export function resolveCodexModelForAccount( + model: string | undefined, + account: CodexAccountSnapshot, +): string | undefined { + if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) { + return model; + } + + return CODEX_DEFAULT_MODEL; +} diff --git a/apps/server/src/provider/codexAppServer.ts b/apps/server/src/provider/codexAppServer.ts new file mode 100644 index 0000000000..d25fc3533e --- /dev/null +++ b/apps/server/src/provider/codexAppServer.ts @@ -0,0 +1,154 @@ +import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process"; +import readline from "node:readline"; +import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount"; + +interface JsonRpcProbeResponse { + readonly id?: unknown; + readonly result?: unknown; + readonly error?: { + readonly message?: unknown; + }; +} + +function readErrorMessage(response: JsonRpcProbeResponse): string | undefined { + return typeof response.error?.message === "string" ? response.error.message : undefined; +} + +export function buildCodexInitializeParams() { + return { + clientInfo: { + name: "t3code_desktop", + title: "T3 Code Desktop", + version: "0.1.0", + }, + capabilities: { + experimentalApi: true, + }, + } as const; +} + +export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void { + if (process.platform === "win32" && child.pid !== undefined) { + try { + spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }); + return; + } catch { + // Fall through to direct kill when taskkill is unavailable. + } + } + + child.kill(); +} + +export async function probeCodexAccount(input: { + readonly binaryPath: string; + readonly homePath?: string; + readonly signal?: AbortSignal; +}): Promise { + return await new Promise((resolve, reject) => { + const child = spawn(input.binaryPath, ["app-server"], { + env: { + ...process.env, + ...(input.homePath ? { CODEX_HOME: input.homePath } : {}), + }, + stdio: ["pipe", "pipe", "pipe"], + shell: process.platform === "win32", + }); + const output = readline.createInterface({ input: child.stdout }); + + let completed = false; + + const cleanup = () => { + output.removeAllListeners(); + output.close(); + child.removeAllListeners(); + if (!child.killed) { + killCodexChildProcess(child); + } + }; + + const finish = (callback: () => void) => { + if (completed) return; + completed = true; + cleanup(); + callback(); + }; + + const fail = (error: unknown) => + finish(() => + reject( + error instanceof Error + ? error + : new Error(`Codex account probe failed: ${String(error)}.`), + ), + ); + + if (input.signal?.aborted) { + fail(new Error("Codex account probe aborted.")); + return; + } + input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted."))); + + const writeMessage = (message: unknown) => { + if (!child.stdin.writable) { + fail(new Error("Cannot write to codex app-server stdin.")); + return; + } + + child.stdin.write(`${JSON.stringify(message)}\n`); + }; + + output.on("line", (line) => { + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + fail(new Error("Received invalid JSON from codex app-server during account probe.")); + return; + } + + if (!parsed || typeof parsed !== "object") { + return; + } + + const response = parsed as JsonRpcProbeResponse; + if (response.id === 1) { + const errorMessage = readErrorMessage(response); + if (errorMessage) { + fail(new Error(`initialize failed: ${errorMessage}`)); + return; + } + + writeMessage({ method: "initialized" }); + writeMessage({ id: 2, method: "account/read", params: {} }); + return; + } + + if (response.id === 2) { + const errorMessage = readErrorMessage(response); + if (errorMessage) { + fail(new Error(`account/read failed: ${errorMessage}`)); + return; + } + + finish(() => resolve(readCodexAccountSnapshot(response.result))); + } + }); + + child.once("error", fail); + child.once("exit", (code, signal) => { + if (completed) return; + fail( + new Error( + `codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`, + ), + ); + }); + + writeMessage({ + id: 1, + method: "initialize", + params: buildCodexInitializeParams(), + }); + }); +} diff --git a/apps/server/src/provider/codexCliVersion.ts b/apps/server/src/provider/codexCliVersion.ts new file mode 100644 index 0000000000..544020016c --- /dev/null +++ b/apps/server/src/provider/codexCliVersion.ts @@ -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; +} + +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.`; +} diff --git a/apps/server/src/provider/makeManagedServerProvider.ts b/apps/server/src/provider/makeManagedServerProvider.ts new file mode 100644 index 0000000000..59aeac1ab5 --- /dev/null +++ b/apps/server/src/provider/makeManagedServerProvider.ts @@ -0,0 +1,74 @@ +import type { ServerProvider } from "@t3tools/contracts"; +import { Duration, Effect, PubSub, Ref, Scope, Stream } from "effect"; +import * as Semaphore from "effect/Semaphore"; + +import type { ServerProviderShape } from "./Services/ServerProvider"; +import { ServerSettingsError } from "@t3tools/contracts"; + +export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* < + Settings, +>(input: { + readonly getSettings: Effect.Effect; + readonly streamSettings: Stream.Stream; + readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean; + readonly checkProvider: Effect.Effect; + readonly refreshInterval?: Duration.Input; +}): Effect.fn.Return { + const refreshSemaphore = yield* Semaphore.make(1); + const changesPubSub = yield* Effect.acquireRelease( + PubSub.unbounded(), + PubSub.shutdown, + ); + const initialSettings = yield* input.getSettings; + const initialSnapshot = yield* input.checkProvider; + const snapshotRef = yield* Ref.make(initialSnapshot); + const settingsRef = yield* Ref.make(initialSettings); + + const applySnapshotBase = Effect.fn("applySnapshot")(function* ( + nextSettings: Settings, + options?: { readonly forceRefresh?: boolean }, + ) { + const forceRefresh = options?.forceRefresh === true; + const previousSettings = yield* Ref.get(settingsRef); + if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) { + yield* Ref.set(settingsRef, nextSettings); + return yield* Ref.get(snapshotRef); + } + + const nextSnapshot = yield* input.checkProvider; + yield* Ref.set(settingsRef, nextSettings); + yield* Ref.set(snapshotRef, nextSnapshot); + yield* PubSub.publish(changesPubSub, nextSnapshot); + return nextSnapshot; + }); + const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) => + refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options)); + + const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () { + const nextSettings = yield* input.getSettings; + return yield* applySnapshot(nextSettings, { forceRefresh: true }); + }); + + yield* Stream.runForEach(input.streamSettings, (nextSettings) => + Effect.asVoid(applySnapshot(nextSettings)), + ).pipe(Effect.forkScoped); + + yield* Effect.forever( + Effect.sleep(input.refreshInterval ?? "60 seconds").pipe( + Effect.flatMap(() => refreshSnapshot()), + Effect.ignoreCause({ log: true }), + ), + ).pipe(Effect.forkScoped); + + return { + getSnapshot: input.getSettings.pipe( + Effect.flatMap(applySnapshot), + Effect.tapError(Effect.logError), + Effect.orDie, + ), + refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie), + get streamChanges() { + return Stream.fromPubSub(changesPubSub); + }, + } satisfies ServerProviderShape; +}); diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts new file mode 100644 index 0000000000..e1243c4bd0 --- /dev/null +++ b/apps/server/src/provider/providerSnapshot.ts @@ -0,0 +1,156 @@ +import type { + ServerProvider, + ServerProviderAuth, + ServerProviderModel, + ServerProviderState, +} from "@t3tools/contracts"; +import { Effect, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; +import { normalizeModelSlug } from "@t3tools/shared/model"; +import { isWindowsCommandNotFound } from "../processRunner"; + +export const DEFAULT_TIMEOUT_MS = 4_000; + +export interface CommandResult { + readonly stdout: string; + readonly stderr: string; + readonly code: number; +} + +export interface ProviderProbeResult { + readonly installed: boolean; + readonly version: string | null; + readonly status: Exclude; + readonly auth: ServerProviderAuth; + readonly message?: string; +} + +export function nonEmptyTrimmed(value: string | undefined): string | undefined { + if (!value) return undefined; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +} + +export function isCommandMissingCause(error: unknown): boolean { + if (!(error instanceof Error)) return false; + const lower = error.message.toLowerCase(); + return lower.includes("enoent") || lower.includes("notfound"); +} + +export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner.spawn(command); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectStreamAsString(child.stdout), + collectStreamAsString(child.stderr), + child.exitCode.pipe(Effect.map(Number)), + ], + { concurrency: "unbounded" }, + ); + + const result: CommandResult = { stdout, stderr, code: exitCode }; + if (isWindowsCommandNotFound(exitCode, stderr)) { + return yield* Effect.fail(new Error(`spawn ${binaryPath} ENOENT`)); + } + return result; + }).pipe(Effect.scoped); + +export function detailFromResult( + result: CommandResult & { readonly timedOut?: boolean }, +): string | undefined { + if (result.timedOut) return "Timed out while running command."; + const stderr = nonEmptyTrimmed(result.stderr); + if (stderr) return stderr; + const stdout = nonEmptyTrimmed(result.stdout); + if (stdout) return stdout; + if (result.code !== 0) { + return `Command exited with code ${result.code}.`; + } + return undefined; +} + +export function extractAuthBoolean(value: unknown): boolean | undefined { + if (globalThis.Array.isArray(value)) { + for (const entry of value) { + const nested = extractAuthBoolean(entry); + if (nested !== undefined) return nested; + } + return undefined; + } + + if (!value || typeof value !== "object") return undefined; + + const record = value as Record; + for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) { + if (typeof record[key] === "boolean") return record[key]; + } + for (const key of ["auth", "status", "session", "account"] as const) { + const nested = extractAuthBoolean(record[key]); + if (nested !== undefined) return nested; + } + return undefined; +} + +export function parseGenericCliVersion(output: string): string | null { + const match = output.match(/\b(\d+\.\d+\.\d+)\b/); + return match?.[1] ?? null; +} + +export function providerModelsFromSettings( + builtInModels: ReadonlyArray, + provider: ServerProvider["provider"], + customModels: ReadonlyArray, +): ReadonlyArray { + const resolvedBuiltInModels = [...builtInModels]; + const seen = new Set(resolvedBuiltInModels.map((model) => model.slug)); + const customEntries: ServerProviderModel[] = []; + + for (const candidate of customModels) { + const normalized = normalizeModelSlug(candidate, provider); + if (!normalized || seen.has(normalized)) { + continue; + } + seen.add(normalized); + customEntries.push({ + slug: normalized, + name: normalized, + isCustom: true, + capabilities: null, + }); + } + + return [...resolvedBuiltInModels, ...customEntries]; +} + +export function buildServerProvider(input: { + provider: ServerProvider["provider"]; + enabled: boolean; + checkedAt: string; + models: ReadonlyArray; + probe: ProviderProbeResult; +}): ServerProvider { + return { + provider: input.provider, + enabled: input.enabled, + installed: input.probe.installed, + version: input.probe.version, + status: input.enabled ? input.probe.status : "disabled", + auth: input.probe.auth, + checkedAt: input.checkedAt, + ...(input.probe.message ? { message: input.probe.message } : {}), + models: input.models, + }; +} + +export const collectStreamAsString = ( + stream: Stream.Stream, +): Effect.Effect => + stream.pipe( + Stream.decodeText(), + Stream.runFold( + () => "", + (acc, chunk) => acc + chunk, + ), + ); diff --git a/apps/server/src/providerManager.test.ts b/apps/server/src/providerManager.test.ts deleted file mode 100644 index 424cfce16c..0000000000 --- a/apps/server/src/providerManager.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { ProviderManager } from "./providerManager"; - -describe("ProviderManager", () => { - it("detaches provider event listener and ends thread log streams on dispose", () => { - const manager = new ProviderManager(); - const internals = manager as unknown as { - codex: { listenerCount: (event: string) => number }; - onCodexEvent: (event: { - id: string; - kind: "notification"; - provider: "codex"; - sessionId: string; - createdAt: string; - method: string; - threadId: string; - }) => void; - threadLogStreams: Map; - }; - internals.onCodexEvent({ - id: "evt-1", - kind: "notification", - provider: "codex", - sessionId: "sess-1", - createdAt: new Date().toISOString(), - method: "thread/started", - threadId: "thread-1", - }); - const stream = internals.threadLogStreams.get("thread-1"); - expect(stream).toBeDefined(); - if (!stream) return; - - expect(internals.codex.listenerCount("event")).toBe(1); - manager.dispose(); - - expect(internals.codex.listenerCount("event")).toBe(0); - expect(stream.writableEnded || stream.destroyed).toBe(true); - expect(internals.threadLogStreams.size).toBe(0); - }); - - it("allows multiple dispose calls", () => { - const manager = new ProviderManager(); - - manager.dispose(); - expect(() => manager.dispose()).not.toThrow(); - }); - - it("rejects request responses for unknown sessions", async () => { - const manager = new ProviderManager(); - - await expect( - manager.respondToRequest({ - sessionId: "missing-session", - requestId: "req-1", - decision: "accept", - }), - ).rejects.toThrow("Unknown provider session: missing-session"); - - manager.dispose(); - }); -}); diff --git a/apps/server/src/providerManager.ts b/apps/server/src/providerManager.ts deleted file mode 100644 index 52fb1b6484..0000000000 --- a/apps/server/src/providerManager.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { EventEmitter } from "node:events"; -import fs from "node:fs"; -import path from "node:path"; - -import { - type ProviderEvent, - type ProviderInterruptTurnInput, - type ProviderRespondToRequestInput, - type ProviderSendTurnInput, - type ProviderSession, - type ProviderSessionStartInput, - type ProviderStopSessionInput, - type ProviderTurnStartResult, - providerInterruptTurnInputSchema, - providerRespondToRequestInputSchema, - providerSendTurnInputSchema, - providerSessionStartInputSchema, - providerStopSessionInputSchema, -} from "@t3tools/contracts"; -import { CodexAppServerManager } from "./codexAppServerManager"; - -export interface ProviderManagerEvents { - event: [event: ProviderEvent]; -} - -export class ProviderManager extends EventEmitter { - private readonly codex = new CodexAppServerManager(); - private readonly threadLogsDir: string; - private readonly threadLogStreams = new Map(); - private readonly sessionThreadIds = new Map(); - private readonly pendingEventsBySession = new Map(); - private disposed = false; - private readonly onCodexEvent = (event: ProviderEvent) => { - if (this.disposed) { - return; - } - - this.routeEventToThreadLog(event); - this.emit("event", event); - }; - - constructor() { - super(); - - const logsDir = path.resolve(process.cwd(), ".logs"); - this.threadLogsDir = path.join(logsDir, "threads"); - fs.mkdirSync(this.threadLogsDir, { recursive: true }); - - this.codex.on("event", this.onCodexEvent); - } - - async startSession(raw: ProviderSessionStartInput): Promise { - const input = providerSessionStartInputSchema.parse(raw); - if (input.provider !== "codex") { - throw new Error(`Provider '${input.provider}' is not implemented yet.`); - } - - const session = await this.codex.startSession(input); - if (session.threadId) { - this.sessionThreadIds.set(session.sessionId, session.threadId); - this.flushPendingSessionEvents(session.sessionId, session.threadId); - } - return session; - } - - async sendTurn(raw: ProviderSendTurnInput): Promise { - const input = providerSendTurnInputSchema.parse(raw); - if (!this.codex.hasSession(input.sessionId)) { - throw new Error(`Unknown provider session: ${input.sessionId}`); - } - - return this.codex.sendTurn(input); - } - - async interruptTurn(raw: ProviderInterruptTurnInput): Promise { - const input = providerInterruptTurnInputSchema.parse(raw); - if (!this.codex.hasSession(input.sessionId)) { - throw new Error(`Unknown provider session: ${input.sessionId}`); - } - - await this.codex.interruptTurn(input.sessionId, input.turnId); - } - - async respondToRequest(raw: ProviderRespondToRequestInput): Promise { - const input = providerRespondToRequestInputSchema.parse(raw); - if (!this.codex.hasSession(input.sessionId)) { - throw new Error(`Unknown provider session: ${input.sessionId}`); - } - - await this.codex.respondToRequest(input.sessionId, input.requestId, input.decision); - } - - stopSession(raw: ProviderStopSessionInput): void { - const input = providerStopSessionInputSchema.parse(raw); - this.codex.stopSession(input.sessionId); - this.sessionThreadIds.delete(input.sessionId); - this.pendingEventsBySession.delete(input.sessionId); - } - - listSessions(): ProviderSession[] { - return this.codex.listSessions(); - } - - stopAll(): void { - this.codex.stopAll(); - } - - dispose(): void { - if (this.disposed) { - return; - } - - this.disposed = true; - this.codex.off("event", this.onCodexEvent); - for (const stream of this.threadLogStreams.values()) { - stream.end(); - } - this.threadLogStreams.clear(); - this.sessionThreadIds.clear(); - this.pendingEventsBySession.clear(); - } - - private routeEventToThreadLog(event: ProviderEvent): void { - const threadId = this.resolveThreadId(event); - if (!threadId) { - const pending = this.pendingEventsBySession.get(event.sessionId) ?? []; - pending.push(event); - this.pendingEventsBySession.set(event.sessionId, pending.slice(-100)); - return; - } - - this.flushPendingSessionEvents(event.sessionId, threadId); - this.writeThreadEvent(threadId, event); - } - - private flushPendingSessionEvents(sessionId: string, threadId: string): void { - const pending = this.pendingEventsBySession.get(sessionId); - if (!pending || pending.length === 0) { - return; - } - - for (const event of pending) { - this.writeThreadEvent(threadId, event); - } - this.pendingEventsBySession.delete(sessionId); - } - - private resolveThreadId(event: ProviderEvent): string | undefined { - const fromPayload = this.readThreadIdFromPayload(event.payload); - const threadId = event.threadId ?? fromPayload ?? this.sessionThreadIds.get(event.sessionId); - - if (threadId) { - this.sessionThreadIds.set(event.sessionId, threadId); - } - - return threadId; - } - - private readThreadIdFromPayload(payload: unknown): string | undefined { - if (!payload || typeof payload !== "object") { - return undefined; - } - - const record = payload as Record; - const direct = record.threadId; - if (typeof direct === "string" && direct.length > 0) { - return direct; - } - - const thread = record.thread; - if (!thread || typeof thread !== "object") { - return undefined; - } - - const nested = (thread as Record).id; - if (typeof nested === "string" && nested.length > 0) { - return nested; - } - - return undefined; - } - - private writeThreadEvent(threadId: string, event: ProviderEvent): void { - const stream = this.getOrCreateThreadLogStream(threadId); - stream.write(`${JSON.stringify(event)}\n`); - } - - private getOrCreateThreadLogStream(threadId: string): fs.WriteStream { - const cached = this.threadLogStreams.get(threadId); - if (cached) { - return cached; - } - - const safeThreadId = threadId.replace(/[^a-zA-Z0-9._-]/g, "_"); - const stream = fs.createWriteStream( - path.join(this.threadLogsDir, `${safeThreadId}.events.ndjson`), - { flags: "a" }, - ); - this.threadLogStreams.set(threadId, stream); - return stream; - } -} diff --git a/apps/server/src/ptyAdapter.test.ts b/apps/server/src/ptyAdapter.test.ts deleted file mode 100644 index 5fd37292fe..0000000000 --- a/apps/server/src/ptyAdapter.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { afterEach, describe, expect, it } from "vitest"; - -import { ensureNodePtySpawnHelperExecutable } from "./ptyAdapter"; - -function fileMode(filePath: string): number { - return fs.statSync(filePath).mode & 0o777; -} - -describe("ensureNodePtySpawnHelperExecutable", () => { - const tempDirs: string[] = []; - - afterEach(() => { - for (const dir of tempDirs.splice(0, tempDirs.length)) { - fs.rmSync(dir, { recursive: true, force: true }); - } - }); - - it("adds executable bits when helper exists but is not executable", () => { - if (process.platform === "win32") return; - - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pty-helper-test-")); - tempDirs.push(dir); - const helperPath = path.join(dir, "spawn-helper"); - fs.writeFileSync(helperPath, "#!/bin/sh\nexit 0\n", "utf8"); - fs.chmodSync(helperPath, 0o644); - - ensureNodePtySpawnHelperExecutable(helperPath); - - expect(fileMode(helperPath) & 0o111).toBe(0o111); - }); - - it("keeps executable helper as executable", () => { - if (process.platform === "win32") return; - - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pty-helper-test-")); - tempDirs.push(dir); - const helperPath = path.join(dir, "spawn-helper"); - fs.writeFileSync(helperPath, "#!/bin/sh\nexit 0\n", "utf8"); - fs.chmodSync(helperPath, 0o755); - - ensureNodePtySpawnHelperExecutable(helperPath); - - expect(fileMode(helperPath) & 0o111).toBe(0o111); - }); - - it("does not throw when helper path is missing", () => { - const missing = path.join(os.tmpdir(), `does-not-exist-${Date.now()}`); - expect(() => ensureNodePtySpawnHelperExecutable(missing)).not.toThrow(); - }); -}); diff --git a/apps/server/src/ptyAdapter.ts b/apps/server/src/ptyAdapter.ts deleted file mode 100644 index 903b5911b1..0000000000 --- a/apps/server/src/ptyAdapter.ts +++ /dev/null @@ -1,130 +0,0 @@ -import fs from "node:fs"; -import { createRequire } from "node:module"; -import path from "node:path"; - -import * as nodePty from "node-pty"; - -export interface PtyExitEvent { - exitCode: number; - signal: number | null; -} - -export interface PtyProcess { - readonly pid: number; - write(data: string): void; - resize(cols: number, rows: number): void; - kill(signal?: string): void; - onData(callback: (data: string) => void): () => void; - onExit(callback: (event: PtyExitEvent) => void): () => void; -} - -export interface PtySpawnInput { - shell: string; - cwd: string; - cols: number; - rows: number; - env: NodeJS.ProcessEnv; -} - -export interface PtyAdapter { - spawn(input: PtySpawnInput): PtyProcess; -} - -const requireForNodePty = createRequire(import.meta.url); -let didEnsureSpawnHelperExecutable = false; - -function resolveNodePtySpawnHelperPath(): string | null { - try { - const packageJsonPath = requireForNodePty.resolve("node-pty/package.json"); - const packageDir = path.dirname(packageJsonPath); - const candidates = [ - path.join(packageDir, "build", "Release", "spawn-helper"), - path.join(packageDir, "build", "Debug", "spawn-helper"), - path.join(packageDir, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper"), - ]; - - for (const candidate of candidates) { - if (fs.existsSync(candidate)) { - return candidate; - } - } - - return null; - } catch { - return null; - } -} - -export function ensureNodePtySpawnHelperExecutable(explicitPath?: string): void { - if (process.platform === "win32") return; - if (!explicitPath && didEnsureSpawnHelperExecutable) return; - - const helperPath = explicitPath ?? resolveNodePtySpawnHelperPath(); - if (!helperPath) return; - if (!explicitPath) { - didEnsureSpawnHelperExecutable = true; - } - - try { - const stat = fs.statSync(helperPath); - const mode = stat.mode & 0o777; - if ((mode & 0o111) === 0) { - fs.chmodSync(helperPath, mode | 0o111); - } - } catch { - // Best effort only. If chmod fails, node-pty spawn will surface the real error. - } -} - -class NodePtyProcess implements PtyProcess { - constructor(private readonly process: nodePty.IPty) {} - - get pid(): number { - return this.process.pid; - } - - write(data: string): void { - this.process.write(data); - } - - resize(cols: number, rows: number): void { - this.process.resize(cols, rows); - } - - kill(signal?: string): void { - this.process.kill(signal); - } - - onData(callback: (data: string) => void): () => void { - const disposable = this.process.onData(callback); - return () => { - disposable.dispose(); - }; - } - - onExit(callback: (event: PtyExitEvent) => void): () => void { - const disposable = this.process.onExit((event) => { - callback({ - exitCode: event.exitCode, - signal: event.signal ?? null, - }); - }); - return () => { - disposable.dispose(); - }; - } -} - -export class NodePtyAdapter implements PtyAdapter { - spawn(input: PtySpawnInput): PtyProcess { - ensureNodePtySpawnHelperExecutable(); - const ptyProcess = nodePty.spawn(input.shell, [], { - cwd: input.cwd, - cols: input.cols, - rows: input.rows, - env: input.env, - name: globalThis.process.platform === "win32" ? "xterm-color" : "xterm-256color", - }); - return new NodePtyProcess(ptyProcess); - } -} diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts new file mode 100644 index 0000000000..3d8e36e0a7 --- /dev/null +++ b/apps/server/src/server.test.ts @@ -0,0 +1,1884 @@ +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + CommandId, + DEFAULT_SERVER_SETTINGS, + GitCommandError, + KeybindingRule, + MessageId, + OpenError, + TerminalNotRunningError, + type OrchestrationCommand, + type OrchestrationEvent, + ORCHESTRATION_WS_METHODS, + ProjectId, + ResolvedKeybindingRule, + ThreadId, + WS_METHODS, + WsRpcGroup, + EditorId, +} from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils"; +import { Effect, FileSystem, Layer, Path, Stream } from "effect"; +import { HttpClient, HttpRouter, HttpServer } from "effect/unstable/http"; +import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; +import { vi } from "vitest"; + +import type { ServerConfigShape } from "./config.ts"; +import { deriveServerPaths, ServerConfig } from "./config.ts"; +import { makeRoutesLayer } from "./server.ts"; +import { resolveAttachmentRelativePath } from "./attachmentPaths.ts"; +import { + CheckpointDiffQuery, + type CheckpointDiffQueryShape, +} from "./checkpointing/Services/CheckpointDiffQuery.ts"; +import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts"; +import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts"; +import { Keybindings, type KeybindingsShape } from "./keybindings.ts"; +import { Open, type OpenShape } from "./open.ts"; +import { + OrchestrationEngineService, + type OrchestrationEngineShape, +} from "./orchestration/Services/OrchestrationEngine.ts"; +import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts"; +import { + ProjectionSnapshotQuery, + type ProjectionSnapshotQueryShape, +} from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import { PersistenceSqlError } from "./persistence/Errors.ts"; +import { + ProviderRegistry, + type ProviderRegistryShape, +} from "./provider/Services/ProviderRegistry.ts"; +import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./serverLifecycleEvents.ts"; +import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts"; +import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts"; +import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager.ts"; +import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts"; +import { + ProjectSetupScriptRunner, + type ProjectSetupScriptRunnerShape, +} from "./project/Services/ProjectSetupScriptRunner.ts"; +import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts"; +import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts"; +import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts"; + +const defaultProjectId = ProjectId.makeUnsafe("project-default"); +const defaultThreadId = ThreadId.makeUnsafe("thread-default"); +const defaultModelSelection = { + provider: "codex", + model: "gpt-5-codex", +} as const; + +const makeDefaultOrchestrationReadModel = () => { + const now = new Date().toISOString(); + return { + snapshotSequence: 0, + updatedAt: now, + projects: [ + { + id: defaultProjectId, + title: "Default Project", + workspaceRoot: "/tmp/default-project", + defaultModelSelection, + scripts: [], + createdAt: now, + updatedAt: now, + deletedAt: null, + }, + ], + threads: [ + { + id: defaultThreadId, + projectId: defaultProjectId, + title: "Default Thread", + modelSelection: defaultModelSelection, + interactionMode: "default" as const, + runtimeMode: "full-access" as const, + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + latestTurn: null, + messages: [], + session: null, + activities: [], + proposedPlans: [], + checkpoints: [], + deletedAt: null, + }, + ], + }; +}; + +const workspaceAndProjectServicesLayer = Layer.mergeAll( + WorkspacePathsLive, + WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)), + WorkspaceFileSystemLive.pipe( + Layer.provide(WorkspacePathsLive), + Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + ), + ProjectFaviconResolverLive, +); + +const buildAppUnderTest = (options?: { + config?: Partial; + layers?: { + keybindings?: Partial; + providerRegistry?: Partial; + serverSettings?: Partial; + open?: Partial; + gitCore?: Partial; + gitManager?: Partial; + projectSetupScriptRunner?: Partial; + terminalManager?: Partial; + orchestrationEngine?: Partial; + projectionSnapshotQuery?: Partial; + checkpointDiffQuery?: Partial; + serverLifecycleEvents?: Partial; + serverRuntimeStartup?: Partial; + }; +}) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const tempBaseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-test-" }); + const baseDir = options?.config?.baseDir ?? tempBaseDir; + const devUrl = options?.config?.devUrl; + const derivedPaths = yield* deriveServerPaths(baseDir, devUrl); + const config: ServerConfigShape = { + logLevel: "Info", + traceMinLevel: "Info", + traceTimingEnabled: true, + traceBatchWindowMs: 200, + traceMaxBytes: 10 * 1024 * 1024, + traceMaxFiles: 10, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpExportIntervalMs: 10_000, + otlpServiceName: "t3-server", + mode: "web", + port: 0, + host: "127.0.0.1", + cwd: process.cwd(), + baseDir, + ...derivedPaths, + staticDir: undefined, + devUrl, + noBrowser: true, + authToken: undefined, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + ...options?.config, + }; + const layerConfig = Layer.succeed(ServerConfig, config); + + const appLayer = HttpRouter.serve(makeRoutesLayer, { + disableListenLog: true, + disableLogger: true, + }).pipe( + Layer.provide( + Layer.mock(Keybindings)({ + streamChanges: Stream.empty, + ...options?.layers?.keybindings, + }), + ), + Layer.provide( + Layer.mock(ProviderRegistry)({ + getProviders: Effect.succeed([]), + refresh: () => Effect.succeed([]), + streamChanges: Stream.empty, + ...options?.layers?.providerRegistry, + }), + ), + Layer.provide( + Layer.mock(ServerSettingsService)({ + start: Effect.void, + ready: Effect.void, + getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS), + updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS), + streamChanges: Stream.empty, + ...options?.layers?.serverSettings, + }), + ), + Layer.provide( + Layer.mock(Open)({ + ...options?.layers?.open, + }), + ), + Layer.provide( + Layer.mock(GitCore)({ + ...options?.layers?.gitCore, + }), + ), + Layer.provide( + Layer.mock(GitManager)({ + ...options?.layers?.gitManager, + }), + ), + Layer.provide( + Layer.mock(ProjectSetupScriptRunner)({ + runForThread: () => Effect.succeed({ status: "no-script" as const }), + ...options?.layers?.projectSetupScriptRunner, + }), + ), + Layer.provide( + Layer.mock(TerminalManager)({ + ...options?.layers?.terminalManager, + }), + ), + Layer.provide( + Layer.mock(OrchestrationEngineService)({ + getReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()), + readEvents: () => Stream.empty, + dispatch: () => Effect.succeed({ sequence: 0 }), + streamDomainEvents: Stream.empty, + ...options?.layers?.orchestrationEngine, + }), + ), + Layer.provide( + Layer.mock(ProjectionSnapshotQuery)({ + getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()), + ...options?.layers?.projectionSnapshotQuery, + }), + ), + Layer.provide( + Layer.mock(CheckpointDiffQuery)({ + getTurnDiff: () => + Effect.succeed({ + threadId: defaultThreadId, + fromTurnCount: 0, + toTurnCount: 0, + diff: "", + }), + getFullThreadDiff: () => + Effect.succeed({ + threadId: defaultThreadId, + fromTurnCount: 0, + toTurnCount: 0, + diff: "", + }), + ...options?.layers?.checkpointDiffQuery, + }), + ), + Layer.provide( + Layer.mock(ServerLifecycleEvents)({ + publish: (event) => Effect.succeed({ ...(event as any), sequence: 1 }), + snapshot: Effect.succeed({ sequence: 0, events: [] }), + stream: Stream.empty, + ...options?.layers?.serverLifecycleEvents, + }), + ), + Layer.provide( + Layer.mock(ServerRuntimeStartup)({ + awaitCommandReady: Effect.void, + markHttpListening: Effect.void, + enqueueCommand: (effect) => effect, + ...options?.layers?.serverRuntimeStartup, + }), + ), + Layer.provide(workspaceAndProjectServicesLayer), + Layer.provide(layerConfig), + ); + + yield* Layer.build(appLayer); + return config; + }); + +const wsRpcProtocolLayer = (wsUrl: string) => + RpcClient.layerProtocolSocket().pipe( + Layer.provide(NodeSocket.layerWebSocket(wsUrl)), + Layer.provide(RpcSerialization.layerJson), + ); + +const makeWsRpcClient = RpcClient.make(WsRpcGroup); +type WsRpcClient = + typeof makeWsRpcClient extends Effect.Effect ? Client : never; + +const withWsRpcClient = ( + wsUrl: string, + f: (client: WsRpcClient) => Effect.Effect, +) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl))); + +const getHttpServerUrl = (pathname = "") => + Effect.gen(function* () { + const server = yield* HttpServer.HttpServer; + const address = server.address as HttpServer.TcpAddress; + return `http://127.0.0.1:${address.port}${pathname}`; + }); + +const getWsServerUrl = (pathname = "") => + Effect.gen(function* () { + const server = yield* HttpServer.HttpServer; + const address = server.address as HttpServer.TcpAddress; + return `ws://127.0.0.1:${address.port}${pathname}`; + }); + +it.layer(NodeServices.layer)("server router seam", (it) => { + it.effect("serves static index content for GET / when staticDir is configured", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-static-" }); + const indexPath = path.join(staticDir, "index.html"); + yield* fileSystem.writeFileString(indexPath, "router-static-ok"); + + yield* buildAppUnderTest({ config: { staticDir } }); + + const response = yield* HttpClient.get("/"); + assert.equal(response.status, 200); + assert.include(yield* response.text, "router-static-ok"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("redirects to dev URL when configured", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { devUrl: new URL("http://127.0.0.1:5173") }, + }); + + const url = yield* getHttpServerUrl("/foo/bar"); + const response = yield* Effect.promise(() => fetch(url, { redirect: "manual" })); + + assert.equal(response.status, 302); + assert.equal(response.headers.get("location"), "http://127.0.0.1:5173/"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves project favicon requests before the dev URL redirect", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const projectDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-router-project-favicon-", + }); + yield* fileSystem.writeFileString( + path.join(projectDir, "favicon.svg"), + "router-project-favicon", + ); + + yield* buildAppUnderTest({ + config: { devUrl: new URL("http://127.0.0.1:5173") }, + }); + + const response = yield* HttpClient.get( + `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, + ); + + assert.equal(response.status, 200); + assert.equal(yield* response.text, "router-project-favicon"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves the fallback project favicon when no icon exists", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const projectDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-router-project-favicon-fallback-", + }); + + yield* buildAppUnderTest({ + config: { devUrl: new URL("http://127.0.0.1:5173") }, + }); + + const response = yield* HttpClient.get( + `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, + ); + + assert.equal(response.status, 200); + assert.include(yield* response.text, 'data-fallback="project-favicon"'); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves attachment files from state dir", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const attachmentId = "thread-11111111-1111-4111-8111-111111111111"; + + const config = yield* buildAppUnderTest(); + const attachmentPath = resolveAttachmentRelativePath({ + attachmentsDir: config.attachmentsDir, + relativePath: `${attachmentId}.bin`, + }); + assert.isNotNull(attachmentPath, "Attachment path should be resolvable"); + + yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }); + yield* fileSystem.writeFileString(attachmentPath, "attachment-ok"); + + const response = yield* HttpClient.get(`/attachments/${attachmentId}`); + assert.equal(response.status, 200); + assert.equal(yield* response.text, "attachment-ok"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves attachment files for URL-encoded paths", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const config = yield* buildAppUnderTest(); + const attachmentPath = resolveAttachmentRelativePath({ + attachmentsDir: config.attachmentsDir, + relativePath: "thread%20folder/message%20folder/file%20name.png", + }); + assert.isNotNull(attachmentPath, "Attachment path should be resolvable"); + + yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }); + yield* fileSystem.writeFileString(attachmentPath, "attachment-encoded-ok"); + + const response = yield* HttpClient.get( + "/attachments/thread%20folder/message%20folder/file%20name.png", + ); + assert.equal(response.status, 200); + assert.equal(yield* response.text, "attachment-encoded-ok"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("returns 404 for missing attachment id lookups", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const response = yield* HttpClient.get( + "/attachments/missing-11111111-1111-4111-8111-111111111111", + ); + assert.equal(response.status, 404); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc server.upsertKeybinding", () => + Effect.gen(function* () { + const rule: KeybindingRule = { + command: "terminal.toggle", + key: "ctrl+k", + }; + const resolved: ResolvedKeybindingRule = { + command: "terminal.toggle", + shortcut: { + key: "k", + metaKey: false, + ctrlKey: true, + shiftKey: false, + altKey: false, + modKey: true, + }, + }; + + yield* buildAppUnderTest({ + layers: { + keybindings: { + upsertKeybindingRule: () => Effect.succeed([resolved]), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverUpsertKeybinding](rule)), + ); + + assert.deepEqual(response.issues, []); + assert.deepEqual(response.keybindings, [resolved]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects websocket rpc handshake when auth token is missing", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-required-" }); + yield* fs.writeFileString( + path.join(workspaceDir, "needle-file.ts"), + "export const needle = 1;", + ); + + yield* buildAppUnderTest({ + config: { + authToken: "secret-token", + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsSearchEntries]({ + cwd: workspaceDir, + query: "needle", + limit: 10, + }), + ).pipe(Effect.result), + ); + + assertTrue(result._tag === "Failure"); + assertInclude(String(result.failure), "SocketOpenError"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("accepts websocket rpc handshake when auth token is provided", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-ok-" }); + yield* fs.writeFileString( + path.join(workspaceDir, "needle-file.ts"), + "export const needle = 1;", + ); + + yield* buildAppUnderTest({ + config: { + authToken: "secret-token", + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws?token=secret-token"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsSearchEntries]({ + cwd: workspaceDir, + query: "needle", + limit: 10, + }), + ), + ); + + assert.isAtLeast(response.entries.length, 1); + assert.equal(response.truncated, false); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () => + Effect.gen(function* () { + const providers = [] as const; + const changeEvent = { + keybindings: [], + issues: [], + } as const; + + yield* buildAppUnderTest({ + config: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, + layers: { + keybindings: { + loadConfigState: Effect.succeed({ + keybindings: [], + issues: [], + }), + streamChanges: Stream.succeed(changeEvent), + }, + providerRegistry: { + getProviders: Effect.succeed(providers), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const events = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect), + ), + ); + + const [first, second] = Array.from(events); + assert.equal(first?.type, "snapshot"); + if (first?.type === "snapshot") { + assert.equal(first.version, 1); + assert.deepEqual(first.config.keybindings, []); + assert.deepEqual(first.config.issues, []); + assert.deepEqual(first.config.providers, providers); + assert.equal(first.config.observability.logsDirectoryPath.endsWith("/logs"), true); + assert.equal(first.config.observability.localTracingEnabled, true); + assert.equal(first.config.observability.otlpTracesUrl, "http://localhost:4318/v1/traces"); + assert.equal(first.config.observability.otlpTracesEnabled, true); + assert.equal(first.config.observability.otlpMetricsUrl, "http://localhost:4318/v1/metrics"); + assert.equal(first.config.observability.otlpMetricsEnabled, true); + assert.deepEqual(first.config.settings, DEFAULT_SERVER_SETTINGS); + } + assert.deepEqual(second, { + version: 1, + type: "keybindingsUpdated", + payload: { issues: [] }, + }); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () => + Effect.gen(function* () { + const providers = [] as const; + + yield* buildAppUnderTest({ + layers: { + keybindings: { + loadConfigState: Effect.succeed({ + keybindings: [], + issues: [], + }), + streamChanges: Stream.empty, + }, + providerRegistry: { + getProviders: Effect.succeed([]), + streamChanges: Stream.succeed(providers), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const events = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect), + ), + ); + + const [first, second] = Array.from(events); + assert.equal(first?.type, "snapshot"); + assert.deepEqual(second, { + version: 1, + type: "providerStatuses", + payload: { providers }, + }); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "routes websocket rpc subscribeServerLifecycle replays snapshot and streams updates", + () => + Effect.gen(function* () { + const lifecycleEvents = [ + { + version: 1 as const, + sequence: 1, + type: "welcome" as const, + payload: { + cwd: "/tmp/project", + projectName: "project", + }, + }, + ] as const; + const liveEvents = Stream.make({ + version: 1 as const, + sequence: 2, + type: "ready" as const, + payload: { at: new Date().toISOString() }, + }); + + yield* buildAppUnderTest({ + layers: { + serverLifecycleEvents: { + snapshot: Effect.succeed({ + sequence: 1, + events: lifecycleEvents, + }), + stream: liveEvents, + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const events = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.subscribeServerLifecycle]({}).pipe(Stream.take(2), Stream.runCollect), + ), + ); + + const [first, second] = Array.from(events); + assert.equal(first?.type, "welcome"); + assert.equal(first?.sequence, 1); + assert.equal(second?.type, "ready"); + assert.equal(second?.sequence, 2); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc projects.searchEntries", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-search-" }); + yield* fs.writeFileString( + path.join(workspaceDir, "needle-file.ts"), + "export const needle = 1;", + ); + + yield* buildAppUnderTest(); + + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsSearchEntries]({ + cwd: workspaceDir, + query: "needle", + limit: 10, + }), + ), + ); + + assert.isAtLeast(response.entries.length, 1); + assert.isTrue(response.entries.some((entry) => entry.path === "needle-file.ts")); + assert.equal(response.truncated, false); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc projects.searchEntries errors", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsSearchEntries]({ + cwd: "/definitely/not/a/real/workspace/path", + query: "needle", + limit: 10, + }), + ).pipe(Effect.result), + ); + + assertTrue(result._tag === "Failure"); + assertTrue(result.failure._tag === "ProjectSearchEntriesError"); + assertInclude( + result.failure.message, + "Workspace root does not exist: /definitely/not/a/real/workspace/path", + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc projects.writeFile", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-write-" }); + + yield* buildAppUnderTest(); + + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsWriteFile]({ + cwd: workspaceDir, + relativePath: "nested/created.txt", + contents: "written-by-rpc", + }), + ), + ); + + assert.equal(response.relativePath, "nested/created.txt"); + const persisted = yield* fs.readFileString(path.join(workspaceDir, "nested", "created.txt")); + assert.equal(persisted, "written-by-rpc"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc projects.writeFile errors", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-write-" }); + + yield* buildAppUnderTest(); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsWriteFile]({ + cwd: workspaceDir, + relativePath: "../escape.txt", + contents: "nope", + }), + ).pipe(Effect.result), + ); + + assertTrue(result._tag === "Failure"); + assertTrue(result.failure._tag === "ProjectWriteFileError"); + assert.equal( + result.failure.message, + "Workspace file path must stay within the project root.", + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc shell.openInEditor", () => + Effect.gen(function* () { + let openedInput: { cwd: string; editor: EditorId } | null = null; + yield* buildAppUnderTest({ + layers: { + open: { + openInEditor: (input) => + Effect.sync(() => { + openedInput = input; + }), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.shellOpenInEditor]({ + cwd: "/tmp/project", + editor: "cursor", + }), + ), + ); + + assert.deepEqual(openedInput, { cwd: "/tmp/project", editor: "cursor" }); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc shell.openInEditor errors", () => + Effect.gen(function* () { + const openError = new OpenError({ message: "Editor command not found: cursor" }); + yield* buildAppUnderTest({ + layers: { + open: { + openInEditor: () => Effect.fail(openError), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.shellOpenInEditor]({ + cwd: "/tmp/project", + editor: "cursor", + }), + ).pipe(Effect.result), + ); + + assertFailure(result, openError); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc git methods", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + layers: { + gitManager: { + status: () => + Effect.succeed({ + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: true, + branch: "main", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + runStackedAction: (input, options) => + Effect.gen(function* () { + const result = { + action: "commit" as const, + branch: { status: "skipped_not_requested" as const }, + commit: { + status: "created" as const, + commitSha: "abc123", + subject: "feat: demo", + }, + push: { status: "skipped_not_requested" as const }, + pr: { status: "skipped_not_requested" as const }, + toast: { + title: "Committed abc123", + description: "feat: demo", + cta: { + kind: "run_action" as const, + label: "Push", + action: { + kind: "push" as const, + }, + }, + }, + }; + + yield* ( + options?.progressReporter?.publish({ + actionId: options.actionId ?? input.actionId, + cwd: input.cwd, + action: input.action, + kind: "phase_started", + phase: "commit", + label: "Committing...", + }) ?? Effect.void + ); + + yield* ( + options?.progressReporter?.publish({ + actionId: options.actionId ?? input.actionId, + cwd: input.cwd, + action: input.action, + kind: "action_finished", + result, + }) ?? Effect.void + ); + + return result; + }), + resolvePullRequest: () => + Effect.succeed({ + pullRequest: { + number: 1, + title: "Demo PR", + url: "https://example.com/pr/1", + baseBranch: "main", + headBranch: "feature/demo", + state: "open", + }, + }), + preparePullRequestThread: () => + Effect.succeed({ + pullRequest: { + number: 1, + title: "Demo PR", + url: "https://example.com/pr/1", + baseBranch: "main", + headBranch: "feature/demo", + state: "open", + }, + branch: "feature/demo", + worktreePath: null, + }), + }, + gitCore: { + pullCurrentBranch: () => + Effect.succeed({ + status: "pulled", + branch: "main", + upstreamBranch: "origin/main", + }), + listBranches: () => + Effect.succeed({ + branches: [ + { + name: "main", + current: true, + isDefault: true, + worktreePath: null, + }, + ], + isRepo: true, + hasOriginRemote: true, + nextCursor: null, + totalCount: 1, + }), + createWorktree: () => + Effect.succeed({ + worktree: { path: "/tmp/wt", branch: "feature/demo" }, + }), + removeWorktree: () => Effect.void, + createBranch: () => Effect.void, + checkoutBranch: () => Effect.void, + initRepo: () => Effect.void, + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + + const status = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitStatus]({ cwd: "/tmp/repo" })), + ); + assert.equal(status.branch, "main"); + + const pull = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })), + ); + assert.equal(pull.status, "pulled"); + + const stackedEvents = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitRunStackedAction]({ + actionId: "action-1", + cwd: "/tmp/repo", + action: "commit", + }).pipe( + Stream.runCollect, + Effect.map((events) => Array.from(events)), + ), + ), + ); + const lastStackedEvent = stackedEvents.at(-1); + assert.equal(lastStackedEvent?.kind, "action_finished"); + if (lastStackedEvent?.kind === "action_finished") { + assert.equal(lastStackedEvent.result.action, "commit"); + } + + const resolvedPr = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitResolvePullRequest]({ + cwd: "/tmp/repo", + reference: "1", + }), + ), + ); + assert.equal(resolvedPr.pullRequest.number, 1); + + const prepared = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitPreparePullRequestThread]({ + cwd: "/tmp/repo", + reference: "1", + mode: "local", + }), + ), + ); + assert.equal(prepared.branch, "feature/demo"); + + const branches = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitListBranches]({ cwd: "/tmp/repo" }), + ), + ); + assert.equal(branches.branches[0]?.name, "main"); + + const worktree = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitCreateWorktree]({ + cwd: "/tmp/repo", + branch: "main", + path: null, + }), + ), + ); + assert.equal(worktree.worktree.branch, "feature/demo"); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitRemoveWorktree]({ + cwd: "/tmp/repo", + path: "/tmp/wt", + }), + ), + ); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitCreateBranch]({ + cwd: "/tmp/repo", + branch: "feature/new", + }), + ), + ); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitCheckout]({ + cwd: "/tmp/repo", + branch: "main", + }), + ), + ); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitInit]({ + cwd: "/tmp/repo", + }), + ), + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc git.pull errors", () => + Effect.gen(function* () { + const gitError = new GitCommandError({ + operation: "pull", + command: "git pull --ff-only", + cwd: "/tmp/repo", + detail: "upstream missing", + }); + yield* buildAppUnderTest({ + layers: { + gitCore: { + pullCurrentBranch: () => Effect.fail(gitError), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })).pipe( + Effect.result, + ), + ); + + assertFailure(result, gitError); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc orchestration methods", () => + Effect.gen(function* () { + const now = new Date().toISOString(); + const snapshot = { + snapshotSequence: 1, + updatedAt: now, + projects: [ + { + id: ProjectId.makeUnsafe("project-a"), + title: "Project A", + workspaceRoot: "/tmp/project-a", + defaultModelSelection, + scripts: [], + createdAt: now, + updatedAt: now, + deletedAt: null, + }, + ], + threads: [ + { + id: ThreadId.makeUnsafe("thread-1"), + projectId: ProjectId.makeUnsafe("project-a"), + title: "Thread A", + modelSelection: defaultModelSelection, + interactionMode: "default" as const, + runtimeMode: "full-access" as const, + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + latestTurn: null, + messages: [], + session: null, + activities: [], + proposedPlans: [], + checkpoints: [], + deletedAt: null, + }, + ], + }; + + yield* buildAppUnderTest({ + layers: { + projectionSnapshotQuery: { + getSnapshot: () => Effect.succeed(snapshot), + }, + orchestrationEngine: { + dispatch: () => Effect.succeed({ sequence: 7 }), + readEvents: () => Stream.empty, + }, + checkpointDiffQuery: { + getTurnDiff: () => + Effect.succeed({ + threadId: ThreadId.makeUnsafe("thread-1"), + fromTurnCount: 0, + toTurnCount: 1, + diff: "turn-diff", + }), + getFullThreadDiff: () => + Effect.succeed({ + threadId: ThreadId.makeUnsafe("thread-1"), + fromTurnCount: 0, + toTurnCount: 1, + diff: "full-diff", + }), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const snapshotResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})), + ); + assert.equal(snapshotResult.snapshotSequence, 1); + + const dispatchResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.session.stop", + commandId: CommandId.makeUnsafe("cmd-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + createdAt: now, + }), + ), + ); + assert.equal(dispatchResult.sequence, 7); + + const turnDiffResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.getTurnDiff]({ + threadId: ThreadId.makeUnsafe("thread-1"), + fromTurnCount: 0, + toTurnCount: 1, + }), + ), + ); + assert.equal(turnDiffResult.diff, "turn-diff"); + + const fullDiffResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.getFullThreadDiff]({ + threadId: ThreadId.makeUnsafe("thread-1"), + toTurnCount: 1, + }), + ), + ); + assert.equal(fullDiffResult.diff, "full-diff"); + + const replayResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.replayEvents]({ + fromSequenceExclusive: 0, + }), + ), + ); + assert.deepEqual(replayResult, []); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("closes thread terminals after a successful archive command", () => + Effect.gen(function* () { + const threadId = ThreadId.makeUnsafe("thread-archive"); + const closeInputs: Array[0]> = []; + + yield* buildAppUnderTest({ + layers: { + terminalManager: { + close: (input) => + Effect.sync(() => { + closeInputs.push(input); + }), + }, + orchestrationEngine: { + dispatch: () => Effect.succeed({ sequence: 8 }), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const dispatchResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.archive", + commandId: CommandId.makeUnsafe("cmd-thread-archive"), + threadId, + }), + ), + ); + + assert.equal(dispatchResult.sequence, 8); + assert.deepEqual(closeInputs, [{ threadId }]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "bootstraps first-send worktree turns on the server before dispatching turn start", + () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.succeed({ + worktree: { + branch: "t3code/bootstrap-branch", + path: "/tmp/bootstrap-worktree", + }, + }), + ); + const runForThread = vi.fn( + (_: Parameters[0]) => + Effect.succeed({ + status: "started" as const, + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup-setup", + cwd: "/tmp/bootstrap-worktree", + }), + ); + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => + Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }), + readEvents: () => Stream.empty, + }, + projectSetupScriptRunner: { + runForThread, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start"), + threadId: ThreadId.makeUnsafe("thread-bootstrap"), + message: { + messageId: MessageId.makeUnsafe("msg-bootstrap"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: true, + }, + createdAt, + }), + ), + ); + + assert.equal(response.sequence, 5); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + [ + "thread.create", + "thread.meta.update", + "thread.activity.append", + "thread.activity.append", + "thread.turn.start", + ], + ); + assert.deepEqual(createWorktree.mock.calls[0]?.[0], { + cwd: "/tmp/project", + branch: "main", + newBranch: "t3code/bootstrap-branch", + path: null, + }); + assert.deepEqual(runForThread.mock.calls[0]?.[0], { + threadId: ThreadId.makeUnsafe("thread-bootstrap"), + projectId: defaultProjectId, + projectCwd: "/tmp/project", + worktreePath: "/tmp/bootstrap-worktree", + }); + + const setupActivities = dispatchedCommands.filter( + (command): command is Extract => + command.type === "thread.activity.append", + ); + assert.deepEqual( + setupActivities.map((command) => command.activity.kind), + ["setup-script.requested", "setup-script.started"], + ); + const finalCommand = dispatchedCommands[4]; + assertTrue(finalCommand?.type === "thread.turn.start"); + if (finalCommand?.type === "thread.turn.start") { + assert.equal(finalCommand.bootstrap, undefined); + } + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("records setup-script failures without aborting bootstrap turn start", () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.succeed({ + worktree: { + branch: "t3code/bootstrap-branch", + path: "/tmp/bootstrap-worktree", + }, + }), + ); + const runForThread = vi.fn( + (_: Parameters[0]) => + Effect.fail(new Error("pty unavailable")), + ); + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => + Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }), + readEvents: () => Stream.empty, + }, + projectSetupScriptRunner: { + runForThread, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-setup-failure"), + threadId: ThreadId.makeUnsafe("thread-bootstrap-setup-failure"), + message: { + messageId: MessageId.makeUnsafe("msg-bootstrap-setup-failure"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: true, + }, + createdAt, + }), + ), + ); + + assert.equal(response.sequence, 4); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + ["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"], + ); + const setupFailureActivity = dispatchedCommands.find( + (command): command is Extract => + command.type === "thread.activity.append", + ); + assert.equal(setupFailureActivity?.activity.kind, "setup-script.failed"); + assert.deepEqual(setupFailureActivity?.activity.payload, { + detail: "pty unavailable", + worktreePath: "/tmp/bootstrap-worktree", + }); + assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete")); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("does not misattribute setup activity dispatch failures as setup launch failures", () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.succeed({ + worktree: { + branch: "t3code/bootstrap-branch", + path: "/tmp/bootstrap-worktree", + }, + }), + ); + const runForThread = vi.fn( + (_: Parameters[0]) => + Effect.succeed({ + status: "started" as const, + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup-setup", + cwd: "/tmp/bootstrap-worktree", + }), + ); + let setupActivityAppendAttempt = 0; + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => { + if ( + command.type === "thread.activity.append" && + command.activity.kind.startsWith("setup-script.") + ) { + setupActivityAppendAttempt += 1; + if (setupActivityAppendAttempt === 2) { + return Effect.fail( + new OrchestrationListenerCallbackError({ + listener: "domain-event", + detail: "failed to append setup-script.started activity", + }), + ); + } + } + + return Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }); + }, + readEvents: () => Stream.empty, + }, + projectSetupScriptRunner: { + runForThread, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-setup-activity-failure"), + threadId: ThreadId.makeUnsafe("thread-bootstrap-setup-activity-failure"), + message: { + messageId: MessageId.makeUnsafe("msg-bootstrap-setup-activity-failure"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: true, + }, + createdAt, + }), + ), + ); + + assert.equal(response.sequence, 4); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + ["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"], + ); + const setupActivities = dispatchedCommands.filter( + (command): command is Extract => + command.type === "thread.activity.append", + ); + assert.deepEqual( + setupActivities.map((command) => command.activity.kind), + ["setup-script.requested"], + ); + assertTrue( + setupActivities.every((command) => command.activity.kind !== "setup-script.failed"), + ); + assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete")); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("cleans up created bootstrap threads when worktree creation defects", () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.die(new Error("worktree exploded")), + ); + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => + Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }), + readEvents: () => Stream.empty, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-defect"), + threadId: ThreadId.makeUnsafe("thread-bootstrap-defect"), + message: { + messageId: MessageId.makeUnsafe("msg-bootstrap-defect"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: false, + }, + createdAt, + }), + ).pipe(Effect.result), + ); + + assertTrue(result._tag === "Failure"); + assertTrue(result.failure._tag === "OrchestrationDispatchCommandError"); + assert.include(result.failure.message, "worktree exploded"); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + ["thread.create", "thread.delete"], + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "routes websocket rpc subscribeOrchestrationDomainEvents with replay/live overlap resilience", + () => + Effect.gen(function* () { + const now = new Date().toISOString(); + const threadId = ThreadId.makeUnsafe("thread-1"); + let replayCursor: number | null = null; + const makeEvent = (sequence: number): OrchestrationEvent => + ({ + sequence, + eventId: `event-${sequence}`, + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "thread.reverted", + payload: { + threadId, + turnCount: sequence, + }, + }) as OrchestrationEvent; + + yield* buildAppUnderTest({ + layers: { + orchestrationEngine: { + getReadModel: () => + Effect.succeed({ + ...makeDefaultOrchestrationReadModel(), + snapshotSequence: 1, + }), + readEvents: (fromSequenceExclusive) => { + replayCursor = fromSequenceExclusive; + return Stream.make(makeEvent(2), makeEvent(3)); + }, + streamDomainEvents: Stream.make(makeEvent(3), makeEvent(4)), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const events = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe( + Stream.take(3), + Stream.runCollect, + ), + ), + ); + + assert.equal(replayCursor, 1); + assert.deepEqual( + Array.from(events).map((event) => event.sequence), + [2, 3, 4], + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc orchestration.getSnapshot errors", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + layers: { + projectionSnapshotQuery: { + getSnapshot: () => + Effect.fail( + new PersistenceSqlError({ + operation: "ProjectionSnapshotQuery.getSnapshot", + detail: "projection unavailable", + }), + ), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})).pipe( + Effect.result, + ), + ); + + assertTrue(result._tag === "Failure"); + assertTrue(result.failure._tag === "OrchestrationGetSnapshotError"); + assertInclude(result.failure.message, "Failed to load orchestration snapshot"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc terminal methods", () => + Effect.gen(function* () { + const snapshot = { + threadId: "thread-1", + terminalId: "default", + cwd: "/tmp/project", + worktreePath: null, + status: "running" as const, + pid: 1234, + history: "", + exitCode: null, + exitSignal: null, + updatedAt: new Date().toISOString(), + }; + + yield* buildAppUnderTest({ + layers: { + terminalManager: { + open: () => Effect.succeed(snapshot), + write: () => Effect.void, + resize: () => Effect.void, + clear: () => Effect.void, + restart: () => Effect.succeed(snapshot), + close: () => Effect.void, + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + + const opened = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalOpen]({ + threadId: "thread-1", + terminalId: "default", + cwd: "/tmp/project", + }), + ), + ); + assert.equal(opened.terminalId, "default"); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalWrite]({ + threadId: "thread-1", + terminalId: "default", + data: "echo hi\n", + }), + ), + ); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalResize]({ + threadId: "thread-1", + terminalId: "default", + cols: 120, + rows: 40, + }), + ), + ); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalClear]({ + threadId: "thread-1", + terminalId: "default", + }), + ), + ); + + const restarted = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalRestart]({ + threadId: "thread-1", + terminalId: "default", + cwd: "/tmp/project", + cols: 120, + rows: 40, + }), + ), + ); + assert.equal(restarted.terminalId, "default"); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalClose]({ + threadId: "thread-1", + terminalId: "default", + }), + ), + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc terminal.write errors", () => + Effect.gen(function* () { + const terminalError = new TerminalNotRunningError({ + threadId: "thread-1", + terminalId: "default", + }); + yield* buildAppUnderTest({ + layers: { + terminalManager: { + write: () => Effect.fail(terminalError), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalWrite]({ + threadId: "thread-1", + terminalId: "default", + data: "echo fail\n", + }), + ).pipe(Effect.result), + ); + + assertFailure(result, terminalError); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); +}); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts new file mode 100644 index 0000000000..04ffaeeeeb --- /dev/null +++ b/apps/server/src/server.ts @@ -0,0 +1,249 @@ +import { Effect, Layer } from "effect"; +import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http"; + +import { ServerConfig } from "./config"; +import { attachmentsRouteLayer, projectFaviconRouteLayer, staticAndDevRouteLayer } from "./http"; +import { fixPath } from "./os-jank"; +import { websocketRpcRouteLayer } from "./ws"; +import { OpenLive } from "./open"; +import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite"; +import { ServerLifecycleEventsLive } from "./serverLifecycleEvents"; +import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService"; +import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger"; +import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory"; +import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime"; +import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter"; +import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter"; +import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry"; +import { makeProviderServiceLive } from "./provider/Layers/ProviderService"; +import { OrchestrationEngineLive } from "./orchestration/Layers/OrchestrationEngine"; +import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline"; +import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore"; +import { OrchestrationCommandReceiptRepositoryLive } from "./persistence/Layers/OrchestrationCommandReceipts"; +import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery"; +import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery"; +import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore"; +import { GitCoreLive } from "./git/Layers/GitCore"; +import { GitHubCliLive } from "./git/Layers/GitHubCli"; +import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration"; +import { TerminalManagerLive } from "./terminal/Layers/Manager"; +import { GitManagerLive } from "./git/Layers/GitManager"; +import { KeybindingsLive } from "./keybindings"; +import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup"; +import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor"; +import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus"; +import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion"; +import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor"; +import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor"; +import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry"; +import { ServerSettingsLive } from "./serverSettings"; +import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver"; +import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries"; +import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem"; +import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths"; +import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner"; +import { ObservabilityLive } from "./observability/Layers/Observability"; + +const PtyAdapterLive = Layer.unwrap( + Effect.gen(function* () { + if (typeof Bun !== "undefined") { + const BunPTY = yield* Effect.promise(() => import("./terminal/Layers/BunPTY")); + return BunPTY.layer; + } else { + const NodePTY = yield* Effect.promise(() => import("./terminal/Layers/NodePTY")); + return NodePTY.layer; + } + }), +); + +const HttpServerLive = Layer.unwrap( + Effect.gen(function* () { + const config = yield* ServerConfig; + if (typeof Bun !== "undefined") { + const BunHttpServer = yield* Effect.promise( + () => import("@effect/platform-bun/BunHttpServer"), + ); + return BunHttpServer.layer({ + port: config.port, + ...(config.host ? { hostname: config.host } : {}), + }); + } else { + const [NodeHttpServer, NodeHttp] = yield* Effect.all([ + Effect.promise(() => import("@effect/platform-node/NodeHttpServer")), + Effect.promise(() => import("node:http")), + ]); + return NodeHttpServer.layer(NodeHttp.createServer, { + host: config.host, + port: config.port, + }); + } + }), +); + +const PlatformServicesLive = Layer.unwrap( + Effect.gen(function* () { + if (typeof Bun !== "undefined") { + const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices")); + return layer; + } else { + const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices")); + return layer; + } + }), +); + +const ReactorLayerLive = Layer.empty.pipe( + Layer.provideMerge(OrchestrationReactorLive), + Layer.provideMerge(ProviderRuntimeIngestionLive), + Layer.provideMerge(ProviderCommandReactorLive), + Layer.provideMerge(CheckpointReactorLive), + Layer.provideMerge(RuntimeReceiptBusLive), +); + +const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll( + OrchestrationEventStoreLive, + OrchestrationCommandReceiptRepositoryLive, +); + +const OrchestrationProjectionPipelineLayerLive = OrchestrationProjectionPipelineLive.pipe( + Layer.provide(OrchestrationEventStoreLive), +); + +const OrchestrationInfrastructureLayerLive = Layer.mergeAll( + OrchestrationProjectionSnapshotQueryLive, + OrchestrationEventInfrastructureLayerLive, + OrchestrationProjectionPipelineLayerLive, +); + +const OrchestrationLayerLive = Layer.mergeAll( + OrchestrationInfrastructureLayerLive, + OrchestrationEngineLive.pipe(Layer.provide(OrchestrationInfrastructureLayerLive)), +); + +const CheckpointingLayerLive = Layer.empty.pipe( + Layer.provideMerge(CheckpointDiffQueryLive), + Layer.provideMerge(CheckpointStoreLive), +); + +const ProviderLayerLive = Layer.unwrap( + Effect.gen(function* () { + const { providerEventLogPath } = yield* ServerConfig; + const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { + stream: "native", + }); + const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { + stream: "canonical", + }); + const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(ProviderSessionRuntimeRepositoryLive), + ); + const codexAdapterLayer = makeCodexAdapterLive( + nativeEventLogger ? { nativeEventLogger } : undefined, + ); + const claudeAdapterLayer = makeClaudeAdapterLive( + nativeEventLogger ? { nativeEventLogger } : undefined, + ); + const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe( + Layer.provide(codexAdapterLayer), + Layer.provide(claudeAdapterLayer), + Layer.provideMerge(providerSessionDirectoryLayer), + ); + return makeProviderServiceLive( + canonicalEventLogger ? { canonicalEventLogger } : undefined, + ).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer)); + }), +); + +const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive)); + +const GitLayerLive = Layer.empty.pipe( + Layer.provideMerge( + GitManagerLive.pipe( + Layer.provideMerge(ProjectSetupScriptRunnerLive), + Layer.provideMerge(GitCoreLive), + Layer.provideMerge(GitHubCliLive), + Layer.provideMerge(RoutingTextGenerationLive), + ), + ), + Layer.provideMerge(GitCoreLive), +); + +const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive)); + +const WorkspaceLayerLive = Layer.mergeAll( + WorkspacePathsLive, + WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)), + WorkspaceFileSystemLive.pipe( + Layer.provide(WorkspacePathsLive), + Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + ), +); + +const RuntimeDependenciesLive = ReactorLayerLive.pipe( + // Core Services + Layer.provideMerge(CheckpointingLayerLive), + Layer.provideMerge(GitLayerLive), + Layer.provideMerge(OrchestrationLayerLive), + Layer.provideMerge(ProviderLayerLive), + Layer.provideMerge(TerminalLayerLive), + Layer.provideMerge(PersistenceLayerLive), + Layer.provideMerge(KeybindingsLive), + Layer.provideMerge(ProviderRegistryLive), + Layer.provideMerge(ServerSettingsLive), + Layer.provideMerge(WorkspaceLayerLive), + Layer.provideMerge(ProjectFaviconResolverLive), + + // Misc. + Layer.provideMerge(AnalyticsServiceLayerLive), + Layer.provideMerge(OpenLive), + Layer.provideMerge(ServerLifecycleEventsLive), +); + +const RuntimeServicesLive = ServerRuntimeStartupLive.pipe( + Layer.provideMerge(RuntimeDependenciesLive), +); + +export const makeRoutesLayer = Layer.mergeAll( + attachmentsRouteLayer, + projectFaviconRouteLayer, + staticAndDevRouteLayer, + websocketRpcRouteLayer, +); + +export const makeServerLayer = Layer.unwrap( + Effect.gen(function* () { + const config = yield* ServerConfig; + + fixPath(); + + const httpListeningLayer = Layer.effectDiscard( + Effect.gen(function* () { + yield* HttpServer.HttpServer; + const startup = yield* ServerRuntimeStartup; + yield* startup.markHttpListening; + }), + ); + + const serverApplicationLayer = Layer.mergeAll( + HttpRouter.serve(makeRoutesLayer, { + disableLogger: !config.logWebSocketEvents, + }), + httpListeningLayer, + ); + + return serverApplicationLayer.pipe( + Layer.provideMerge(RuntimeServicesLive), + Layer.provideMerge(HttpServerLive), + Layer.provide(ObservabilityLive), + Layer.provideMerge(FetchHttpClient.layer), + Layer.provideMerge(PlatformServicesLive), + ); + }), +); + +// Important: Only `ServerConfig` should be provided by the CLI layer!!! Don't let other requirements leak into the launch layer. +export const runServer = Layer.launch(makeServerLayer) satisfies Effect.Effect< + never, + any, + ServerConfig +>; diff --git a/apps/server/src/serverLifecycleEvents.test.ts b/apps/server/src/serverLifecycleEvents.test.ts new file mode 100644 index 0000000000..1cd8c25c03 --- /dev/null +++ b/apps/server/src/serverLifecycleEvents.test.ts @@ -0,0 +1,42 @@ +import { assert, it } from "@effect/vitest"; +import { assertTrue } from "@effect/vitest/utils"; +import { Effect, Option } from "effect"; + +import { ServerLifecycleEvents, ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts"; + +it.effect( + "publishes lifecycle events without subscribers and snapshots the latest welcome/ready", + () => + Effect.gen(function* () { + const lifecycleEvents = yield* ServerLifecycleEvents; + + const welcome = yield* lifecycleEvents + .publish({ + version: 1, + type: "welcome", + payload: { + cwd: "/tmp/project", + projectName: "project", + }, + }) + .pipe(Effect.timeoutOption("50 millis")); + assertTrue(Option.isSome(welcome)); + assert.equal(welcome.value.sequence, 1); + + const ready = yield* lifecycleEvents + .publish({ + version: 1, + type: "ready", + payload: { + at: new Date().toISOString(), + }, + }) + .pipe(Effect.timeoutOption("50 millis")); + assertTrue(Option.isSome(ready)); + assert.equal(ready.value.sequence, 2); + + const snapshot = yield* lifecycleEvents.snapshot; + assert.equal(snapshot.sequence, 2); + assert.deepEqual(snapshot.events.map((event) => event.type).toSorted(), ["ready", "welcome"]); + }).pipe(Effect.provide(ServerLifecycleEventsLive)), +); diff --git a/apps/server/src/serverLifecycleEvents.ts b/apps/server/src/serverLifecycleEvents.ts new file mode 100644 index 0000000000..4808a19d72 --- /dev/null +++ b/apps/server/src/serverLifecycleEvents.ts @@ -0,0 +1,53 @@ +import type { ServerLifecycleStreamEvent } from "@t3tools/contracts"; +import { Effect, Layer, PubSub, Ref, ServiceMap, Stream } from "effect"; + +type LifecycleEventInput = + | Omit, "sequence"> + | Omit, "sequence">; + +interface SnapshotState { + readonly sequence: number; + readonly events: ReadonlyArray; +} + +export interface ServerLifecycleEventsShape { + readonly publish: (event: LifecycleEventInput) => Effect.Effect; + readonly snapshot: Effect.Effect; + readonly stream: Stream.Stream; +} + +export class ServerLifecycleEvents extends ServiceMap.Service< + ServerLifecycleEvents, + ServerLifecycleEventsShape +>()("t3/serverLifecycleEvents") {} + +export const ServerLifecycleEventsLive = Layer.effect( + ServerLifecycleEvents, + Effect.gen(function* () { + const pubsub = yield* PubSub.unbounded(); + const state = yield* Ref.make({ + sequence: 0, + events: [], + }); + + return { + publish: (event) => + Ref.modify(state, (current) => { + const nextSequence = current.sequence + 1; + const nextEvent = { + ...event, + sequence: nextSequence, + } satisfies ServerLifecycleStreamEvent; + const nextEvents = + nextEvent.type === "welcome" + ? [nextEvent, ...current.events.filter((entry) => entry.type !== "welcome")] + : [nextEvent, ...current.events.filter((entry) => entry.type !== "ready")]; + return [nextEvent, { sequence: nextSequence, events: nextEvents }] as const; + }).pipe(Effect.tap((event) => PubSub.publish(pubsub, event))), + snapshot: Ref.get(state), + get stream() { + return Stream.fromPubSub(pubsub); + }, + } satisfies ServerLifecycleEventsShape; + }), +); diff --git a/apps/server/src/serverLogger.ts b/apps/server/src/serverLogger.ts new file mode 100644 index 0000000000..ea098dcbbe --- /dev/null +++ b/apps/server/src/serverLogger.ts @@ -0,0 +1,13 @@ +import { Effect, Logger, References, Layer } from "effect"; + +import { ServerConfig } from "./config"; + +export const ServerLoggerLive = Effect.gen(function* () { + const config = yield* ServerConfig; + const minimumLogLevelLayer = Layer.succeed(References.MinimumLogLevel, config.logLevel); + const loggerLayer = Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { + mergeWithExisting: false, + }); + + return Layer.mergeAll(loggerLayer, minimumLogLevelLayer); +}).pipe(Layer.unwrap); diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts new file mode 100644 index 0000000000..fc06d77566 --- /dev/null +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -0,0 +1,82 @@ +import { assert, it } from "@effect/vitest"; +import { Deferred, Effect, Fiber, Option, Ref } from "effect"; + +import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import { + launchStartupHeartbeat, + makeCommandGate, + ServerRuntimeStartupError, +} from "./serverRuntimeStartup.ts"; + +it.effect("enqueueCommand waits for readiness and then drains queued work", () => + Effect.scoped( + Effect.gen(function* () { + const executionCount = yield* Ref.make(0); + const commandGate = yield* makeCommandGate; + + const queuedCommandFiber = yield* commandGate + .enqueueCommand(Ref.updateAndGet(executionCount, (count) => count + 1)) + .pipe(Effect.forkScoped); + + yield* Effect.yieldNow; + assert.equal(yield* Ref.get(executionCount), 0); + + yield* commandGate.signalCommandReady; + + const result = yield* Fiber.join(queuedCommandFiber); + assert.equal(result, 1); + assert.equal(yield* Ref.get(executionCount), 1); + }), + ), +); + +it.effect("enqueueCommand fails queued work when readiness fails", () => + Effect.scoped( + Effect.gen(function* () { + const commandGate = yield* makeCommandGate; + const failure = yield* Deferred.make(); + + const queuedCommandFiber = yield* commandGate + .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run"))) + .pipe(Effect.forkScoped); + + yield* commandGate.failCommandReady( + new ServerRuntimeStartupError({ + message: "startup failed", + }), + ); + + const error = yield* Effect.flip(Fiber.join(queuedCommandFiber)); + assert.equal(error.message, "startup failed"); + }), + ), +); + +it.effect("launchStartupHeartbeat does not block the caller while counts are loading", () => + Effect.scoped( + Effect.gen(function* () { + const releaseCounts = yield* Deferred.make(); + + yield* launchStartupHeartbeat.pipe( + Effect.provideService(ProjectionSnapshotQuery, { + getSnapshot: () => Effect.die("unused"), + getCounts: () => + Deferred.await(releaseCounts).pipe( + Effect.as({ + projectCount: 2, + threadCount: 3, + }), + ), + getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), + getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), + getThreadCheckpointContext: () => Effect.succeed(Option.none()), + }), + Effect.provideService(AnalyticsService, { + record: () => Effect.void, + flush: Effect.void, + }), + ); + }), + ), +); diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts new file mode 100644 index 0000000000..7c9231ac93 --- /dev/null +++ b/apps/server/src/serverRuntimeStartup.ts @@ -0,0 +1,379 @@ +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + type ModelSelection, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { + Data, + Deferred, + Effect, + Exit, + Layer, + Option, + Path, + Queue, + Ref, + Scope, + ServiceMap, +} from "effect"; + +import { ServerConfig } from "./config"; +import { Keybindings } from "./keybindings"; +import { Open } from "./open"; +import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; +import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor"; +import { ServerLifecycleEvents } from "./serverLifecycleEvents"; +import { ServerSettingsService } from "./serverSettings"; +import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; + +const isWildcardHost = (host: string | undefined): boolean => + host === "0.0.0.0" || host === "::" || host === "[::]"; + +const formatHostForUrl = (host: string): string => + host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; + +export class ServerRuntimeStartupError extends Data.TaggedError("ServerRuntimeStartupError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export interface ServerRuntimeStartupShape { + readonly awaitCommandReady: Effect.Effect; + readonly markHttpListening: Effect.Effect; + readonly enqueueCommand: ( + effect: Effect.Effect, + ) => Effect.Effect; +} + +export class ServerRuntimeStartup extends ServiceMap.Service< + ServerRuntimeStartup, + ServerRuntimeStartupShape +>()("t3/serverRuntimeStartup") {} + +interface QueuedCommand { + readonly run: Effect.Effect; +} + +type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError; + +interface CommandGate { + readonly awaitCommandReady: Effect.Effect; + readonly signalCommandReady: Effect.Effect; + readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect; + readonly enqueueCommand: ( + effect: Effect.Effect, + ) => Effect.Effect; +} + +const settleQueuedCommand = (deferred: Deferred.Deferred, exit: Exit.Exit) => + Exit.isSuccess(exit) + ? Deferred.succeed(deferred, exit.value) + : Deferred.failCause(deferred, exit.cause); + +export const makeCommandGate = Effect.gen(function* () { + const commandReady = yield* Deferred.make(); + const commandQueue = yield* Queue.unbounded(); + const commandReadinessState = yield* Ref.make("pending"); + + const commandWorker = Effect.forever( + Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)), + ); + yield* Effect.forkScoped(commandWorker); + + return { + awaitCommandReady: Deferred.await(commandReady), + signalCommandReady: Effect.gen(function* () { + yield* Ref.set(commandReadinessState, "ready"); + yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie); + }), + failCommandReady: (error) => + Effect.gen(function* () { + yield* Ref.set(commandReadinessState, error); + yield* Deferred.fail(commandReady, error).pipe(Effect.orDie); + }), + enqueueCommand: (effect: Effect.Effect) => + Effect.gen(function* () { + const readinessState = yield* Ref.get(commandReadinessState); + if (readinessState === "ready") { + return yield* effect; + } + if (readinessState !== "pending") { + return yield* readinessState; + } + + const result = yield* Deferred.make(); + yield* Queue.offer(commandQueue, { + run: Deferred.await(commandReady).pipe( + Effect.flatMap(() => effect), + Effect.exit, + Effect.flatMap((exit) => settleQueuedCommand(result, exit)), + ), + }); + return yield* Deferred.await(result); + }), + } satisfies CommandGate; +}); + +export const recordStartupHeartbeat = Effect.gen(function* () { + const analytics = yield* AnalyticsService; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + + const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe( + Effect.catch((cause) => + Effect.logWarning("failed to gather startup projection counts for telemetry", { + cause, + }).pipe( + Effect.as({ + threadCount: 0, + projectCount: 0, + }), + ), + ), + ); + + yield* analytics.record("server.boot.heartbeat", { + threadCount, + projectCount, + }); +}); + +export const launchStartupHeartbeat = recordStartupHeartbeat.pipe( + Effect.annotateSpans({ "startup.phase": "heartbeat.record" }), + Effect.withSpan("server.startup.heartbeat.record"), + Effect.ignoreCause({ log: true }), + Effect.forkScoped, + Effect.asVoid, +); + +const autoBootstrapWelcome = Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + const projectionReadModelQuery = yield* ProjectionSnapshotQuery; + const orchestrationEngine = yield* OrchestrationEngineService; + const path = yield* Path.Path; + + let bootstrapProjectId: ProjectId | undefined; + let bootstrapThreadId: ThreadId | undefined; + + if (serverConfig.autoBootstrapProjectFromCwd) { + yield* Effect.gen(function* () { + const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot( + serverConfig.cwd, + ); + let nextProjectId: ProjectId; + let nextProjectDefaultModelSelection: ModelSelection; + + if (Option.isNone(existingProject)) { + const createdAt = new Date().toISOString(); + nextProjectId = ProjectId.makeUnsafe(crypto.randomUUID()); + const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project"; + nextProjectDefaultModelSelection = { + provider: "codex", + model: "gpt-5-codex", + }; + yield* orchestrationEngine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe(crypto.randomUUID()), + projectId: nextProjectId, + title: bootstrapProjectTitle, + workspaceRoot: serverConfig.cwd, + defaultModelSelection: nextProjectDefaultModelSelection, + createdAt, + }); + } else { + nextProjectId = existingProject.value.id; + nextProjectDefaultModelSelection = existingProject.value.defaultModelSelection ?? { + provider: "codex", + model: "gpt-5-codex", + }; + } + + const existingThreadId = + yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId); + if (Option.isNone(existingThreadId)) { + const createdAt = new Date().toISOString(); + const createdThreadId = ThreadId.makeUnsafe(crypto.randomUUID()); + yield* orchestrationEngine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe(crypto.randomUUID()), + threadId: createdThreadId, + projectId: nextProjectId, + title: "New thread", + modelSelection: nextProjectDefaultModelSelection, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }); + bootstrapProjectId = nextProjectId; + bootstrapThreadId = createdThreadId; + } else { + bootstrapProjectId = nextProjectId; + bootstrapThreadId = existingThreadId.value; + } + }); + } + + const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean); + const projectName = segments[segments.length - 1] ?? "project"; + + return { + cwd: serverConfig.cwd, + projectName, + ...(bootstrapProjectId ? { bootstrapProjectId } : {}), + ...(bootstrapThreadId ? { bootstrapThreadId } : {}), + } as const; +}); + +const maybeOpenBrowser = Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + if (serverConfig.noBrowser) { + return; + } + const { openBrowser } = yield* Open; + const localUrl = `http://localhost:${serverConfig.port}`; + const bindUrl = + serverConfig.host && !isWildcardHost(serverConfig.host) + ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}` + : localUrl; + const target = serverConfig.devUrl?.toString() ?? bindUrl; + + yield* openBrowser(target).pipe( + Effect.catch(() => + Effect.logInfo("browser auto-open unavailable", { + hint: `Open ${target} in your browser.`, + }), + ), + ); +}); + +const runStartupPhase = (phase: string, effect: Effect.Effect) => + effect.pipe( + Effect.annotateSpans({ "startup.phase": phase }), + Effect.withSpan(`server.startup.${phase}`), + ); + +const makeServerRuntimeStartup = Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + const keybindings = yield* Keybindings; + const orchestrationReactor = yield* OrchestrationReactor; + const lifecycleEvents = yield* ServerLifecycleEvents; + const serverSettings = yield* ServerSettingsService; + + const commandGate = yield* makeCommandGate; + const httpListening = yield* Deferred.make(); + const reactorScope = yield* Scope.make("sequential"); + + yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void)); + + const startup = Effect.gen(function* () { + yield* Effect.logDebug("startup phase: starting keybindings runtime"); + yield* runStartupPhase( + "keybindings.start", + keybindings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start keybindings runtime", { + path: error.configPath, + detail: error.detail, + cause: error.cause, + }), + ), + Effect.forkScoped, + ), + ); + + yield* Effect.logDebug("startup phase: starting server settings runtime"); + yield* runStartupPhase( + "settings.start", + serverSettings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start server settings runtime", { + path: error.settingsPath, + detail: error.detail, + cause: error.cause, + }), + ), + Effect.forkScoped, + ), + ); + + yield* Effect.logDebug("startup phase: starting orchestration reactors"); + yield* runStartupPhase( + "reactors.start", + orchestrationReactor.start().pipe(Scope.provide(reactorScope)), + ); + + yield* Effect.logDebug("startup phase: preparing welcome payload"); + const welcome = yield* runStartupPhase("welcome.prepare", autoBootstrapWelcome); + yield* Effect.logDebug("startup phase: publishing welcome event", { + cwd: welcome.cwd, + projectName: welcome.projectName, + bootstrapProjectId: welcome.bootstrapProjectId, + bootstrapThreadId: welcome.bootstrapThreadId, + }); + yield* runStartupPhase( + "welcome.publish", + lifecycleEvents.publish({ + version: 1, + type: "welcome", + payload: welcome, + }), + ); + }).pipe( + Effect.annotateSpans({ + "server.mode": serverConfig.mode, + "server.port": serverConfig.port, + "server.host": serverConfig.host ?? "default", + }), + Effect.withSpan("server.startup", { kind: "server", root: true }), + ); + + yield* Effect.forkScoped( + Effect.gen(function* () { + const startupExit = yield* Effect.exit(startup); + if (Exit.isFailure(startupExit)) { + const error = new ServerRuntimeStartupError({ + message: "Server runtime startup failed before command readiness.", + cause: startupExit.cause, + }); + yield* Effect.logError("server runtime startup failed", { cause: startupExit.cause }); + yield* commandGate.failCommandReady(error); + return; + } + + yield* Effect.logDebug("Accepting commands"); + yield* commandGate.signalCommandReady; + yield* Effect.logDebug("startup phase: waiting for http listener"); + yield* runStartupPhase("http.wait", Deferred.await(httpListening)); + yield* Effect.logDebug("startup phase: publishing ready event"); + yield* runStartupPhase( + "ready.publish", + lifecycleEvents.publish({ + version: 1, + type: "ready", + payload: { at: new Date().toISOString() }, + }), + ); + + yield* Effect.logDebug("startup phase: recording startup heartbeat"); + yield* launchStartupHeartbeat; + yield* Effect.logDebug("startup phase: browser open check"); + yield* runStartupPhase("browser.open", maybeOpenBrowser); + yield* Effect.logDebug("startup phase: complete"); + }), + ); + + return { + awaitCommandReady: commandGate.awaitCommandReady, + markHttpListening: Deferred.succeed(httpListening, undefined), + enqueueCommand: commandGate.enqueueCommand, + } satisfies ServerRuntimeStartupShape; +}); + +export const ServerRuntimeStartupLive = Layer.effect( + ServerRuntimeStartup, + makeServerRuntimeStartup, +); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts new file mode 100644 index 0000000000..289bc68961 --- /dev/null +++ b/apps/server/src/serverSettings.test.ts @@ -0,0 +1,245 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { DEFAULT_SERVER_SETTINGS, ServerSettingsPatch } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Schema } from "effect"; +import { ServerConfig } from "./config"; +import { ServerSettingsLive, ServerSettingsService } from "./serverSettings"; + +const makeServerSettingsLayer = () => + ServerSettingsLive.pipe( + Layer.provideMerge( + Layer.fresh( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3code-server-settings-test-", + }), + ), + ), + ); + +it.layer(NodeServices.layer)("server settings", (it) => { + it.effect("decodes nested settings patches", () => + Effect.sync(() => { + const decodePatch = Schema.decodeUnknownSync(ServerSettingsPatch); + + assert.deepEqual(decodePatch({ providers: { codex: { binaryPath: "/tmp/codex" } } }), { + providers: { codex: { binaryPath: "/tmp/codex" } }, + }); + + assert.deepEqual( + decodePatch({ + textGenerationModelSelection: { + options: { + fastMode: false, + }, + }, + }), + { + textGenerationModelSelection: { + options: { + fastMode: false, + }, + }, + }, + ); + }), + ); + + it.effect("deep merges nested settings updates without dropping siblings", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + + yield* serverSettings.updateSettings({ + providers: { + codex: { + binaryPath: "/usr/local/bin/codex", + homePath: "/Users/julius/.codex", + }, + claudeAgent: { + binaryPath: "/usr/local/bin/claude", + customModels: ["claude-custom"], + }, + }, + textGenerationModelSelection: { + provider: "codex", + model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, + options: { + reasoningEffort: "high", + fastMode: true, + }, + }, + }); + + const next = yield* serverSettings.updateSettings({ + providers: { + codex: { + binaryPath: "/opt/homebrew/bin/codex", + }, + }, + textGenerationModelSelection: { + options: { + fastMode: false, + }, + }, + }); + + assert.deepEqual(next.providers.codex, { + enabled: true, + binaryPath: "/opt/homebrew/bin/codex", + homePath: "/Users/julius/.codex", + customModels: [], + }); + assert.deepEqual(next.providers.claudeAgent, { + enabled: true, + binaryPath: "/usr/local/bin/claude", + customModels: ["claude-custom"], + }); + assert.deepEqual(next.textGenerationModelSelection, { + provider: "codex", + model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, + options: { + reasoningEffort: "high", + fastMode: false, + }, + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + + it.effect("preserves model when switching providers via textGenerationModelSelection", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + + // Start with Claude text generation selection + yield* serverSettings.updateSettings({ + textGenerationModelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "high", + }, + }, + }); + + // Switch to Codex — the stale Claude "effort" in options must not + // cause the update to lose the selected model. + const next = yield* serverSettings.updateSettings({ + textGenerationModelSelection: { + provider: "codex", + model: "gpt-5.4", + options: { + reasoningEffort: "high", + }, + }, + }); + + assert.deepEqual(next.textGenerationModelSelection, { + provider: "codex", + model: "gpt-5.4", + options: { + reasoningEffort: "high", + }, + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + + it.effect("trims provider path settings when updates are applied", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + + const next = yield* serverSettings.updateSettings({ + providers: { + codex: { + binaryPath: " /opt/homebrew/bin/codex ", + homePath: " ", + }, + claudeAgent: { + binaryPath: " /opt/homebrew/bin/claude ", + }, + }, + }); + + assert.deepEqual(next.providers.codex, { + enabled: true, + binaryPath: "/opt/homebrew/bin/codex", + homePath: "", + customModels: [], + }); + assert.deepEqual(next.providers.claudeAgent, { + enabled: true, + binaryPath: "/opt/homebrew/bin/claude", + customModels: [], + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + + it.effect("trims observability settings when updates are applied", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + + const next = yield* serverSettings.updateSettings({ + observability: { + otlpTracesUrl: " http://localhost:4318/v1/traces ", + otlpMetricsUrl: " http://localhost:4318/v1/metrics ", + }, + }); + + assert.deepEqual(next.observability, { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + + it.effect("defaults blank binary paths to provider executables", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + + const next = yield* serverSettings.updateSettings({ + providers: { + codex: { + binaryPath: " ", + }, + claudeAgent: { + binaryPath: "", + }, + }, + }); + + assert.equal(next.providers.codex.binaryPath, "codex"); + assert.equal(next.providers.claudeAgent.binaryPath, "claude"); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + + it.effect("writes only non-default server settings to disk", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const serverConfig = yield* ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const next = yield* serverSettings.updateSettings({ + observability: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, + providers: { + codex: { + binaryPath: "/opt/homebrew/bin/codex", + }, + }, + }); + + assert.equal(next.providers.codex.binaryPath, "/opt/homebrew/bin/codex"); + + const raw = yield* fileSystem.readFileString(serverConfig.settingsPath); + assert.deepEqual(JSON.parse(raw), { + observability: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, + providers: { + codex: { + binaryPath: "/opt/homebrew/bin/codex", + }, + }, + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); +}); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts new file mode 100644 index 0000000000..79fdc29a8b --- /dev/null +++ b/apps/server/src/serverSettings.ts @@ -0,0 +1,339 @@ +/** + * ServerSettings - Server-authoritative settings service. + * + * Owns persistence, validation, and change notification of settings that affect + * server-side behavior (binary paths, streaming mode, env mode, custom models, + * text generation model selection). + * + * Follows the same pattern as `keybindings.ts`: JSON file + Cache + PubSub + + * Semaphore + FileSystem.watch for concurrency and external edit detection. + * + * @module ServerSettings + */ +import { + DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER, + DEFAULT_SERVER_SETTINGS, + type ModelSelection, + type ProviderKind, + ServerSettings, + ServerSettingsError, + type ServerSettingsPatch, +} from "@t3tools/contracts"; +import { + Cache, + Deferred, + Duration, + Effect, + Exit, + FileSystem, + Layer, + Path, + Equal, + PubSub, + Ref, + Schema, + SchemaIssue, + Scope, + ServiceMap, + Stream, + Cause, +} from "effect"; +import * as Semaphore from "effect/Semaphore"; +import { ServerConfig } from "./config"; +import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct"; +import { fromLenientJson } from "@t3tools/shared/schemaJson"; + +export interface ServerSettingsShape { + /** Start the settings runtime and attach file watching. */ + readonly start: Effect.Effect; + + /** Await settings runtime readiness. */ + readonly ready: Effect.Effect; + + /** Read the current settings. */ + readonly getSettings: Effect.Effect; + + /** Patch settings and persist. Returns the new full settings object. */ + readonly updateSettings: ( + patch: ServerSettingsPatch, + ) => Effect.Effect; + + /** Stream of settings change events. */ + readonly streamChanges: Stream.Stream; +} + +export class ServerSettingsService extends ServiceMap.Service< + ServerSettingsService, + ServerSettingsShape +>()("t3/serverSettings/ServerSettingsService") { + static readonly layerTest = (overrides: DeepPartial = {}) => + Layer.effect( + ServerSettingsService, + Effect.gen(function* () { + const currentSettingsRef = yield* Ref.make( + deepMerge(DEFAULT_SERVER_SETTINGS, overrides), + ); + + return { + start: Effect.void, + ready: Effect.void, + getSettings: Ref.get(currentSettingsRef), + updateSettings: (patch) => + Ref.get(currentSettingsRef).pipe( + Effect.map((currentSettings) => deepMerge(currentSettings, patch)), + Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)), + ), + streamChanges: Stream.empty, + } satisfies ServerSettingsShape; + }), + ); +} + +const ServerSettingsJson = fromLenientJson(ServerSettings); + +const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent"]; + +/** + * Ensure the `textGenerationModelSelection` points to an enabled provider. + * If the selected provider is disabled, fall back to the first enabled + * provider with its default model. This is applied at read-time so the + * persisted preference is preserved for when a provider is re-enabled. + */ +function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings { + const selection = settings.textGenerationModelSelection; + if (settings.providers[selection.provider].enabled) { + return settings; + } + + const fallback = PROVIDER_ORDER.find((p) => settings.providers[p].enabled); + if (!fallback) { + // No providers enabled — return as-is; callers will report the error. + return settings; + } + + return { + ...settings, + textGenerationModelSelection: { + provider: fallback, + model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback], + } as ModelSelection, + }; +} + +// Values under these keys are compared as a whole — never stripped field-by-field. +const ATOMIC_SETTINGS_KEYS: ReadonlySet = new Set(["textGenerationModelSelection"]); + +function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined { + if (Array.isArray(current) || Array.isArray(defaults)) { + return Equal.equals(current, defaults) ? undefined : current; + } + + if ( + current !== null && + defaults !== null && + typeof current === "object" && + typeof defaults === "object" + ) { + const currentRecord = current as Record; + const defaultsRecord = defaults as Record; + const next: Record = {}; + + for (const key of Object.keys(currentRecord)) { + if (ATOMIC_SETTINGS_KEYS.has(key)) { + if (!Equal.equals(currentRecord[key], defaultsRecord[key])) { + next[key] = currentRecord[key]; + } + } else { + const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]); + if (stripped !== undefined) { + next[key] = stripped; + } + } + } + + return Object.keys(next).length > 0 ? next : undefined; + } + + return Object.is(current, defaults) ? undefined : current; +} + +const makeServerSettings = Effect.gen(function* () { + const { settingsPath } = yield* ServerConfig; + const fs = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + const writeSemaphore = yield* Semaphore.make(1); + const cacheKey = "settings" as const; + const changesPubSub = yield* PubSub.unbounded(); + const startedRef = yield* Ref.make(false); + const startedDeferred = yield* Deferred.make(); + const watcherScope = yield* Scope.make("sequential"); + yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void)); + + const emitChange = (settings: ServerSettings) => + PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid); + + const readConfigExists = fs.exists(settingsPath).pipe( + Effect.mapError( + (cause) => + new ServerSettingsError({ + settingsPath, + detail: "failed to check settings file existence", + cause, + }), + ), + ); + + const readRawConfig = fs.readFileString(settingsPath).pipe( + Effect.mapError( + (cause) => + new ServerSettingsError({ + settingsPath, + detail: "failed to read settings file", + cause, + }), + ), + ); + + const loadSettingsFromDisk = Effect.gen(function* () { + if (!(yield* readConfigExists)) { + return DEFAULT_SERVER_SETTINGS; + } + + const raw = yield* readRawConfig; + const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw); + if (decoded._tag === "Failure") { + yield* Effect.logWarning("failed to parse settings.json, using defaults", { + path: settingsPath, + issues: Cause.pretty(decoded.cause), + }); + return DEFAULT_SERVER_SETTINGS; + } + return decoded.value; + }); + + const settingsCache = yield* Cache.make({ + capacity: 1, + lookup: () => loadSettingsFromDisk, + }); + + const getSettingsFromCache = Cache.get(settingsCache, cacheKey); + + const writeSettingsAtomically = (settings: ServerSettings) => { + const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`; + const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {}; + + return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe( + Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })), + Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)), + Effect.flatMap(() => fs.rename(tempPath, settingsPath)), + Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))), + Effect.mapError( + (cause) => + new ServerSettingsError({ + settingsPath, + detail: "failed to write settings file", + cause, + }), + ), + ); + }; + + const revalidateAndEmit = writeSemaphore.withPermits(1)( + Effect.gen(function* () { + yield* Cache.invalidate(settingsCache, cacheKey); + const settings = yield* getSettingsFromCache; + yield* emitChange(settings); + }), + ); + + const startWatcher = Effect.gen(function* () { + const settingsDir = pathService.dirname(settingsPath); + const settingsFile = pathService.basename(settingsPath); + const settingsPathResolved = pathService.resolve(settingsPath); + + yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe( + Effect.mapError( + (cause) => + new ServerSettingsError({ + settingsPath, + detail: "failed to prepare settings directory", + cause, + }), + ), + ); + + const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true })); + + // Debounce watch events so the file is fully written before we read it. + // Editors emit multiple events per save (truncate, write, rename) and + // `fs.watch` can fire before the content has been flushed to disk. + const debouncedSettingsEvents = fs.watch(settingsDir).pipe( + Stream.filter((event) => { + return ( + event.path === settingsFile || + event.path === settingsPath || + pathService.resolve(settingsDir, event.path) === settingsPathResolved + ); + }), + Stream.debounce(Duration.millis(100)), + ); + + yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe( + Effect.ignoreCause({ log: true }), + Effect.forkIn(watcherScope), + Effect.asVoid, + ); + }); + + const start = Effect.gen(function* () { + const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]); + if (!shouldStart) { + return yield* Deferred.await(startedDeferred); + } + + const startup = Effect.gen(function* () { + yield* startWatcher; + yield* Cache.invalidate(settingsCache, cacheKey); + yield* getSettingsFromCache; + }); + + const startupExit = yield* Effect.exit(startup); + if (startupExit._tag === "Failure") { + yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie); + return yield* Effect.failCause(startupExit.cause); + } + + yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie); + }); + + return { + start, + ready: Deferred.await(startedDeferred), + getSettings: getSettingsFromCache.pipe(Effect.map(resolveTextGenerationProvider)), + updateSettings: (patch) => + writeSemaphore.withPermits(1)( + Effect.gen(function* () { + const current = yield* getSettingsFromCache; + const next = yield* Schema.decodeEffect(ServerSettings)(deepMerge(current, patch)).pipe( + Effect.mapError( + (cause) => + new ServerSettingsError({ + settingsPath: "", + detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`, + cause, + }), + ), + ); + yield* writeSettingsAtomically(next); + yield* Cache.set(settingsCache, cacheKey, next); + yield* emitChange(next); + return resolveTextGenerationProvider(next); + }), + ), + get streamChanges() { + return Stream.fromPubSub(changesPubSub).pipe(Stream.map(resolveTextGenerationProvider)); + }, + } satisfies ServerSettingsShape; +}); + +export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings); diff --git a/apps/server/src/telemetry/Identify.ts b/apps/server/src/telemetry/Identify.ts new file mode 100644 index 0000000000..d7784eb88b --- /dev/null +++ b/apps/server/src/telemetry/Identify.ts @@ -0,0 +1,100 @@ +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, + }), +}); + +const ClaudeJsonSchema = Schema.Struct({ + userID: Schema.String, +}); + +class IdentifyUserError extends Schema.TaggedErrorClass()("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 getClaudeUserId = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const claudeJsonPath = path.join(homedir(), ".claude.json"); + const claudeJson = yield* Effect.flatMap( + fileSystem.readFileString(claudeJsonPath), + Schema.decodeEffect(Schema.fromJsonString(ClaudeJsonSchema)), + ); + + return claudeJson.userID; +}); + +const upsertAnonymousId = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const { anonymousIdPath } = yield* ServerConfig; + + 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. ~/.claude.json userID + * 3. ~/.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 claudeUserId = yield* Effect.result(getClaudeUserId); + if (claudeUserId._tag === "Success") { + return yield* hash(claudeUserId.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), +); diff --git a/apps/server/src/telemetry/Layers/AnalyticsService.test.ts b/apps/server/src/telemetry/Layers/AnalyticsService.test.ts new file mode 100644 index 0000000000..5fe0795ce4 --- /dev/null +++ b/apps/server/src/telemetry/Layers/AnalyticsService.test.ts @@ -0,0 +1,119 @@ +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, 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 capturedRequests: Array = []; + const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-telemetry-base-", + }); + + 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, + ); + }), + ); +}); diff --git a/apps/server/src/telemetry/Layers/AnalyticsService.ts b/apps/server/src/telemetry/Layers/AnalyticsService.ts new file mode 100644 index 0000000000..e933576dff --- /dev/null +++ b/apps/server/src/telemetry/Layers/AnalyticsService.ts @@ -0,0 +1,154 @@ +/** + * 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>; + 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>([]); + const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client"; + + const enqueueBufferedEvent = (event: string, properties?: Readonly>) => + 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 = Effect.fn("sendBatch")(function* ( + events: ReadonlyArray, + ) { + 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, 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.fn("record")( + 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); diff --git a/apps/server/src/telemetry/Services/AnalyticsService.ts b/apps/server/src/telemetry/Services/AnalyticsService.ts new file mode 100644 index 0000000000..64f8c8de55 --- /dev/null +++ b/apps/server/src/telemetry/Services/AnalyticsService.ts @@ -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>, + ) => Effect.Effect; + + /** + * Flush queued telemetry. + */ + readonly flush: Effect.Effect; +} + +export class AnalyticsService extends ServiceMap.Service()( + "t3/telemetry/Services/AnalyticsService", +) { + static readonly layerTest = Layer.succeed(AnalyticsService, { + record: () => Effect.void, + flush: Effect.void, + }); +} diff --git a/apps/server/src/terminal/Layers/BunPTY.ts b/apps/server/src/terminal/Layers/BunPTY.ts new file mode 100644 index 0000000000..1fb4bdd636 --- /dev/null +++ b/apps/server/src/terminal/Layers/BunPTY.ts @@ -0,0 +1,118 @@ +import { Effect, Layer } from "effect"; +import { PtyAdapter, PtyAdapterShape, PtyExitEvent, PtyProcess } from "../Services/PTY"; + +class BunPtyProcess implements PtyProcess { + private readonly dataListeners = new Set<(data: string) => void>(); + private readonly exitListeners = new Set<(event: PtyExitEvent) => void>(); + private readonly decoder = new TextDecoder(); + private didExit = false; + + constructor(private readonly process: Bun.Subprocess) { + void this.process.exited + .then((exitCode) => { + this.emitExit({ + exitCode: Number.isInteger(exitCode) ? exitCode : 0, + signal: typeof this.process.signalCode === "number" ? this.process.signalCode : null, + }); + }) + .catch(() => { + this.emitExit({ exitCode: 1, signal: null }); + }); + } + + get pid(): number { + return this.process.pid; + } + + write(data: string): void { + if (!this.process.terminal) { + throw new Error("Bun PTY terminal handle is unavailable"); + } + this.process.terminal.write(data); + } + + resize(cols: number, rows: number): void { + if (!this.process.terminal?.resize) { + throw new Error("Bun PTY resize is unavailable"); + } + this.process.terminal.resize(cols, rows); + } + + kill(signal?: string): void { + if (!signal) { + this.process.kill(); + return; + } + this.process.kill(signal as NodeJS.Signals); + } + + onData(callback: (data: string) => void): () => void { + this.dataListeners.add(callback); + return () => { + this.dataListeners.delete(callback); + }; + } + + onExit(callback: (event: PtyExitEvent) => void): () => void { + this.exitListeners.add(callback); + return () => { + this.exitListeners.delete(callback); + }; + } + + emitData(data: Uint8Array): void { + if (this.didExit) return; + const text = this.decoder.decode(data, { stream: true }); + if (text.length === 0) return; + for (const listener of this.dataListeners) { + listener(text); + } + } + + private emitExit(event: PtyExitEvent): void { + if (this.didExit) return; + this.didExit = true; + + const remainder = this.decoder.decode(); + if (remainder.length > 0) { + for (const listener of this.dataListeners) { + listener(remainder); + } + } + + for (const listener of this.exitListeners) { + listener(event); + } + } +} + +export const layer = Layer.effect( + PtyAdapter, + Effect.gen(function* () { + if (process.platform === "win32") { + return yield* Effect.die( + "Bun PTY terminal support is unavailable on Windows. Please use Node.js (e.g. by running `npx t3`) instead.", + ); + } + return { + spawn: (input) => + Effect.sync(() => { + let processHandle: BunPtyProcess | null = null; + const command = [input.shell, ...(input.args ?? [])]; + const subprocess = Bun.spawn(command, { + cwd: input.cwd, + env: input.env, + terminal: { + cols: input.cols, + rows: input.rows, + data: (_terminal, data) => { + processHandle?.emitData(data); + }, + }, + }); + processHandle = new BunPtyProcess(subprocess); + return processHandle; + }), + } satisfies PtyAdapterShape; + }), +); diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts new file mode 100644 index 0000000000..c059c97983 --- /dev/null +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -0,0 +1,1078 @@ +import path from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + DEFAULT_TERMINAL_ID, + type TerminalEvent, + type TerminalOpenInput, + type TerminalRestartInput, +} from "@t3tools/contracts"; +import { + Duration, + Effect, + Encoding, + Exit, + Fiber, + FileSystem, + Option, + PlatformError, + Ref, + Schedule, + Scope, +} from "effect"; +import { TestClock } from "effect/testing"; +import { expect } from "vitest"; + +import type { TerminalManagerShape } from "../Services/Manager"; +import { + type PtyAdapterShape, + type PtyExitEvent, + type PtyProcess, + type PtySpawnInput, + PtySpawnError, +} from "../Services/PTY"; +import { makeTerminalManagerWithOptions } from "./Manager"; + +class FakePtyProcess implements PtyProcess { + readonly writes: string[] = []; + readonly resizeCalls: Array<{ cols: number; rows: number }> = []; + readonly killSignals: Array = []; + private readonly dataListeners = new Set<(data: string) => void>(); + private readonly exitListeners = new Set<(event: PtyExitEvent) => void>(); + killed = false; + + constructor(readonly pid: number) {} + + write(data: string): void { + this.writes.push(data); + } + + resize(cols: number, rows: number): void { + this.resizeCalls.push({ cols, rows }); + } + + kill(signal?: string): void { + this.killed = true; + this.killSignals.push(signal); + } + + onData(callback: (data: string) => void): () => void { + this.dataListeners.add(callback); + return () => { + this.dataListeners.delete(callback); + }; + } + + onExit(callback: (event: PtyExitEvent) => void): () => void { + this.exitListeners.add(callback); + return () => { + this.exitListeners.delete(callback); + }; + } + + emitData(data: string): void { + for (const listener of this.dataListeners) { + listener(data); + } + } + + emitExit(event: PtyExitEvent): void { + for (const listener of this.exitListeners) { + listener(event); + } + } +} + +class FakePtyAdapter implements PtyAdapterShape { + readonly spawnInputs: PtySpawnInput[] = []; + readonly processes: FakePtyProcess[] = []; + readonly spawnFailures: Error[] = []; + private nextPid = 9000; + + constructor(private readonly mode: "sync" | "async" = "sync") {} + + spawn(input: PtySpawnInput): Effect.Effect { + this.spawnInputs.push(input); + const failure = this.spawnFailures.shift(); + if (failure) { + return Effect.fail( + new PtySpawnError({ + adapter: "fake", + message: "Failed to spawn PTY process", + cause: failure, + }), + ); + } + const process = new FakePtyProcess(this.nextPid++); + this.processes.push(process); + if (this.mode === "async") { + return Effect.tryPromise({ + try: async () => process, + catch: (cause) => + new PtySpawnError({ + adapter: "fake", + message: "Failed to spawn PTY process", + cause, + }), + }); + } + return Effect.succeed(process); + } +} + +const waitFor = ( + predicate: Effect.Effect, + timeout: Duration.Input = 800, +): Effect.Effect => + predicate.pipe( + Effect.filterOrFail( + (done) => done, + () => new Error("Condition not met"), + ), + Effect.retry(Schedule.spaced("15 millis")), + Effect.timeoutOption(timeout), + Effect.flatMap((result) => + Option.match(result, { + onNone: () => Effect.fail(new Error("Timed out waiting for condition")), + onSome: () => Effect.void, + }), + ), + ); + +function openInput(overrides: Partial = {}): TerminalOpenInput { + return { + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + cwd: process.cwd(), + cols: 100, + rows: 24, + ...overrides, + }; +} + +function restartInput(overrides: Partial = {}): TerminalRestartInput { + return { + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + cwd: process.cwd(), + cols: 100, + rows: 24, + ...overrides, + }; +} + +function historyLogName(threadId: string): string { + return `terminal_${Encoding.encodeBase64Url(threadId)}.log`; +} + +function multiTerminalHistoryLogName(threadId: string, terminalId: string): string { + const threadPart = `terminal_${Encoding.encodeBase64Url(threadId)}`; + if (terminalId === DEFAULT_TERMINAL_ID) { + return `${threadPart}.log`; + } + return `${threadPart}_${Encoding.encodeBase64Url(terminalId)}.log`; +} + +function historyLogPath(logsDir: string, threadId = "thread-1"): string { + return path.join(logsDir, historyLogName(threadId)); +} + +function multiTerminalHistoryLogPath( + logsDir: string, + threadId = "thread-1", + terminalId = "default", +): string { + return path.join(logsDir, multiTerminalHistoryLogName(threadId, terminalId)); +} + +interface CreateManagerOptions { + shellResolver?: () => string; + subprocessChecker?: (terminalPid: number) => Effect.Effect; + subprocessInspector?: ( + terminalPid: number, + ) => Effect.Effect<{ hasRunningSubprocess: boolean; runningPorts: number[] }>; + webPortInspector?: (port: number) => Effect.Effect; + subprocessPollIntervalMs?: number; + processKillGraceMs?: number; + maxRetainedInactiveSessions?: number; + ptyAdapter?: FakePtyAdapter; +} + +interface ManagerFixture { + readonly baseDir: string; + readonly logsDir: string; + readonly ptyAdapter: FakePtyAdapter; + readonly manager: TerminalManagerShape; + readonly getEvents: Effect.Effect>; +} + +const createManager = ( + historyLineLimit = 5, + options: CreateManagerOptions = {}, +): Effect.Effect< + ManagerFixture, + PlatformError.PlatformError, + FileSystem.FileSystem | Scope.Scope +> => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => + Effect.gen(function* () { + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-terminal-" }); + const logsDir = path.join(baseDir, "userdata", "logs", "terminals"); + const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter(); + + const manager = yield* makeTerminalManagerWithOptions({ + logsDir, + historyLineLimit, + ptyAdapter, + ...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}), + ...(options.subprocessChecker !== undefined + ? { subprocessChecker: options.subprocessChecker } + : {}), + ...(options.subprocessInspector !== undefined + ? { subprocessInspector: options.subprocessInspector } + : {}), + ...(options.webPortInspector !== undefined + ? { webPortInspector: options.webPortInspector } + : {}), + ...(options.subprocessPollIntervalMs !== undefined + ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs } + : {}), + ...(options.processKillGraceMs !== undefined + ? { processKillGraceMs: options.processKillGraceMs } + : {}), + ...(options.maxRetainedInactiveSessions !== undefined + ? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions } + : {}), + }); + const eventsRef = yield* Ref.make>([]); + const scope = yield* Effect.scope; + const unsubscribe = yield* manager.subscribe((event) => + Ref.update(eventsRef, (events) => [...events, event]), + ); + yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe)); + + return { + baseDir, + logsDir, + ptyAdapter, + manager, + getEvents: Ref.get(eventsRef), + }; + }), + ); + +it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (it) => { + it.effect("spawns lazily and reuses running terminal per thread", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const [first, second] = yield* Effect.all( + [manager.open(openInput()), manager.open(openInput())], + { concurrency: "unbounded" }, + ); + const third = yield* manager.open(openInput()); + + assert.equal(first.threadId, "thread-1"); + assert.equal(first.terminalId, "default"); + assert.equal(second.threadId, "thread-1"); + assert.equal(third.threadId, "thread-1"); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + }), + ); + + const makeDirectory = (filePath: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => + fs.makeDirectory(filePath, { recursive: true }), + ); + + const chmod = (filePath: string, mode: number) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.chmod(filePath, mode)); + + const pathExists = (filePath: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.exists(filePath)); + + const readFileString = (filePath: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.readFileString(filePath)); + + const writeFileString = (filePath: string, contents: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => + fs.writeFileString(filePath, contents), + ); + + it.effect("preserves non-notFound cwd stat failures", () => + Effect.gen(function* () { + const { manager, baseDir } = yield* createManager(); + const blockedRoot = path.join(baseDir, "blocked-root"); + const blockedCwd = path.join(blockedRoot, "cwd"); + yield* makeDirectory(blockedCwd); + yield* chmod(blockedRoot, 0o000); + + const error = yield* Effect.flip(manager.open(openInput({ cwd: blockedCwd }))).pipe( + Effect.ensuring(chmod(blockedRoot, 0o755).pipe(Effect.ignore)), + ); + + expect(error).toMatchObject({ + _tag: "TerminalCwdError", + cwd: blockedCwd, + reason: "statFailed", + }); + }), + ); + + it.effect("supports asynchronous PTY spawn effects", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); + + const snapshot = yield* manager.open(openInput()); + + assert.equal(snapshot.status, "running"); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + expect(ptyAdapter.processes).toHaveLength(1); + }), + ); + + it.effect("forwards write and resize to active pty process", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + yield* manager.write({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + data: "ls\n", + }); + yield* manager.resize({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + cols: 120, + rows: 30, + }); + + expect(process.writes).toEqual(["ls\n"]); + expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); + }), + ); + + it.effect("resizes running terminal on open when a different size is requested", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput({ cols: 100, rows: 24 })); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + const reopened = yield* manager.open(openInput({ cols: 120, rows: 30 })); + + assert.equal(reopened.status, "running"); + expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); + }), + ); + + it.effect("supports multiple terminals per thread independently", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput({ terminalId: "default" })); + yield* manager.open(openInput({ terminalId: "term-2" })); + + const first = ptyAdapter.processes[0]; + const second = ptyAdapter.processes[1]; + expect(first).toBeDefined(); + expect(second).toBeDefined(); + if (!first || !second) return; + + yield* manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" }); + yield* manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" }); + + expect(first.writes).toEqual(["pwd\n"]); + expect(second.writes).toEqual(["ls\n"]); + expect(ptyAdapter.spawnInputs).toHaveLength(2); + }), + ); + + it.effect("clears transcript and emits cleared event", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("hello\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + yield* manager.clear({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }); + yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === "")); + + const events = yield* getEvents; + expect(events.some((event) => event.type === "cleared")).toBe(true); + expect( + events.some( + (event) => + event.type === "cleared" && + event.threadId === "thread-1" && + event.terminalId === "default", + ), + ).toBe(true); + }), + ); + + it.effect("restarts terminal with empty transcript and respawns pty", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const firstProcess = ptyAdapter.processes[0]; + expect(firstProcess).toBeDefined(); + if (!firstProcess) return; + firstProcess.emitData("before restart\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + + const snapshot = yield* manager.restart(restartInput()); + assert.equal(snapshot.history, ""); + assert.equal(snapshot.status, "running"); + expect(ptyAdapter.spawnInputs).toHaveLength(2); + yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === "")); + }), + ); + + it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () => + Effect.gen(function* () { + const { manager, getEvents, baseDir } = yield* createManager(); + const firstWorktreePath = path.join(baseDir, "worktrees", "feature-a"); + const secondWorktreePath = path.join(baseDir, "worktrees", "feature-b"); + yield* makeDirectory(firstWorktreePath); + yield* makeDirectory(secondWorktreePath); + const startedSnapshot = yield* manager.open( + openInput({ + cwd: firstWorktreePath, + worktreePath: firstWorktreePath, + }), + ); + const restartedSnapshot = yield* manager.restart( + restartInput({ + cwd: secondWorktreePath, + worktreePath: secondWorktreePath, + }), + ); + + assert.equal(startedSnapshot.worktreePath, firstWorktreePath); + assert.equal(restartedSnapshot.worktreePath, secondWorktreePath); + + const events = yield* getEvents; + const startedEvent = events.find( + (event): event is Extract => event.type === "started", + ); + const restartedEvent = events.find( + (event): event is Extract => + event.type === "restarted", + ); + + assert.equal(startedEvent?.snapshot.worktreePath, firstWorktreePath); + assert.equal(restartedEvent?.snapshot.worktreePath, secondWorktreePath); + }), + ); + + it.effect("preserves worktree metadata when reopening an exited session", () => + Effect.gen(function* () { + const { manager, ptyAdapter, getEvents, baseDir } = yield* createManager(); + const worktreePath = path.join(baseDir, "worktrees", "feature-a"); + yield* makeDirectory(worktreePath); + + yield* manager.open( + openInput({ + cwd: worktreePath, + worktreePath, + }), + ); + + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")), + ); + + const reopenedSnapshot = yield* manager.open( + openInput({ + cwd: worktreePath, + worktreePath, + }), + ); + + assert.equal(reopenedSnapshot.worktreePath, worktreePath); + + const events = yield* getEvents; + const reopenedEvent = events + .toReversed() + .find( + (event): event is Extract => event.type === "started", + ); + + assert.equal(reopenedEvent?.snapshot.worktreePath, worktreePath); + }), + ); + + it.effect("emits exited event and reopens with clean transcript after exit", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + process.emitData("old data\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")), + ); + const reopened = yield* manager.open(openInput()); + + assert.equal(reopened.history, ""); + expect(ptyAdapter.spawnInputs).toHaveLength(2); + expect(yield* readFileString(historyLogPath(logsDir))).toBe(""); + }), + ); + + it.effect("ignores trailing writes after terminal exit", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* manager.write({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + data: "\r", + }); + expect(process.writes).toEqual([]); + }), + ); + + it.effect("emits subprocess activity events when child-process state or web ports change", () => + Effect.gen(function* () { + let activity = { + hasRunningSubprocess: false, + runningPorts: [] as number[], + }; + const { manager, getEvents } = yield* createManager(5, { + subprocessInspector: () => Effect.succeed(activity), + webPortInspector: (port) => Effect.succeed(port === 3000), + subprocessPollIntervalMs: 20, + }); + + yield* manager.open(openInput()); + expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false); + + activity = { hasRunningSubprocess: true, runningPorts: [3000] }; + yield* waitFor( + Effect.map(getEvents, (events) => + events.some( + (event) => + event.type === "activity" && + event.hasRunningSubprocess === true && + event.runningPorts.join(",") === "3000", + ), + ), + "1200 millis", + ); + + activity = { hasRunningSubprocess: true, runningPorts: [5173] }; + yield* waitFor( + Effect.map(getEvents, (events) => + events.some( + (event) => + event.type === "activity" && + event.hasRunningSubprocess === true && + event.runningPorts.length === 0, + ), + ), + "1200 millis", + ); + + activity = { hasRunningSubprocess: false, runningPorts: [5173] }; + yield* waitFor( + Effect.map(getEvents, (events) => + events.some( + (event) => + event.type === "activity" && + event.hasRunningSubprocess === false && + event.runningPorts.length === 0, + ), + ), + "1200 millis", + ); + }), + ); + + it.effect("does not invoke subprocess polling until a terminal session is running", () => + Effect.gen(function* () { + let checks = 0; + const { manager } = yield* createManager(5, { + subprocessChecker: () => { + checks += 1; + return Effect.succeed(false); + }, + subprocessPollIntervalMs: 20, + }); + + yield* Effect.sleep("80 millis"); + assert.equal(checks, 0); + + yield* manager.open(openInput()); + yield* waitFor( + Effect.sync(() => checks > 0), + "1200 millis", + ); + }), + ); + + it.effect("caps persisted history to configured line limit", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(3); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("line1\nline2\nline3\nline4\n"); + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + const nonEmptyLines = reopened.history.split("\n").filter((line) => line.length > 0); + expect(nonEmptyLines).toEqual(["line2", "line3", "line4"]); + }), + ); + + it.effect("strips replay-unsafe terminal query and reply sequences from persisted history", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("prompt "); + process.emitData("\u001b[32mok\u001b[0m "); + process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007"); + process.emitData("\u001b[1;1R"); + process.emitData("done\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal(reopened.history, "prompt \u001b[32mok\u001b[0m done\n"); + }), + ); + + it.effect( + "preserves clear and style control sequences while dropping chunk-split query traffic", + () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("before clear\n"); + process.emitData("\u001b[H\u001b[2J"); + process.emitData("prompt "); + process.emitData("\u001b]11;"); + process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1"); + process.emitData("R\u001b[36mdone\u001b[0m\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal( + reopened.history, + "before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n", + ); + }), + ); + + it.effect("does not leak final bytes from ESC sequences with intermediate bytes", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("before "); + process.emitData("\u001b(B"); + process.emitData("after\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal(reopened.history, "before \u001b(Bafter\n"); + }), + ); + + it.effect( + "preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", + () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("before "); + process.emitData("\u001b("); + process.emitData("Bafter\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal(reopened.history, "before \u001b(Bafter\n"); + }), + ); + + it.effect("deletes history file when close(deleteHistory=true)", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + process.emitData("bye\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + + yield* manager.close({ threadId: "thread-1", deleteHistory: true }); + expect(yield* pathExists(historyLogPath(logsDir))).toBe(false); + }), + ); + + it.effect("closes all terminals for a thread when close omits terminalId", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput({ terminalId: "default" })); + yield* manager.open(openInput({ terminalId: "sidecar" })); + const defaultProcess = ptyAdapter.processes[0]; + const sidecarProcess = ptyAdapter.processes[1]; + expect(defaultProcess).toBeDefined(); + expect(sidecarProcess).toBeDefined(); + if (!defaultProcess || !sidecarProcess) return; + + defaultProcess.emitData("default\n"); + sidecarProcess.emitData("sidecar\n"); + yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))); + yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))); + + yield* manager.close({ threadId: "thread-1", deleteHistory: true }); + + assert.equal(defaultProcess.killed, true); + assert.equal(sidecarProcess.killed, true); + expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe( + false, + ); + expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe( + false, + ); + }), + ); + + it.effect("escalates terminal shutdown to SIGKILL when process does not exit in time", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { processKillGraceMs: 10 }); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + const closeFiber = yield* manager.close({ threadId: "thread-1" }).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + yield* TestClock.adjust("10 millis"); + yield* Fiber.join(closeFiber); + + assert.equal(process.killSignals[0], "SIGTERM"); + expect(process.killSignals).toContain("SIGKILL"); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("evicts oldest inactive terminal sessions when retention limit is exceeded", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(5, { + maxRetainedInactiveSessions: 1, + }); + + yield* manager.open(openInput({ threadId: "thread-1" })); + yield* manager.open(openInput({ threadId: "thread-2" })); + + const first = ptyAdapter.processes[0]; + const second = ptyAdapter.processes[1]; + expect(first).toBeDefined(); + expect(second).toBeDefined(); + if (!first || !second) return; + + first.emitData("first-history\n"); + second.emitData("second-history\n"); + yield* waitFor(pathExists(historyLogPath(logsDir, "thread-1"))); + first.emitExit({ exitCode: 0, signal: 0 }); + yield* Effect.sleep(Duration.millis(5)); + second.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map( + getEvents, + (events) => events.filter((event) => event.type === "exited").length === 2, + ), + ); + + const reopenedSecond = yield* manager.open(openInput({ threadId: "thread-2" })); + const reopenedFirst = yield* manager.open(openInput({ threadId: "thread-1" })); + + assert.equal(reopenedFirst.history, "first-history\n"); + assert.equal(reopenedSecond.history, ""); + }), + ); + + it.effect("migrates legacy transcript filenames to terminal-scoped history path on open", () => + Effect.gen(function* () { + const { manager, logsDir } = yield* createManager(); + const legacyPath = path.join(logsDir, "thread-1.log"); + const nextPath = historyLogPath(logsDir); + yield* writeFileString(legacyPath, "legacy-line\n"); + + const snapshot = yield* manager.open(openInput()); + + assert.equal(snapshot.history, "legacy-line\n"); + expect(yield* pathExists(nextPath)).toBe(true); + expect(yield* readFileString(nextPath)).toBe("legacy-line\n"); + expect(yield* pathExists(legacyPath)).toBe(false); + }), + ); + + it.effect("retries with fallback shells when preferred shell spawn fails", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + shellResolver: () => "/definitely/missing-shell -l", + }); + ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed.")); + + const snapshot = yield* manager.open(openInput()); + + assert.equal(snapshot.status, "running"); + expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2); + expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell"); + + if (process.platform === "win32") { + expect( + ptyAdapter.spawnInputs.some( + (input) => input.shell === "cmd.exe" || input.shell === "powershell.exe", + ), + ).toBe(true); + } else { + expect( + ptyAdapter.spawnInputs + .slice(1) + .some((input) => input.shell !== "/definitely/missing-shell"), + ).toBe(true); + } + }), + ); + + it.effect("filters app runtime env variables from terminal sessions", () => + Effect.gen(function* () { + const originalValues = new Map(); + const setEnv = (key: string, value: string | undefined) => { + if (!originalValues.has(key)) { + originalValues.set(key, process.env[key]); + } + if (value === undefined) { + delete process.env[key]; + return; + } + process.env[key] = value; + }; + const restoreEnv = () => { + for (const [key, value] of originalValues) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } + }; + + setEnv("PORT", "5173"); + setEnv("T3CODE_PORT", "3773"); + setEnv("VITE_DEV_SERVER_URL", "http://localhost:5173"); + setEnv("TEST_TERMINAL_KEEP", "keep-me"); + + try { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const spawnInput = ptyAdapter.spawnInputs[0]; + expect(spawnInput).toBeDefined(); + if (!spawnInput) return; + + expect(spawnInput.env.PORT).toBeUndefined(); + expect(spawnInput.env.T3CODE_PORT).toBeUndefined(); + expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined(); + expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me"); + } finally { + restoreEnv(); + } + }), + ); + + it.effect("injects runtime env overrides into spawned terminals", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open( + openInput({ + env: { + T3CODE_PROJECT_ROOT: "/repo", + T3CODE_WORKTREE_PATH: "/repo/worktree-a", + CUSTOM_FLAG: "1", + }, + }), + ); + const spawnInput = ptyAdapter.spawnInputs[0]; + expect(spawnInput).toBeDefined(); + if (!spawnInput) return; + + assert.equal(spawnInput.env.T3CODE_PROJECT_ROOT, "/repo"); + assert.equal(spawnInput.env.T3CODE_WORKTREE_PATH, "/repo/worktree-a"); + assert.equal(spawnInput.env.CUSTOM_FLAG, "1"); + }), + ); + + it.effect("starts zsh with prompt spacer disabled to avoid `%` end markers", () => + Effect.gen(function* () { + if (process.platform === "win32") return; + const { manager, ptyAdapter } = yield* createManager(5, { + shellResolver: () => "/bin/zsh", + }); + yield* manager.open(openInput()); + const spawnInput = ptyAdapter.spawnInputs[0]; + expect(spawnInput).toBeDefined(); + if (!spawnInput) return; + + expect(spawnInput.args).toEqual(["-o", "nopromptsp"]); + }), + ); + + it.effect("bridges PTY callbacks back into Effect-managed event streaming", () => + Effect.gen(function* () { + const { manager, ptyAdapter, getEvents } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); + + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("hello from callback\n"); + + yield* waitFor( + Effect.map(getEvents, (events) => + events.some((event) => event.type === "output" && event.data === "hello from callback\n"), + ), + "1200 millis", + ); + }), + ); + + it.effect("pushes PTY callbacks to direct event subscribers", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); + const scope = yield* Effect.scope; + const subscriberEvents = yield* Ref.make>([]); + const unsubscribe = yield* manager.subscribe((event) => + Ref.update(subscriberEvents, (events) => [...events, event]), + ); + yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe)); + + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("hello from subscriber\n"); + + yield* waitFor( + Effect.map(Ref.get(subscriberEvents), (events) => + events.some( + (event) => event.type === "output" && event.data === "hello from subscriber\n", + ), + ), + "1200 millis", + ); + }), + ); + + it.effect("preserves queued PTY output ordering through exit callbacks", () => + Effect.gen(function* () { + const { manager, ptyAdapter, getEvents } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); + + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("first\n"); + process.emitData("second\n"); + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map(getEvents, (events) => { + const relevant = events.filter( + (event) => event.type === "output" || event.type === "exited", + ); + return relevant.length >= 3; + }), + "1200 millis", + ); + + const relevant = (yield* getEvents).filter( + (event) => event.type === "output" || event.type === "exited", + ); + expect(relevant).toEqual([ + expect.objectContaining({ type: "output", data: "first\n" }), + expect.objectContaining({ type: "output", data: "second\n" }), + expect.objectContaining({ type: "exited", exitCode: 0, exitSignal: 0 }), + ]); + }), + ); + + it.effect("scoped runtime shutdown stops active terminals cleanly", () => + Effect.gen(function* () { + const scope = yield* Scope.make("sequential"); + const { manager, ptyAdapter } = yield* createManager(5, { + processKillGraceMs: 10, + }).pipe(Effect.provideService(Scope.Scope, scope)); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + const closeScope = yield* Scope.close(scope, Exit.void).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + yield* TestClock.adjust("10 millis"); + yield* Fiber.join(closeScope); + + assert.equal(process.killSignals[0], "SIGTERM"); + expect(process.killSignals).toContain("SIGKILL"); + }).pipe(Effect.provide(TestClock.layer())), + ); +}); diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts new file mode 100644 index 0000000000..930e764e36 --- /dev/null +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -0,0 +1,1859 @@ +import path from "node:path"; + +import { + DEFAULT_TERMINAL_ID, + type TerminalEvent, + type TerminalSessionSnapshot, + type TerminalSessionStatus, +} from "@t3tools/contracts"; +import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker"; +import { + Data, + Effect, + Encoding, + Equal, + Exit, + Fiber, + FileSystem, + Layer, + Option, + Scope, + Semaphore, + SynchronizedRef, +} from "effect"; + +import { ServerConfig } from "../../config"; +import { + increment, + terminalRestartsTotal, + terminalSessionsTotal, +} from "../../observability/Metrics"; +import { + arePortListsEqual, + defaultSubprocessInspector, + normalizeRunningPorts, +} from "../../terminalProcessInspector"; +import { DEFAULT_WEB_PORT_PROBE_TTL_MS, defaultWebPortInspector } from "../../webPortInspector"; +import { + TerminalCwdError, + TerminalHistoryError, + TerminalManager, + TerminalNotRunningError, + TerminalSessionLookupError, + type TerminalManagerShape, +} from "../Services/Manager"; +import { + PtyAdapter, + PtySpawnError, + type PtyAdapterShape, + type PtyExitEvent, + type PtyProcess, +} from "../Services/PTY"; + +const DEFAULT_HISTORY_LINE_LIMIT = 5_000; +const DEFAULT_PERSIST_DEBOUNCE_MS = 40; +const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000; +const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000; +const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128; +const DEFAULT_OPEN_COLS = 120; +const DEFAULT_OPEN_ROWS = 30; +const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]); + +type TerminalSubprocessChecker = ( + terminalPid: number, +) => Effect.Effect; +type TerminalSubprocessActivity = { + hasRunningSubprocess: boolean; + runningPorts: number[]; +}; +type TerminalSubprocessInspector = ( + terminalPid: number, +) => Effect.Effect; +type TerminalWebPortInspector = (port: number) => Effect.Effect; + +class TerminalSubprocessCheckError extends Data.TaggedError("TerminalSubprocessCheckError")<{ + readonly message: string; + readonly cause?: unknown; + readonly terminalPid: number; + readonly command: "powershell" | "pgrep" | "ps"; +}> {} + +class TerminalProcessSignalError extends Data.TaggedError("TerminalProcessSignalError")<{ + readonly message: string; + readonly cause?: unknown; + readonly signal: "SIGTERM" | "SIGKILL"; +}> {} + +interface ShellCandidate { + shell: string; + args?: string[]; +} + +interface TerminalStartInput { + threadId: string; + terminalId: string; + cwd: string; + worktreePath?: string | null; + cols: number; + rows: number; + env?: Record; +} + +interface TerminalSessionState { + threadId: string; + terminalId: string; + cwd: string; + worktreePath: string | null; + status: TerminalSessionStatus; + pid: number | null; + history: string; + pendingHistoryControlSequence: string; + pendingProcessEvents: Array; + pendingProcessEventIndex: number; + processEventDrainRunning: boolean; + exitCode: number | null; + exitSignal: number | null; + updatedAt: string; + cols: number; + rows: number; + process: PtyProcess | null; + unsubscribeData: (() => void) | null; + unsubscribeExit: (() => void) | null; + hasRunningSubprocess: boolean; + runningSubprocessPorts: number[]; + runtimeEnv: Record | null; +} + +interface PersistHistoryRequest { + history: string; + immediate: boolean; +} + +type PendingProcessEvent = { type: "output"; data: string } | { type: "exit"; event: PtyExitEvent }; + +type DrainProcessEventAction = + | { type: "idle" } + | { + type: "output"; + threadId: string; + terminalId: string; + history: string | null; + data: string; + } + | { + type: "exit"; + process: PtyProcess | null; + threadId: string; + terminalId: string; + exitCode: number | null; + exitSignal: number | null; + }; + +interface TerminalManagerState { + sessions: Map; + killFibers: Map>; +} + +function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { + return { + threadId: session.threadId, + terminalId: session.terminalId, + cwd: session.cwd, + worktreePath: session.worktreePath, + status: session.status, + pid: session.pid, + history: session.history, + exitCode: session.exitCode, + exitSignal: session.exitSignal, + updatedAt: session.updatedAt, + }; +} + +function cleanupProcessHandles(session: TerminalSessionState): void { + session.unsubscribeData?.(); + session.unsubscribeData = null; + session.unsubscribeExit?.(); + session.unsubscribeExit = null; +} + +function enqueueProcessEvent( + session: TerminalSessionState, + expectedPid: number, + event: PendingProcessEvent, +): boolean { + if (!session.process || session.status !== "running" || session.pid !== expectedPid) { + return false; + } + + session.pendingProcessEvents.push(event); + if (session.processEventDrainRunning) { + return false; + } + + session.processEventDrainRunning = true; + return true; +} + +function defaultShellResolver(): string { + if (process.platform === "win32") { + return process.env.ComSpec ?? "cmd.exe"; + } + return process.env.SHELL ?? "bash"; +} + +function normalizeShellCommand(value: string | undefined): string | null { + if (!value) return null; + const trimmed = value.trim(); + if (trimmed.length === 0) return null; + + if (process.platform === "win32") { + return trimmed; + } + + const firstToken = trimmed.split(/\s+/g)[0]?.trim(); + if (!firstToken) return null; + return firstToken.replace(/^['"]|['"]$/g, ""); +} + +function shellCandidateFromCommand(command: string | null): ShellCandidate | null { + if (!command || command.length === 0) return null; + const shellName = path.basename(command).toLowerCase(); + if (process.platform !== "win32" && shellName === "zsh") { + return { shell: command, args: ["-o", "nopromptsp"] }; + } + return { shell: command }; +} + +function formatShellCandidate(candidate: ShellCandidate): string { + if (!candidate.args || candidate.args.length === 0) return candidate.shell; + return `${candidate.shell} ${candidate.args.join(" ")}`; +} + +function uniqueShellCandidates(candidates: Array): ShellCandidate[] { + const seen = new Set(); + const ordered: ShellCandidate[] = []; + for (const candidate of candidates) { + if (!candidate) continue; + const key = formatShellCandidate(candidate); + if (seen.has(key)) continue; + seen.add(key); + ordered.push(candidate); + } + return ordered; +} + +function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] { + const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver())); + + if (process.platform === "win32") { + return uniqueShellCandidates([ + requested, + shellCandidateFromCommand(process.env.ComSpec ?? null), + shellCandidateFromCommand("powershell.exe"), + shellCandidateFromCommand("cmd.exe"), + ]); + } + + return uniqueShellCandidates([ + requested, + shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)), + shellCandidateFromCommand("/bin/zsh"), + shellCandidateFromCommand("/bin/bash"), + shellCandidateFromCommand("/bin/sh"), + shellCandidateFromCommand("zsh"), + shellCandidateFromCommand("bash"), + shellCandidateFromCommand("sh"), + ]); +} + +function isRetryableShellSpawnError(error: PtySpawnError): boolean { + const queue: unknown[] = [error]; + const seen = new Set(); + const messages: string[] = []; + + while (queue.length > 0) { + const current = queue.shift(); + if (!current || seen.has(current)) { + continue; + } + seen.add(current); + + if (typeof current === "string") { + messages.push(current); + continue; + } + + if (current instanceof Error) { + messages.push(current.message); + const cause = (current as { cause?: unknown }).cause; + if (cause) { + queue.push(cause); + } + continue; + } + + if (typeof current === "object") { + const value = current as { message?: unknown; cause?: unknown }; + if (typeof value.message === "string") { + messages.push(value.message); + } + if (value.cause) { + queue.push(value.cause); + } + } + } + + const message = messages.join(" ").toLowerCase(); + return ( + message.includes("posix_spawnp failed") || + message.includes("enoent") || + message.includes("not found") || + message.includes("file not found") || + message.includes("no such file") + ); +} + +function capHistory(history: string, maxLines: number): string { + if (history.length === 0) return history; + const hasTrailingNewline = history.endsWith("\n"); + const lines = history.split("\n"); + if (hasTrailingNewline) { + lines.pop(); + } + if (lines.length <= maxLines) return history; + const capped = lines.slice(lines.length - maxLines).join("\n"); + return hasTrailingNewline ? `${capped}\n` : capped; +} + +function isCsiFinalByte(codePoint: number): boolean { + return codePoint >= 0x40 && codePoint <= 0x7e; +} + +function shouldStripCsiSequence(body: string, finalByte: string): boolean { + if (finalByte === "n") { + return true; + } + if (finalByte === "R" && /^[0-9;?]*$/.test(body)) { + return true; + } + if (finalByte === "c" && /^[>0-9;?]*$/.test(body)) { + return true; + } + return false; +} + +function shouldStripOscSequence(content: string): boolean { + return /^(10|11|12);(?:\?|rgb:)/.test(content); +} + +function stripStringTerminator(value: string): string { + if (value.endsWith("\u001b\\")) { + return value.slice(0, -2); + } + const lastCharacter = value.at(-1); + if (lastCharacter === "\u0007" || lastCharacter === "\u009c") { + return value.slice(0, -1); + } + return value; +} + +function findStringTerminatorIndex(input: string, start: number): number | null { + for (let index = start; index < input.length; index += 1) { + const codePoint = input.charCodeAt(index); + if (codePoint === 0x07 || codePoint === 0x9c) { + return index + 1; + } + if (codePoint === 0x1b && input.charCodeAt(index + 1) === 0x5c) { + return index + 2; + } + } + return null; +} + +function isEscapeIntermediateByte(codePoint: number): boolean { + return codePoint >= 0x20 && codePoint <= 0x2f; +} + +function isEscapeFinalByte(codePoint: number): boolean { + return codePoint >= 0x30 && codePoint <= 0x7e; +} + +function findEscapeSequenceEndIndex(input: string, start: number): number | null { + let cursor = start; + while (cursor < input.length && isEscapeIntermediateByte(input.charCodeAt(cursor))) { + cursor += 1; + } + if (cursor >= input.length) { + return null; + } + return isEscapeFinalByte(input.charCodeAt(cursor)) ? cursor + 1 : start + 1; +} + +function sanitizeTerminalHistoryChunk( + pendingControlSequence: string, + data: string, +): { visibleText: string; pendingControlSequence: string } { + const input = `${pendingControlSequence}${data}`; + let visibleText = ""; + let index = 0; + + const append = (value: string) => { + visibleText += value; + }; + + while (index < input.length) { + const codePoint = input.charCodeAt(index); + + if (codePoint === 0x1b) { + const nextCodePoint = input.charCodeAt(index + 1); + if (Number.isNaN(nextCodePoint)) { + return { visibleText, pendingControlSequence: input.slice(index) }; + } + + if (nextCodePoint === 0x5b) { + let cursor = index + 2; + while (cursor < input.length) { + if (isCsiFinalByte(input.charCodeAt(cursor))) { + const sequence = input.slice(index, cursor + 1); + const body = input.slice(index + 2, cursor); + if (!shouldStripCsiSequence(body, input[cursor] ?? "")) { + append(sequence); + } + index = cursor + 1; + break; + } + cursor += 1; + } + if (cursor >= input.length) { + return { visibleText, pendingControlSequence: input.slice(index) }; + } + continue; + } + + if ( + nextCodePoint === 0x5d || + nextCodePoint === 0x50 || + nextCodePoint === 0x5e || + nextCodePoint === 0x5f + ) { + const terminatorIndex = findStringTerminatorIndex(input, index + 2); + if (terminatorIndex === null) { + return { visibleText, pendingControlSequence: input.slice(index) }; + } + const sequence = input.slice(index, terminatorIndex); + const content = stripStringTerminator(input.slice(index + 2, terminatorIndex)); + if (nextCodePoint !== 0x5d || !shouldStripOscSequence(content)) { + append(sequence); + } + index = terminatorIndex; + continue; + } + + const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1); + if (escapeSequenceEndIndex === null) { + return { visibleText, pendingControlSequence: input.slice(index) }; + } + append(input.slice(index, escapeSequenceEndIndex)); + index = escapeSequenceEndIndex; + continue; + } + + if (codePoint === 0x9b) { + let cursor = index + 1; + while (cursor < input.length) { + if (isCsiFinalByte(input.charCodeAt(cursor))) { + const sequence = input.slice(index, cursor + 1); + const body = input.slice(index + 1, cursor); + if (!shouldStripCsiSequence(body, input[cursor] ?? "")) { + append(sequence); + } + index = cursor + 1; + break; + } + cursor += 1; + } + if (cursor >= input.length) { + return { visibleText, pendingControlSequence: input.slice(index) }; + } + continue; + } + + if (codePoint === 0x9d || codePoint === 0x90 || codePoint === 0x9e || codePoint === 0x9f) { + const terminatorIndex = findStringTerminatorIndex(input, index + 1); + if (terminatorIndex === null) { + return { visibleText, pendingControlSequence: input.slice(index) }; + } + const sequence = input.slice(index, terminatorIndex); + const content = stripStringTerminator(input.slice(index + 1, terminatorIndex)); + if (codePoint !== 0x9d || !shouldStripOscSequence(content)) { + append(sequence); + } + index = terminatorIndex; + continue; + } + + append(input[index] ?? ""); + index += 1; + } + + return { visibleText, pendingControlSequence: "" }; +} + +function legacySafeThreadId(threadId: string): string { + return threadId.replace(/[^a-zA-Z0-9._-]/g, "_"); +} + +function toSafeThreadId(threadId: string): string { + return `terminal_${Encoding.encodeBase64Url(threadId)}`; +} + +function toSafeTerminalId(terminalId: string): string { + return Encoding.encodeBase64Url(terminalId); +} + +function toSessionKey(threadId: string, terminalId: string): string { + return `${threadId}\u0000${terminalId}`; +} + +function shouldExcludeTerminalEnvKey(key: string): boolean { + const normalizedKey = key.toUpperCase(); + if (normalizedKey.startsWith("T3CODE_")) { + return true; + } + if (normalizedKey.startsWith("VITE_")) { + return true; + } + return TERMINAL_ENV_BLOCKLIST.has(normalizedKey); +} + +function createTerminalSpawnEnv( + baseEnv: NodeJS.ProcessEnv, + runtimeEnv?: Record | null, +): NodeJS.ProcessEnv { + const spawnEnv: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(baseEnv)) { + if (value === undefined) continue; + if (shouldExcludeTerminalEnvKey(key)) continue; + spawnEnv[key] = value; + } + if (runtimeEnv) { + for (const [key, value] of Object.entries(runtimeEnv)) { + spawnEnv[key] = value; + } + } + return spawnEnv; +} + +function normalizedRuntimeEnv( + env: Record | undefined, +): Record | null { + if (!env) return null; + const entries = Object.entries(env); + if (entries.length === 0) return null; + return Object.fromEntries(entries.toSorted(([left], [right]) => left.localeCompare(right))); +} + +interface TerminalManagerOptions { + logsDir: string; + historyLineLimit?: number; + ptyAdapter: PtyAdapterShape; + shellResolver?: () => string; + subprocessChecker?: TerminalSubprocessChecker; + subprocessInspector?: TerminalSubprocessInspector; + webPortInspector?: TerminalWebPortInspector; + webPortProbeCacheTtlMs?: number; + subprocessPollIntervalMs?: number; + processKillGraceMs?: number; + maxRetainedInactiveSessions?: number; +} + +const makeTerminalManager = Effect.fn("makeTerminalManager")(function* () { + const { terminalLogsDir } = yield* ServerConfig; + const ptyAdapter = yield* PtyAdapter; + return yield* makeTerminalManagerWithOptions({ + logsDir: terminalLogsDir, + ptyAdapter, + }); +}); + +export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWithOptions")( + function* (options: TerminalManagerOptions) { + const fileSystem = yield* FileSystem.FileSystem; + const services = yield* Effect.services(); + const runFork = Effect.runForkWith(services); + + const logsDir = options.logsDir; + const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; + const shellResolver = options.shellResolver ?? defaultShellResolver; + const subprocessInspector = + options.subprocessInspector ?? + (options.subprocessChecker + ? (terminalPid: number) => + Effect.map(options.subprocessChecker!(terminalPid), (hasRunningSubprocess) => ({ + hasRunningSubprocess, + runningPorts: [], + })) + : (terminalPid: number) => + Effect.tryPromise({ + try: () => defaultSubprocessInspector(terminalPid), + catch: (cause) => + new TerminalSubprocessCheckError({ + message: "Failed to inspect terminal subprocess activity", + cause, + terminalPid, + command: process.platform === "win32" ? "powershell" : "ps", + }), + })); + const webPortInspector = + options.webPortInspector ?? + ((port: number) => + Effect.tryPromise({ + try: () => defaultWebPortInspector(port), + catch: () => false, + })); + const webPortProbeCacheTtlMs = options.webPortProbeCacheTtlMs ?? DEFAULT_WEB_PORT_PROBE_TTL_MS; + const subprocessPollIntervalMs = + options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS; + const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; + const maxRetainedInactiveSessions = + options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS; + const webPortProbeCache = new Map(); + + yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie); + + const managerStateRef = yield* SynchronizedRef.make({ + sessions: new Map(), + killFibers: new Map(), + }); + const threadLocksRef = yield* SynchronizedRef.make(new Map()); + const terminalEventListeners = new Set<(event: TerminalEvent) => Effect.Effect>(); + const workerScope = yield* Scope.make("sequential"); + yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void)); + + const publishEvent = (event: TerminalEvent) => + Effect.gen(function* () { + for (const listener of terminalEventListeners) { + yield* listener(event).pipe(Effect.ignoreCause({ log: true })); + } + }); + + const inspectWebPortCached = (port: number) => + Effect.gen(function* () { + const now = Date.now(); + const cached = webPortProbeCache.get(port); + if (cached && now - cached.checkedAt <= webPortProbeCacheTtlMs) { + return cached.isWeb; + } + + const isWeb = yield* webPortInspector(port).pipe(Effect.catch(() => Effect.succeed(false))); + webPortProbeCache.set(port, { + isWeb, + checkedAt: Date.now(), + }); + return isWeb; + }); + + const detectWebPorts = (runningPorts: number[]) => + Effect.gen(function* () { + if (runningPorts.length === 0) { + return [] as number[]; + } + + const checks = yield* Effect.forEach( + runningPorts, + (port) => + Effect.map(inspectWebPortCached(port), (isWeb) => ({ + port, + isWeb, + })), + { concurrency: "unbounded" }, + ); + + return checks + .filter((entry) => entry.isWeb) + .map((entry) => entry.port) + .toSorted((left, right) => left - right); + }); + + const historyPath = (threadId: string, terminalId: string) => { + const threadPart = toSafeThreadId(threadId); + if (terminalId === DEFAULT_TERMINAL_ID) { + return path.join(logsDir, `${threadPart}.log`); + } + return path.join(logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`); + }; + + const legacyHistoryPath = (threadId: string) => + path.join(logsDir, `${legacySafeThreadId(threadId)}.log`); + + const toTerminalHistoryError = + (operation: "read" | "truncate" | "migrate", threadId: string, terminalId: string) => + (cause: unknown) => + new TerminalHistoryError({ + operation, + threadId, + terminalId, + cause, + }); + + const readManagerState = SynchronizedRef.get(managerStateRef); + + const modifyManagerState = ( + f: (state: TerminalManagerState) => readonly [A, TerminalManagerState], + ) => SynchronizedRef.modify(managerStateRef, f); + + const getThreadSemaphore = (threadId: string) => + SynchronizedRef.modifyEffect(threadLocksRef, (current) => { + const existing: Option.Option = Option.fromNullishOr( + current.get(threadId), + ); + return Option.match(existing, { + onNone: () => + Semaphore.make(1).pipe( + Effect.map((semaphore) => { + const next = new Map(current); + next.set(threadId, semaphore); + return [semaphore, next] as const; + }), + ), + onSome: (semaphore) => Effect.succeed([semaphore, current] as const), + }); + }); + + const withThreadLock = ( + threadId: string, + effect: Effect.Effect, + ): Effect.Effect => + Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect)); + + const clearKillFiber = Effect.fn("terminal.clearKillFiber")(function* ( + process: PtyProcess | null, + ) { + if (!process) return; + const fiber: Option.Option> = yield* modifyManagerState< + Option.Option> + >((state) => { + const existing: Option.Option> = Option.fromNullishOr( + state.killFibers.get(process), + ); + if (Option.isNone(existing)) { + return [Option.none>(), state] as const; + } + const killFibers = new Map(state.killFibers); + killFibers.delete(process); + return [existing, { ...state, killFibers }] as const; + }); + if (Option.isSome(fiber)) { + yield* Fiber.interrupt(fiber.value).pipe(Effect.ignore); + } + }); + + const registerKillFiber = Effect.fn("terminal.registerKillFiber")(function* ( + process: PtyProcess, + fiber: Fiber.Fiber, + ) { + yield* modifyManagerState((state) => { + const killFibers = new Map(state.killFibers); + killFibers.set(process, fiber); + return [undefined, { ...state, killFibers }] as const; + }); + }); + + const runKillEscalation = Effect.fn("terminal.runKillEscalation")(function* ( + process: PtyProcess, + threadId: string, + terminalId: string, + ) { + const terminated = yield* Effect.try({ + try: () => process.kill("SIGTERM"), + catch: (cause) => + new TerminalProcessSignalError({ + message: "Failed to send SIGTERM to terminal process.", + cause, + signal: "SIGTERM", + }), + }).pipe( + Effect.as(true), + Effect.catch((error) => + Effect.logWarning("failed to kill terminal process", { + threadId, + terminalId, + signal: "SIGTERM", + error: error.message, + }).pipe(Effect.as(false)), + ), + ); + if (!terminated) { + return; + } + + yield* Effect.sleep(processKillGraceMs); + + yield* Effect.try({ + try: () => process.kill("SIGKILL"), + catch: (cause) => + new TerminalProcessSignalError({ + message: "Failed to send SIGKILL to terminal process.", + cause, + signal: "SIGKILL", + }), + }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to force-kill terminal process", { + threadId, + terminalId, + signal: "SIGKILL", + error: error.message, + }), + ), + ); + }); + + const startKillEscalation = Effect.fn("terminal.startKillEscalation")(function* ( + process: PtyProcess, + threadId: string, + terminalId: string, + ) { + const fiber = yield* runKillEscalation(process, threadId, terminalId).pipe( + Effect.ensuring( + modifyManagerState((state) => { + if (!state.killFibers.has(process)) { + return [undefined, state] as const; + } + const killFibers = new Map(state.killFibers); + killFibers.delete(process); + return [undefined, { ...state, killFibers }] as const; + }), + ), + Effect.forkIn(workerScope), + ); + + yield* registerKillFiber(process, fiber); + }); + + const persistWorker = yield* makeKeyedCoalescingWorker< + string, + PersistHistoryRequest, + never, + never + >({ + merge: (current, next) => ({ + history: next.history, + immediate: current.immediate || next.immediate, + }), + process: Effect.fn("terminal.persistHistoryWorker")(function* (sessionKey, request) { + if (!request.immediate) { + yield* Effect.sleep(DEFAULT_PERSIST_DEBOUNCE_MS); + } + + const [threadId, terminalId] = sessionKey.split("\u0000"); + if (!threadId || !terminalId) { + return; + } + + yield* fileSystem.writeFileString(historyPath(threadId, terminalId), request.history).pipe( + Effect.catch((error) => + Effect.logWarning("failed to persist terminal history", { + threadId, + terminalId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ); + }), + }); + + const queuePersist = Effect.fn("terminal.queuePersist")(function* ( + threadId: string, + terminalId: string, + history: string, + ) { + yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), { + history, + immediate: false, + }); + }); + + const flushPersist = Effect.fn("terminal.flushPersist")(function* ( + threadId: string, + terminalId: string, + ) { + yield* persistWorker.drainKey(toSessionKey(threadId, terminalId)); + }); + + const persistHistory = Effect.fn("terminal.persistHistory")(function* ( + threadId: string, + terminalId: string, + history: string, + ) { + yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), { + history, + immediate: true, + }); + yield* flushPersist(threadId, terminalId); + }); + + const readHistory = Effect.fn("terminal.readHistory")(function* ( + threadId: string, + terminalId: string, + ) { + const nextPath = historyPath(threadId, terminalId); + if ( + yield* fileSystem + .exists(nextPath) + .pipe(Effect.mapError(toTerminalHistoryError("read", threadId, terminalId))) + ) { + const raw = yield* fileSystem + .readFileString(nextPath) + .pipe(Effect.mapError(toTerminalHistoryError("read", threadId, terminalId))); + const capped = capHistory(raw, historyLineLimit); + if (capped !== raw) { + yield* fileSystem + .writeFileString(nextPath, capped) + .pipe(Effect.mapError(toTerminalHistoryError("truncate", threadId, terminalId))); + } + return capped; + } + + if (terminalId !== DEFAULT_TERMINAL_ID) { + return ""; + } + + const legacyPath = legacyHistoryPath(threadId); + if ( + !(yield* fileSystem + .exists(legacyPath) + .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId)))) + ) { + return ""; + } + + const raw = yield* fileSystem + .readFileString(legacyPath) + .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId))); + const capped = capHistory(raw, historyLineLimit); + yield* fileSystem + .writeFileString(nextPath, capped) + .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId))); + yield* fileSystem.remove(legacyPath, { force: true }).pipe( + Effect.catch((cleanupError) => + Effect.logWarning("failed to remove legacy terminal history", { + threadId, + error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), + }), + ), + ); + return capped; + }); + + const deleteHistory = Effect.fn("terminal.deleteHistory")(function* ( + threadId: string, + terminalId: string, + ) { + yield* fileSystem.remove(historyPath(threadId, terminalId), { force: true }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to delete terminal history", { + threadId, + terminalId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ); + if (terminalId === DEFAULT_TERMINAL_ID) { + yield* fileSystem.remove(legacyHistoryPath(threadId), { force: true }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to delete terminal history", { + threadId, + terminalId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ); + } + }); + + const deleteAllHistoryForThread = Effect.fn("terminal.deleteAllHistoryForThread")(function* ( + threadId: string, + ) { + const threadPrefix = `${toSafeThreadId(threadId)}_`; + const entries = yield* fileSystem + .readDirectory(logsDir, { recursive: false }) + .pipe(Effect.catch(() => Effect.succeed([] as Array))); + yield* Effect.forEach( + entries.filter( + (name) => + name === `${toSafeThreadId(threadId)}.log` || + name === `${legacySafeThreadId(threadId)}.log` || + name.startsWith(threadPrefix), + ), + (name) => + fileSystem.remove(path.join(logsDir, name), { force: true }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to delete terminal histories for thread", { + threadId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ), + { discard: true }, + ); + }); + + const assertValidCwd = Effect.fn("terminal.assertValidCwd")(function* (cwd: string) { + const stats = yield* fileSystem.stat(cwd).pipe( + Effect.mapError( + (cause) => + new TerminalCwdError({ + cwd, + reason: cause.reason._tag === "NotFound" ? "notFound" : "statFailed", + cause, + }), + ), + ); + if (stats.type !== "Directory") { + return yield* new TerminalCwdError({ + cwd, + reason: "notDirectory", + }); + } + }); + + const getSession = Effect.fn("terminal.getSession")(function* ( + threadId: string, + terminalId: string, + ): Effect.fn.Return> { + return yield* Effect.map(readManagerState, (state) => + Option.fromNullishOr(state.sessions.get(toSessionKey(threadId, terminalId))), + ); + }); + + const requireSession = Effect.fn("terminal.requireSession")(function* ( + threadId: string, + terminalId: string, + ): Effect.fn.Return { + return yield* Effect.flatMap(getSession(threadId, terminalId), (session) => + Option.match(session, { + onNone: () => + Effect.fail( + new TerminalSessionLookupError({ + threadId, + terminalId, + }), + ), + onSome: Effect.succeed, + }), + ); + }); + + const sessionsForThread = Effect.fn("terminal.sessionsForThread")(function* (threadId: string) { + return yield* readManagerState.pipe( + Effect.map((state) => + [...state.sessions.values()].filter((session) => session.threadId === threadId), + ), + ); + }); + + const evictInactiveSessionsIfNeeded = Effect.fn("terminal.evictInactiveSessionsIfNeeded")( + function* () { + yield* modifyManagerState((state) => { + const inactiveSessions = [...state.sessions.values()].filter( + (session) => session.status !== "running", + ); + if (inactiveSessions.length <= maxRetainedInactiveSessions) { + return [undefined, state] as const; + } + + inactiveSessions.sort( + (left, right) => + left.updatedAt.localeCompare(right.updatedAt) || + left.threadId.localeCompare(right.threadId) || + left.terminalId.localeCompare(right.terminalId), + ); + + const sessions = new Map(state.sessions); + + const toEvict = inactiveSessions.length - maxRetainedInactiveSessions; + for (const session of inactiveSessions.slice(0, toEvict)) { + const key = toSessionKey(session.threadId, session.terminalId); + sessions.delete(key); + } + + return [undefined, { ...state, sessions }] as const; + }); + }, + ); + + const drainProcessEvents = Effect.fn("terminal.drainProcessEvents")(function* ( + session: TerminalSessionState, + expectedPid: number, + ) { + while (true) { + const action: DrainProcessEventAction = yield* Effect.sync(() => { + if (session.pid !== expectedPid || !session.process || session.status !== "running") { + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + return { type: "idle" } as const; + } + + const nextEvent = session.pendingProcessEvents[session.pendingProcessEventIndex]; + if (!nextEvent) { + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + return { type: "idle" } as const; + } + + session.pendingProcessEventIndex += 1; + if (session.pendingProcessEventIndex >= session.pendingProcessEvents.length) { + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + } + + if (nextEvent.type === "output") { + const sanitized = sanitizeTerminalHistoryChunk( + session.pendingHistoryControlSequence, + nextEvent.data, + ); + session.pendingHistoryControlSequence = sanitized.pendingControlSequence; + if (sanitized.visibleText.length > 0) { + session.history = capHistory( + `${session.history}${sanitized.visibleText}`, + historyLineLimit, + ); + } + session.updatedAt = new Date().toISOString(); + + return { + type: "output", + threadId: session.threadId, + terminalId: session.terminalId, + history: sanitized.visibleText.length > 0 ? session.history : null, + data: nextEvent.data, + } as const; + } + + const process = session.process; + cleanupProcessHandles(session); + session.process = null; + session.pid = null; + session.hasRunningSubprocess = false; + session.runningSubprocessPorts = []; + session.status = "exited"; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.exitCode = Number.isInteger(nextEvent.event.exitCode) + ? nextEvent.event.exitCode + : null; + session.exitSignal = Number.isInteger(nextEvent.event.signal) + ? nextEvent.event.signal + : null; + session.updatedAt = new Date().toISOString(); + + return { + type: "exit", + process, + threadId: session.threadId, + terminalId: session.terminalId, + exitCode: session.exitCode, + exitSignal: session.exitSignal, + } as const; + }); + + if (action.type === "idle") { + return; + } + + if (action.type === "output") { + if (action.history !== null) { + yield* queuePersist(action.threadId, action.terminalId, action.history); + } + + yield* publishEvent({ + type: "output", + threadId: action.threadId, + terminalId: action.terminalId, + createdAt: new Date().toISOString(), + data: action.data, + }); + continue; + } + + yield* clearKillFiber(action.process); + yield* publishEvent({ + type: "exited", + threadId: action.threadId, + terminalId: action.terminalId, + createdAt: new Date().toISOString(), + exitCode: action.exitCode, + exitSignal: action.exitSignal, + }); + yield* evictInactiveSessionsIfNeeded(); + return; + } + }); + + const stopProcess = Effect.fn("terminal.stopProcess")(function* ( + session: TerminalSessionState, + ) { + const process = session.process; + if (!process) return; + + yield* modifyManagerState((state) => { + cleanupProcessHandles(session); + session.process = null; + session.pid = null; + session.hasRunningSubprocess = false; + session.runningSubprocessPorts = []; + session.status = "exited"; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + return [undefined, state] as const; + }); + + yield* clearKillFiber(process); + yield* startKillEscalation(process, session.threadId, session.terminalId); + yield* evictInactiveSessionsIfNeeded(); + }); + + const trySpawn = Effect.fn("terminal.trySpawn")(function* ( + shellCandidates: ReadonlyArray, + spawnEnv: NodeJS.ProcessEnv, + session: TerminalSessionState, + index = 0, + lastError: PtySpawnError | null = null, + ): Effect.fn.Return<{ process: PtyProcess; shellLabel: string }, PtySpawnError> { + if (index >= shellCandidates.length) { + const detail = lastError?.message ?? "Failed to spawn PTY process"; + const tried = + shellCandidates.length > 0 + ? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.` + : ""; + return yield* new PtySpawnError({ + adapter: "terminal-manager", + message: `${detail}.${tried}`.trim(), + ...(lastError ? { cause: lastError } : {}), + }); + } + + const candidate = shellCandidates[index]; + if (!candidate) { + return yield* ( + lastError ?? + new PtySpawnError({ + adapter: "terminal-manager", + message: "No shell candidate available for PTY spawn.", + }) + ); + } + + const attempt = yield* Effect.result( + options.ptyAdapter.spawn({ + shell: candidate.shell, + ...(candidate.args ? { args: candidate.args } : {}), + cwd: session.cwd, + cols: session.cols, + rows: session.rows, + env: spawnEnv, + }), + ); + + if (attempt._tag === "Success") { + return { + process: attempt.success, + shellLabel: formatShellCandidate(candidate), + }; + } + + const spawnError = attempt.failure; + if (!isRetryableShellSpawnError(spawnError)) { + return yield* spawnError; + } + + return yield* trySpawn(shellCandidates, spawnEnv, session, index + 1, spawnError); + }); + + const startSession = Effect.fn("terminal.startSession")(function* ( + session: TerminalSessionState, + input: TerminalStartInput, + eventType: "started" | "restarted", + ) { + yield* stopProcess(session); + yield* Effect.annotateCurrentSpan({ + "terminal.thread_id": session.threadId, + "terminal.id": session.terminalId, + "terminal.event_type": eventType, + "terminal.cwd": input.cwd, + }); + + yield* modifyManagerState((state) => { + session.status = "starting"; + session.cwd = input.cwd; + session.worktreePath = input.worktreePath ?? null; + session.cols = input.cols; + session.rows = input.rows; + session.exitCode = null; + session.exitSignal = null; + session.hasRunningSubprocess = false; + session.runningSubprocessPorts = []; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + return [undefined, state] as const; + }); + + let ptyProcess: PtyProcess | null = null; + let startedShell: string | null = null; + + const startResult = yield* Effect.result( + increment(terminalSessionsTotal, { lifecycle: eventType }).pipe( + Effect.andThen( + Effect.gen(function* () { + const shellCandidates = resolveShellCandidates(shellResolver); + const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv); + const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session); + ptyProcess = spawnResult.process; + startedShell = spawnResult.shellLabel; + + const processPid = ptyProcess.pid; + const unsubscribeData = ptyProcess.onData((data) => { + if (!enqueueProcessEvent(session, processPid, { type: "output", data })) { + return; + } + runFork(drainProcessEvents(session, processPid)); + }); + const unsubscribeExit = ptyProcess.onExit((event) => { + if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) { + return; + } + runFork(drainProcessEvents(session, processPid)); + }); + + yield* modifyManagerState((state) => { + session.process = ptyProcess; + session.pid = processPid; + session.status = "running"; + session.updatedAt = new Date().toISOString(); + session.unsubscribeData = unsubscribeData; + session.unsubscribeExit = unsubscribeExit; + return [undefined, state] as const; + }); + + yield* publishEvent({ + type: eventType, + threadId: session.threadId, + terminalId: session.terminalId, + createdAt: new Date().toISOString(), + snapshot: snapshot(session), + }); + }), + ), + ), + ); + + if (startResult._tag === "Success") { + return; + } + + { + const error = startResult.failure; + if (ptyProcess) { + yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId); + } + + yield* modifyManagerState((state) => { + session.status = "error"; + session.pid = null; + session.process = null; + session.unsubscribeData = null; + session.unsubscribeExit = null; + session.hasRunningSubprocess = false; + session.runningSubprocessPorts = []; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + return [undefined, state] as const; + }); + + yield* evictInactiveSessionsIfNeeded(); + + const message = error.message; + yield* publishEvent({ + type: "error", + threadId: session.threadId, + terminalId: session.terminalId, + createdAt: new Date().toISOString(), + message, + }); + yield* Effect.logError("failed to start terminal", { + threadId: session.threadId, + terminalId: session.terminalId, + error: message, + ...(startedShell ? { shell: startedShell } : {}), + }); + } + }); + + const closeSession = Effect.fn("terminal.closeSession")(function* ( + threadId: string, + terminalId: string, + deleteHistoryOnClose: boolean, + ) { + const key = toSessionKey(threadId, terminalId); + const session = yield* getSession(threadId, terminalId); + + if (Option.isSome(session)) { + yield* stopProcess(session.value); + yield* persistHistory(threadId, terminalId, session.value.history); + } + + yield* flushPersist(threadId, terminalId); + + yield* modifyManagerState((state) => { + if (!state.sessions.has(key)) { + return [undefined, state] as const; + } + const sessions = new Map(state.sessions); + sessions.delete(key); + return [undefined, { ...state, sessions }] as const; + }); + + if (deleteHistoryOnClose) { + yield* deleteHistory(threadId, terminalId); + } + }); + + const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () { + const state = yield* readManagerState; + const runningSessions = [...state.sessions.values()].filter( + (session): session is TerminalSessionState & { pid: number } => + session.status === "running" && Number.isInteger(session.pid), + ); + + if (runningSessions.length === 0) { + return; + } + + const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* ( + session: TerminalSessionState & { pid: number }, + ) { + const terminalPid = session.pid; + const activity = yield* subprocessInspector(terminalPid).pipe( + Effect.map(Option.some), + Effect.catch((error) => + Effect.logWarning("failed to check terminal subprocess activity", { + threadId: session.threadId, + terminalId: session.terminalId, + terminalPid, + error: error instanceof Error ? error.message : String(error), + }).pipe(Effect.as(Option.none())), + ), + ); + + if (Option.isNone(activity)) { + return; + } + + const hasRunningSubprocess = activity.value.hasRunningSubprocess === true; + const runningPorts = hasRunningSubprocess + ? normalizeRunningPorts( + yield* detectWebPorts(normalizeRunningPorts(activity.value.runningPorts)), + ) + : []; + + const event = yield* modifyManagerState((state) => { + const liveSession: Option.Option = Option.fromNullishOr( + state.sessions.get(toSessionKey(session.threadId, session.terminalId)), + ); + if ( + Option.isNone(liveSession) || + liveSession.value.status !== "running" || + liveSession.value.pid !== terminalPid || + (liveSession.value.hasRunningSubprocess === hasRunningSubprocess && + arePortListsEqual(liveSession.value.runningSubprocessPorts, runningPorts)) + ) { + return [Option.none(), state] as const; + } + + liveSession.value.hasRunningSubprocess = hasRunningSubprocess; + liveSession.value.runningSubprocessPorts = runningPorts; + liveSession.value.updatedAt = new Date().toISOString(); + + return [ + Option.some({ + type: "activity" as const, + threadId: liveSession.value.threadId, + terminalId: liveSession.value.terminalId, + createdAt: new Date().toISOString(), + hasRunningSubprocess, + runningPorts, + }), + state, + ] as const; + }); + + if (Option.isSome(event)) { + yield* publishEvent(event.value); + } + }); + + yield* Effect.forEach(runningSessions, checkSubprocessActivity, { + concurrency: "unbounded", + discard: true, + }); + }); + + const hasRunningSessions = readManagerState.pipe( + Effect.map((state) => + [...state.sessions.values()].some((session) => session.status === "running"), + ), + ); + + yield* Effect.forever( + hasRunningSessions.pipe( + Effect.flatMap((active) => + active + ? pollSubprocessActivity().pipe( + Effect.flatMap(() => Effect.sleep(subprocessPollIntervalMs)), + ) + : Effect.sleep(subprocessPollIntervalMs), + ), + ), + ).pipe(Effect.forkIn(workerScope)); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const sessions = yield* modifyManagerState( + (state) => + [ + [...state.sessions.values()], + { + ...state, + sessions: new Map(), + }, + ] as const, + ); + + const cleanupSession = Effect.fn("terminal.cleanupSession")(function* ( + session: TerminalSessionState, + ) { + cleanupProcessHandles(session); + if (!session.process) return; + yield* clearKillFiber(session.process); + yield* runKillEscalation(session.process, session.threadId, session.terminalId); + }); + + yield* Effect.forEach(sessions, cleanupSession, { + concurrency: "unbounded", + discard: true, + }); + }).pipe(Effect.ignoreCause({ log: true })), + ); + + const open: TerminalManagerShape["open"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + yield* assertValidCwd(input.cwd); + + const sessionKey = toSessionKey(input.threadId, terminalId); + const existing = yield* getSession(input.threadId, terminalId); + if (Option.isNone(existing)) { + yield* flushPersist(input.threadId, terminalId); + const history = yield* readHistory(input.threadId, terminalId); + const cols = input.cols ?? DEFAULT_OPEN_COLS; + const rows = input.rows ?? DEFAULT_OPEN_ROWS; + const session: TerminalSessionState = { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + worktreePath: input.worktreePath ?? null, + status: "starting", + pid: null, + history, + pendingHistoryControlSequence: "", + pendingProcessEvents: [], + pendingProcessEventIndex: 0, + processEventDrainRunning: false, + exitCode: null, + exitSignal: null, + updatedAt: new Date().toISOString(), + cols, + rows, + process: null, + unsubscribeData: null, + unsubscribeExit: null, + hasRunningSubprocess: false, + runningSubprocessPorts: [], + runtimeEnv: normalizedRuntimeEnv(input.env), + }; + + const createdSession = session; + yield* modifyManagerState((state) => { + const sessions = new Map(state.sessions); + sessions.set(sessionKey, createdSession); + return [undefined, { ...state, sessions }] as const; + }); + + yield* evictInactiveSessionsIfNeeded(); + yield* startSession( + session, + { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), + cols, + rows, + ...(input.env ? { env: input.env } : {}), + }, + "started", + ); + return snapshot(session); + } + + const liveSession = existing.value; + const nextRuntimeEnv = normalizedRuntimeEnv(input.env); + const currentRuntimeEnv = liveSession.runtimeEnv; + const targetCols = input.cols ?? liveSession.cols; + const targetRows = input.rows ?? liveSession.rows; + const runtimeEnvChanged = !Equal.equals(currentRuntimeEnv, nextRuntimeEnv); + + if (liveSession.cwd !== input.cwd || runtimeEnvChanged) { + yield* stopProcess(liveSession); + liveSession.cwd = input.cwd; + liveSession.worktreePath = input.worktreePath ?? null; + liveSession.runtimeEnv = nextRuntimeEnv; + liveSession.history = ""; + liveSession.pendingHistoryControlSequence = ""; + liveSession.pendingProcessEvents = []; + liveSession.pendingProcessEventIndex = 0; + liveSession.processEventDrainRunning = false; + yield* persistHistory( + liveSession.threadId, + liveSession.terminalId, + liveSession.history, + ); + } else if (liveSession.status === "exited" || liveSession.status === "error") { + liveSession.runtimeEnv = nextRuntimeEnv; + liveSession.worktreePath = input.worktreePath ?? null; + liveSession.history = ""; + liveSession.pendingHistoryControlSequence = ""; + liveSession.pendingProcessEvents = []; + liveSession.pendingProcessEventIndex = 0; + liveSession.processEventDrainRunning = false; + yield* persistHistory( + liveSession.threadId, + liveSession.terminalId, + liveSession.history, + ); + } + + if (!liveSession.process) { + yield* startSession( + liveSession, + { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + worktreePath: liveSession.worktreePath, + cols: targetCols, + rows: targetRows, + ...(input.env ? { env: input.env } : {}), + }, + "started", + ); + return snapshot(liveSession); + } + + if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) { + liveSession.cols = targetCols; + liveSession.rows = targetRows; + liveSession.updatedAt = new Date().toISOString(); + liveSession.process.resize(targetCols, targetRows); + } + + return snapshot(liveSession); + }), + ); + + const write: TerminalManagerShape["write"] = Effect.fn("terminal.write")(function* (input) { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const session = yield* requireSession(input.threadId, terminalId); + const process = session.process; + if (!process || session.status !== "running") { + if (session.status === "exited") return; + return yield* new TerminalNotRunningError({ + threadId: input.threadId, + terminalId, + }); + } + yield* Effect.sync(() => process.write(input.data)); + }); + + const resize: TerminalManagerShape["resize"] = Effect.fn("terminal.resize")(function* (input) { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const session = yield* requireSession(input.threadId, terminalId); + const process = session.process; + if (!process || session.status !== "running") { + return yield* new TerminalNotRunningError({ + threadId: input.threadId, + terminalId, + }); + } + session.cols = input.cols; + session.rows = input.rows; + session.updatedAt = new Date().toISOString(); + yield* Effect.sync(() => process.resize(input.cols, input.rows)); + }); + + const clear: TerminalManagerShape["clear"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const session = yield* requireSession(input.threadId, terminalId); + session.history = ""; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + yield* persistHistory(input.threadId, terminalId, session.history); + yield* publishEvent({ + type: "cleared", + threadId: input.threadId, + terminalId, + createdAt: new Date().toISOString(), + }); + }), + ); + + const restart: TerminalManagerShape["restart"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + yield* increment(terminalRestartsTotal, { scope: "thread" }); + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + yield* assertValidCwd(input.cwd); + + const sessionKey = toSessionKey(input.threadId, terminalId); + const existingSession = yield* getSession(input.threadId, terminalId); + let session: TerminalSessionState; + if (Option.isNone(existingSession)) { + const cols = input.cols ?? DEFAULT_OPEN_COLS; + const rows = input.rows ?? DEFAULT_OPEN_ROWS; + session = { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + worktreePath: input.worktreePath ?? null, + status: "starting", + pid: null, + history: "", + pendingHistoryControlSequence: "", + pendingProcessEvents: [], + pendingProcessEventIndex: 0, + processEventDrainRunning: false, + exitCode: null, + exitSignal: null, + updatedAt: new Date().toISOString(), + cols, + rows, + process: null, + unsubscribeData: null, + unsubscribeExit: null, + hasRunningSubprocess: false, + runningSubprocessPorts: [], + runtimeEnv: normalizedRuntimeEnv(input.env), + }; + const createdSession = session; + yield* modifyManagerState((state) => { + const sessions = new Map(state.sessions); + sessions.set(sessionKey, createdSession); + return [undefined, { ...state, sessions }] as const; + }); + yield* evictInactiveSessionsIfNeeded(); + } else { + session = existingSession.value; + yield* stopProcess(session); + session.cwd = input.cwd; + session.worktreePath = input.worktreePath ?? null; + session.runtimeEnv = normalizedRuntimeEnv(input.env); + } + + const cols = input.cols ?? session.cols; + const rows = input.rows ?? session.rows; + + session.history = ""; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + yield* persistHistory(input.threadId, terminalId, session.history); + yield* startSession( + session, + { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), + cols, + rows, + ...(input.env ? { env: input.env } : {}), + }, + "restarted", + ); + return snapshot(session); + }), + ); + + const close: TerminalManagerShape["close"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + if (input.terminalId) { + yield* closeSession(input.threadId, input.terminalId, input.deleteHistory === true); + return; + } + + const threadSessions = yield* sessionsForThread(input.threadId); + yield* Effect.forEach( + threadSessions, + (session) => closeSession(input.threadId, session.terminalId, false), + { discard: true }, + ); + + if (input.deleteHistory) { + yield* deleteAllHistoryForThread(input.threadId); + } + }), + ); + + return { + open, + write, + resize, + clear, + restart, + close, + subscribe: (listener) => + Effect.sync(() => { + terminalEventListeners.add(listener); + return () => { + terminalEventListeners.delete(listener); + }; + }), + } satisfies TerminalManagerShape; + }, +); + +export const TerminalManagerLive = Layer.effect(TerminalManager, makeTerminalManager()); diff --git a/apps/server/src/terminal/Layers/NodePTY.test.ts b/apps/server/src/terminal/Layers/NodePTY.test.ts new file mode 100644 index 0000000000..58fcc70e4e --- /dev/null +++ b/apps/server/src/terminal/Layers/NodePTY.test.ts @@ -0,0 +1,45 @@ +import { FileSystem, Path, Effect } from "effect"; +import { assert, it } from "@effect/vitest"; + +import { ensureNodePtySpawnHelperExecutable } from "./NodePTY"; +import * as NodeServices from "@effect/platform-node/NodeServices"; + +it.layer(NodeServices.layer)("ensureNodePtySpawnHelperExecutable", (it) => { + it.effect("adds executable bits when helper exists but is not executable", () => + Effect.gen(function* () { + if (process.platform === "win32") return; + + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "pty-helper-test-" }); + const helperPath = path.join(dir, "spawn-helper"); + yield* fs.writeFileString(helperPath, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(helperPath, 0o644); + + yield* ensureNodePtySpawnHelperExecutable(helperPath); + + const mode = (yield* fs.stat(helperPath)).mode & 0o777; + assert.equal(mode & 0o111, 0o111); + }), + ); + + it.effect("keeps executable helper as executable", () => + Effect.gen(function* () { + if (process.platform === "win32") return; + + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "pty-helper-test-" }); + const helperPath = path.join(dir, "spawn-helper"); + yield* fs.writeFileString(helperPath, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(helperPath, 0o755); + + yield* ensureNodePtySpawnHelperExecutable(helperPath); + + const mode = (yield* fs.stat(helperPath)).mode & 0o777; + assert.equal(mode & 0o111, 0o111); + }), + ); +}); diff --git a/apps/server/src/terminal/Layers/NodePTY.ts b/apps/server/src/terminal/Layers/NodePTY.ts new file mode 100644 index 0000000000..cf1fdd2198 --- /dev/null +++ b/apps/server/src/terminal/Layers/NodePTY.ts @@ -0,0 +1,117 @@ +import { createRequire } from "node:module"; + +import { Effect, FileSystem, Layer, Path } from "effect"; +import { PtyAdapter, PtyAdapterShape, PtyExitEvent, PtyProcess } from "../Services/PTY"; + +let didEnsureSpawnHelperExecutable = false; + +const resolveNodePtySpawnHelperPath = Effect.gen(function* () { + const requireForNodePty = createRequire(import.meta.url); + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; + + const packageJsonPath = requireForNodePty.resolve("node-pty/package.json"); + const packageDir = path.dirname(packageJsonPath); + const candidates = [ + path.join(packageDir, "build", "Release", "spawn-helper"), + path.join(packageDir, "build", "Debug", "spawn-helper"), + path.join(packageDir, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper"), + ]; + + for (const candidate of candidates) { + if (yield* fs.exists(candidate)) { + return candidate; + } + } + return null; +}).pipe(Effect.orElseSucceed(() => null)); + +export const ensureNodePtySpawnHelperExecutable = Effect.fn(function* (explicitPath?: string) { + const fs = yield* FileSystem.FileSystem; + if (process.platform === "win32") return; + if (!explicitPath && didEnsureSpawnHelperExecutable) return; + + const helperPath = explicitPath ?? (yield* resolveNodePtySpawnHelperPath); + if (!helperPath) return; + if (!explicitPath) { + didEnsureSpawnHelperExecutable = true; + } + + if (!(yield* fs.exists(helperPath))) { + return; + } + + // Best-effort: avoid FileSystem.stat in packaged mode where some fs metadata can be missing. + yield* fs.chmod(helperPath, 0o755).pipe(Effect.orElseSucceed(() => undefined)); +}); + +class NodePtyProcess implements PtyProcess { + constructor(private readonly process: import("node-pty").IPty) {} + + get pid(): number { + return this.process.pid; + } + + write(data: string): void { + this.process.write(data); + } + + resize(cols: number, rows: number): void { + this.process.resize(cols, rows); + } + + kill(signal?: string): void { + this.process.kill(signal); + } + + onData(callback: (data: string) => void): () => void { + const disposable = this.process.onData(callback); + return () => { + disposable.dispose(); + }; + } + + onExit(callback: (event: PtyExitEvent) => void): () => void { + const disposable = this.process.onExit((event) => { + callback({ + exitCode: event.exitCode, + signal: event.signal ?? null, + }); + }); + return () => { + disposable.dispose(); + }; + } +} + +export const layer = Layer.effect( + PtyAdapter, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const nodePty = yield* Effect.promise(() => import("node-pty")); + + const ensureNodePtySpawnHelperExecutableCached = yield* Effect.cached( + ensureNodePtySpawnHelperExecutable().pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.orElseSucceed(() => undefined), + ), + ); + + return { + spawn: Effect.fn(function* (input) { + yield* ensureNodePtySpawnHelperExecutableCached; + const ptyProcess = nodePty.spawn(input.shell, input.args ?? [], { + cwd: input.cwd, + cols: input.cols, + rows: input.rows, + env: input.env, + name: globalThis.process.platform === "win32" ? "xterm-color" : "xterm-256color", + }); + return new NodePtyProcess(ptyProcess); + }), + } satisfies PtyAdapterShape; + }), +); diff --git a/apps/server/src/terminal/Services/Manager.ts b/apps/server/src/terminal/Services/Manager.ts new file mode 100644 index 0000000000..9ff4881b00 --- /dev/null +++ b/apps/server/src/terminal/Services/Manager.ts @@ -0,0 +1,128 @@ +/** + * TerminalManager - Terminal session orchestration service interface. + * + * Owns terminal lifecycle operations, output fanout, and session state + * transitions for thread-scoped terminals. + * + * @module TerminalManager + */ +import { + TerminalClearInput, + TerminalCloseInput, + TerminalEvent, + TerminalCwdError, + TerminalError, + TerminalHistoryError, + TerminalNotRunningError, + TerminalOpenInput, + TerminalResizeInput, + TerminalRestartInput, + TerminalSessionSnapshot, + TerminalSessionLookupError, + TerminalSessionStatus, + TerminalWriteInput, +} from "@t3tools/contracts"; +import { PtyProcess } from "./PTY"; +import { Effect, ServiceMap } from "effect"; + +export { + TerminalCwdError, + TerminalError, + TerminalHistoryError, + TerminalNotRunningError, + TerminalSessionLookupError, +}; + +export interface TerminalSessionState { + threadId: string; + terminalId: string; + cwd: string; + worktreePath: string | null; + status: TerminalSessionStatus; + pid: number | null; + history: string; + pendingHistoryControlSequence: string; + exitCode: number | null; + exitSignal: number | null; + updatedAt: string; + cols: number; + rows: number; + process: PtyProcess | null; + unsubscribeData: (() => void) | null; + unsubscribeExit: (() => void) | null; + hasRunningSubprocess: boolean; + runningSubprocessPorts: number[]; + runtimeEnv: Record | null; +} + +export interface ShellCandidate { + shell: string; + args?: string[]; +} + +export interface TerminalStartInput extends TerminalOpenInput { + cols: number; + rows: number; +} + +/** + * TerminalManagerShape - Service API for terminal session lifecycle operations. + */ +export interface TerminalManagerShape { + /** + * Open or attach to a terminal session. + * + * Reuses an existing session for the same thread/terminal id and restores + * persisted history on first open. + */ + readonly open: ( + input: TerminalOpenInput, + ) => Effect.Effect; + + /** + * Write input bytes to a terminal session. + */ + readonly write: (input: TerminalWriteInput) => Effect.Effect; + + /** + * Resize the PTY backing a terminal session. + */ + readonly resize: (input: TerminalResizeInput) => Effect.Effect; + + /** + * Clear terminal output history. + */ + readonly clear: (input: TerminalClearInput) => Effect.Effect; + + /** + * Restart a terminal session in place. + * + * Always resets history before spawning the new process. + */ + readonly restart: ( + input: TerminalRestartInput, + ) => Effect.Effect; + + /** + * Close an active terminal session. + * + * When `terminalId` is omitted, closes all sessions for the thread. + */ + readonly close: (input: TerminalCloseInput) => Effect.Effect; + + /** + * Subscribe to terminal runtime events with a direct callback. + * + * Returns an unsubscribe function. + */ + readonly subscribe: ( + listener: (event: TerminalEvent) => Effect.Effect, + ) => Effect.Effect<() => void>; +} + +/** + * TerminalManager - Service tag for terminal session orchestration. + */ +export class TerminalManager extends ServiceMap.Service()( + "t3/terminal/Services/Manager/TerminalManager", +) {} diff --git a/apps/server/src/terminal/Services/PTY.ts b/apps/server/src/terminal/Services/PTY.ts new file mode 100644 index 0000000000..dc164b2621 --- /dev/null +++ b/apps/server/src/terminal/Services/PTY.ts @@ -0,0 +1,58 @@ +/** + * PtyAdapter - Terminal PTY adapter service contract. + * + * Defines the process primitives required by terminal session management + * without binding to a specific PTY implementation. + * + * @module PtyAdapter + */ +import { Effect, Schema, ServiceMap } from "effect"; + +/** + * PtyError - Error type for PTY adapter operations. + */ +export class PtySpawnError extends Schema.TaggedErrorClass()("PtySpawnError", { + adapter: Schema.String, + message: Schema.String, + cause: Schema.optional(Schema.Defect), +}) {} + +export interface PtyExitEvent { + exitCode: number; + signal: number | null; +} + +export interface PtyProcess { + readonly pid: number; + write(data: string): void; + resize(cols: number, rows: number): void; + kill(signal?: string): void; + onData(callback: (data: string) => void): () => void; + onExit(callback: (event: PtyExitEvent) => void): () => void; +} + +export interface PtySpawnInput { + shell: string; + args?: string[]; + cwd: string; + cols: number; + rows: number; + env: NodeJS.ProcessEnv; +} + +/** + * PtyAdapterShape - Service API for spawning and controlling PTY processes. + */ +export interface PtyAdapterShape { + /** + * Spawn a PTY process for a terminal session. + */ + spawn(input: PtySpawnInput): Effect.Effect; +} + +/** + * PtyAdapter - Service tag for PTY process integration. + */ +export class PtyAdapter extends ServiceMap.Service()( + "t3/terminal/Services/PTY/PtyAdapter", +) {} diff --git a/apps/server/src/terminalManager.test.ts b/apps/server/src/terminalManager.test.ts deleted file mode 100644 index 7266c8cf3b..0000000000 --- a/apps/server/src/terminalManager.test.ts +++ /dev/null @@ -1,563 +0,0 @@ -import fs from "node:fs"; -import { createServer } from "node:http"; -import os from "node:os"; -import path from "node:path"; - -import { - DEFAULT_TERMINAL_ID, - type TerminalEvent, - type TerminalOpenInput, -} from "@t3tools/contracts"; -import { afterEach, describe, expect, it } from "vitest"; - -import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter"; -import { TerminalManager } from "./terminalManager"; - -class FakePtyProcess implements PtyProcess { - readonly writes: string[] = []; - readonly resizeCalls: Array<{ cols: number; rows: number }> = []; - private readonly dataListeners = new Set<(data: string) => void>(); - private readonly exitListeners = new Set<(event: PtyExitEvent) => void>(); - killed = false; - - constructor(readonly pid: number) {} - - write(data: string): void { - this.writes.push(data); - } - - resize(cols: number, rows: number): void { - this.resizeCalls.push({ cols, rows }); - } - - kill(): void { - this.killed = true; - } - - onData(callback: (data: string) => void): () => void { - this.dataListeners.add(callback); - return () => { - this.dataListeners.delete(callback); - }; - } - - onExit(callback: (event: PtyExitEvent) => void): () => void { - this.exitListeners.add(callback); - return () => { - this.exitListeners.delete(callback); - }; - } - - emitData(data: string): void { - for (const listener of this.dataListeners) { - listener(data); - } - } - - emitExit(event: PtyExitEvent): void { - for (const listener of this.exitListeners) { - listener(event); - } - } -} - -class FakePtyAdapter implements PtyAdapter { - readonly spawnInputs: PtySpawnInput[] = []; - readonly processes: FakePtyProcess[] = []; - readonly spawnFailures: Error[] = []; - private nextPid = 9000; - - spawn(input: PtySpawnInput): PtyProcess { - this.spawnInputs.push(input); - const failure = this.spawnFailures.shift(); - if (failure) { - throw failure; - } - const process = new FakePtyProcess(this.nextPid++); - this.processes.push(process); - return process; - } -} - -function waitFor(predicate: () => boolean, timeoutMs = 800): Promise { - const started = Date.now(); - return new Promise((resolve, reject) => { - const poll = () => { - if (predicate()) { - resolve(); - return; - } - if (Date.now() - started > timeoutMs) { - reject(new Error("Timed out waiting for condition")); - return; - } - setTimeout(poll, 15); - }; - poll(); - }); -} - -function openInput(overrides: Partial = {}): TerminalOpenInput { - return { - threadId: "thread-1", - cwd: process.cwd(), - cols: 100, - rows: 24, - ...overrides, - }; -} - -function historyLogName(threadId: string): string { - return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}.log`; -} - -function multiTerminalHistoryLogName(threadId: string, terminalId: string): string { - const threadPart = `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`; - if (terminalId === DEFAULT_TERMINAL_ID) { - return `${threadPart}.log`; - } - return `${threadPart}_${Buffer.from(terminalId, "utf8").toString("base64url")}.log`; -} - -function historyLogPath(logsDir: string, threadId = "thread-1"): string { - return path.join(logsDir, historyLogName(threadId)); -} - -function multiTerminalHistoryLogPath( - logsDir: string, - threadId = "thread-1", - terminalId = "default", -): string { - return path.join(logsDir, multiTerminalHistoryLogName(threadId, terminalId)); -} - -describe("TerminalManager", () => { - const tempDirs: string[] = []; - - afterEach(() => { - for (const dir of tempDirs.splice(0, tempDirs.length)) { - fs.rmSync(dir, { recursive: true, force: true }); - } - }); - - function makeManager( - historyLineLimit = 5, - options: { - shellResolver?: () => string; - subprocessChecker?: (terminalPid: number) => Promise; - subprocessInspector?: ( - terminalPid: number, - ) => Promise<{ hasRunningSubprocess: boolean; runningPorts: number[] }>; - webPortInspector?: (port: number) => Promise; - subprocessPollIntervalMs?: number; - } = {}, - ) { - const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-")); - tempDirs.push(logsDir); - const ptyAdapter = new FakePtyAdapter(); - const manager = new TerminalManager({ - logsDir, - ptyAdapter, - historyLineLimit, - shellResolver: options.shellResolver ?? (() => "/bin/bash"), - ...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}), - ...(options.subprocessInspector ? { subprocessInspector: options.subprocessInspector } : {}), - ...(options.webPortInspector ? { webPortInspector: options.webPortInspector } : {}), - ...(options.subprocessPollIntervalMs - ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs } - : {}), - }); - return { logsDir, ptyAdapter, manager }; - } - - it("spawns lazily and reuses running terminal per thread", async () => { - const { manager, ptyAdapter } = makeManager(); - const [first, second] = await Promise.all([ - manager.open(openInput()), - manager.open(openInput()), - ]); - const third = await manager.open(openInput()); - - expect(first.threadId).toBe("thread-1"); - expect(first.terminalId).toBe("default"); - expect(second.threadId).toBe("thread-1"); - expect(third.threadId).toBe("thread-1"); - expect(ptyAdapter.spawnInputs).toHaveLength(1); - - manager.dispose(); - }); - - it("forwards write and resize to active pty process", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - await manager.write({ threadId: "thread-1", data: "ls\n" }); - await manager.resize({ threadId: "thread-1", cols: 120, rows: 30 }); - - expect(process.writes).toEqual(["ls\n"]); - expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); - - manager.dispose(); - }); - - it("supports multiple terminals per thread with isolated sessions", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput({ terminalId: "default" })); - await manager.open(openInput({ terminalId: "term-2" })); - - const first = ptyAdapter.processes[0]; - const second = ptyAdapter.processes[1]; - expect(first).toBeDefined(); - expect(second).toBeDefined(); - if (!first || !second) return; - - await manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" }); - await manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" }); - - expect(first.writes).toEqual(["pwd\n"]); - expect(second.writes).toEqual(["ls\n"]); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - - manager.dispose(); - }); - - it("clears transcript and emits cleared event", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - const events: TerminalEvent[] = []; - manager.on("event", (event) => { - events.push(event); - }); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("hello\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - await manager.clear({ threadId: "thread-1" }); - await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === ""); - - expect(events.some((event) => event.type === "cleared")).toBe(true); - expect( - events.some( - (event) => - event.type === "cleared" && - event.threadId === "thread-1" && - event.terminalId === "default", - ), - ).toBe(true); - - manager.dispose(); - }); - - it("restarts terminal with empty transcript and respawns pty", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - await manager.open(openInput()); - const firstProcess = ptyAdapter.processes[0]; - expect(firstProcess).toBeDefined(); - if (!firstProcess) return; - firstProcess.emitData("before restart\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - - const snapshot = await manager.restart(openInput()); - expect(snapshot.history).toBe(""); - expect(snapshot.status).toBe("running"); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === ""); - - manager.dispose(); - }); - - it("emits exited event and reopens with clean transcript after exit", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - const events: TerminalEvent[] = []; - manager.on("event", (event) => { - events.push(event); - }); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - process.emitData("old data\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - process.emitExit({ exitCode: 0, signal: 0 }); - - await waitFor(() => events.some((event) => event.type === "exited")); - const reopened = await manager.open(openInput()); - - expect(reopened.history).toBe(""); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - expect(fs.readFileSync(historyLogPath(logsDir), "utf8")).toBe(""); - - manager.dispose(); - }); - - it("emits subprocess activity events when child-process state changes", async () => { - let activity = { - hasRunningSubprocess: false, - runningPorts: [] as number[], - }; - const { manager } = makeManager(5, { - subprocessInspector: async () => activity, - webPortInspector: async (port) => port === 3000, - subprocessPollIntervalMs: 20, - }); - const events: TerminalEvent[] = []; - manager.on("event", (event) => { - events.push(event); - }); - - await manager.open(openInput()); - await waitFor(() => events.some((event) => event.type === "started")); - expect(events.some((event) => event.type === "activity")).toBe(false); - - activity = { hasRunningSubprocess: true, runningPorts: [3000] }; - await waitFor( - () => - events.some( - (event) => - event.type === "activity" && - event.hasRunningSubprocess === true && - event.runningPorts.join(",") === "3000", - ), - 1_200, - ); - - activity = { hasRunningSubprocess: true, runningPorts: [5173] }; - await waitFor( - () => - events.some( - (event) => - event.type === "activity" && - event.hasRunningSubprocess === true && - event.runningPorts.length === 0, - ), - 1_200, - ); - - activity = { hasRunningSubprocess: false, runningPorts: [5173] }; - await waitFor( - () => - events.some( - (event) => - event.type === "activity" && - event.hasRunningSubprocess === false && - event.runningPorts.length === 0, - ), - 1_200, - ); - - manager.dispose(); - }); - - it("ignores ports that return HTTP 404 at root during web-port detection", async () => { - const notFoundServer = createServer((_req, res) => { - res.statusCode = 404; - res.end(); - }); - await new Promise((resolve, reject) => { - notFoundServer.listen(0, "127.0.0.1", (error?: Error) => { - if (error) { - reject(error); - return; - } - resolve(); - }); - }); - - const address = notFoundServer.address(); - const port = typeof address === "object" && address ? address.port : 0; - expect(port).toBeGreaterThan(0); - - const events: TerminalEvent[] = []; - let activity = { - hasRunningSubprocess: false, - runningPorts: [] as number[], - }; - const { manager } = makeManager(5, { - subprocessInspector: async () => activity, - subprocessPollIntervalMs: 20, - }); - manager.on("event", (event) => { - events.push(event); - }); - - try { - await manager.open(openInput()); - await waitFor(() => events.some((event) => event.type === "started")); - - activity = { hasRunningSubprocess: true, runningPorts: [port] }; - await waitFor( - () => - events.some( - (event) => - event.type === "activity" && - event.hasRunningSubprocess === true && - event.runningPorts.length === 0, - ), - 1_500, - ); - } finally { - manager.dispose(); - await new Promise((resolve, reject) => { - notFoundServer.close((error?: Error) => { - if (error) { - reject(error); - return; - } - resolve(); - }); - }); - } - }); - - it("caps persisted history to configured line limit", async () => { - const { manager, ptyAdapter } = makeManager(3); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("line1\nline2\nline3\nline4\n"); - await manager.close({ threadId: "thread-1" }); - - const reopened = await manager.open(openInput()); - const nonEmptyLines = reopened.history.split("\n").filter((line) => line.length > 0); - expect(nonEmptyLines).toEqual(["line2", "line3", "line4"]); - - manager.dispose(); - }); - - it("deletes history file when close(deleteHistory=true)", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - process.emitData("bye\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - - await manager.close({ threadId: "thread-1", deleteHistory: true }); - expect(fs.existsSync(historyLogPath(logsDir))).toBe(false); - - manager.dispose(); - }); - - it("closes all terminals for a thread when close omits terminalId", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - await manager.open(openInput({ terminalId: "default" })); - await manager.open(openInput({ terminalId: "sidecar" })); - const defaultProcess = ptyAdapter.processes[0]; - const sidecarProcess = ptyAdapter.processes[1]; - expect(defaultProcess).toBeDefined(); - expect(sidecarProcess).toBeDefined(); - if (!defaultProcess || !sidecarProcess) return; - - defaultProcess.emitData("default\n"); - sidecarProcess.emitData("sidecar\n"); - await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))); - await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))); - - await manager.close({ threadId: "thread-1", deleteHistory: true }); - - expect(defaultProcess.killed).toBe(true); - expect(sidecarProcess.killed).toBe(true); - expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(false); - expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(false); - - manager.dispose(); - }); - - it("migrates legacy transcript filenames to terminal-scoped history path on open", async () => { - const { manager, logsDir } = makeManager(); - const legacyPath = path.join(logsDir, "thread-1.log"); - const nextPath = historyLogPath(logsDir); - fs.writeFileSync(legacyPath, "legacy-line\n", "utf8"); - - const snapshot = await manager.open(openInput()); - - expect(snapshot.history).toBe("legacy-line\n"); - expect(fs.existsSync(nextPath)).toBe(true); - expect(fs.readFileSync(nextPath, "utf8")).toBe("legacy-line\n"); - expect(fs.existsSync(legacyPath)).toBe(false); - - manager.dispose(); - }); - - it("retries with fallback shells when preferred shell spawn fails", async () => { - const { manager, ptyAdapter } = makeManager(5, { - shellResolver: () => "/definitely/missing-shell -l", - }); - ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed.")); - - const snapshot = await manager.open(openInput()); - - expect(snapshot.status).toBe("running"); - expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2); - expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell"); - - if (process.platform === "win32") { - expect( - ptyAdapter.spawnInputs.some( - (input) => input.shell === "cmd.exe" || input.shell === "powershell.exe", - ), - ).toBe(true); - } else { - expect( - ptyAdapter.spawnInputs.some((input) => - ["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(input.shell), - ), - ).toBe(true); - } - - manager.dispose(); - }); - - it("filters app runtime env variables from terminal sessions", async () => { - const originalValues = new Map(); - const setEnv = (key: string, value: string | undefined) => { - if (!originalValues.has(key)) { - originalValues.set(key, process.env[key]); - } - if (value === undefined) { - delete process.env[key]; - return; - } - process.env[key] = value; - }; - const restoreEnv = () => { - for (const [key, value] of originalValues) { - if (value === undefined) { - delete process.env[key]; - } else { - process.env[key] = value; - } - } - }; - - setEnv("PORT", "5173"); - setEnv("T3CODE_PORT", "3773"); - setEnv("VITE_DEV_SERVER_URL", "http://localhost:5173"); - setEnv("TEST_TERMINAL_KEEP", "keep-me"); - - try { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const spawnInput = ptyAdapter.spawnInputs[0]; - expect(spawnInput).toBeDefined(); - if (!spawnInput) return; - - expect(spawnInput.env.PORT).toBeUndefined(); - expect(spawnInput.env.T3CODE_PORT).toBeUndefined(); - expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined(); - expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me"); - - manager.dispose(); - } finally { - restoreEnv(); - } - }); -}); diff --git a/apps/server/src/terminalManager.ts b/apps/server/src/terminalManager.ts deleted file mode 100644 index cba76392e7..0000000000 --- a/apps/server/src/terminalManager.ts +++ /dev/null @@ -1,985 +0,0 @@ -import { EventEmitter } from "node:events"; -import fs from "node:fs"; -import path from "node:path"; - -import { - DEFAULT_TERMINAL_ID, - type TerminalClearInput, - type TerminalCloseInput, - type TerminalEvent, - type TerminalOpenInput, - type TerminalResizeInput, - type TerminalSessionSnapshot, - type TerminalSessionStatus, - type TerminalWriteInput, - terminalClearInputSchema, - terminalCloseInputSchema, - terminalOpenInputSchema, - terminalResizeInputSchema, - terminalWriteInputSchema, -} from "@t3tools/contracts"; - -import { createLogger } from "./logger"; -import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter"; -import { - arePortListsEqual, - defaultSubprocessInspector, - normalizeRunningPorts, - subprocessCheckerToInspector, - type TerminalSubprocessActivity, - type TerminalSubprocessChecker, - type TerminalSubprocessInspector, - type TerminalWebPortInspector, -} from "./terminalProcessInspector"; -import { DEFAULT_WEB_PORT_PROBE_TTL_MS, defaultWebPortInspector } from "./webPortInspector"; - -const DEFAULT_HISTORY_LINE_LIMIT = 5_000; -const DEFAULT_PERSIST_DEBOUNCE_MS = 40; -const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000; -const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]); - -export interface TerminalManagerEvents { - event: [event: TerminalEvent]; -} - -export interface TerminalManagerOptions { - logsDir?: string; - historyLineLimit?: number; - ptyAdapter?: PtyAdapter; - shellResolver?: () => string; - subprocessChecker?: TerminalSubprocessChecker; - subprocessInspector?: TerminalSubprocessInspector; - webPortInspector?: TerminalWebPortInspector; - webPortProbeCacheTtlMs?: number; - subprocessPollIntervalMs?: number; -} - -interface TerminalSessionState { - threadId: string; - terminalId: string; - cwd: string; - status: TerminalSessionStatus; - pid: number | null; - history: string; - exitCode: number | null; - exitSignal: number | null; - updatedAt: string; - cols: number; - rows: number; - process: PtyProcess | null; - unsubscribeData: (() => void) | null; - unsubscribeExit: (() => void) | null; - hasRunningSubprocess: boolean; - runningSubprocessPorts: number[]; -} - -function defaultShellResolver(): string { - if (process.platform === "win32") { - return process.env.ComSpec ?? "cmd.exe"; - } - return process.env.SHELL ?? "bash"; -} - -function normalizeShellCommand(value: string | undefined): string | null { - if (!value) return null; - const trimmed = value.trim(); - if (trimmed.length === 0) return null; - - if (process.platform === "win32") { - return trimmed; - } - - const firstToken = trimmed.split(/\s+/g)[0]?.trim(); - if (!firstToken) return null; - return firstToken.replace(/^['"]|['"]$/g, ""); -} - -function uniqueShells(shells: Array): string[] { - const seen = new Set(); - const ordered: string[] = []; - for (const shell of shells) { - if (!shell || shell.length === 0) continue; - if (seen.has(shell)) continue; - seen.add(shell); - ordered.push(shell); - } - return ordered; -} - -function resolveShellCandidates(shellResolver: () => string): string[] { - const requested = normalizeShellCommand(shellResolver()); - - if (process.platform === "win32") { - return uniqueShells([requested, process.env.ComSpec ?? null, "powershell.exe", "cmd.exe"]); - } - - return uniqueShells([ - requested, - normalizeShellCommand(process.env.SHELL), - "/bin/zsh", - "/bin/bash", - "/bin/sh", - "zsh", - "bash", - "sh", - ]); -} - -function isRetryableShellSpawnError(error: unknown): boolean { - if (!(error instanceof Error)) return false; - const message = error.message.toLowerCase(); - return ( - message.includes("posix_spawnp failed") || - message.includes("enoent") || - message.includes("not found") || - message.includes("file not found") || - message.includes("no such file") - ); -} - -function capHistory(history: string, maxLines: number): string { - if (history.length === 0) return history; - const hasTrailingNewline = history.endsWith("\n"); - const lines = history.split("\n"); - if (hasTrailingNewline) { - lines.pop(); - } - if (lines.length <= maxLines) return history; - const capped = lines.slice(lines.length - maxLines).join("\n"); - return hasTrailingNewline ? `${capped}\n` : capped; -} - -function legacySafeThreadId(threadId: string): string { - return threadId.replace(/[^a-zA-Z0-9._-]/g, "_"); -} - -function toSafeThreadId(threadId: string): string { - return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`; -} - -function toSafeTerminalId(terminalId: string): string { - return Buffer.from(terminalId, "utf8").toString("base64url"); -} - -function toSessionKey(threadId: string, terminalId: string): string { - return `${threadId}\u0000${terminalId}`; -} - -function shouldExcludeTerminalEnvKey(key: string): boolean { - const normalizedKey = key.toUpperCase(); - if (normalizedKey.startsWith("T3CODE_")) { - return true; - } - if (normalizedKey.startsWith("VITE_")) { - return true; - } - return TERMINAL_ENV_BLOCKLIST.has(normalizedKey); -} - -function createTerminalSpawnEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv { - const spawnEnv: NodeJS.ProcessEnv = {}; - for (const [key, value] of Object.entries(baseEnv)) { - if (value === undefined) continue; - if (shouldExcludeTerminalEnvKey(key)) continue; - spawnEnv[key] = value; - } - return spawnEnv; -} - -export class TerminalManager extends EventEmitter { - private readonly sessions = new Map(); - private readonly logsDir: string; - private readonly historyLineLimit: number; - private readonly ptyAdapter: PtyAdapter; - private readonly shellResolver: () => string; - private readonly persistQueues = new Map>(); - private readonly persistTimers = new Map>(); - private readonly pendingPersistHistory = new Map(); - private readonly threadLocks = new Map>(); - private readonly persistDebounceMs: number; - private readonly subprocessInspector: TerminalSubprocessInspector; - private readonly webPortInspector: TerminalWebPortInspector; - private readonly webPortProbeCacheTtlMs: number; - private readonly webPortProbeCache = new Map< - number, - { isWeb: boolean; checkedAt: number } - >(); - private readonly webPortProbeInFlight = new Map>(); - private readonly subprocessPollIntervalMs: number; - private subprocessPollTimer: ReturnType | null = null; - private subprocessPollInFlight = false; - private readonly logger = createLogger("terminal"); - - constructor(options: TerminalManagerOptions = {}) { - super(); - this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals"); - this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; - this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter(); - this.shellResolver = options.shellResolver ?? defaultShellResolver; - this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS; - this.subprocessInspector = - options.subprocessInspector ?? - (options.subprocessChecker - ? subprocessCheckerToInspector(options.subprocessChecker) - : defaultSubprocessInspector); - this.webPortInspector = options.webPortInspector ?? defaultWebPortInspector; - this.webPortProbeCacheTtlMs = - options.webPortProbeCacheTtlMs ?? DEFAULT_WEB_PORT_PROBE_TTL_MS; - this.subprocessPollIntervalMs = - options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS; - fs.mkdirSync(this.logsDir, { recursive: true }); - } - - async open(raw: TerminalOpenInput): Promise { - const input = terminalOpenInputSchema.parse(raw); - return this.runWithThreadLock(input.threadId, async () => { - await this.assertValidCwd(input.cwd); - - const sessionKey = toSessionKey(input.threadId, input.terminalId); - const existing = this.sessions.get(sessionKey); - if (!existing) { - await this.flushPersistQueue(input.threadId, input.terminalId); - const history = await this.readHistory(input.threadId, input.terminalId); - const session: TerminalSessionState = { - threadId: input.threadId, - terminalId: input.terminalId, - cwd: input.cwd, - status: "starting", - pid: null, - history, - exitCode: null, - exitSignal: null, - updatedAt: new Date().toISOString(), - cols: input.cols, - rows: input.rows, - process: null, - unsubscribeData: null, - unsubscribeExit: null, - hasRunningSubprocess: false, - runningSubprocessPorts: [], - }; - this.sessions.set(sessionKey, session); - this.startSession(session, input, "started"); - return this.snapshot(session); - } - - if (existing.cwd !== input.cwd) { - this.stopProcess(existing); - existing.cwd = input.cwd; - existing.history = ""; - await this.persistHistory(existing.threadId, existing.terminalId, existing.history); - } else if (existing.status === "exited" || existing.status === "error") { - existing.history = ""; - await this.persistHistory(existing.threadId, existing.terminalId, existing.history); - } - - if (!existing.process) { - this.startSession(existing, input, "started"); - return this.snapshot(existing); - } - - if (existing.cols !== input.cols || existing.rows !== input.rows) { - existing.cols = input.cols; - existing.rows = input.rows; - existing.process.resize(input.cols, input.rows); - existing.updatedAt = new Date().toISOString(); - } - - return this.snapshot(existing); - }); - } - - async write(raw: TerminalWriteInput): Promise { - const input = terminalWriteInputSchema.parse(raw); - const session = this.requireSession(input.threadId, input.terminalId); - if (!session.process || session.status !== "running") { - throw new Error( - `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`, - ); - } - session.process.write(input.data); - } - - async resize(raw: TerminalResizeInput): Promise { - const input = terminalResizeInputSchema.parse(raw); - const session = this.requireSession(input.threadId, input.terminalId); - if (!session.process || session.status !== "running") { - throw new Error( - `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`, - ); - } - session.cols = input.cols; - session.rows = input.rows; - session.updatedAt = new Date().toISOString(); - session.process.resize(input.cols, input.rows); - } - - async clear(raw: TerminalClearInput): Promise { - const input = terminalClearInputSchema.parse(raw); - await this.runWithThreadLock(input.threadId, async () => { - const session = this.requireSession(input.threadId, input.terminalId); - session.history = ""; - session.updatedAt = new Date().toISOString(); - await this.persistHistory(input.threadId, input.terminalId, session.history); - this.emitEvent({ - type: "cleared", - threadId: input.threadId, - terminalId: input.terminalId, - createdAt: new Date().toISOString(), - }); - }); - } - - async restart(raw: TerminalOpenInput): Promise { - const input = terminalOpenInputSchema.parse(raw); - return this.runWithThreadLock(input.threadId, async () => { - await this.assertValidCwd(input.cwd); - - const sessionKey = toSessionKey(input.threadId, input.terminalId); - let session = this.sessions.get(sessionKey); - if (!session) { - session = { - threadId: input.threadId, - terminalId: input.terminalId, - cwd: input.cwd, - status: "starting", - pid: null, - history: "", - exitCode: null, - exitSignal: null, - updatedAt: new Date().toISOString(), - cols: input.cols, - rows: input.rows, - process: null, - unsubscribeData: null, - unsubscribeExit: null, - hasRunningSubprocess: false, - runningSubprocessPorts: [], - }; - this.sessions.set(sessionKey, session); - } else { - this.stopProcess(session); - session.cwd = input.cwd; - } - - session.history = ""; - await this.persistHistory(input.threadId, input.terminalId, session.history); - this.startSession(session, input, "restarted"); - return this.snapshot(session); - }); - } - - async close(raw: TerminalCloseInput): Promise { - const input = terminalCloseInputSchema.parse(raw); - await this.runWithThreadLock(input.threadId, async () => { - if (input.terminalId) { - await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true); - return; - } - - const threadSessions = this.sessionsForThread(input.threadId); - for (const session of threadSessions) { - this.stopProcess(session); - this.sessions.delete(toSessionKey(session.threadId, session.terminalId)); - } - await Promise.all( - threadSessions.map((session) => - this.flushPersistQueue(session.threadId, session.terminalId), - ), - ); - - if (input.deleteHistory) { - await this.deleteAllHistoryForThread(input.threadId); - } - this.updateSubprocessPollingState(); - }); - } - - dispose(): void { - this.stopSubprocessPolling(); - const sessions = [...this.sessions.values()]; - this.sessions.clear(); - for (const session of sessions) { - this.stopProcess(session); - } - for (const timer of this.persistTimers.values()) { - clearTimeout(timer); - } - this.persistTimers.clear(); - this.pendingPersistHistory.clear(); - this.threadLocks.clear(); - this.persistQueues.clear(); - this.webPortProbeCache.clear(); - this.webPortProbeInFlight.clear(); - } - - private startSession( - session: TerminalSessionState, - input: TerminalOpenInput, - eventType: "started" | "restarted", - ): void { - this.stopProcess(session); - - session.status = "starting"; - session.cwd = input.cwd; - session.cols = input.cols; - session.rows = input.rows; - session.exitCode = null; - session.exitSignal = null; - session.hasRunningSubprocess = false; - session.runningSubprocessPorts = []; - session.updatedAt = new Date().toISOString(); - - let ptyProcess: PtyProcess | null = null; - let startedShell: string | null = null; - try { - const shellCandidates = resolveShellCandidates(this.shellResolver); - const terminalEnv = createTerminalSpawnEnv(process.env); - let lastSpawnError: unknown = null; - - for (const shell of shellCandidates) { - try { - ptyProcess = this.ptyAdapter.spawn({ - shell, - cwd: session.cwd, - cols: session.cols, - rows: session.rows, - env: terminalEnv, - }); - startedShell = shell; - break; - } catch (error) { - lastSpawnError = error; - if (!isRetryableShellSpawnError(error)) { - throw error; - } - } - } - - if (!ptyProcess) { - const detail = - lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed"; - const tried = - shellCandidates.length > 0 ? ` Tried shells: ${shellCandidates.join(", ")}.` : ""; - throw new Error(`${detail}.${tried}`.trim()); - } - - session.process = ptyProcess; - session.pid = ptyProcess.pid; - session.status = "running"; - session.updatedAt = new Date().toISOString(); - session.unsubscribeData = ptyProcess.onData((data) => { - this.onProcessData(session, data); - }); - session.unsubscribeExit = ptyProcess.onExit((event) => { - this.onProcessExit(session, event); - }); - this.updateSubprocessPollingState(); - this.emitEvent({ - type: eventType, - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - snapshot: this.snapshot(session), - }); - } catch (error) { - if (ptyProcess) { - try { - ptyProcess.kill(); - } catch { - // Ignore kill errors during failed startup cleanup. - } - } - session.status = "error"; - session.pid = null; - session.process = null; - session.hasRunningSubprocess = false; - session.runningSubprocessPorts = []; - session.updatedAt = new Date().toISOString(); - this.updateSubprocessPollingState(); - const message = error instanceof Error ? error.message : "Terminal start failed"; - this.emitEvent({ - type: "error", - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - message, - }); - this.logger.error("failed to start terminal", { - threadId: session.threadId, - terminalId: session.terminalId, - error: message, - ...(startedShell ? { shell: startedShell } : {}), - }); - } - } - - private onProcessData(session: TerminalSessionState, data: string): void { - session.history = capHistory(`${session.history}${data}`, this.historyLineLimit); - session.updatedAt = new Date().toISOString(); - this.queuePersist(session.threadId, session.terminalId, session.history); - this.emitEvent({ - type: "output", - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - data, - }); - } - - private onProcessExit(session: TerminalSessionState, event: PtyExitEvent): void { - this.cleanupProcessHandles(session); - session.process = null; - session.pid = null; - session.hasRunningSubprocess = false; - session.runningSubprocessPorts = []; - session.status = "exited"; - session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null; - session.exitSignal = Number.isInteger(event.signal) ? event.signal : null; - session.updatedAt = new Date().toISOString(); - this.emitEvent({ - type: "exited", - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - exitCode: session.exitCode, - exitSignal: session.exitSignal, - }); - this.updateSubprocessPollingState(); - } - - private stopProcess(session: TerminalSessionState): void { - const process = session.process; - if (!process) return; - this.cleanupProcessHandles(session); - session.process = null; - session.pid = null; - session.hasRunningSubprocess = false; - session.runningSubprocessPorts = []; - session.status = "exited"; - session.updatedAt = new Date().toISOString(); - try { - process.kill(); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - this.logger.warn("failed to kill terminal process", { - threadId: session.threadId, - terminalId: session.terminalId, - error: message, - }); - } - this.updateSubprocessPollingState(); - } - - private cleanupProcessHandles(session: TerminalSessionState): void { - session.unsubscribeData?.(); - session.unsubscribeData = null; - session.unsubscribeExit?.(); - session.unsubscribeExit = null; - } - - private queuePersist(threadId: string, terminalId: string, history: string): void { - const persistenceKey = toSessionKey(threadId, terminalId); - this.pendingPersistHistory.set(persistenceKey, history); - this.schedulePersist(threadId, terminalId); - } - - private async persistHistory( - threadId: string, - terminalId: string, - history: string, - ): Promise { - const persistenceKey = toSessionKey(threadId, terminalId); - this.clearPersistTimer(threadId, terminalId); - this.pendingPersistHistory.delete(persistenceKey); - await this.enqueuePersistWrite(threadId, terminalId, history); - } - - private enqueuePersistWrite( - threadId: string, - terminalId: string, - history: string, - ): Promise { - const persistenceKey = toSessionKey(threadId, terminalId); - const task = async () => { - await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8"); - }; - const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve(); - const next = previous - .catch(() => undefined) - .then(task) - .catch((error) => { - this.logger.warn("failed to persist terminal history", { - threadId, - terminalId, - error: error instanceof Error ? error.message : String(error), - }); - }); - this.persistQueues.set(persistenceKey, next); - const finalized = next.finally(() => { - if (this.persistQueues.get(persistenceKey) === next) { - this.persistQueues.delete(persistenceKey); - } - if ( - this.pendingPersistHistory.has(persistenceKey) && - !this.persistTimers.has(persistenceKey) - ) { - this.schedulePersist(threadId, terminalId); - } - }); - void finalized.catch(() => undefined); - return finalized; - } - - private schedulePersist(threadId: string, terminalId: string): void { - const persistenceKey = toSessionKey(threadId, terminalId); - if (this.persistTimers.has(persistenceKey)) return; - const timer = setTimeout(() => { - this.persistTimers.delete(persistenceKey); - const pendingHistory = this.pendingPersistHistory.get(persistenceKey); - if (pendingHistory === undefined) return; - this.pendingPersistHistory.delete(persistenceKey); - void this.enqueuePersistWrite(threadId, terminalId, pendingHistory); - }, this.persistDebounceMs); - this.persistTimers.set(persistenceKey, timer); - } - - private clearPersistTimer(threadId: string, terminalId: string): void { - const persistenceKey = toSessionKey(threadId, terminalId); - const timer = this.persistTimers.get(persistenceKey); - if (!timer) return; - clearTimeout(timer); - this.persistTimers.delete(persistenceKey); - } - - private async readHistory(threadId: string, terminalId: string): Promise { - const nextPath = this.historyPath(threadId, terminalId); - try { - const raw = await fs.promises.readFile(nextPath, "utf8"); - const capped = capHistory(raw, this.historyLineLimit); - if (capped !== raw) { - await fs.promises.writeFile(nextPath, capped, "utf8"); - } - return capped; - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") { - throw error; - } - } - - if (terminalId !== DEFAULT_TERMINAL_ID) { - return ""; - } - - const legacyPath = this.legacyHistoryPath(threadId); - try { - const raw = await fs.promises.readFile(legacyPath, "utf8"); - const capped = capHistory(raw, this.historyLineLimit); - - // Migrate legacy transcript filename to the terminal-scoped path. - await fs.promises.writeFile(nextPath, capped, "utf8"); - try { - await fs.promises.rm(legacyPath, { force: true }); - } catch (cleanupError) { - this.logger.warn("failed to remove legacy terminal history", { - threadId, - error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), - }); - } - - return capped; - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - return ""; - } - throw error; - } - } - - private async deleteHistory(threadId: string, terminalId: string): Promise { - const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })]; - if (terminalId === DEFAULT_TERMINAL_ID) { - deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true })); - } - try { - await Promise.all(deletions); - } catch (error) { - this.logger.warn("failed to delete terminal history", { - threadId, - terminalId, - error: error instanceof Error ? error.message : String(error), - }); - } - } - - private async flushPersistQueue(threadId: string, terminalId: string): Promise { - const persistenceKey = toSessionKey(threadId, terminalId); - this.clearPersistTimer(threadId, terminalId); - - while (true) { - const pendingHistory = this.pendingPersistHistory.get(persistenceKey); - if (pendingHistory !== undefined) { - this.pendingPersistHistory.delete(persistenceKey); - await this.enqueuePersistWrite(threadId, terminalId, pendingHistory); - } - - const pending = this.persistQueues.get(persistenceKey); - if (!pending) { - return; - } - await pending.catch(() => undefined); - } - } - - private updateSubprocessPollingState(): void { - const hasRunningSessions = [...this.sessions.values()].some( - (session) => session.status === "running" && session.pid !== null, - ); - if (hasRunningSessions) { - this.ensureSubprocessPolling(); - return; - } - this.stopSubprocessPolling(); - } - - private ensureSubprocessPolling(): void { - if (this.subprocessPollTimer) return; - this.subprocessPollTimer = setInterval(() => { - void this.pollSubprocessActivity(); - }, this.subprocessPollIntervalMs); - this.subprocessPollTimer.unref?.(); - void this.pollSubprocessActivity(); - } - - private stopSubprocessPolling(): void { - if (!this.subprocessPollTimer) return; - clearInterval(this.subprocessPollTimer); - this.subprocessPollTimer = null; - } - - private async inspectWebPortCached(port: number): Promise { - const now = Date.now(); - const cached = this.webPortProbeCache.get(port); - if (cached && now - cached.checkedAt <= this.webPortProbeCacheTtlMs) { - return cached.isWeb; - } - - const inFlight = this.webPortProbeInFlight.get(port); - if (inFlight) { - return inFlight; - } - - const probe = this.webPortInspector(port) - .then((isWeb) => { - this.webPortProbeCache.set(port, { - isWeb, - checkedAt: Date.now(), - }); - return isWeb; - }) - .catch(() => false) - .finally(() => { - this.webPortProbeInFlight.delete(port); - }); - this.webPortProbeInFlight.set(port, probe); - return probe; - } - - private async detectWebPorts(runningPorts: number[]): Promise { - if (runningPorts.length === 0) return []; - const checks = await Promise.all( - runningPorts.map(async (port) => ({ - port, - isWeb: await this.inspectWebPortCached(port), - })), - ); - return checks - .filter((entry) => entry.isWeb) - .map((entry) => entry.port) - .toSorted((left, right) => left - right); - } - - private async pollSubprocessActivity(): Promise { - if (this.subprocessPollInFlight) return; - - const runningSessions = [...this.sessions.values()].filter( - (session): session is TerminalSessionState & { pid: number } => - session.status === "running" && Number.isInteger(session.pid), - ); - if (runningSessions.length === 0) { - this.stopSubprocessPolling(); - return; - } - - this.subprocessPollInFlight = true; - try { - await Promise.all( - runningSessions.map(async (session) => { - const terminalPid = session.pid; - let activity: TerminalSubprocessActivity = { - hasRunningSubprocess: false, - runningPorts: [], - }; - try { - activity = await this.subprocessInspector(terminalPid); - } catch (error) { - this.logger.warn("failed to check terminal subprocess activity", { - threadId: session.threadId, - terminalId: session.terminalId, - terminalPid, - error: error instanceof Error ? error.message : String(error), - }); - return; - } - - const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId)); - if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) { - return; - } - const hasRunningSubprocess = activity.hasRunningSubprocess === true; - const runningPorts = hasRunningSubprocess - ? normalizeRunningPorts( - await this.detectWebPorts(normalizeRunningPorts(activity.runningPorts)), - ) - : []; - if ( - liveSession.hasRunningSubprocess === hasRunningSubprocess && - arePortListsEqual(liveSession.runningSubprocessPorts, runningPorts) - ) { - return; - } - - liveSession.hasRunningSubprocess = hasRunningSubprocess; - liveSession.runningSubprocessPorts = runningPorts; - liveSession.updatedAt = new Date().toISOString(); - this.emitEvent({ - type: "activity", - threadId: liveSession.threadId, - terminalId: liveSession.terminalId, - createdAt: new Date().toISOString(), - hasRunningSubprocess, - runningPorts, - }); - }), - ); - } finally { - this.subprocessPollInFlight = false; - } - } - - private async assertValidCwd(cwd: string): Promise { - let stats: fs.Stats; - try { - stats = await fs.promises.stat(cwd); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - throw new Error(`Terminal cwd does not exist: ${cwd}`, { cause: error }); - } - throw error; - } - if (!stats.isDirectory()) { - throw new Error(`Terminal cwd is not a directory: ${cwd}`); - } - } - - private async closeSession( - threadId: string, - terminalId: string, - deleteHistory: boolean, - ): Promise { - const key = toSessionKey(threadId, terminalId); - const session = this.sessions.get(key); - if (session) { - this.stopProcess(session); - this.sessions.delete(key); - } - this.updateSubprocessPollingState(); - await this.flushPersistQueue(threadId, terminalId); - if (deleteHistory) { - await this.deleteHistory(threadId, terminalId); - } - } - - private sessionsForThread(threadId: string): TerminalSessionState[] { - return [...this.sessions.values()].filter((session) => session.threadId === threadId); - } - - private async deleteAllHistoryForThread(threadId: string): Promise { - const threadPrefix = `${toSafeThreadId(threadId)}_`; - try { - const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true }); - const removals = entries - .filter((entry) => entry.isFile()) - .map((entry) => entry.name) - .filter( - (name) => - name === `${toSafeThreadId(threadId)}.log` || - name === `${legacySafeThreadId(threadId)}.log` || - name.startsWith(threadPrefix), - ) - .map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true })); - await Promise.all(removals); - } catch (error) { - this.logger.warn("failed to delete terminal histories for thread", { - threadId, - error: error instanceof Error ? error.message : String(error), - }); - } - } - - private requireSession(threadId: string, terminalId: string): TerminalSessionState { - const session = this.sessions.get(toSessionKey(threadId, terminalId)); - if (!session) { - throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`); - } - return session; - } - - private snapshot(session: TerminalSessionState): TerminalSessionSnapshot { - return { - threadId: session.threadId, - terminalId: session.terminalId, - cwd: session.cwd, - status: session.status, - pid: session.pid, - history: session.history, - exitCode: session.exitCode, - exitSignal: session.exitSignal, - updatedAt: session.updatedAt, - }; - } - - private emitEvent(event: TerminalEvent): void { - this.emit("event", event); - } - - private historyPath(threadId: string, terminalId: string): string { - const threadPart = toSafeThreadId(threadId); - if (terminalId === DEFAULT_TERMINAL_ID) { - return path.join(this.logsDir, `${threadPart}.log`); - } - return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`); - } - - private legacyHistoryPath(threadId: string): string { - return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`); - } - - private async runWithThreadLock(threadId: string, task: () => Promise): Promise { - const previous = this.threadLocks.get(threadId) ?? Promise.resolve(); - let release: () => void = () => {}; - const current = new Promise((resolve) => { - release = resolve; - }); - this.threadLocks.set(threadId, current); - await previous.catch(() => undefined); - try { - return await task(); - } finally { - release(); - if (this.threadLocks.get(threadId) === current) { - this.threadLocks.delete(threadId); - } - } - } -} diff --git a/apps/server/src/terminalProcessInspector/index.test.ts b/apps/server/src/terminalProcessInspector/index.test.ts index d01a641068..248b8bd2bf 100644 --- a/apps/server/src/terminalProcessInspector/index.test.ts +++ b/apps/server/src/terminalProcessInspector/index.test.ts @@ -1,15 +1,18 @@ -import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; +import { spawn, type ChildProcess, type ChildProcessByStdio } from "node:child_process"; +import type { Readable } from "node:stream"; import { afterEach, describe, expect, it } from "vitest"; import { defaultSubprocessInspector } from "./index"; +type ListenerProcess = ChildProcessByStdio; + interface StartedProcess { - process: ChildProcessWithoutNullStreams; + process: ListenerProcess; port: number; } -async function waitForPort(child: ChildProcessWithoutNullStreams): Promise { +async function waitForPort(child: ListenerProcess): Promise { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { cleanup(); @@ -80,7 +83,7 @@ async function startListenerProcess(): Promise { return { process, port }; } -async function stopProcess(child: ChildProcessWithoutNullStreams): Promise { +async function stopProcess(child: ChildProcess): Promise { if (child.exitCode !== null || child.signalCode !== null) { return; } @@ -100,7 +103,7 @@ async function stopProcess(child: ChildProcessWithoutNullStreams): Promise } describe("defaultSubprocessInspector", () => { - const spawned: ChildProcessWithoutNullStreams[] = []; + const spawned: ChildProcess[] = []; afterEach(async () => { await Promise.all(spawned.splice(0, spawned.length).map((child) => stopProcess(child))); @@ -109,8 +112,12 @@ describe("defaultSubprocessInspector", () => { it("detects listening ports when the terminal root PID is the listener", async () => { const listener = await startListenerProcess(); spawned.push(listener.process); + const listenerPid = listener.process.pid; + if (!listenerPid) { + throw new Error("Listener process pid missing"); + } - const activity = await defaultSubprocessInspector(listener.process.pid); + const activity = await defaultSubprocessInspector(listenerPid); expect(activity.hasRunningSubprocess).toBe(true); expect(activity.runningPorts).toContain(listener.port); @@ -121,8 +128,12 @@ describe("defaultSubprocessInspector", () => { stdio: ["ignore", "ignore", "ignore"], }); spawned.push(idle); + const idlePid = idle.pid; + if (!idlePid) { + throw new Error("Idle process pid missing"); + } - const activity = await defaultSubprocessInspector(idle.pid); + const activity = await defaultSubprocessInspector(idlePid); expect(activity.hasRunningSubprocess).toBe(false); expect(activity.runningPorts).toEqual([]); diff --git a/apps/server/src/terminalProcessInspector/index.ts b/apps/server/src/terminalProcessInspector/index.ts index 54f25311bb..21871d5b8a 100644 --- a/apps/server/src/terminalProcessInspector/index.ts +++ b/apps/server/src/terminalProcessInspector/index.ts @@ -7,10 +7,7 @@ import { } from "./types"; import { checkWindowsListeningPorts, collectWindowsChildPids } from "./win32"; -export { - arePortListsEqual, - normalizeRunningPorts, -} from "./utils"; +export { arePortListsEqual, normalizeRunningPorts } from "./utils"; export type { TerminalSubprocessActivity, diff --git a/apps/server/src/terminalProcessInspector/win32.ts b/apps/server/src/terminalProcessInspector/win32.ts index 0469b392b0..a0f5b99110 100644 --- a/apps/server/src/terminalProcessInspector/win32.ts +++ b/apps/server/src/terminalProcessInspector/win32.ts @@ -30,9 +30,7 @@ export async function collectWindowsChildPids(terminalPid: number): Promise { if (processIds.length === 0) return []; - const processFilter = processIds - .map((pid) => `$_.OwningProcess -eq ${pid}`) - .join(" -or "); + const processFilter = processIds.map((pid) => `$_.OwningProcess -eq ${pid}`).join(" -or "); const command = [ "$connections = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue", `$matching = $connections | Where-Object { ${processFilter} }`, diff --git a/apps/server/src/webPortInspector.test.ts b/apps/server/src/webPortInspector.test.ts index 5f2d0203aa..791a6bbf71 100644 --- a/apps/server/src/webPortInspector.test.ts +++ b/apps/server/src/webPortInspector.test.ts @@ -58,7 +58,9 @@ describe("defaultWebPortInspector", () => { const server = createServer((_req, res) => { res.statusCode = 200; res.setHeader("content-type", "text/html; charset=utf-8"); - res.end(`x${"x".repeat(20_000)}`); + res.end( + `x${"x".repeat(20_000)}`, + ); }); servers.push(server); const port = await listenServer(server); diff --git a/apps/server/src/webPortInspector.ts b/apps/server/src/webPortInspector.ts index 038042e3fa..80bc034b4f 100644 --- a/apps/server/src/webPortInspector.ts +++ b/apps/server/src/webPortInspector.ts @@ -28,17 +28,10 @@ function isLikelyWebProbe(result: WebProbeResult | null): boolean { return true; } const body = result.body.toLowerCase(); - return ( - body.includes(" { +async function probeWebPortOnHost(port: number, host: string): Promise { return new Promise((resolve) => { let timer: ReturnType | null = null; let settled = false; diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts new file mode 100644 index 0000000000..960cb69bf1 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts @@ -0,0 +1,266 @@ +import fsPromises from "node:fs/promises"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, afterEach, describe, expect, vi } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path, PlatformError } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { GitCore } from "../../git/Services/GitCore.ts"; +import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; +import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts"; +import { WorkspacePathsLive } from "./WorkspacePaths.ts"; + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + Layer.provideMerge(WorkspacePathsLive), + Layer.provideMerge(GitCoreLive), + Layer.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-workspace-entries-test-", + }), + ), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) { + const fileSystem = yield* FileSystem.FileSystem; + const gitCore = yield* GitCore; + const dir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: opts?.prefix ?? "t3code-workspace-entries-", + }); + if (opts?.git) { + yield* gitCore.initRepo({ cwd: dir }); + } + return dir; +}); + +function writeTextFile( + cwd: string, + relativePath: string, + contents = "", +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true }); + yield* fileSystem.writeFileString(absolutePath, contents); + }); +} + +const git = (cwd: string, args: ReadonlyArray, env?: NodeJS.ProcessEnv) => + Effect.gen(function* () { + const gitCore = yield* GitCore; + const result = yield* gitCore.execute({ + operation: "WorkspaceEntries.test.git", + cwd, + args, + ...(env ? { env } : {}), + timeoutMs: 10_000, + }); + return result.stdout.trim(); + }); + +const searchWorkspaceEntries = (input: { cwd: string; query: string; limit: number }) => + Effect.gen(function* () { + const workspaceEntries = yield* WorkspaceEntries; + return yield* workspaceEntries.search(input); + }); + +it.layer(TestLayer)("WorkspaceEntriesLive", (it) => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("search", () => { + it.effect("returns files and directories relative to cwd", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir(); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/index.ts"); + yield* writeTextFile(cwd, "README.md"); + yield* writeTextFile(cwd, ".git/HEAD"); + yield* writeTextFile(cwd, "node_modules/pkg/index.js"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/components"); + expect(paths).toContain("src/components/Composer.tsx"); + expect(paths).toContain("README.md"); + expect(paths.some((entryPath) => entryPath.startsWith(".git"))).toBe(false); + expect(paths.some((entryPath) => entryPath.startsWith("node_modules"))).toBe(false); + expect(result.truncated).toBe(false); + }), + ); + + it.effect("filters and ranks entries by query", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-query-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/components/composePrompt.ts"); + yield* writeTextFile(cwd, "docs/composition.md"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "compo", limit: 5 }); + + expect(result.entries.length).toBeGreaterThan(0); + expect(result.entries.some((entry) => entry.path === "src/components")).toBe(true); + expect(result.entries.every((entry) => entry.path.toLowerCase().includes("compo"))).toBe( + true, + ); + }), + ); + + it.effect("supports fuzzy subsequence queries for composer path search", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-query-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/components/composePrompt.ts"); + yield* writeTextFile(cwd, "docs/composition.md"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 }); + const paths = result.entries.map((entry) => entry.path); + + expect(result.entries.length).toBeGreaterThan(0); + expect(paths).toContain("src/components"); + expect(paths).toContain("src/components/Composer.tsx"); + }), + ); + + it.effect("tracks truncation without sorting every fuzzy match", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-limit-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/components/composePrompt.ts"); + yield* writeTextFile(cwd, "docs/composition.md"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 }); + + expect(result.entries).toHaveLength(1); + expect(result.truncated).toBe(true); + }), + ); + + it.effect("excludes gitignored paths for git repositories", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true }); + yield* writeTextFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n"); + yield* writeTextFile(cwd, "src/keep.ts", "export {};"); + yield* writeTextFile(cwd, "ignored.txt", "ignore me"); + yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); + yield* writeTextFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/keep.ts"); + expect(paths).not.toContain("ignored.txt"); + expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); + expect(paths.some((entryPath) => entryPath.startsWith("convex/"))).toBe(false); + }), + ); + + it.effect("excludes tracked paths that match ignore rules", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ + prefix: "t3code-workspace-tracked-gitignore-", + git: true, + }); + yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); + yield* writeTextFile(cwd, "src/keep.ts", "export {};"); + yield* git(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]); + yield* writeTextFile(cwd, ".gitignore", ".convex/\n"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/keep.ts"); + expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); + }), + ); + + it.effect("excludes .convex in non-git workspaces", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-non-git-convex-" }); + yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); + yield* writeTextFile(cwd, "src/keep.ts", "export {};"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/keep.ts"); + expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); + }), + ); + + it.effect("deduplicates concurrent index builds for the same cwd", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-concurrent-build-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + + let rootReadCount = 0; + const originalReaddir = fsPromises.readdir.bind(fsPromises); + vi.spyOn(fsPromises, "readdir").mockImplementation((async ( + ...args: Parameters + ) => { + if (args[0] === cwd) { + rootReadCount += 1; + await new Promise((resolve) => setTimeout(resolve, 20)); + } + return originalReaddir(...args); + }) as typeof fsPromises.readdir); + + yield* Effect.all( + [ + searchWorkspaceEntries({ cwd, query: "", limit: 100 }), + searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }), + searchWorkspaceEntries({ cwd, query: "src", limit: 100 }), + ], + { concurrency: "unbounded" }, + ); + + expect(rootReadCount).toBe(1); + }), + ); + + it.effect("limits concurrent directory reads while walking the filesystem", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-read-concurrency-" }); + yield* Effect.forEach( + Array.from({ length: 80 }, (_, index) => index), + (index) => writeTextFile(cwd, `group-${index}/entry-${index}.ts`, "export {};"), + { discard: true }, + ); + + let activeReads = 0; + let peakReads = 0; + const originalReaddir = fsPromises.readdir.bind(fsPromises); + vi.spyOn(fsPromises, "readdir").mockImplementation((async ( + ...args: Parameters + ) => { + const target = args[0]; + if (typeof target === "string" && target.startsWith(cwd)) { + activeReads += 1; + peakReads = Math.max(peakReads, activeReads); + await new Promise((resolve) => setTimeout(resolve, 4)); + try { + return await originalReaddir(...args); + } finally { + activeReads -= 1; + } + } + return originalReaddir(...args); + }) as typeof fsPromises.readdir); + + yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 }); + + expect(peakReads).toBeLessThanOrEqual(32); + }), + ); + }); +}); diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.ts new file mode 100644 index 0000000000..12af8601ca --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.ts @@ -0,0 +1,503 @@ +import fsPromises from "node:fs/promises"; +import type { Dirent } from "node:fs"; + +import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect"; + +import { type ProjectEntry } from "@t3tools/contracts"; + +import { GitCore } from "../../git/Services/GitCore.ts"; +import { + WorkspaceEntries, + WorkspaceEntriesError, + type WorkspaceEntriesShape, +} from "../Services/WorkspaceEntries.ts"; +import { WorkspacePaths } from "../Services/WorkspacePaths.ts"; + +const WORKSPACE_CACHE_TTL_MS = 15_000; +const WORKSPACE_CACHE_MAX_KEYS = 4; +const WORKSPACE_INDEX_MAX_ENTRIES = 25_000; +const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32; +const IGNORED_DIRECTORY_NAMES = new Set([ + ".git", + ".convex", + "node_modules", + ".next", + ".turbo", + "dist", + "build", + "out", + ".cache", +]); + +interface WorkspaceIndex { + scannedAt: number; + entries: SearchableWorkspaceEntry[]; + truncated: boolean; +} + +interface SearchableWorkspaceEntry extends ProjectEntry { + normalizedPath: string; + normalizedName: string; +} + +interface RankedWorkspaceEntry { + entry: SearchableWorkspaceEntry; + score: number; +} + +function toPosixPath(input: string): string { + return input.replaceAll("\\", "/"); +} + +function parentPathOf(input: string): string | undefined { + const separatorIndex = input.lastIndexOf("/"); + if (separatorIndex === -1) { + return undefined; + } + return input.slice(0, separatorIndex); +} + +function basenameOf(input: string): string { + const separatorIndex = input.lastIndexOf("/"); + if (separatorIndex === -1) { + return input; + } + return input.slice(separatorIndex + 1); +} + +function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry { + const normalizedPath = entry.path.toLowerCase(); + return { + ...entry, + normalizedPath, + normalizedName: basenameOf(normalizedPath), + }; +} + +function normalizeQuery(input: string): string { + return input + .trim() + .replace(/^[@./]+/, "") + .toLowerCase(); +} + +function scoreSubsequenceMatch(value: string, query: string): number | null { + if (!query) return 0; + + let queryIndex = 0; + let firstMatchIndex = -1; + let previousMatchIndex = -1; + let gapPenalty = 0; + + for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) { + if (value[valueIndex] !== query[queryIndex]) { + continue; + } + + if (firstMatchIndex === -1) { + firstMatchIndex = valueIndex; + } + if (previousMatchIndex !== -1) { + gapPenalty += valueIndex - previousMatchIndex - 1; + } + + previousMatchIndex = valueIndex; + queryIndex += 1; + if (queryIndex === query.length) { + const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length; + const lengthPenalty = Math.min(64, value.length - query.length); + return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty; + } + } + + return null; +} + +function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null { + if (!query) { + return entry.kind === "directory" ? 0 : 1; + } + + const { normalizedPath, normalizedName } = entry; + + if (normalizedName === query) return 0; + if (normalizedPath === query) return 1; + if (normalizedName.startsWith(query)) return 2; + if (normalizedPath.startsWith(query)) return 3; + if (normalizedPath.includes(`/${query}`)) return 4; + if (normalizedName.includes(query)) return 5; + if (normalizedPath.includes(query)) return 6; + + const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query); + if (nameFuzzyScore !== null) { + return 100 + nameFuzzyScore; + } + + const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query); + if (pathFuzzyScore !== null) { + return 200 + pathFuzzyScore; + } + + return null; +} + +function compareRankedWorkspaceEntries( + left: RankedWorkspaceEntry, + right: RankedWorkspaceEntry, +): number { + const scoreDelta = left.score - right.score; + if (scoreDelta !== 0) return scoreDelta; + return left.entry.path.localeCompare(right.entry.path); +} + +function findInsertionIndex( + rankedEntries: RankedWorkspaceEntry[], + candidate: RankedWorkspaceEntry, +): number { + let low = 0; + let high = rankedEntries.length; + + while (low < high) { + const middle = low + Math.floor((high - low) / 2); + const current = rankedEntries[middle]; + if (!current) { + break; + } + + if (compareRankedWorkspaceEntries(candidate, current) < 0) { + high = middle; + } else { + low = middle + 1; + } + } + + return low; +} + +function insertRankedEntry( + rankedEntries: RankedWorkspaceEntry[], + candidate: RankedWorkspaceEntry, + limit: number, +): void { + if (limit <= 0) { + return; + } + + const insertionIndex = findInsertionIndex(rankedEntries, candidate); + if (rankedEntries.length < limit) { + rankedEntries.splice(insertionIndex, 0, candidate); + return; + } + + if (insertionIndex >= limit) { + return; + } + + rankedEntries.splice(insertionIndex, 0, candidate); + rankedEntries.pop(); +} + +function isPathInIgnoredDirectory(relativePath: string): boolean { + const firstSegment = relativePath.split("/")[0]; + if (!firstSegment) return false; + return IGNORED_DIRECTORY_NAMES.has(firstSegment); +} + +function directoryAncestorsOf(relativePath: string): string[] { + const segments = relativePath.split("/").filter((segment) => segment.length > 0); + if (segments.length <= 1) return []; + + const directories: string[] = []; + for (let index = 1; index < segments.length; index += 1) { + directories.push(segments.slice(0, index).join("/")); + } + return directories; +} + +const processErrorDetail = (cause: unknown): string => + cause instanceof Error ? cause.message : String(cause); + +export const makeWorkspaceEntries = Effect.gen(function* () { + const path = yield* Path.Path; + const gitOption = yield* Effect.serviceOption(GitCore); + const workspacePaths = yield* WorkspacePaths; + + const isInsideGitWorkTree = (cwd: string): Effect.Effect => + Option.match(gitOption, { + onSome: (git) => git.isInsideWorkTree(cwd).pipe(Effect.catch(() => Effect.succeed(false))), + onNone: () => Effect.succeed(false), + }); + + const filterGitIgnoredPaths = ( + cwd: string, + relativePaths: string[], + ): Effect.Effect => + Option.match(gitOption, { + onSome: (git) => + git.filterIgnoredPaths(cwd, relativePaths).pipe( + Effect.map((paths) => [...paths]), + Effect.catch(() => Effect.succeed(relativePaths)), + ), + onNone: () => Effect.succeed(relativePaths), + }); + + const buildWorkspaceIndexFromGit = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromGit")( + function* (cwd: string) { + if (Option.isNone(gitOption)) { + return null; + } + if (!(yield* isInsideGitWorkTree(cwd))) { + return null; + } + + const listedFiles = yield* gitOption.value + .listWorkspaceFiles(cwd) + .pipe(Effect.catch(() => Effect.succeed(null))); + + if (!listedFiles) { + return null; + } + + const listedPaths = [...listedFiles.paths] + .map((entry) => toPosixPath(entry)) + .filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry)); + const filePaths = yield* filterGitIgnoredPaths(cwd, listedPaths); + + const directorySet = new Set(); + for (const filePath of filePaths) { + for (const directoryPath of directoryAncestorsOf(filePath)) { + if (!isPathInIgnoredDirectory(directoryPath)) { + directorySet.add(directoryPath); + } + } + } + + const directoryEntries = [...directorySet] + .toSorted((left, right) => left.localeCompare(right)) + .map( + (directoryPath): ProjectEntry => ({ + path: directoryPath, + kind: "directory", + parentPath: parentPathOf(directoryPath), + }), + ) + .map(toSearchableWorkspaceEntry); + const fileEntries = [...new Set(filePaths)] + .toSorted((left, right) => left.localeCompare(right)) + .map( + (filePath): ProjectEntry => ({ + path: filePath, + kind: "file", + parentPath: parentPathOf(filePath), + }), + ) + .map(toSearchableWorkspaceEntry); + + const entries = [...directoryEntries, ...fileEntries]; + return { + scannedAt: Date.now(), + entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES), + truncated: listedFiles.truncated || entries.length > WORKSPACE_INDEX_MAX_ENTRIES, + }; + }, + ); + + const readDirectoryEntries = Effect.fn("WorkspaceEntries.readDirectoryEntries")(function* ( + cwd: string, + relativeDir: string, + ): Effect.fn.Return< + { readonly relativeDir: string; readonly dirents: Dirent[] | null }, + WorkspaceEntriesError + > { + return yield* Effect.tryPromise({ + try: async () => { + const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd; + const dirents = await fsPromises.readdir(absoluteDir, { withFileTypes: true }); + return { relativeDir, dirents }; + }, + catch: (cause) => + new WorkspaceEntriesError({ + cwd, + operation: "workspaceEntries.readDirectoryEntries", + detail: processErrorDetail(cause), + cause, + }), + }).pipe( + Effect.catchIf( + () => relativeDir.length > 0, + () => Effect.succeed({ relativeDir, dirents: null }), + ), + ); + }); + + const buildWorkspaceIndexFromFilesystem = Effect.fn( + "WorkspaceEntries.buildWorkspaceIndexFromFilesystem", + )(function* (cwd: string): Effect.fn.Return { + const shouldFilterWithGitIgnore = yield* isInsideGitWorkTree(cwd); + + let pendingDirectories: string[] = [""]; + const entries: SearchableWorkspaceEntry[] = []; + let truncated = false; + + while (pendingDirectories.length > 0 && !truncated) { + const currentDirectories = pendingDirectories; + pendingDirectories = []; + + const directoryEntries = yield* Effect.forEach( + currentDirectories, + (relativeDir) => readDirectoryEntries(cwd, relativeDir), + { concurrency: WORKSPACE_SCAN_READDIR_CONCURRENCY }, + ); + + const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => { + const { relativeDir, dirents } = directoryEntry; + if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>; + + dirents.sort((left, right) => left.name.localeCompare(right.name)); + const candidates: Array<{ dirent: Dirent; relativePath: string }> = []; + for (const dirent of dirents) { + if (!dirent.name || dirent.name === "." || dirent.name === "..") { + continue; + } + if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) { + continue; + } + if (!dirent.isDirectory() && !dirent.isFile()) { + continue; + } + + const relativePath = toPosixPath( + relativeDir ? path.join(relativeDir, dirent.name) : dirent.name, + ); + if (isPathInIgnoredDirectory(relativePath)) { + continue; + } + candidates.push({ dirent, relativePath }); + } + return candidates; + }); + + const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) => + candidateEntries.map((entry) => entry.relativePath), + ); + const allowedPathSet = shouldFilterWithGitIgnore + ? new Set(yield* filterGitIgnoredPaths(cwd, candidatePaths)) + : null; + + for (const candidateEntries of candidateEntriesByDirectory) { + for (const candidate of candidateEntries) { + if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) { + continue; + } + + const entry = toSearchableWorkspaceEntry({ + path: candidate.relativePath, + kind: candidate.dirent.isDirectory() ? "directory" : "file", + parentPath: parentPathOf(candidate.relativePath), + }); + entries.push(entry); + + if (candidate.dirent.isDirectory()) { + pendingDirectories.push(candidate.relativePath); + } + + if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) { + truncated = true; + break; + } + } + + if (truncated) { + break; + } + } + } + + return { + scannedAt: Date.now(), + entries, + truncated, + }; + }); + + const buildWorkspaceIndex = Effect.fn("WorkspaceEntries.buildWorkspaceIndex")(function* ( + cwd: string, + ): Effect.fn.Return { + const gitIndexed = yield* buildWorkspaceIndexFromGit(cwd); + if (gitIndexed) { + return gitIndexed; + } + return yield* buildWorkspaceIndexFromFilesystem(cwd); + }); + + const workspaceIndexCache = yield* Cache.makeWith({ + capacity: WORKSPACE_CACHE_MAX_KEYS, + lookup: buildWorkspaceIndex, + timeToLive: (exit) => + Exit.isSuccess(exit) ? Duration.millis(WORKSPACE_CACHE_TTL_MS) : Duration.zero, + }); + + const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* ( + cwd: string, + ): Effect.fn.Return { + return yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe( + Effect.mapError( + (cause) => + new WorkspaceEntriesError({ + cwd, + operation: "workspaceEntries.normalizeWorkspaceRoot", + detail: cause.message, + cause, + }), + ), + ); + }); + + const invalidate: WorkspaceEntriesShape["invalidate"] = Effect.fn("WorkspaceEntries.invalidate")( + function* (cwd) { + const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe( + Effect.catch(() => Effect.succeed(cwd)), + ); + yield* Cache.invalidate(workspaceIndexCache, cwd); + if (normalizedCwd !== cwd) { + yield* Cache.invalidate(workspaceIndexCache, normalizedCwd); + } + }, + ); + + const search: WorkspaceEntriesShape["search"] = Effect.fn("WorkspaceEntries.search")( + function* (input) { + const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd); + return yield* Cache.get(workspaceIndexCache, normalizedCwd).pipe( + Effect.map((index) => { + const normalizedQuery = normalizeQuery(input.query); + const limit = Math.max(0, Math.floor(input.limit)); + const rankedEntries: RankedWorkspaceEntry[] = []; + let matchedEntryCount = 0; + + for (const entry of index.entries) { + const score = scoreEntry(entry, normalizedQuery); + if (score === null) { + continue; + } + + matchedEntryCount += 1; + insertRankedEntry(rankedEntries, { entry, score }, limit); + } + + return { + entries: rankedEntries.map((candidate) => candidate.entry), + truncated: index.truncated || matchedEntryCount > limit, + }; + }), + ); + }, + ); + + return { + invalidate, + search, + } satisfies WorkspaceEntriesShape; +}); + +export const WorkspaceEntriesLive = Layer.effect(WorkspaceEntries, makeWorkspaceEntries); diff --git a/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts new file mode 100644 index 0000000000..fcfd13c912 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts @@ -0,0 +1,136 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, describe, expect } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; +import { WorkspaceFileSystem } from "../Services/WorkspaceFileSystem.ts"; +import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts"; +import { WorkspaceFileSystemLive } from "./WorkspaceFileSystem.ts"; +import { WorkspacePathsLive } from "./WorkspacePaths.ts"; + +const ProjectLayer = WorkspaceFileSystemLive.pipe( + Layer.provide(WorkspacePathsLive), + Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), +); + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(ProjectLayer), + Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + Layer.provideMerge(WorkspacePathsLive), + Layer.provideMerge(GitCoreLive), + Layer.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-workspace-files-test-", + }), + ), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3code-workspace-files-", + }); +}); + +const writeTextFile = Effect.fn("writeTextFile")(function* ( + cwd: string, + relativePath: string, + contents = "", +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem + .makeDirectory(path.dirname(absolutePath), { recursive: true }) + .pipe(Effect.orDie); + yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); +}); + +it.layer(TestLayer)("WorkspaceFileSystemLive", (it) => { + describe("writeFile", () => { + it.effect("writes files relative to the workspace root", () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem; + const cwd = yield* makeTempDir; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const result = yield* workspaceFileSystem.writeFile({ + cwd, + relativePath: "plans/effect-rpc.md", + contents: "# Plan\n", + }); + const saved = yield* fileSystem + .readFileString(path.join(cwd, "plans/effect-rpc.md")) + .pipe(Effect.orDie); + + expect(result).toEqual({ relativePath: "plans/effect-rpc.md" }); + expect(saved).toBe("# Plan\n"); + }), + ); + + it.effect("invalidates workspace entry search cache after writes", () => + Effect.gen(function* () { + const workspaceEntries = yield* WorkspaceEntries; + const workspaceFileSystem = yield* WorkspaceFileSystem; + const cwd = yield* makeTempDir; + yield* writeTextFile(cwd, "src/existing.ts", "export {};\n"); + + const beforeWrite = yield* workspaceEntries.search({ + cwd, + query: "rpc", + limit: 10, + }); + expect(beforeWrite).toEqual({ + entries: [], + truncated: false, + }); + + yield* workspaceFileSystem.writeFile({ + cwd, + relativePath: "plans/effect-rpc.md", + contents: "# Plan\n", + }); + + const afterWrite = yield* workspaceEntries.search({ + cwd, + query: "rpc", + limit: 10, + }); + expect(afterWrite.entries).toEqual( + expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]), + ); + expect(afterWrite.truncated).toBe(false); + }), + ); + + it.effect("rejects writes outside the workspace root", () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem; + const cwd = yield* makeTempDir; + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + + const error = yield* workspaceFileSystem + .writeFile({ + cwd, + relativePath: "../escape.md", + contents: "# nope\n", + }) + .pipe(Effect.flip); + + expect(error.message).toContain( + "Workspace file path must be relative to the project root: ../escape.md", + ); + + const escapedPath = path.resolve(cwd, "..", "escape.md"); + const escapedStat = yield* fileSystem + .stat(escapedPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + expect(escapedStat).toBeNull(); + }), + ); + }); +}); diff --git a/apps/server/src/workspace/Layers/WorkspaceFileSystem.ts b/apps/server/src/workspace/Layers/WorkspaceFileSystem.ts new file mode 100644 index 0000000000..84e5d9c6d1 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceFileSystem.ts @@ -0,0 +1,55 @@ +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { + WorkspaceFileSystem, + WorkspaceFileSystemError, + type WorkspaceFileSystemShape, +} from "../Services/WorkspaceFileSystem.ts"; +import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; +import { WorkspacePaths } from "../Services/WorkspacePaths.ts"; + +export const makeWorkspaceFileSystem = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspacePaths = yield* WorkspacePaths; + const workspaceEntries = yield* WorkspaceEntries; + + const writeFile: WorkspaceFileSystemShape["writeFile"] = Effect.fn( + "WorkspaceFileSystem.writeFile", + )(function* (input) { + const target = yield* workspacePaths.resolveRelativePathWithinRoot({ + workspaceRoot: input.cwd, + relativePath: input.relativePath, + }); + + yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe( + Effect.mapError( + (cause) => + new WorkspaceFileSystemError({ + cwd: input.cwd, + relativePath: input.relativePath, + operation: "workspaceFileSystem.makeDirectory", + detail: cause.message, + cause, + }), + ), + ); + yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe( + Effect.mapError( + (cause) => + new WorkspaceFileSystemError({ + cwd: input.cwd, + relativePath: input.relativePath, + operation: "workspaceFileSystem.writeFile", + detail: cause.message, + cause, + }), + ), + ); + yield* workspaceEntries.invalidate(input.cwd); + return { relativePath: target.relativePath }; + }); + return { writeFile } satisfies WorkspaceFileSystemShape; +}); + +export const WorkspaceFileSystemLive = Layer.effect(WorkspaceFileSystem, makeWorkspaceFileSystem); diff --git a/apps/server/src/workspace/Layers/WorkspacePaths.test.ts b/apps/server/src/workspace/Layers/WorkspacePaths.test.ts new file mode 100644 index 0000000000..d02a5929d2 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspacePaths.test.ts @@ -0,0 +1,113 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, describe, expect } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { WorkspacePaths } from "../Services/WorkspacePaths.ts"; +import { WorkspacePathsLive } from "./WorkspacePaths.ts"; + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(WorkspacePathsLive), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.fn("makeTempDir")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3code-project-paths-", + }); +}); + +const writeTextFile = Effect.fn("writeTextFile")(function* ( + cwd: string, + relativePath: string, + contents = "", +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem + .makeDirectory(path.dirname(absolutePath), { recursive: true }) + .pipe(Effect.orDie); + yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); +}); + +it.layer(TestLayer)("WorkspacePathsLive", (it) => { + describe("normalizeWorkspaceRoot", () => { + it.effect("resolves an existing directory", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + + const resolved = yield* workspacePaths.normalizeWorkspaceRoot(cwd); + + expect(resolved).toBe(cwd); + }), + ); + + it.effect("rejects missing directories", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + const path = yield* Path.Path; + + const error = yield* workspacePaths + .normalizeWorkspaceRoot(path.join(cwd, "missing")) + .pipe(Effect.flip); + + expect(error.message).toContain("Workspace root does not exist:"); + }), + ); + + it.effect("rejects file paths", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + const path = yield* Path.Path; + const filePath = path.join(cwd, "README.md"); + yield* writeTextFile(cwd, "README.md", "# hi\n"); + + const error = yield* workspacePaths.normalizeWorkspaceRoot(filePath).pipe(Effect.flip); + + expect(error.message).toContain("Workspace root is not a directory:"); + }), + ); + }); + + describe("resolveRelativePathWithinRoot", () => { + it.effect("resolves relative paths inside the workspace root", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + const path = yield* Path.Path; + + const resolved = yield* workspacePaths.resolveRelativePathWithinRoot({ + workspaceRoot: cwd, + relativePath: "plans/effect-rpc.md", + }); + + expect(resolved).toEqual({ + absolutePath: path.join(cwd, "plans/effect-rpc.md"), + relativePath: "plans/effect-rpc.md", + }); + }), + ); + + it.effect("rejects paths that escape the workspace root", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + + const error = yield* workspacePaths + .resolveRelativePathWithinRoot({ + workspaceRoot: cwd, + relativePath: "../escape.md", + }) + .pipe(Effect.flip); + + expect(error.message).toContain( + "Workspace file path must be relative to the project root: ../escape.md", + ); + }), + ); + }); +}); diff --git a/apps/server/src/workspace/Layers/WorkspacePaths.ts b/apps/server/src/workspace/Layers/WorkspacePaths.ts new file mode 100644 index 0000000000..fa7a90cf07 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspacePaths.ts @@ -0,0 +1,89 @@ +import * as OS from "node:os"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { + WorkspacePaths, + WorkspacePathOutsideRootError, + WorkspaceRootNotDirectoryError, + WorkspaceRootNotExistsError, + type WorkspacePathsShape, +} from "../Services/WorkspacePaths.ts"; + +function toPosixRelativePath(input: string): string { + return input.replaceAll("\\", "/"); +} + +function expandHomePath(input: string, path: Path.Path): string { + if (input === "~") { + return OS.homedir(); + } + if (input.startsWith("~/") || input.startsWith("~\\")) { + return path.join(OS.homedir(), input.slice(2)); + } + return input; +} + +export const makeWorkspacePaths = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const normalizeWorkspaceRoot: WorkspacePathsShape["normalizeWorkspaceRoot"] = Effect.fn( + "WorkspacePaths.normalizeWorkspaceRoot", + )(function* (workspaceRoot) { + const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path)); + const workspaceStat = yield* fileSystem + .stat(normalizedWorkspaceRoot) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!workspaceStat) { + return yield* new WorkspaceRootNotExistsError({ + workspaceRoot, + normalizedWorkspaceRoot, + }); + } + if (workspaceStat.type !== "Directory") { + return yield* new WorkspaceRootNotDirectoryError({ + workspaceRoot, + normalizedWorkspaceRoot, + }); + } + return normalizedWorkspaceRoot; + }); + + const resolveRelativePathWithinRoot: WorkspacePathsShape["resolveRelativePathWithinRoot"] = + Effect.fn("WorkspacePaths.resolveRelativePathWithinRoot")(function* (input) { + const normalizedInputPath = input.relativePath.trim(); + if (path.isAbsolute(normalizedInputPath)) { + return yield* new WorkspacePathOutsideRootError({ + workspaceRoot: input.workspaceRoot, + relativePath: input.relativePath, + }); + } + + const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath); + const relativeToRoot = toPosixRelativePath(path.relative(input.workspaceRoot, absolutePath)); + if ( + relativeToRoot.length === 0 || + relativeToRoot === "." || + relativeToRoot.startsWith("../") || + relativeToRoot === ".." || + path.isAbsolute(relativeToRoot) + ) { + return yield* new WorkspacePathOutsideRootError({ + workspaceRoot: input.workspaceRoot, + relativePath: input.relativePath, + }); + } + + return { + absolutePath, + relativePath: relativeToRoot, + }; + }); + + return { + normalizeWorkspaceRoot, + resolveRelativePathWithinRoot, + } satisfies WorkspacePathsShape; +}); + +export const WorkspacePathsLive = Layer.effect(WorkspacePaths, makeWorkspacePaths); diff --git a/apps/server/src/workspace/Services/WorkspaceEntries.ts b/apps/server/src/workspace/Services/WorkspaceEntries.ts new file mode 100644 index 0000000000..2841b1fe2f --- /dev/null +++ b/apps/server/src/workspace/Services/WorkspaceEntries.ts @@ -0,0 +1,48 @@ +/** + * WorkspaceEntries - Effect service contract for cached workspace entry search. + * + * Owns indexed workspace entry search plus cache invalidation for workspace + * roots when the underlying filesystem changes. + * + * @module WorkspaceEntries + */ +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "@t3tools/contracts"; + +export class WorkspaceEntriesError extends Schema.TaggedErrorClass()( + "WorkspaceEntriesError", + { + cwd: Schema.String, + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) {} + +/** + * WorkspaceEntriesShape - Service API for workspace entry search and cache + * invalidation. + */ +export interface WorkspaceEntriesShape { + /** + * Search indexed workspace entries for files and directories matching the + * provided query. + */ + readonly search: ( + input: ProjectSearchEntriesInput, + ) => Effect.Effect; + + /** + * Drop any cached workspace entries for the given workspace root. + */ + readonly invalidate: (cwd: string) => Effect.Effect; +} + +/** + * WorkspaceEntries - Service tag for cached workspace entry search. + */ +export class WorkspaceEntries extends ServiceMap.Service()( + "t3/workspace/Services/WorkspaceEntries", +) {} diff --git a/apps/server/src/workspace/Services/WorkspaceFileSystem.ts b/apps/server/src/workspace/Services/WorkspaceFileSystem.ts new file mode 100644 index 0000000000..85db1514a3 --- /dev/null +++ b/apps/server/src/workspace/Services/WorkspaceFileSystem.ts @@ -0,0 +1,50 @@ +/** + * WorkspaceFileSystem - Effect service contract for workspace file mutations. + * + * Owns workspace-root-relative file write operations and their associated + * safety checks and cache invalidation hooks. + * + * @module WorkspaceFileSystem + */ +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectWriteFileInput, ProjectWriteFileResult } from "@t3tools/contracts"; +import { WorkspacePathOutsideRootError } from "./WorkspacePaths.ts"; + +export class WorkspaceFileSystemError extends Schema.TaggedErrorClass()( + "WorkspaceFileSystemError", + { + cwd: Schema.String, + relativePath: Schema.optional(Schema.String), + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) {} + +/** + * WorkspaceFileSystemShape - Service API for workspace-relative file operations. + */ +export interface WorkspaceFileSystemShape { + /** + * Write a file relative to the workspace root. + * + * Creates parent directories as needed and rejects paths that escape the + * workspace root. + */ + readonly writeFile: ( + input: ProjectWriteFileInput, + ) => Effect.Effect< + ProjectWriteFileResult, + WorkspaceFileSystemError | WorkspacePathOutsideRootError + >; +} + +/** + * WorkspaceFileSystem - Service tag for workspace file operations. + */ +export class WorkspaceFileSystem extends ServiceMap.Service< + WorkspaceFileSystem, + WorkspaceFileSystemShape +>()("t3/workspace/Services/WorkspaceFileSystem") {} diff --git a/apps/server/src/workspace/Services/WorkspacePaths.ts b/apps/server/src/workspace/Services/WorkspacePaths.ts new file mode 100644 index 0000000000..ad6d9cd3e5 --- /dev/null +++ b/apps/server/src/workspace/Services/WorkspacePaths.ts @@ -0,0 +1,85 @@ +/** + * WorkspacePaths - Effect service contract for workspace path handling. + * + * Owns normalization and validation of workspace roots plus safe resolution of + * workspace-root-relative paths. + * + * @module WorkspacePaths + */ +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +export class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass()( + "WorkspaceRootNotExistsError", + { + workspaceRoot: Schema.String, + normalizedWorkspaceRoot: Schema.String, + }, +) { + override get message(): string { + return `Workspace root does not exist: ${this.normalizedWorkspaceRoot}`; + } +} + +export class WorkspaceRootNotDirectoryError extends Schema.TaggedErrorClass()( + "WorkspaceRootNotDirectoryError", + { + workspaceRoot: Schema.String, + normalizedWorkspaceRoot: Schema.String, + }, +) { + override get message(): string { + return `Workspace root is not a directory: ${this.normalizedWorkspaceRoot}`; + } +} + +export class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass()( + "WorkspacePathOutsideRootError", + { + workspaceRoot: Schema.String, + relativePath: Schema.String, + }, +) { + override get message(): string { + return `Workspace file path must be relative to the project root: ${this.relativePath}`; + } +} + +export const WorkspacePathsError = Schema.Union([ + WorkspaceRootNotExistsError, + WorkspaceRootNotDirectoryError, + WorkspacePathOutsideRootError, +]); +export type WorkspacePathsError = typeof WorkspacePathsError.Type; + +/** + * WorkspacePathsShape - Service API for workspace path normalization and guards. + */ +export interface WorkspacePathsShape { + /** + * Normalize a user-provided workspace root and verify it exists as a directory. + */ + readonly normalizeWorkspaceRoot: ( + workspaceRoot: string, + ) => Effect.Effect; + + /** + * Resolve a relative path within a validated workspace root. + * + * Rejects absolute paths and traversal attempts outside the workspace root. + */ + readonly resolveRelativePathWithinRoot: (input: { + workspaceRoot: string; + relativePath: string; + }) => Effect.Effect< + { absolutePath: string; relativePath: string }, + WorkspacePathOutsideRootError + >; +} + +/** + * WorkspacePaths - Service tag for workspace path normalization and resolution. + */ +export class WorkspacePaths extends ServiceMap.Service()( + "t3/workspace/Services/WorkspacePaths", +) {} diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts new file mode 100644 index 0000000000..33a0518611 --- /dev/null +++ b/apps/server/src/ws.ts @@ -0,0 +1,744 @@ +import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect"; +import { + CommandId, + EventId, + type OrchestrationCommand, + type GitActionProgressEvent, + type GitManagerServiceError, + OrchestrationDispatchCommandError, + type OrchestrationEvent, + OrchestrationGetFullThreadDiffError, + OrchestrationGetSnapshotError, + OrchestrationGetTurnDiffError, + ORCHESTRATION_WS_METHODS, + ProjectSearchEntriesError, + ProjectWriteFileError, + OrchestrationReplayEventsError, + ThreadId, + type TerminalEvent, + WS_METHODS, + WsRpcGroup, +} from "@t3tools/contracts"; +import { clamp } from "effect/Number"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; +import { RpcSerialization, RpcServer } from "effect/unstable/rpc"; + +import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery"; +import { ServerConfig } from "./config"; +import { GitCore } from "./git/Services/GitCore"; +import { GitManager } from "./git/Services/GitManager"; +import { Keybindings } from "./keybindings"; +import { Open, resolveAvailableEditors } from "./open"; +import { normalizeDispatchCommand } from "./orchestration/Normalizer"; +import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; +import { + observeRpcEffect, + observeRpcStream, + observeRpcStreamEffect, +} from "./observability/RpcInstrumentation"; +import { ProviderRegistry } from "./provider/Services/ProviderRegistry"; +import { ServerLifecycleEvents } from "./serverLifecycleEvents"; +import { ServerRuntimeStartup } from "./serverRuntimeStartup"; +import { ServerSettingsService } from "./serverSettings"; +import { TerminalManager } from "./terminal/Services/Manager"; +import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries"; +import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem"; +import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths"; +import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner"; + +const WsRpcLayer = WsRpcGroup.toLayer( + Effect.gen(function* () { + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + const orchestrationEngine = yield* OrchestrationEngineService; + const checkpointDiffQuery = yield* CheckpointDiffQuery; + const keybindings = yield* Keybindings; + const open = yield* Open; + const gitManager = yield* GitManager; + const git = yield* GitCore; + const terminalManager = yield* TerminalManager; + const providerRegistry = yield* ProviderRegistry; + const config = yield* ServerConfig; + const lifecycleEvents = yield* ServerLifecycleEvents; + const serverSettings = yield* ServerSettingsService; + const startup = yield* ServerRuntimeStartup; + const workspaceEntries = yield* WorkspaceEntries; + const workspaceFileSystem = yield* WorkspaceFileSystem; + const projectSetupScriptRunner = yield* ProjectSetupScriptRunner; + + const serverCommandId = (tag: string) => + CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`); + + const appendSetupScriptActivity = (input: { + readonly threadId: ThreadId; + readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed"; + readonly summary: string; + readonly createdAt: string; + readonly payload: Record; + readonly tone: "info" | "error"; + }) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: serverCommandId("setup-script-activity"), + threadId: input.threadId, + activity: { + id: EventId.makeUnsafe(crypto.randomUUID()), + tone: input.tone, + kind: input.kind, + summary: input.summary, + payload: input.payload, + turnId: null, + createdAt: input.createdAt, + }, + createdAt: input.createdAt, + }); + + const toDispatchCommandError = (cause: unknown, fallbackMessage: string) => + Schema.is(OrchestrationDispatchCommandError)(cause) + ? cause + : new OrchestrationDispatchCommandError({ + message: cause instanceof Error ? cause.message : fallbackMessage, + cause, + }); + + const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause) => { + const error = Cause.squash(cause); + return Schema.is(OrchestrationDispatchCommandError)(error) + ? error + : new OrchestrationDispatchCommandError({ + message: + error instanceof Error ? error.message : "Failed to bootstrap thread turn start.", + cause, + }); + }; + + const dispatchBootstrapTurnStart = ( + command: Extract, + ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => + Effect.gen(function* () { + const bootstrap = command.bootstrap; + const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command; + let createdThread = false; + let targetProjectId = bootstrap?.createThread?.projectId; + let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd; + let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null; + + const cleanupCreatedThread = () => + createdThread + ? orchestrationEngine + .dispatch({ + type: "thread.delete", + commandId: serverCommandId("bootstrap-thread-delete"), + threadId: command.threadId, + }) + .pipe(Effect.ignoreCause({ log: true })) + : Effect.void; + + const recordSetupScriptLaunchFailure = (input: { + readonly error: unknown; + readonly requestedAt: string; + readonly worktreePath: string; + }) => { + const detail = + input.error instanceof Error ? input.error.message : "Unknown setup failure."; + return appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.failed", + summary: "Setup script failed to start", + createdAt: input.requestedAt, + payload: { + detail, + worktreePath: input.worktreePath, + }, + tone: "error", + }).pipe( + Effect.ignoreCause({ log: false }), + Effect.flatMap(() => + Effect.logWarning("bootstrap turn start failed to launch setup script", { + threadId: command.threadId, + worktreePath: input.worktreePath, + detail, + }), + ), + ); + }; + + const recordSetupScriptStarted = (input: { + readonly requestedAt: string; + readonly worktreePath: string; + readonly scriptId: string; + readonly scriptName: string; + readonly terminalId: string; + }) => { + const payload = { + scriptId: input.scriptId, + scriptName: input.scriptName, + terminalId: input.terminalId, + worktreePath: input.worktreePath, + }; + return Effect.all([ + appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.requested", + summary: "Starting setup script", + createdAt: input.requestedAt, + payload, + tone: "info", + }), + appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.started", + summary: "Setup script started", + createdAt: new Date().toISOString(), + payload, + tone: "info", + }), + ]).pipe( + Effect.asVoid, + Effect.catch((error) => + Effect.logWarning( + "bootstrap turn start launched setup script but failed to record setup activity", + { + threadId: command.threadId, + worktreePath: input.worktreePath, + scriptId: input.scriptId, + terminalId: input.terminalId, + detail: + error instanceof Error + ? error.message + : "Unknown setup activity dispatch failure.", + }, + ), + ), + ); + }; + + const runSetupProgram = () => + bootstrap?.runSetupScript && targetWorktreePath + ? (() => { + const worktreePath = targetWorktreePath; + const requestedAt = new Date().toISOString(); + return projectSetupScriptRunner + .runForThread({ + threadId: command.threadId, + ...(targetProjectId ? { projectId: targetProjectId } : {}), + ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}), + worktreePath, + }) + .pipe( + Effect.matchEffect({ + onFailure: (error) => + recordSetupScriptLaunchFailure({ + error, + requestedAt, + worktreePath, + }), + onSuccess: (setupResult) => { + if (setupResult.status !== "started") { + return Effect.void; + } + return recordSetupScriptStarted({ + requestedAt, + worktreePath, + scriptId: setupResult.scriptId, + scriptName: setupResult.scriptName, + terminalId: setupResult.terminalId, + }); + }, + }), + ); + })() + : Effect.void; + + const bootstrapProgram = Effect.gen(function* () { + if (bootstrap?.createThread) { + yield* orchestrationEngine.dispatch({ + type: "thread.create", + commandId: serverCommandId("bootstrap-thread-create"), + threadId: command.threadId, + projectId: bootstrap.createThread.projectId, + title: bootstrap.createThread.title, + modelSelection: bootstrap.createThread.modelSelection, + runtimeMode: bootstrap.createThread.runtimeMode, + interactionMode: bootstrap.createThread.interactionMode, + branch: bootstrap.createThread.branch, + worktreePath: bootstrap.createThread.worktreePath, + createdAt: bootstrap.createThread.createdAt, + }); + createdThread = true; + } + + if (bootstrap?.prepareWorktree) { + const worktree = yield* git.createWorktree({ + cwd: bootstrap.prepareWorktree.projectCwd, + branch: bootstrap.prepareWorktree.baseBranch, + newBranch: bootstrap.prepareWorktree.branch, + path: null, + }); + targetWorktreePath = worktree.worktree.path; + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: serverCommandId("bootstrap-thread-meta-update"), + threadId: command.threadId, + branch: worktree.worktree.branch, + worktreePath: targetWorktreePath, + }); + } + + yield* runSetupProgram(); + + return yield* orchestrationEngine.dispatch(finalTurnStartCommand); + }); + + return yield* bootstrapProgram.pipe( + Effect.catchCause((cause) => { + const dispatchError = toBootstrapDispatchCommandCauseError(cause); + if (Cause.hasInterruptsOnly(cause)) { + return Effect.fail(dispatchError); + } + return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError))); + }), + ); + }); + + const dispatchNormalizedCommand = ( + normalizedCommand: OrchestrationCommand, + ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => { + const dispatchEffect = + normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap + ? dispatchBootstrapTurnStart(normalizedCommand) + : orchestrationEngine + .dispatch(normalizedCommand) + .pipe( + Effect.mapError((cause) => + toDispatchCommandError(cause, "Failed to dispatch orchestration command"), + ), + ); + + return startup + .enqueueCommand(dispatchEffect) + .pipe( + Effect.mapError((cause) => + toDispatchCommandError(cause, "Failed to dispatch orchestration command"), + ), + ); + }; + + const loadServerConfig = Effect.gen(function* () { + const keybindingsConfig = yield* keybindings.loadConfigState; + const providers = yield* providerRegistry.getProviders; + const settings = yield* serverSettings.getSettings; + + return { + cwd: config.cwd, + keybindingsConfigPath: config.keybindingsConfigPath, + keybindings: keybindingsConfig.keybindings, + issues: keybindingsConfig.issues, + providers, + availableEditors: resolveAvailableEditors(), + observability: { + logsDirectoryPath: config.logsDir, + localTracingEnabled: true, + ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}), + otlpTracesEnabled: config.otlpTracesUrl !== undefined, + ...(config.otlpMetricsUrl !== undefined ? { otlpMetricsUrl: config.otlpMetricsUrl } : {}), + otlpMetricsEnabled: config.otlpMetricsUrl !== undefined, + }, + settings, + }; + }); + + return WsRpcGroup.of({ + [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getSnapshot, + projectionSnapshotQuery.getSnapshot().pipe( + Effect.mapError( + (cause) => + new OrchestrationGetSnapshotError({ + message: "Failed to load orchestration snapshot", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.dispatchCommand, + Effect.gen(function* () { + const normalizedCommand = yield* normalizeDispatchCommand(command); + const result = yield* dispatchNormalizedCommand(normalizedCommand); + if (normalizedCommand.type === "thread.archive") { + yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to close thread terminals after archive", { + threadId: normalizedCommand.threadId, + error: error.message, + }), + ), + ); + } + return result; + }).pipe( + Effect.mapError((cause) => + Schema.is(OrchestrationDispatchCommandError)(cause) + ? cause + : new OrchestrationDispatchCommandError({ + message: "Failed to dispatch orchestration command", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getTurnDiff, + checkpointDiffQuery.getTurnDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetTurnDiffError({ + message: "Failed to load turn diff", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getFullThreadDiff, + checkpointDiffQuery.getFullThreadDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetFullThreadDiffError({ + message: "Failed to load full thread diff", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_WS_METHODS.replayEvents]: (input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.replayEvents, + Stream.runCollect( + orchestrationEngine.readEvents( + clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }), + ), + ).pipe( + Effect.map((events) => Array.from(events)), + Effect.mapError( + (cause) => + new OrchestrationReplayEventsError({ + message: "Failed to replay orchestration events", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeOrchestrationDomainEvents, + Effect.gen(function* () { + const snapshot = yield* orchestrationEngine.getReadModel(); + const fromSequenceExclusive = snapshot.snapshotSequence; + const replayEvents: Array = yield* Stream.runCollect( + orchestrationEngine.readEvents(fromSequenceExclusive), + ).pipe( + Effect.map((events) => Array.from(events)), + Effect.catch(() => Effect.succeed([] as Array)), + ); + const replayStream = Stream.fromIterable(replayEvents); + const source = Stream.merge(replayStream, orchestrationEngine.streamDomainEvents); + type SequenceState = { + readonly nextSequence: number; + readonly pendingBySequence: Map; + }; + const state = yield* Ref.make({ + nextSequence: fromSequenceExclusive + 1, + pendingBySequence: new Map(), + }); + + return source.pipe( + Stream.mapEffect((event) => + Ref.modify( + state, + ({ + nextSequence, + pendingBySequence, + }): [Array, SequenceState] => { + if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) { + return [[], { nextSequence, pendingBySequence }]; + } + + const updatedPending = new Map(pendingBySequence); + updatedPending.set(event.sequence, event); + + const emit: Array = []; + let expected = nextSequence; + for (;;) { + const expectedEvent = updatedPending.get(expected); + if (!expectedEvent) { + break; + } + emit.push(expectedEvent); + updatedPending.delete(expected); + expected += 1; + } + + return [emit, { nextSequence: expected, pendingBySequence: updatedPending }]; + }, + ), + ), + Stream.flatMap((events) => Stream.fromIterable(events)), + ); + }), + { "rpc.aggregate": "orchestration" }, + ), + [WS_METHODS.serverGetConfig]: (_input) => + observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, { + "rpc.aggregate": "server", + }), + [WS_METHODS.serverRefreshProviders]: (_input) => + observeRpcEffect( + WS_METHODS.serverRefreshProviders, + providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.serverUpsertKeybinding]: (rule) => + observeRpcEffect( + WS_METHODS.serverUpsertKeybinding, + Effect.gen(function* () { + const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule); + return { keybindings: keybindingsConfig, issues: [] }; + }), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.serverGetSettings]: (_input) => + observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, { + "rpc.aggregate": "server", + }), + [WS_METHODS.serverUpdateSettings]: ({ patch }) => + observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), { + "rpc.aggregate": "server", + }), + [WS_METHODS.projectsSearchEntries]: (input) => + observeRpcEffect( + WS_METHODS.projectsSearchEntries, + workspaceEntries.search(input).pipe( + Effect.mapError( + (cause) => + new ProjectSearchEntriesError({ + message: `Failed to search workspace entries: ${cause.detail}`, + cause, + }), + ), + ), + { "rpc.aggregate": "workspace" }, + ), + [WS_METHODS.projectsWriteFile]: (input) => + observeRpcEffect( + WS_METHODS.projectsWriteFile, + workspaceFileSystem.writeFile(input).pipe( + Effect.mapError((cause) => { + const message = Schema.is(WorkspacePathOutsideRootError)(cause) + ? "Workspace file path must stay within the project root." + : "Failed to write workspace file"; + return new ProjectWriteFileError({ + message, + cause, + }); + }), + ), + { "rpc.aggregate": "workspace" }, + ), + [WS_METHODS.shellOpenInEditor]: (input) => + observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), { + "rpc.aggregate": "workspace", + }), + [WS_METHODS.gitStatus]: (input) => + observeRpcEffect(WS_METHODS.gitStatus, gitManager.status(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitPull]: (input) => + observeRpcEffect(WS_METHODS.gitPull, git.pullCurrentBranch(input.cwd), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitRunStackedAction]: (input) => + observeRpcStream( + WS_METHODS.gitRunStackedAction, + Stream.callback((queue) => + gitManager + .runStackedAction(input, { + actionId: input.actionId, + progressReporter: { + publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid), + }, + }) + .pipe( + Effect.matchCauseEffect({ + onFailure: (cause) => Queue.failCause(queue, cause), + onSuccess: () => Queue.end(queue).pipe(Effect.asVoid), + }), + ), + ), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitResolvePullRequest]: (input) => + observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitPreparePullRequestThread]: (input) => + observeRpcEffect( + WS_METHODS.gitPreparePullRequestThread, + gitManager.preparePullRequestThread(input), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitListBranches]: (input) => + observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitCreateWorktree]: (input) => + observeRpcEffect(WS_METHODS.gitCreateWorktree, git.createWorktree(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitRemoveWorktree]: (input) => + observeRpcEffect(WS_METHODS.gitRemoveWorktree, git.removeWorktree(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitCreateBranch]: (input) => + observeRpcEffect(WS_METHODS.gitCreateBranch, git.createBranch(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitCheckout]: (input) => + observeRpcEffect(WS_METHODS.gitCheckout, Effect.scoped(git.checkoutBranch(input)), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitInit]: (input) => + observeRpcEffect(WS_METHODS.gitInit, git.initRepo(input), { "rpc.aggregate": "git" }), + [WS_METHODS.terminalOpen]: (input) => + observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalWrite]: (input) => + observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalResize]: (input) => + observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalClear]: (input) => + observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalRestart]: (input) => + observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalClose]: (input) => + observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.subscribeTerminalEvents]: (_input) => + observeRpcStream( + WS_METHODS.subscribeTerminalEvents, + Stream.callback((queue) => + Effect.acquireRelease( + terminalManager.subscribe((event) => Queue.offer(queue, event)), + (unsubscribe) => Effect.sync(unsubscribe), + ), + ), + { "rpc.aggregate": "terminal" }, + ), + [WS_METHODS.subscribeServerConfig]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeServerConfig, + Effect.gen(function* () { + const keybindingsUpdates = keybindings.streamChanges.pipe( + Stream.map((event) => ({ + version: 1 as const, + type: "keybindingsUpdated" as const, + payload: { + issues: event.issues, + }, + })), + ); + const providerStatuses = providerRegistry.streamChanges.pipe( + Stream.map((providers) => ({ + version: 1 as const, + type: "providerStatuses" as const, + payload: { providers }, + })), + ); + const settingsUpdates = serverSettings.streamChanges.pipe( + Stream.map((settings) => ({ + version: 1 as const, + type: "settingsUpdated" as const, + payload: { settings }, + })), + ); + + return Stream.concat( + Stream.make({ + version: 1 as const, + type: "snapshot" as const, + config: yield* loadServerConfig, + }), + Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)), + ); + }), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.subscribeServerLifecycle]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeServerLifecycle, + Effect.gen(function* () { + const snapshot = yield* lifecycleEvents.snapshot; + const snapshotEvents = Array.from(snapshot.events).toSorted( + (left, right) => left.sequence - right.sequence, + ); + const liveEvents = lifecycleEvents.stream.pipe( + Stream.filter((event) => event.sequence > snapshot.sequence), + ); + return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents); + }), + { "rpc.aggregate": "server" }, + ), + }); + }), +); + +export const websocketRpcRouteLayer = Layer.unwrap( + Effect.gen(function* () { + const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, { + spanPrefix: "ws.rpc", + spanAttributes: { + "rpc.transport": "websocket", + "rpc.system": "effect-rpc", + }, + }).pipe(Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson))); + return HttpRouter.add( + "GET", + "/ws", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const config = yield* ServerConfig; + if (config.authToken) { + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) { + return HttpServerResponse.text("Invalid WebSocket URL", { status: 400 }); + } + const token = url.value.searchParams.get("token"); + if (token !== config.authToken) { + return HttpServerResponse.text("Unauthorized WebSocket connection", { status: 401 }); + } + } + return yield* rpcWebSocketHttpEffect; + }), + ); + }), +); diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts deleted file mode 100644 index 0c64f78773..0000000000 --- a/apps/server/src/wsServer.test.ts +++ /dev/null @@ -1,937 +0,0 @@ -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { EventEmitter } from "node:events"; - -import { describe, expect, it, afterEach, vi } from "vitest"; -import { createServer } from "./wsServer"; -import WebSocket from "ws"; - -import { - DEFAULT_TERMINAL_ID, - WS_CHANNELS, - WS_METHODS, - type KeybindingsConfig, - type ResolvedKeybindingsConfig, - type WsPush, - type WsResponse, -} from "@t3tools/contracts"; -import { ProjectRegistry } from "./projectRegistry"; -import { compileResolvedKeybindingRule, DEFAULT_KEYBINDINGS } from "./keybindings"; -import type { - TerminalClearInput, - TerminalCloseInput, - TerminalEvent, - TerminalOpenInput, - TerminalResizeInput, - TerminalSessionSnapshot, - TerminalWriteInput, -} from "@t3tools/contracts"; -import type { TerminalManager } from "./terminalManager"; - -interface PendingMessages { - queue: unknown[]; - waiters: Array<(message: unknown) => void>; -} - -const pendingBySocket = new WeakMap(); - -class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }> { - private readonly sessions = new Map(); - - private key(threadId: string, terminalId: string): string { - return `${threadId}\u0000${terminalId}`; - } - - async open(input: TerminalOpenInput): Promise { - const now = new Date().toISOString(); - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - const snapshot: TerminalSessionSnapshot = { - threadId: input.threadId, - terminalId, - cwd: input.cwd, - status: "running", - pid: 4242, - history: "", - exitCode: null, - exitSignal: null, - updatedAt: now, - }; - this.sessions.set(this.key(input.threadId, terminalId), snapshot); - queueMicrotask(() => { - this.emit("event", { - type: "started", - threadId: input.threadId, - terminalId, - createdAt: now, - snapshot, - }); - }); - return snapshot; - } - - async write(input: TerminalWriteInput): Promise { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - const existing = this.sessions.get(this.key(input.threadId, terminalId)); - if (!existing) { - throw new Error(`Unknown terminal thread: ${input.threadId}`); - } - queueMicrotask(() => { - this.emit("event", { - type: "output", - threadId: input.threadId, - terminalId, - createdAt: new Date().toISOString(), - data: input.data, - }); - }); - } - - async resize(_input: TerminalResizeInput): Promise {} - - async clear(input: TerminalClearInput): Promise { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - queueMicrotask(() => { - this.emit("event", { - type: "cleared", - threadId: input.threadId, - terminalId, - createdAt: new Date().toISOString(), - }); - }); - } - - async restart(input: TerminalOpenInput): Promise { - const now = new Date().toISOString(); - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - const snapshot: TerminalSessionSnapshot = { - threadId: input.threadId, - terminalId, - cwd: input.cwd, - status: "running", - pid: 5252, - history: "", - exitCode: null, - exitSignal: null, - updatedAt: now, - }; - this.sessions.set(this.key(input.threadId, terminalId), snapshot); - queueMicrotask(() => { - this.emit("event", { - type: "restarted", - threadId: input.threadId, - terminalId, - createdAt: now, - snapshot, - }); - }); - return snapshot; - } - - async close(input: TerminalCloseInput): Promise { - if (input.terminalId) { - this.sessions.delete(this.key(input.threadId, input.terminalId)); - return; - } - for (const key of [...this.sessions.keys()]) { - if (key.startsWith(`${input.threadId}\u0000`)) { - this.sessions.delete(key); - } - } - } - - dispose(): void {} -} - -function connectWs(port: number, token?: string): Promise { - return new Promise((resolve, reject) => { - const query = token ? `?token=${encodeURIComponent(token)}` : ""; - const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`); - const pending: PendingMessages = { queue: [], waiters: [] }; - pendingBySocket.set(ws, pending); - - ws.on("message", (raw) => { - const parsed = JSON.parse(String(raw)); - const waiter = pending.waiters.shift(); - if (waiter) { - waiter(parsed); - return; - } - pending.queue.push(parsed); - }); - - ws.once("open", () => resolve(ws)); - ws.once("error", () => reject(new Error("WebSocket connection failed"))); - }); -} - -function waitForMessage(ws: WebSocket): Promise { - const pending = pendingBySocket.get(ws); - if (!pending) { - return Promise.reject(new Error("WebSocket not initialized")); - } - - const queued = pending.queue.shift(); - if (queued !== undefined) { - return Promise.resolve(queued); - } - - return new Promise((resolve) => { - pending.waiters.push(resolve); - }); -} - -async function sendRequest(ws: WebSocket, method: string, params?: unknown): Promise { - const id = crypto.randomUUID(); - const message = JSON.stringify({ id, method, ...(params !== undefined ? { params } : {}) }); - ws.send(message); - - // Wait for response with matching id - while (true) { - const parsed = (await waitForMessage(ws)) as Record; - if (parsed.id === id) { - return parsed as WsResponse; - } - } -} - -function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig { - const resolved: ResolvedKeybindingsConfig = []; - for (const binding of bindings) { - const compiled = compileResolvedKeybindingRule(binding); - if (!compiled) { - throw new Error(`Unexpected invalid keybinding in test setup: ${binding.command}`); - } - resolved.push(compiled); - } - return resolved; -} - -const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]); - -function mergeWithDefaultsForTest(custom: KeybindingsConfig): ResolvedKeybindingsConfig { - if (custom.length === 0) { - return DEFAULT_RESOLVED_KEYBINDINGS; - } - - const overriddenCommands = new Set(custom.map((binding) => binding.command)); - const retainedDefaults = DEFAULT_KEYBINDINGS.filter( - (binding) => !overriddenCommands.has(binding.command), - ); - return compileKeybindings([...retainedDefaults, ...custom].slice(-256)); -} - -describe("WebSocket Server", () => { - let server: ReturnType | null = null; - const connections: WebSocket[] = []; - const tempDirs: string[] = []; - - function makeTempDir(prefix: string): string { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); - tempDirs.push(dir); - return dir; - } - - function createTestServer( - options: { - cwd?: string; - devUrl?: string; - authToken?: string; - stateDir?: string; - gitManager?: { - status: (input: { cwd: string }) => Promise; - runStackedAction: (input: { cwd: string; action: string }) => Promise; - }; - terminalManager?: TerminalManager; - } = {}, - ): ReturnType { - const stateDir = options.stateDir ?? makeTempDir("t3code-ws-state-"); - return createServer({ - port: 0, - cwd: options.cwd ?? "/test/project", - ...(options.devUrl ? { devUrl: options.devUrl } : {}), - ...(options.authToken ? { authToken: options.authToken } : {}), - projectRegistry: new ProjectRegistry(stateDir), - ...(options.gitManager ? { gitManager: options.gitManager as never } : {}), - ...(options.terminalManager ? { terminalManager: options.terminalManager } : {}), - }); - } - - afterEach(async () => { - for (const ws of connections) { - ws.close(); - } - connections.length = 0; - if (server) { - await server.stop(); - } - server = null; - for (const dir of tempDirs.splice(0, tempDirs.length)) { - fs.rmSync(dir, { recursive: true, force: true }); - } - vi.restoreAllMocks(); - }); - - it("sends welcome message on connect", async () => { - server = createTestServer({ cwd: "/test/project" }); - // Get the actual port after listen - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const ws = await connectWs(port); - connections.push(ws); - - const message = (await waitForMessage(ws)) as WsPush; - expect(message.type).toBe("push"); - expect(message.channel).toBe(WS_CHANNELS.serverWelcome); - expect(message.data).toEqual({ - cwd: "/test/project", - projectName: "project", - }); - }); - - it("logs outbound websocket push events in dev mode", async () => { - const logSpy = vi.spyOn(console, "log").mockImplementation(() => { - // Keep test output clean while verifying websocket logs. - }); - - server = createTestServer({ - cwd: "/test/project", - devUrl: "http://localhost:5173", - }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const ws = await connectWs(port); - connections.push(ws); - await waitForMessage(ws); - - expect( - logSpy.mock.calls.some(([message]) => { - if (typeof message !== "string") return false; - return ( - message.includes("[ws]") && - message.includes("outgoing push") && - message.includes(`channel="${WS_CHANNELS.serverWelcome}"`) - ); - }), - ).toBe(true); - }); - - it("responds to server.getConfig", async () => { - server = createTestServer({ cwd: "/my/workspace" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - - // Consume welcome message - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - cwd: "/my/workspace", - keybindings: DEFAULT_RESOLVED_KEYBINDINGS, - }); - }); - - it("reads keybindings from ~/.t3/keybindings.json", async () => { - const fakeHome = makeTempDir("t3code-home-"); - const configDir = path.join(fakeHome, ".t3"); - fs.mkdirSync(configDir, { recursive: true }); - fs.writeFileSync( - path.join(configDir, "keybindings.json"), - JSON.stringify([ - { key: "cmd+j", command: "terminal.toggle" }, - { key: "mod+d", command: "terminal.split", when: "terminalFocus" }, - { key: "mod+n", command: "terminal.new", when: "terminalFocus" }, - ]), - "utf8", - ); - vi.spyOn(os, "homedir").mockReturnValue(fakeHome); - - server = createTestServer({ cwd: "/my/workspace" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - cwd: "/my/workspace", - keybindings: mergeWithDefaultsForTest([ - { key: "cmd+j", command: "terminal.toggle" }, - { key: "mod+d", command: "terminal.split", when: "terminalFocus" }, - { key: "mod+n", command: "terminal.new", when: "terminalFocus" }, - ]), - }); - }); - - it("warns and ignores invalid keybinding entries", async () => { - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - const fakeHome = makeTempDir("t3code-home-invalid-entry-"); - const configDir = path.join(fakeHome, ".t3"); - fs.mkdirSync(configDir, { recursive: true }); - fs.writeFileSync( - path.join(configDir, "keybindings.json"), - JSON.stringify([ - { key: "mod+j", command: "terminal.toggle" }, - { key: "mod+z", command: "invalid.command", when: "terminalFocus" }, - ]), - "utf8", - ); - vi.spyOn(os, "homedir").mockReturnValue(fakeHome); - - server = createTestServer({ cwd: "/my/workspace" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - cwd: "/my/workspace", - keybindings: mergeWithDefaultsForTest([{ key: "mod+j", command: "terminal.toggle" }]), - }); - expect( - warnSpy.mock.calls.some(([message]) => - String(message).includes("ignoring invalid keybinding entries"), - ), - ).toBe(true); - }); - - it("warns and ignores keybindings with malformed when expressions", async () => { - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - const fakeHome = makeTempDir("t3code-home-invalid-when-"); - const configDir = path.join(fakeHome, ".t3"); - fs.mkdirSync(configDir, { recursive: true }); - fs.writeFileSync( - path.join(configDir, "keybindings.json"), - JSON.stringify([{ key: "mod+j", command: "terminal.toggle", when: "terminalFocus && (" }]), - "utf8", - ); - vi.spyOn(os, "homedir").mockReturnValue(fakeHome); - - server = createTestServer({ cwd: "/my/workspace" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - cwd: "/my/workspace", - keybindings: DEFAULT_RESOLVED_KEYBINDINGS, - }); - expect( - warnSpy.mock.calls.some(([message]) => - String(message).includes("ignoring invalid keybinding entries"), - ), - ).toBe(true); - }); - - it("reads keybindings once at startup and caches the resolved config", async () => { - const fakeHome = makeTempDir("t3code-home-cached-config-"); - const configDir = path.join(fakeHome, ".t3"); - fs.mkdirSync(configDir, { recursive: true }); - const keybindingsPath = path.join(configDir, "keybindings.json"); - fs.writeFileSync( - keybindingsPath, - JSON.stringify([{ key: "cmd+j", command: "terminal.toggle" }]), - "utf8", - ); - vi.spyOn(os, "homedir").mockReturnValue(fakeHome); - - server = createTestServer({ cwd: "/my/workspace" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - await waitForMessage(ws); - - const firstResponse = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(firstResponse.error).toBeUndefined(); - expect(firstResponse.result).toEqual({ - cwd: "/my/workspace", - keybindings: mergeWithDefaultsForTest([{ key: "cmd+j", command: "terminal.toggle" }]), - }); - - fs.writeFileSync( - keybindingsPath, - JSON.stringify([{ key: "cmd+k", command: "terminal.toggle" }]), - "utf8", - ); - - const secondResponse = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(secondResponse.error).toBeUndefined(); - expect(secondResponse.result).toEqual(firstResponse.result); - }); - - it("warns and ignores unsupported keybindings config format", async () => { - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - const fakeHome = makeTempDir("t3code-home-unsupported-format-"); - const configDir = path.join(fakeHome, ".t3"); - fs.mkdirSync(configDir, { recursive: true }); - fs.writeFileSync( - path.join(configDir, "keybindings.json"), - JSON.stringify({ "terminal.toggle": "mod+j" }), - "utf8", - ); - vi.spyOn(os, "homedir").mockReturnValue(fakeHome); - - server = createTestServer({ cwd: "/my/workspace" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - cwd: "/my/workspace", - keybindings: DEFAULT_RESOLVED_KEYBINDINGS, - }); - expect( - warnSpy.mock.calls.some(([message]) => - String(message).includes("unsupported format; expected array"), - ), - ).toBe(true); - }); - - it("warns and ignores malformed keybindings config files", async () => { - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - const fakeHome = makeTempDir("t3code-home-invalid-"); - const configDir = path.join(fakeHome, ".t3"); - fs.mkdirSync(configDir, { recursive: true }); - fs.writeFileSync(path.join(configDir, "keybindings.json"), "{not-json", "utf8"); - vi.spyOn(os, "homedir").mockReturnValue(fakeHome); - - server = createTestServer({ cwd: "/my/workspace" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - cwd: "/my/workspace", - keybindings: DEFAULT_RESOLVED_KEYBINDINGS, - }); - expect( - warnSpy.mock.calls.some(([message]) => - String(message).includes("ignoring malformed keybindings config"), - ), - ).toBe(true); - }); - - it("returns error for unknown methods", async () => { - server = createTestServer({ cwd: "/test" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - - // Consume welcome - await waitForMessage(ws); - - const response = await sendRequest(ws, "nonexistent.method"); - expect(response.error).toBeDefined(); - expect(response.error!.message).toContain("Unknown method"); - }); - - it("responds to providers.listSessions with empty array", async () => { - server = createTestServer({ cwd: "/test" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - - // Consume welcome - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.providersListSessions); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual([]); - }); - - it("routes terminal RPC methods and broadcasts terminal events", async () => { - const cwd = makeTempDir("t3code-ws-terminal-cwd-"); - const terminalManager = new MockTerminalManager(); - server = createTestServer({ - cwd: "/test", - terminalManager: terminalManager as unknown as TerminalManager, - }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - await waitForMessage(ws); - - const open = await sendRequest(ws, WS_METHODS.terminalOpen, { - threadId: "thread-1", - cwd, - cols: 100, - rows: 24, - }); - expect(open.error).toBeUndefined(); - expect((open.result as TerminalSessionSnapshot).threadId).toBe("thread-1"); - expect((open.result as TerminalSessionSnapshot).terminalId).toBe(DEFAULT_TERMINAL_ID); - - const write = await sendRequest(ws, WS_METHODS.terminalWrite, { - threadId: "thread-1", - data: "echo hello\n", - }); - expect(write.error).toBeUndefined(); - - const resize = await sendRequest(ws, WS_METHODS.terminalResize, { - threadId: "thread-1", - cols: 120, - rows: 30, - }); - expect(resize.error).toBeUndefined(); - - const clear = await sendRequest(ws, WS_METHODS.terminalClear, { - threadId: "thread-1", - }); - expect(clear.error).toBeUndefined(); - - const restart = await sendRequest(ws, WS_METHODS.terminalRestart, { - threadId: "thread-1", - cwd, - cols: 120, - rows: 30, - }); - expect(restart.error).toBeUndefined(); - - const close = await sendRequest(ws, WS_METHODS.terminalClose, { - threadId: "thread-1", - deleteHistory: true, - }); - expect(close.error).toBeUndefined(); - - const manualEvent: TerminalEvent = { - type: "output", - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - createdAt: new Date().toISOString(), - data: "manual test output\n", - }; - terminalManager.emit("event", manualEvent); - - const push = (await waitForMessage(ws)) as WsPush; - expect(push.type).toBe("push"); - expect(push.channel).toBe(WS_CHANNELS.terminalEvent); - expect((push.data as TerminalEvent).type).toBe("output"); - }); - - it("detaches terminal event listener on stop for injected manager", async () => { - const terminalManager = new MockTerminalManager(); - server = createTestServer({ - cwd: "/test", - terminalManager: terminalManager as unknown as TerminalManager, - }); - await server.start(); - - expect(terminalManager.listenerCount("event")).toBe(1); - - await server.stop(); - server = null; - - expect(terminalManager.listenerCount("event")).toBe(0); - }); - - it("returns validation errors for invalid terminal open params", async () => { - server = createTestServer({ cwd: "/test" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.terminalOpen, { - threadId: "", - cwd: "", - cols: 1, - rows: 1, - }); - expect(response.error).toBeDefined(); - }); - - it("handles invalid JSON gracefully", async () => { - server = createTestServer({ cwd: "/test" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - - // Consume welcome - await waitForMessage(ws); - - // Send garbage - ws.send("not json at all"); - - const response = (await waitForMessage(ws)) as WsResponse; - expect(response.error).toBeDefined(); - expect(response.error!.message).toContain("Invalid request format"); - }); - - it("supports projects list/add/dedupe/remove", async () => { - const stateDir = makeTempDir("t3code-ws-projects-state-"); - const firstProjectCwd = makeTempDir("t3code-ws-project-a-"); - - server = createTestServer({ stateDir, cwd: "/test" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - await waitForMessage(ws); - - const emptyList = await sendRequest(ws, WS_METHODS.projectsList); - expect(emptyList.error).toBeUndefined(); - expect(emptyList.result).toEqual([]); - - const created = await sendRequest(ws, WS_METHODS.projectsAdd, { - cwd: firstProjectCwd, - }); - expect(created.error).toBeUndefined(); - expect((created.result as { created: boolean }).created).toBe(true); - - const duplicate = await sendRequest(ws, WS_METHODS.projectsAdd, { - cwd: firstProjectCwd, - }); - expect(duplicate.error).toBeUndefined(); - expect((duplicate.result as { created: boolean }).created).toBe(false); - - const listed = await sendRequest(ws, WS_METHODS.projectsList); - expect(listed.error).toBeUndefined(); - const listedProjects = listed.result as Array<{ id: string; cwd: string }>; - expect(listedProjects).toHaveLength(1); - - const projectId = listedProjects[0]?.id; - expect(projectId).toBeTruthy(); - if (!projectId) return; - - const removed = await sendRequest(ws, WS_METHODS.projectsRemove, { - id: projectId, - }); - expect(removed.error).toBeUndefined(); - - const afterRemove = await sendRequest(ws, WS_METHODS.projectsList); - expect(afterRemove.error).toBeUndefined(); - expect(afterRemove.result).toEqual([]); - }); - - it("supports git methods over websocket", async () => { - const repoCwd = makeTempDir("t3code-ws-git-project-"); - - server = createTestServer({ cwd: "/test" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - await waitForMessage(ws); - - const beforeInit = await sendRequest(ws, WS_METHODS.gitListBranches, { cwd: repoCwd }); - expect(beforeInit.error).toBeUndefined(); - expect(beforeInit.result).toEqual({ branches: [], isRepo: false }); - - const initResponse = await sendRequest(ws, WS_METHODS.gitInit, { cwd: repoCwd }); - expect(initResponse.error).toBeUndefined(); - - const afterInit = await sendRequest(ws, WS_METHODS.gitListBranches, { - cwd: repoCwd, - }); - expect(afterInit.error).toBeUndefined(); - expect((afterInit.result as { isRepo: boolean }).isRepo).toBe(true); - - const pullResponse = await sendRequest(ws, WS_METHODS.gitPull, { cwd: repoCwd }); - expect(pullResponse.result).toBeUndefined(); - expect(pullResponse.error?.message).toBeDefined(); - expect(pullResponse.error?.message).not.toContain("Unknown method"); - }); - - it("responds to git.status via the git manager", async () => { - const gitManager = { - status: vi.fn().mockResolvedValue({ - branch: "feature/test", - hasWorkingTreeChanges: true, - workingTree: { - files: [{ path: "src/index.ts", insertions: 7, deletions: 2 }], - insertions: 7, - deletions: 2, - }, - hasUpstream: false, - aheadCount: 0, - behindCount: 0, - openPr: null, - }), - runStackedAction: vi.fn(), - }; - - server = createTestServer({ cwd: "/test", gitManager }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.gitStatus, { - cwd: "/test", - }); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - branch: "feature/test", - hasWorkingTreeChanges: true, - workingTree: { - files: [{ path: "src/index.ts", insertions: 7, deletions: 2 }], - insertions: 7, - deletions: 2, - }, - hasUpstream: false, - aheadCount: 0, - behindCount: 0, - openPr: null, - }); - expect(gitManager.status).toHaveBeenCalledWith({ cwd: "/test" }); - }); - - it("returns errors from git.runStackedAction", async () => { - const gitManager = { - status: vi.fn(), - runStackedAction: vi.fn().mockRejectedValue(new Error("Cannot push from detached HEAD.")), - }; - - server = createTestServer({ cwd: "/test", gitManager }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.gitRunStackedAction, { - cwd: "/test", - action: "commit_push", - }); - expect(response.result).toBeUndefined(); - expect(response.error?.message).toContain("detached HEAD"); - expect(gitManager.runStackedAction).toHaveBeenCalledWith({ - cwd: "/test", - action: "commit_push", - }); - }); - - it("prunes missing projects on startup", async () => { - const stateDir = makeTempDir("t3code-ws-prune-state-"); - const existing = makeTempDir("t3code-ws-existing-project-"); - const missing = path.join(stateDir, "definitely-missing"); - const now = new Date().toISOString(); - const projectsFile = path.join(stateDir, "projects.json"); - - fs.writeFileSync( - projectsFile, - JSON.stringify( - { - version: 1, - projects: [ - { - id: "project-existing", - cwd: existing, - name: "existing", - createdAt: now, - updatedAt: now, - }, - { - id: "project-missing", - cwd: missing, - name: "missing", - createdAt: now, - updatedAt: now, - }, - ], - }, - null, - 2, - ), - ); - - server = createTestServer({ stateDir, cwd: "/test" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const ws = await connectWs(port); - connections.push(ws); - await waitForMessage(ws); - - const response = await sendRequest(ws, WS_METHODS.projectsList); - expect(response.error).toBeUndefined(); - const listed = response.result as Array<{ id: string }>; - expect(listed).toHaveLength(1); - expect(listed[0]?.id).toBe("project-existing"); - }); - - it("rejects websocket connections without a valid auth token", async () => { - server = createTestServer({ cwd: "/test", authToken: "secret-token" }); - await server.start(); - const addr = server.httpServer.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed"); - - const authorizedWs = await connectWs(port, "secret-token"); - connections.push(authorizedWs); - const welcome = (await waitForMessage(authorizedWs)) as WsPush; - expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome); - }); -}); diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts deleted file mode 100644 index a8cbbba51e..0000000000 --- a/apps/server/src/wsServer.ts +++ /dev/null @@ -1,488 +0,0 @@ -import { spawn } from "node:child_process"; -import fs from "node:fs"; -import http from "node:http"; -import os from "node:os"; -import path from "node:path"; -import type { Duplex } from "node:stream"; - -import { - EDITORS, - WS_CHANNELS, - WS_METHODS, - type TerminalEvent, - type WsPush, - type WsRequest, - type WsResponse, - wsRequestSchema, -} from "@t3tools/contracts"; -import { WebSocketServer, type WebSocket } from "ws"; - -import { createLogger } from "./logger"; -import { ProjectRegistry } from "./projectRegistry"; -import { ProviderManager } from "./providerManager"; -import { GitManager } from "./gitManager"; -import { - checkoutGitBranch, - createGitBranch, - createGitWorktree, - initGitRepo, - listGitBranches, - pullGitBranch, - removeGitWorktree, -} from "./git"; -import { TerminalManager } from "./terminalManager"; -import { loadResolvedKeybindingsConfig } from "./keybindings"; - -const MIME_TYPES: Record = { - ".html": "text/html; charset=utf-8", - ".js": "application/javascript; charset=utf-8", - ".css": "text/css; charset=utf-8", - ".json": "application/json; charset=utf-8", - ".png": "image/png", - ".jpg": "image/jpeg", - ".svg": "image/svg+xml", - ".ico": "image/x-icon", - ".woff": "font/woff", - ".woff2": "font/woff2", - ".ttf": "font/ttf", - ".map": "application/json", -}; - -export interface ServerOptions { - port: number; - host?: string | undefined; - cwd: string; - staticDir?: string | undefined; - devUrl?: string | undefined; - logWebSocketEvents?: boolean | undefined; - projectRegistry?: ProjectRegistry | undefined; - gitManager?: GitManager | undefined; - terminalManager?: TerminalManager | undefined; - authToken?: string | undefined; -} - -function parseBooleanEnv(value: string | undefined): boolean | undefined { - if (value === undefined) return undefined; - const normalized = value.trim().toLowerCase(); - if (["1", "true", "yes", "on"].includes(normalized)) return true; - if (["0", "false", "no", "off"].includes(normalized)) return false; - return undefined; -} - -export function createServer(options: ServerOptions) { - const { - port, - host, - cwd, - staticDir, - devUrl, - logWebSocketEvents: explicitLogWsEvents, - projectRegistry: providedRegistry, - gitManager: providedGitManager, - terminalManager: providedTerminalManager, - authToken, - } = options; - const providerManager = new ProviderManager(); - const terminalManager = providedTerminalManager ?? new TerminalManager(); - const projectRegistry = - providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata")); - const gitManager = providedGitManager ?? new GitManager(); - const clients = new Set(); - const logger = createLogger("ws"); - const logWebSocketEvents = - explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl); - const keybindingsConfig = loadResolvedKeybindingsConfig(logger); - - function logOutgoingPush(push: WsPush, recipients: number) { - if (!logWebSocketEvents) return; - logger.event("outgoing push", { - channel: push.channel, - recipients, - payload: push.data, - }); - } - - // Forward provider events to all connected WebSocket clients - providerManager.on("event", (event) => { - const push: WsPush = { - type: "push", - channel: WS_CHANNELS.providerEvent, - data: event, - }; - const message = JSON.stringify(push); - let recipients = 0; - for (const client of clients) { - if (client.readyState === client.OPEN) { - client.send(message); - recipients += 1; - } - } - logOutgoingPush(push, recipients); - }); - - const onTerminalEvent = (event: TerminalEvent) => { - const push: WsPush = { - type: "push", - channel: WS_CHANNELS.terminalEvent, - data: event, - }; - const message = JSON.stringify(push); - let recipients = 0; - for (const client of clients) { - if (client.readyState === client.OPEN) { - client.send(message); - recipients += 1; - } - } - logOutgoingPush(push, recipients); - }; - terminalManager.on("event", onTerminalEvent); - - // HTTP server — serves static files or redirects to Vite dev server - const httpServer = http.createServer((req, res) => { - // In dev mode, redirect to Vite dev server - if (devUrl) { - res.writeHead(302, { Location: devUrl }); - res.end(); - return; - } - - // Serve static files from the web app build - if (!staticDir) { - res.writeHead(503, { "Content-Type": "text/plain" }); - res.end("No static directory configured and no dev URL set."); - return; - } - - const url = new URL(req.url ?? "/", `http://localhost:${port}`); - let filePath = path.join(staticDir, url.pathname); - - // SPA fallback: if no file extension and not found, serve index.html - const ext = path.extname(filePath); - if (!ext) { - filePath = path.join(filePath, "index.html"); - } - - fs.stat(filePath, (err, stats) => { - if (err || !stats?.isFile()) { - // SPA fallback - const indexPath = path.join(staticDir, "index.html"); - fs.readFile(indexPath, (readErr, data) => { - if (readErr) { - res.writeHead(404, { "Content-Type": "text/plain" }); - res.end("Not Found"); - return; - } - res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); - res.end(data); - }); - return; - } - - const fileExt = path.extname(filePath); - const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream"; - - fs.readFile(filePath, (readErr, data) => { - if (readErr) { - res.writeHead(500, { "Content-Type": "text/plain" }); - res.end("Internal Server Error"); - return; - } - res.writeHead(200, { "Content-Type": contentType }); - res.end(data); - }); - }); - }); - - // WebSocket server — upgrades from the HTTP server - const wss = new WebSocketServer({ noServer: true }); - - function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void { - socket.write( - `HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` + - "Connection: close\r\n" + - "Content-Type: text/plain\r\n" + - `Content-Length: ${Buffer.byteLength(message)}\r\n` + - "\r\n" + - message, - ); - socket.destroy(); - } - - httpServer.on("upgrade", (request, socket, head) => { - if (authToken) { - let providedToken: string | null = null; - try { - const url = new URL(request.url ?? "/", `http://localhost:${port}`); - providedToken = url.searchParams.get("token"); - } catch { - rejectUpgrade(socket, 400, "Invalid WebSocket URL"); - return; - } - - if (providedToken !== authToken) { - rejectUpgrade(socket, 401, "Unauthorized WebSocket connection"); - return; - } - } - - wss.handleUpgrade(request, socket, head, (ws) => { - wss.emit("connection", ws, request); - }); - }); - - wss.on("connection", (ws) => { - clients.add(ws); - - // Send welcome message with project info - const segments = cwd.split(/[/\\]/).filter(Boolean); - const projectName = segments[segments.length - 1] ?? "project"; - - const welcome: WsPush = { - type: "push", - channel: WS_CHANNELS.serverWelcome, - data: { cwd, projectName }, - }; - logOutgoingPush(welcome, 1); - ws.send(JSON.stringify(welcome)); - - ws.on("message", (raw) => { - void handleMessage(ws, raw); - }); - - ws.on("close", () => { - clients.delete(ws); - }); - - ws.on("error", () => { - clients.delete(ws); - }); - }); - - async function handleMessage(ws: WebSocket, raw: unknown) { - let request: WsRequest; - try { - const parsed = JSON.parse(String(raw)); - request = wsRequestSchema.parse(parsed); - } catch { - const errorResponse: WsResponse = { - id: "unknown", - error: { message: "Invalid request format" }, - }; - ws.send(JSON.stringify(errorResponse)); - return; - } - - try { - const result = await routeRequest(request); - const response: WsResponse = { id: request.id, result }; - ws.send(JSON.stringify(response)); - } catch (err) { - const message = err instanceof Error ? err.message : "Unknown server error"; - const response: WsResponse = { - id: request.id, - error: { message }, - }; - ws.send(JSON.stringify(response)); - } - } - - async function routeRequest(request: WsRequest): Promise { - switch (request.method) { - case WS_METHODS.providersStartSession: - return providerManager.startSession(request.params as never); - - case WS_METHODS.providersSendTurn: - return providerManager.sendTurn(request.params as never); - - case WS_METHODS.providersInterruptTurn: - return providerManager.interruptTurn(request.params as never); - - case WS_METHODS.providersRespondToRequest: - return providerManager.respondToRequest(request.params as never); - - case WS_METHODS.providersStopSession: { - providerManager.stopSession(request.params as never); - return undefined; - } - - case WS_METHODS.providersListSessions: - return providerManager.listSessions(); - - case WS_METHODS.projectsList: - return projectRegistry.list(); - - case WS_METHODS.projectsAdd: - return projectRegistry.add(request.params as never); - - case WS_METHODS.projectsRemove: - projectRegistry.remove(request.params as never); - return undefined; - - case WS_METHODS.shellOpenInEditor: { - const params = request.params as { - cwd: string; - editor: string; - }; - if (!params?.cwd) throw new Error("cwd is required"); - const editorDef = EDITORS.find((e) => e.id === params.editor); - if (!editorDef) throw new Error(`Unknown editor: ${params.editor}`); - - let command: string; - let args: string[]; - - if (editorDef.command) { - command = editorDef.command; - args = [params.cwd]; - } else if (editorDef.id === "file-manager") { - // Use platform-specific file manager command - switch (process.platform) { - case "darwin": - command = "open"; - break; - case "win32": - command = "explorer"; - break; - default: - command = "xdg-open"; - break; - } - args = [params.cwd]; - } else { - return undefined; - } - - const child = spawn(command, args, { - detached: true, - stdio: "ignore", - }); - child.on("error", () => { - /* ignore spawn failures for detached editors */ - }); - child.unref(); - return undefined; - } - - case WS_METHODS.gitStatus: - return gitManager.status(request.params as never); - - case WS_METHODS.gitPull: - return pullGitBranch(request.params as never); - - case WS_METHODS.gitRunStackedAction: - return gitManager.runStackedAction(request.params as never); - case WS_METHODS.gitListBranches: - return listGitBranches(request.params as never); - - case WS_METHODS.gitCreateWorktree: - return createGitWorktree(request.params as never); - - case WS_METHODS.gitRemoveWorktree: - return removeGitWorktree(request.params as never); - - case WS_METHODS.gitCreateBranch: - return createGitBranch(request.params as never); - - case WS_METHODS.gitCheckout: - return checkoutGitBranch(request.params as never); - - case WS_METHODS.gitInit: - return initGitRepo(request.params as never); - - case WS_METHODS.terminalOpen: - return terminalManager.open(request.params as never); - - case WS_METHODS.terminalWrite: - await terminalManager.write(request.params as never); - return undefined; - - case WS_METHODS.terminalResize: - await terminalManager.resize(request.params as never); - return undefined; - - case WS_METHODS.terminalClear: - await terminalManager.clear(request.params as never); - return undefined; - - case WS_METHODS.terminalRestart: - return terminalManager.restart(request.params as never); - - case WS_METHODS.terminalClose: - await terminalManager.close(request.params as never); - return undefined; - - case WS_METHODS.serverGetConfig: - return { - cwd, - keybindings: keybindingsConfig, - }; - - default: - throw new Error(`Unknown method: ${request.method}`); - } - } - - function start() { - return new Promise((resolve, reject) => { - const onError = (error: Error) => { - httpServer.off("error", onError); - reject(error); - }; - httpServer.once("error", onError); - const onListening = () => { - httpServer.off("error", onError); - resolve(); - }; - if (host) { - httpServer.listen(port, host, onListening); - return; - } - httpServer.listen(port, onListening); - }); - } - - async function stop(): Promise { - terminalManager.off("event", onTerminalEvent); - providerManager.stopAll(); - providerManager.dispose(); - terminalManager.dispose(); - - for (const client of clients) { - client.close(); - } - clients.clear(); - - const isServerNotRunningError = (error: unknown): boolean => { - if (!(error instanceof Error)) return false; - const maybeCode = (error as NodeJS.ErrnoException).code; - return ( - maybeCode === "ERR_SERVER_NOT_RUNNING" || - error.message.toLowerCase().includes("not running") - ); - }; - - const closeWebSocketServer = new Promise((resolve, reject) => { - wss.close((error) => { - if (error && !isServerNotRunningError(error)) { - reject(error); - return; - } - resolve(); - }); - }); - - const closeHttpServer = new Promise((resolve, reject) => { - httpServer.close((error) => { - if (error && !isServerNotRunningError(error)) { - reject(error); - return; - } - resolve(); - }); - }); - - await Promise.all([closeWebSocketServer, closeHttpServer]); - } - - return { start, stop, httpServer }; -} diff --git a/apps/server/tsconfig.json b/apps/server/tsconfig.json index bf7111184a..07d52467f5 100644 --- a/apps/server/tsconfig.json +++ b/apps/server/tsconfig.json @@ -2,8 +2,24 @@ "extends": "../../tsconfig.base.json", "compilerOptions": { "composite": true, - "types": ["node"], - "lib": ["ES2023", "esnext.disposable"] + "types": ["node", "bun"], + "lib": ["ES2023", "esnext.disposable"], + "noEmit": true, + "allowImportingTsExtensions": true, + "plugins": [ + { + "name": "@effect/language-service", + "namespaceImportPackages": ["@effect/platform-node"], + "diagnosticSeverity": { + "importFromBarrel": "error", + "anyUnknownInErrorContext": "warning", + "instanceOfSchema": "warning", + "deterministicKeys": "warning", + "preferSchemaOverJson": "off", + "globalErrorInEffectFailure": "off" + } + } + ] }, - "include": ["src", "tsdown.config.ts"] + "include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"] } diff --git a/apps/server/tsdown.config.ts b/apps/server/tsdown.config.ts index 1a67bab626..f11dd37869 100644 --- a/apps/server/tsdown.config.ts +++ b/apps/server/tsdown.config.ts @@ -1,12 +1,15 @@ import { defineConfig } from "tsdown"; export default defineConfig({ - entry: ["src/index.ts"], + entry: ["src/bin.ts"], format: ["esm", "cjs"], + checks: { + legacyCjs: false, + }, outDir: "dist", sourcemap: true, clean: true, - noExternal: ["@t3tools/contracts", "zod"], + noExternal: (id) => id.startsWith("@t3tools/"), inlineOnly: false, banner: { js: "#!/usr/bin/env node\n", diff --git a/apps/server/vitest.config.ts b/apps/server/vitest.config.ts new file mode 100644 index 0000000000..1c5b2f0d38 --- /dev/null +++ b/apps/server/vitest.config.ts @@ -0,0 +1,18 @@ +import { defineConfig, mergeConfig } from "vitest/config"; + +import baseConfig from "../../vitest.config"; + +export default mergeConfig( + baseConfig, + defineConfig({ + test: { + // The server suite exercises sqlite, git, temp worktrees, and orchestration + // runtimes heavily. Running files in parallel introduces load-sensitive flakes. + fileParallelism: false, + // Server integration tests exercise sqlite, git, and orchestration together. + // Under package-wide parallel runs they regularly exceed the default 15s budget. + testTimeout: 60_000, + hookTimeout: 60_000, + }, + }), +); diff --git a/apps/web/index.html b/apps/web/index.html index 25aace82a3..0322f2d019 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -3,13 +3,15 @@ + + - T3 Code + T3 Code (Alpha)
diff --git a/apps/web/package.json b/apps/web/package.json index 8f610f069f..499943c3f0 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,40 +1,64 @@ { "name": "@t3tools/web", - "version": "0.0.0", + "version": "0.0.15", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "vite build", + "prepare": "effect-language-service patch", "preview": "vite preview", "typecheck": "tsc --noEmit", - "test": "vitest run --passWithNoTests" + "test": "vitest run --passWithNoTests", + "test:browser": "vitest run --config vitest.browser.config.ts", + "test:browser:install": "playwright install --with-deps chromium" }, "dependencies": { "@base-ui/react": "^1.2.0", + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/modifiers": "^9.0.0", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", + "@effect/atom-react": "catalog:", + "@formkit/auto-animate": "^0.9.0", + "@lexical/react": "^0.41.0", + "@pierre/diffs": "^1.1.0-beta.16", "@t3tools/contracts": "workspace:*", + "@t3tools/shared": "workspace:*", + "@tanstack/react-pacer": "^0.19.4", "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.160.2", + "@tanstack/react-virtual": "^3.13.18", "@xterm/addon-fit": "^0.11.0", "@xterm/xterm": "^6.0.0", "class-variance-authority": "^0.7.1", - "highlight.js": "^11.11.1", + "effect": "catalog:", + "lexical": "^0.41.0", "lucide-react": "^0.564.0", "react": "^19.0.0", "react-dom": "^19.0.0", "react-markdown": "^10.1.0", - "rehype-highlight": "^7.0.2", "remark-gfm": "^4.0.1", "tailwind-merge": "^3.4.0", - "zod": "^3.24.1" + "zustand": "^5.0.11" }, "devDependencies": { + "@effect/language-service": "catalog:", + "@rolldown/plugin-babel": "^0.2.0", "@tailwindcss/vite": "^4.0.0", + "@tanstack/router-plugin": "^1.161.0", + "@types/babel__core": "^7.20.5", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", - "@vitejs/plugin-react": "^5.1.4", + "@vitejs/plugin-react": "^6.0.0", + "@vitest/browser-playwright": "^4.0.18", "babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112", + "msw": "2.12.11", + "playwright": "^1.58.2", "tailwindcss": "^4.0.0", - "typescript": "^5.7.3", - "vite": "^8.0.0-beta.12" + "typescript": "catalog:", + "vite": "^8.0.0", + "vitest": "catalog:", + "vitest-browser-react": "^2.0.5" } } diff --git a/apps/web/public/apple-touch-icon.png b/apps/web/public/apple-touch-icon.png new file mode 100644 index 0000000000..e0e1b9659b Binary files /dev/null and b/apps/web/public/apple-touch-icon.png differ diff --git a/apps/web/public/favicon-16x16.png b/apps/web/public/favicon-16x16.png new file mode 100644 index 0000000000..673d845999 Binary files /dev/null and b/apps/web/public/favicon-16x16.png differ diff --git a/apps/web/public/favicon-32x32.png b/apps/web/public/favicon-32x32.png new file mode 100644 index 0000000000..25bcc95d4a Binary files /dev/null and b/apps/web/public/favicon-32x32.png differ diff --git a/apps/web/public/favicon.ico b/apps/web/public/favicon.ico new file mode 100644 index 0000000000..36975b9978 Binary files /dev/null and b/apps/web/public/favicon.ico differ diff --git a/apps/web/public/mockServiceWorker.js b/apps/web/public/mockServiceWorker.js new file mode 100644 index 0000000000..8fa9dca80e --- /dev/null +++ b/apps/web/public/mockServiceWorker.js @@ -0,0 +1,349 @@ +/* eslint-disable */ +/* tslint:disable */ + +/** + * Mock Service Worker. + * @see https://github.com/mswjs/msw + * - Please do NOT modify this file. + */ + +const PACKAGE_VERSION = '2.12.11' +const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82' +const IS_MOCKED_RESPONSE = Symbol('isMockedResponse') +const activeClientIds = new Set() + +addEventListener('install', function () { + self.skipWaiting() +}) + +addEventListener('activate', function (event) { + event.waitUntil(self.clients.claim()) +}) + +addEventListener('message', async function (event) { + const clientId = Reflect.get(event.source || {}, 'id') + + if (!clientId || !self.clients) { + return + } + + const client = await self.clients.get(clientId) + + if (!client) { + return + } + + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + switch (event.data) { + case 'KEEPALIVE_REQUEST': { + sendToClient(client, { + type: 'KEEPALIVE_RESPONSE', + }) + break + } + + case 'INTEGRITY_CHECK_REQUEST': { + sendToClient(client, { + type: 'INTEGRITY_CHECK_RESPONSE', + payload: { + packageVersion: PACKAGE_VERSION, + checksum: INTEGRITY_CHECKSUM, + }, + }) + break + } + + case 'MOCK_ACTIVATE': { + activeClientIds.add(clientId) + + sendToClient(client, { + type: 'MOCKING_ENABLED', + payload: { + client: { + id: client.id, + frameType: client.frameType, + }, + }, + }) + break + } + + case 'CLIENT_CLOSED': { + activeClientIds.delete(clientId) + + const remainingClients = allClients.filter((client) => { + return client.id !== clientId + }) + + // Unregister itself when there are no more clients + if (remainingClients.length === 0) { + self.registration.unregister() + } + + break + } + } +}) + +addEventListener('fetch', function (event) { + const requestInterceptedAt = Date.now() + + // Bypass navigation requests. + if (event.request.mode === 'navigate') { + return + } + + // Opening the DevTools triggers the "only-if-cached" request + // that cannot be handled by the worker. Bypass such requests. + if ( + event.request.cache === 'only-if-cached' && + event.request.mode !== 'same-origin' + ) { + return + } + + // Bypass all requests when there are no active clients. + // Prevents the self-unregistered worked from handling requests + // after it's been terminated (still remains active until the next reload). + if (activeClientIds.size === 0) { + return + } + + const requestId = crypto.randomUUID() + event.respondWith(handleRequest(event, requestId, requestInterceptedAt)) +}) + +/** + * @param {FetchEvent} event + * @param {string} requestId + * @param {number} requestInterceptedAt + */ +async function handleRequest(event, requestId, requestInterceptedAt) { + const client = await resolveMainClient(event) + const requestCloneForEvents = event.request.clone() + const response = await getResponse( + event, + client, + requestId, + requestInterceptedAt, + ) + + // Send back the response clone for the "response:*" life-cycle events. + // Ensure MSW is active and ready to handle the message, otherwise + // this message will pend indefinitely. + if (client && activeClientIds.has(client.id)) { + const serializedRequest = await serializeRequest(requestCloneForEvents) + + // Clone the response so both the client and the library could consume it. + const responseClone = response.clone() + + sendToClient( + client, + { + type: 'RESPONSE', + payload: { + isMockedResponse: IS_MOCKED_RESPONSE in response, + request: { + id: requestId, + ...serializedRequest, + }, + response: { + type: responseClone.type, + status: responseClone.status, + statusText: responseClone.statusText, + headers: Object.fromEntries(responseClone.headers.entries()), + body: responseClone.body, + }, + }, + }, + responseClone.body ? [serializedRequest.body, responseClone.body] : [], + ) + } + + return response +} + +/** + * Resolve the main client for the given event. + * Client that issues a request doesn't necessarily equal the client + * that registered the worker. It's with the latter the worker should + * communicate with during the response resolving phase. + * @param {FetchEvent} event + * @returns {Promise} + */ +async function resolveMainClient(event) { + const client = await self.clients.get(event.clientId) + + if (activeClientIds.has(event.clientId)) { + return client + } + + if (client?.frameType === 'top-level') { + return client + } + + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + return allClients + .filter((client) => { + // Get only those clients that are currently visible. + return client.visibilityState === 'visible' + }) + .find((client) => { + // Find the client ID that's recorded in the + // set of clients that have registered the worker. + return activeClientIds.has(client.id) + }) +} + +/** + * @param {FetchEvent} event + * @param {Client | undefined} client + * @param {string} requestId + * @param {number} requestInterceptedAt + * @returns {Promise} + */ +async function getResponse(event, client, requestId, requestInterceptedAt) { + // Clone the request because it might've been already used + // (i.e. its body has been read and sent to the client). + const requestClone = event.request.clone() + + function passthrough() { + // Cast the request headers to a new Headers instance + // so the headers can be manipulated with. + const headers = new Headers(requestClone.headers) + + // Remove the "accept" header value that marked this request as passthrough. + // This prevents request alteration and also keeps it compliant with the + // user-defined CORS policies. + const acceptHeader = headers.get('accept') + if (acceptHeader) { + const values = acceptHeader.split(',').map((value) => value.trim()) + const filteredValues = values.filter( + (value) => value !== 'msw/passthrough', + ) + + if (filteredValues.length > 0) { + headers.set('accept', filteredValues.join(', ')) + } else { + headers.delete('accept') + } + } + + return fetch(requestClone, { headers }) + } + + // Bypass mocking when the client is not active. + if (!client) { + return passthrough() + } + + // Bypass initial page load requests (i.e. static assets). + // The absence of the immediate/parent client in the map of the active clients + // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet + // and is not ready to handle requests. + if (!activeClientIds.has(client.id)) { + return passthrough() + } + + // Notify the client that a request has been intercepted. + const serializedRequest = await serializeRequest(event.request) + const clientMessage = await sendToClient( + client, + { + type: 'REQUEST', + payload: { + id: requestId, + interceptedAt: requestInterceptedAt, + ...serializedRequest, + }, + }, + [serializedRequest.body], + ) + + switch (clientMessage.type) { + case 'MOCK_RESPONSE': { + return respondWithMock(clientMessage.data) + } + + case 'PASSTHROUGH': { + return passthrough() + } + } + + return passthrough() +} + +/** + * @param {Client} client + * @param {any} message + * @param {Array} transferrables + * @returns {Promise} + */ +function sendToClient(client, message, transferrables = []) { + return new Promise((resolve, reject) => { + const channel = new MessageChannel() + + channel.port1.onmessage = (event) => { + if (event.data && event.data.error) { + return reject(event.data.error) + } + + resolve(event.data) + } + + client.postMessage(message, [ + channel.port2, + ...transferrables.filter(Boolean), + ]) + }) +} + +/** + * @param {Response} response + * @returns {Response} + */ +function respondWithMock(response) { + // Setting response status code to 0 is a no-op. + // However, when responding with a "Response.error()", the produced Response + // instance will have status code set to 0. Since it's not possible to create + // a Response instance with status code 0, handle that use-case separately. + if (response.status === 0) { + return Response.error() + } + + const mockedResponse = new Response(response.body, response) + + Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, { + value: true, + enumerable: true, + }) + + return mockedResponse +} + +/** + * @param {Request} request + */ +async function serializeRequest(request) { + return { + url: request.url, + mode: request.mode, + method: request.method, + headers: Object.fromEntries(request.headers.entries()), + cache: request.cache, + credentials: request.credentials, + destination: request.destination, + integrity: request.integrity, + redirect: request.redirect, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy, + body: await request.arrayBuffer(), + keepalive: request.keepalive, + } +} diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx deleted file mode 100644 index 1ade5ad892..0000000000 --- a/apps/web/src/App.tsx +++ /dev/null @@ -1,216 +0,0 @@ -import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query"; -import { useEffect, useRef } from "react"; - -import ChatView from "./components/ChatView"; -import DiffPanel from "./components/DiffPanel"; -import Sidebar from "./components/Sidebar"; -import { isElectron } from "./env"; -import { DEFAULT_MODEL } from "./model-logic"; -import { StoreProvider, useStore } from "./store"; -import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types"; -import { onServerWelcome } from "./wsNativeApi"; -import { useNativeApi } from "./hooks/useNativeApi"; -import { AnchoredToastProvider, ToastProvider } from "./components/ui/toast"; -import { invalidateGitQueries } from "./lib/gitReactQuery"; - -function EventRouter() { - const api = useNativeApi(); - const { dispatch } = useStore(); - const queryClient = useQueryClient(); - const activeAssistantItemRef = useRef(null); - - useEffect(() => { - if (!api) return; - return api.providers.onEvent((event) => { - if (event.method === "turn/completed") { - void invalidateGitQueries(queryClient); - } - dispatch({ - type: "APPLY_EVENT", - event, - activeAssistantItemRef, - }); - }); - }, [api, dispatch, queryClient]); - - useEffect(() => { - if (!api) return; - return api.terminal.onEvent((event) => { - dispatch({ - type: "APPLY_TERMINAL_EVENT", - event, - }); - }); - }, [api, dispatch]); - - return null; -} - -function AutoProjectBootstrap() { - const { state, dispatch } = useStore(); - const bootstrappedRef = useRef(false); - - useEffect(() => { - // Browser mode bootstraps from server welcome. - // Electron bootstraps from persisted projects via DesktopProjectBootstrap. - if (isElectron) return; - - return onServerWelcome((payload) => { - if (bootstrappedRef.current) return; - - // Don't create duplicate projects for the same cwd - const existing = state.projects.find((p) => p.cwd === payload.cwd); - if (existing) { - bootstrappedRef.current = true; - // Ensure a thread is active - const existingThread = state.threads.find((t) => t.projectId === existing.id); - if (existingThread && !state.activeThreadId) { - dispatch({ - type: "SET_ACTIVE_THREAD", - threadId: existingThread.id, - }); - } - return; - } - - bootstrappedRef.current = true; - - // Create project + thread from server cwd - const projectId = crypto.randomUUID(); - dispatch({ - type: "ADD_PROJECT", - project: { - id: projectId, - name: payload.projectName, - cwd: payload.cwd, - model: DEFAULT_MODEL, - expanded: true, - }, - }); - dispatch({ - type: "ADD_THREAD", - thread: { - id: crypto.randomUUID(), - codexThreadId: null, - projectId, - title: "New thread", - model: DEFAULT_MODEL, - terminalOpen: false, - terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT, - terminalIds: [DEFAULT_THREAD_TERMINAL_ID], - runningTerminalIds: [], - runningTerminalPorts: {}, - activeTerminalId: DEFAULT_THREAD_TERMINAL_ID, - terminalGroups: [ - { - id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, - terminalIds: [DEFAULT_THREAD_TERMINAL_ID], - }, - ], - activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`, - session: null, - messages: [], - events: [], - error: null, - createdAt: new Date().toISOString(), - branch: null, - worktreePath: null, - }, - }); - }); - }, [state.projects, state.threads, state.activeThreadId, dispatch]); - - return null; -} - -function DesktopProjectBootstrap() { - const api = useNativeApi(); - const { dispatch } = useStore(); - const bootstrappedRef = useRef(false); - - useEffect(() => { - if (!isElectron || !api || bootstrappedRef.current) return; - - let disposed = false; - let retryDelayMs = 500; - let retryTimer: ReturnType | null = null; - - const attemptBootstrap = async () => { - try { - const projects = await api.projects.list(); - if (disposed) return; - dispatch({ - type: "SYNC_PROJECTS", - projects: projects.map((project) => ({ - id: project.id, - name: project.name, - cwd: project.cwd, - model: DEFAULT_MODEL, - expanded: true, - })), - }); - bootstrappedRef.current = true; - } catch { - if (disposed) return; - retryTimer = setTimeout(() => { - retryTimer = null; - void attemptBootstrap(); - }, retryDelayMs); - retryDelayMs = Math.min(retryDelayMs * 2, 5_000); - } - }; - - void attemptBootstrap(); - - return () => { - disposed = true; - if (retryTimer) { - clearTimeout(retryTimer); - } - }; - }, [api, dispatch]); - - return null; -} - -function Layout() { - const api = useNativeApi(); - const { state } = useStore(); - - if (!api) { - return ( -
-
-

Connecting to T3 Code server...

-
-
- ); - } - - return ( -
- - - - - - {state.diffOpen && } -
- ); -} - -const queryClient = new QueryClient(); - -export default function App() { - return ( - - - - - - - - - - ); -} diff --git a/apps/web/src/branding.ts b/apps/web/src/branding.ts new file mode 100644 index 0000000000..bffd983815 --- /dev/null +++ b/apps/web/src/branding.ts @@ -0,0 +1,4 @@ +export const APP_BASE_NAME = "T3 Code"; +export const APP_STAGE_LABEL = import.meta.env.DEV ? "Dev" : "Alpha"; +export const APP_DISPLAY_NAME = `${APP_BASE_NAME} (${APP_STAGE_LABEL})`; +export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0"; diff --git a/apps/web/src/chat-scroll.test.ts b/apps/web/src/chat-scroll.test.ts index 4d85278bc1..5311fb40ae 100644 --- a/apps/web/src/chat-scroll.test.ts +++ b/apps/web/src/chat-scroll.test.ts @@ -1,9 +1,6 @@ import { describe, expect, it } from "vitest"; -import { - AUTO_SCROLL_BOTTOM_THRESHOLD_PX, - isScrollContainerNearBottom, -} from "./chat-scroll"; +import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll"; describe("isScrollContainerNearBottom", () => { it("returns true when already at bottom", () => { diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx new file mode 100644 index 0000000000..a2b27bb1e9 --- /dev/null +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -0,0 +1,49 @@ +import { useEffect, type ReactNode } from "react"; +import { useNavigate } from "@tanstack/react-router"; + +import ThreadSidebar from "./Sidebar"; +import { Sidebar, SidebarProvider, SidebarRail } from "./ui/sidebar"; + +const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width"; +const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16; +const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16; + +export function AppSidebarLayout({ children }: { children: ReactNode }) { + const navigate = useNavigate(); + + useEffect(() => { + const onMenuAction = window.desktopBridge?.onMenuAction; + if (typeof onMenuAction !== "function") { + return; + } + + const unsubscribe = onMenuAction((action) => { + if (action !== "open-settings") return; + void navigate({ to: "/settings" }); + }); + + return () => { + unsubscribe?.(); + }; + }, [navigate]); + + return ( + + + wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH, + storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY, + }} + > + + + + {children} + + ); +} diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts new file mode 100644 index 0000000000..2f66e063ad --- /dev/null +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -0,0 +1,305 @@ +import type { GitBranch } from "@t3tools/contracts"; +import { describe, expect, it } from "vitest"; +import { + dedupeRemoteBranchesWithLocalMatches, + deriveLocalBranchNameFromRemoteRef, + resolveBranchSelectionTarget, + resolveDraftEnvModeAfterBranchChange, + resolveBranchToolbarValue, + shouldIncludeBranchPickerItem, +} from "./BranchToolbar.logic"; + +describe("resolveDraftEnvModeAfterBranchChange", () => { + it("switches to local mode when returning from an existing worktree to the main worktree", () => { + expect( + resolveDraftEnvModeAfterBranchChange({ + nextWorktreePath: null, + currentWorktreePath: "/repo/.t3/worktrees/feature-a", + effectiveEnvMode: "worktree", + }), + ).toBe("local"); + }); + + it("keeps new-worktree mode when selecting a base branch before worktree creation", () => { + expect( + resolveDraftEnvModeAfterBranchChange({ + nextWorktreePath: null, + currentWorktreePath: null, + effectiveEnvMode: "worktree", + }), + ).toBe("worktree"); + }); + + it("uses worktree mode when selecting a branch already attached to a worktree", () => { + expect( + resolveDraftEnvModeAfterBranchChange({ + nextWorktreePath: "/repo/.t3/worktrees/feature-a", + currentWorktreePath: null, + effectiveEnvMode: "local", + }), + ).toBe("worktree"); + }); +}); + +describe("resolveBranchToolbarValue", () => { + it("defaults new-worktree mode to current git branch when no explicit base branch is set", () => { + expect( + resolveBranchToolbarValue({ + envMode: "worktree", + activeWorktreePath: null, + activeThreadBranch: null, + currentGitBranch: "main", + }), + ).toBe("main"); + }); + + it("keeps an explicitly selected worktree base branch", () => { + expect( + resolveBranchToolbarValue({ + envMode: "worktree", + activeWorktreePath: null, + activeThreadBranch: "feature/base", + currentGitBranch: "main", + }), + ).toBe("feature/base"); + }); + + it("shows the actual checked-out branch when not selecting a new worktree base", () => { + expect( + resolveBranchToolbarValue({ + envMode: "local", + activeWorktreePath: null, + activeThreadBranch: "feature/base", + currentGitBranch: "main", + }), + ).toBe("main"); + }); +}); + +describe("deriveLocalBranchNameFromRemoteRef", () => { + it("strips the remote prefix from a remote ref", () => { + expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo"); + }); + + it("supports remote names that contain slashes", () => { + expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe( + "upstream/feature/demo", + ); + }); + + it("returns the original name when ref is malformed", () => { + expect(deriveLocalBranchNameFromRemoteRef("origin/")).toBe("origin/"); + expect(deriveLocalBranchNameFromRemoteRef("/feature/demo")).toBe("/feature/demo"); + }); +}); + +describe("dedupeRemoteBranchesWithLocalMatches", () => { + it("hides remote refs when the matching local branch exists", () => { + const input: GitBranch[] = [ + { + name: "feature/demo", + current: false, + isDefault: false, + worktreePath: null, + }, + { + name: "origin/feature/demo", + isRemote: true, + remoteName: "origin", + current: false, + isDefault: false, + worktreePath: null, + }, + { + name: "origin/feature/remote-only", + isRemote: true, + remoteName: "origin", + current: false, + isDefault: false, + worktreePath: null, + }, + ]; + + expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([ + "feature/demo", + "origin/feature/remote-only", + ]); + }); + + it("keeps all entries when no local match exists for a remote ref", () => { + const input: GitBranch[] = [ + { + name: "feature/local", + current: false, + isDefault: false, + worktreePath: null, + }, + { + name: "origin/feature/remote-only", + isRemote: true, + remoteName: "origin", + current: false, + isDefault: false, + worktreePath: null, + }, + ]; + + expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([ + "feature/local", + "origin/feature/remote-only", + ]); + }); + + it("keeps non-origin remote refs visible even when a matching local branch exists", () => { + const input: GitBranch[] = [ + { + name: "feature/demo", + current: false, + isDefault: false, + worktreePath: null, + }, + { + name: "my-org/upstream/feature/demo", + isRemote: true, + remoteName: "my-org/upstream", + current: false, + isDefault: false, + worktreePath: null, + }, + ]; + + expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([ + "feature/demo", + "my-org/upstream/feature/demo", + ]); + }); + + it("keeps non-origin remote refs visible when git tracks with first-slash local naming", () => { + const input: GitBranch[] = [ + { + name: "upstream/feature", + current: false, + isDefault: false, + worktreePath: null, + }, + { + name: "my-org/upstream/feature", + isRemote: true, + remoteName: "my-org/upstream", + current: false, + isDefault: false, + worktreePath: null, + }, + ]; + + expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([ + "upstream/feature", + "my-org/upstream/feature", + ]); + }); +}); + +describe("resolveBranchSelectionTarget", () => { + it("reuses an existing secondary worktree for the selected branch", () => { + expect( + resolveBranchSelectionTarget({ + activeProjectCwd: "/repo", + activeWorktreePath: "/repo/.t3/worktrees/feature-a", + branch: { + isDefault: false, + worktreePath: "/repo/.t3/worktrees/feature-b", + }, + }), + ).toEqual({ + checkoutCwd: "/repo/.t3/worktrees/feature-b", + nextWorktreePath: "/repo/.t3/worktrees/feature-b", + reuseExistingWorktree: true, + }); + }); + + it("switches back to the main repo when the branch already lives there", () => { + expect( + resolveBranchSelectionTarget({ + activeProjectCwd: "/repo", + activeWorktreePath: "/repo/.t3/worktrees/feature-a", + branch: { + isDefault: true, + worktreePath: "/repo", + }, + }), + ).toEqual({ + checkoutCwd: "/repo", + nextWorktreePath: null, + reuseExistingWorktree: true, + }); + }); + + it("checks out the default branch in the main repo when leaving a secondary worktree", () => { + expect( + resolveBranchSelectionTarget({ + activeProjectCwd: "/repo", + activeWorktreePath: "/repo/.t3/worktrees/feature-a", + branch: { + isDefault: true, + worktreePath: null, + }, + }), + ).toEqual({ + checkoutCwd: "/repo", + nextWorktreePath: null, + reuseExistingWorktree: false, + }); + }); + + it("keeps checkout in the current worktree for non-default branches", () => { + expect( + resolveBranchSelectionTarget({ + activeProjectCwd: "/repo", + activeWorktreePath: "/repo/.t3/worktrees/feature-a", + branch: { + isDefault: false, + worktreePath: null, + }, + }), + ).toEqual({ + checkoutCwd: "/repo/.t3/worktrees/feature-a", + nextWorktreePath: "/repo/.t3/worktrees/feature-a", + reuseExistingWorktree: false, + }); + }); +}); + +describe("shouldIncludeBranchPickerItem", () => { + it("keeps the synthetic checkout PR item visible for gh pr checkout input", () => { + expect( + shouldIncludeBranchPickerItem({ + itemValue: "__checkout_pull_request__:1359", + normalizedQuery: "gh pr checkout 1359", + createBranchItemValue: "__create_new_branch__:gh pr checkout 1359", + checkoutPullRequestItemValue: "__checkout_pull_request__:1359", + }), + ).toBe(true); + }); + + it("keeps the synthetic create-branch item visible for arbitrary branch input", () => { + expect( + shouldIncludeBranchPickerItem({ + itemValue: "__create_new_branch__:feature/demo", + normalizedQuery: "feature/demo", + createBranchItemValue: "__create_new_branch__:feature/demo", + checkoutPullRequestItemValue: null, + }), + ).toBe(true); + }); + + it("still filters ordinary branch items by query text", () => { + expect( + shouldIncludeBranchPickerItem({ + itemValue: "main", + normalizedQuery: "gh pr checkout 1359", + createBranchItemValue: "__create_new_branch__:gh pr checkout 1359", + checkoutPullRequestItemValue: "__checkout_pull_request__:1359", + }), + ).toBe(false); + }); +}); diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts new file mode 100644 index 0000000000..c9e336bf48 --- /dev/null +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -0,0 +1,100 @@ +import type { GitBranch } from "@t3tools/contracts"; +import { Schema } from "effect"; +export { + dedupeRemoteBranchesWithLocalMatches, + deriveLocalBranchNameFromRemoteRef, +} from "@t3tools/shared/git"; + +export const EnvMode = Schema.Literals(["local", "worktree"]); +export type EnvMode = typeof EnvMode.Type; + +export function resolveEffectiveEnvMode(input: { + activeWorktreePath: string | null; + hasServerThread: boolean; + draftThreadEnvMode: EnvMode | undefined; +}): EnvMode { + const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input; + return activeWorktreePath || (!hasServerThread && draftThreadEnvMode === "worktree") + ? "worktree" + : "local"; +} + +export function resolveDraftEnvModeAfterBranchChange(input: { + nextWorktreePath: string | null; + currentWorktreePath: string | null; + effectiveEnvMode: EnvMode; +}): EnvMode { + const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input; + if (nextWorktreePath) { + return "worktree"; + } + if (effectiveEnvMode === "worktree" && !currentWorktreePath) { + return "worktree"; + } + return "local"; +} + +export function resolveBranchToolbarValue(input: { + envMode: EnvMode; + activeWorktreePath: string | null; + activeThreadBranch: string | null; + currentGitBranch: string | null; +}): string | null { + const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input; + if (envMode === "worktree" && !activeWorktreePath) { + return activeThreadBranch ?? currentGitBranch; + } + return currentGitBranch ?? activeThreadBranch; +} + +export function resolveBranchSelectionTarget(input: { + activeProjectCwd: string; + activeWorktreePath: string | null; + branch: Pick; +}): { + checkoutCwd: string; + nextWorktreePath: string | null; + reuseExistingWorktree: boolean; +} { + const { activeProjectCwd, activeWorktreePath, branch } = input; + + if (branch.worktreePath) { + return { + checkoutCwd: branch.worktreePath, + nextWorktreePath: branch.worktreePath === activeProjectCwd ? null : branch.worktreePath, + reuseExistingWorktree: true, + }; + } + + const nextWorktreePath = + activeWorktreePath !== null && branch.isDefault ? null : activeWorktreePath; + + return { + checkoutCwd: nextWorktreePath ?? activeProjectCwd, + nextWorktreePath, + reuseExistingWorktree: false, + }; +} + +export function shouldIncludeBranchPickerItem(input: { + itemValue: string; + normalizedQuery: string; + createBranchItemValue: string | null; + checkoutPullRequestItemValue: string | null; +}): boolean { + const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input; + + if (normalizedQuery.length === 0) { + return true; + } + + if (createBranchItemValue && itemValue === createBranchItemValue) { + return true; + } + + if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) { + return true; + } + + return itemValue.toLowerCase().includes(normalizedQuery); +} diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 1e6dd9e923..79c453c0f5 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -1,276 +1,171 @@ -import type { GitBranch } from "@t3tools/contracts"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { useEffect, useState } from "react"; +import type { ThreadId } from "@t3tools/contracts"; +import { FolderIcon, GitForkIcon } from "lucide-react"; +import { useCallback } from "react"; -import { useNativeApi } from "../hooks/useNativeApi"; -import { - gitBranchesQueryOptions, - gitCheckoutMutationOptions, - gitCreateBranchAndCheckoutMutationOptions, -} from "../lib/gitReactQuery"; +import { newCommandId } from "../lib/utils"; +import { readNativeApi } from "../nativeApi"; +import { useComposerDraftStore } from "../composerDraftStore"; import { useStore } from "../store"; -import { Button } from "./ui/button"; import { - Combobox, - ComboboxEmpty, - ComboboxInput, - ComboboxItem, - ComboboxList, - ComboboxPopup, - ComboboxTrigger, -} from "./ui/combobox"; -import { ChevronDownIcon } from "lucide-react"; + EnvMode, + resolveDraftEnvModeAfterBranchChange, + resolveEffectiveEnvMode, +} from "./BranchToolbar.logic"; +import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; + +const envModeItems = [ + { value: "local", label: "Local" }, + { value: "worktree", label: "New worktree" }, +] as const; interface BranchToolbarProps { - envMode: "local" | "worktree"; - onEnvModeChange: (mode: "local" | "worktree") => void; + threadId: ThreadId; + onEnvModeChange: (mode: EnvMode) => void; envLocked: boolean; + onCheckoutPullRequestRequest?: (reference: string) => void; onComposerFocusRequest?: () => void; } export default function BranchToolbar({ - envMode, + threadId, onEnvModeChange, envLocked, + onCheckoutPullRequestRequest, onComposerFocusRequest, }: BranchToolbarProps) { - const { state, dispatch } = useStore(); - const api = useNativeApi(); - const queryClient = useQueryClient(); + const threads = useStore((store) => store.threads); + const projects = useStore((store) => store.projects); + const setThreadBranchAction = useStore((store) => store.setThreadBranch); + const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId)); + const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); - const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false); - const [branchQuery, setBranchQuery] = useState(""); - - const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId); - const activeProject = state.projects.find((project) => project.id === activeThread?.projectId); - const activeThreadId = activeThread?.id; - const activeThreadBranch = activeThread?.branch ?? null; - const activeWorktreePath = activeThread?.worktreePath ?? null; + const serverThread = threads.find((thread) => thread.id === threadId); + const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null; + const activeProject = projects.find((project) => project.id === activeProjectId); + const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined); + const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null; + const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null; + const hasServerThread = serverThread !== undefined; + const effectiveEnvMode = resolveEffectiveEnvMode({ + activeWorktreePath, + hasServerThread, + draftThreadEnvMode: draftThread?.envMode, + }); - // ── Queries ─────────────────────────────────────────────────────────── - - const branchesQuery = useQuery(gitBranchesQueryOptions(api, branchCwd)); - - const branches = branchesQuery.data?.branches ?? []; - const branchNames = branches.map((branch) => branch.name); - const branchByName = new Map(branches.map((branch) => [branch.name, branch])); - const trimmedBranchQuery = branchQuery.trim(); - const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0; - const hasExactBranchMatch = branchByName.has(trimmedBranchQuery); - const createBranchItemValue = canCreateBranch - ? `__create_new_branch__:${trimmedBranchQuery}` - : null; - const branchPickerItems = - createBranchItemValue && !hasExactBranchMatch - ? [...branchNames, createBranchItemValue] - : branchNames; - // ── Mutations ───────────────────────────────────────────────────────── - - const checkoutMutation = useMutation({ - ...gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }), - onError: (error) => { - setThreadError(error instanceof Error ? error.message : "Failed to checkout branch."); - setIsBranchMenuOpen(true); + const setThreadBranch = useCallback( + (branch: string | null, worktreePath: string | null) => { + if (!activeThreadId) return; + const api = readNativeApi(); + // If the effective cwd is about to change, stop the running session so the + // next message creates a new one with the correct cwd. + if (serverThread?.session && worktreePath !== activeWorktreePath && api) { + void api.orchestration + .dispatchCommand({ + type: "thread.session.stop", + commandId: newCommandId(), + threadId: activeThreadId, + createdAt: new Date().toISOString(), + }) + .catch(() => undefined); + } + if (api && hasServerThread) { + void api.orchestration.dispatchCommand({ + type: "thread.meta.update", + commandId: newCommandId(), + threadId: activeThreadId, + branch, + worktreePath, + }); + } + if (hasServerThread) { + setThreadBranchAction(activeThreadId, branch, worktreePath); + return; + } + const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({ + nextWorktreePath: worktreePath, + currentWorktreePath: activeWorktreePath, + effectiveEnvMode, + }); + setDraftThreadContext(threadId, { + branch, + worktreePath, + envMode: nextDraftEnvMode, + }); }, - }); + [ + activeThreadId, + serverThread?.session, + activeWorktreePath, + hasServerThread, + setThreadBranchAction, + setDraftThreadContext, + threadId, + effectiveEnvMode, + ], + ); - const createBranchMutation = useMutation({ - ...gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }), - onError: (error) => - setThreadError(error instanceof Error ? error.message : "Failed to create branch."), - }); - - // ── Effects ─────────────────────────────────────────────────────────── - - // Keep thread branch synced to git current branch for local threads. - const queryBranches = branchesQuery.data?.branches; - useEffect(() => { - if (!activeThreadId || activeWorktreePath) return; - const current = queryBranches?.find((branch) => branch.current); - if (!current) return; - if (current.name === activeThreadBranch) return; - dispatch({ - type: "SET_THREAD_BRANCH", - threadId: activeThreadId, - branch: current.name, - worktreePath: null, - }); - }, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]); - - useEffect(() => { - if (isBranchMenuOpen) return; - setBranchQuery(""); - }, [isBranchMenuOpen]); - - // ── Helpers ─────────────────────────────────────────────────────────── - - const setThreadError = (error: string | null) => { - if (!activeThreadId) return; - dispatch({ type: "SET_ERROR", threadId: activeThreadId, error }); - }; - - const setThreadBranch = (branch: string | null, worktreePath: string | null) => { - if (!activeThreadId) return; - // If the effective cwd is about to change, stop the running session so the - // next message creates a new one with the correct cwd. - const sessionId = activeThread?.session?.sessionId; - if (sessionId && worktreePath !== activeWorktreePath) { - void api?.providers.stopSession({ sessionId }).catch(() => undefined); - } - dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath }); - }; - - const selectBranch = (branch: GitBranch) => { - if (!api || !activeThreadId || !branchCwd) return; - - // For new worktree mode, selecting a branch picks the base branch. - if (envMode === "worktree" && !envLocked && !activeWorktreePath) { - setThreadError(null); - setThreadBranch(branch.name, null); - setIsBranchMenuOpen(false); - onComposerFocusRequest?.(); - return; - } - - // If the branch already lives in a worktree, redirect there instead of - // trying to checkout (which git would reject with "already used by worktree"). - if (branch.worktreePath) { - const isMainWorktree = branch.worktreePath === activeProject?.cwd; - setThreadError(null); - // Main worktree → switch back to local (project cwd, worktreePath=null). - // Secondary worktree → point the thread at that worktree path. - setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath); - setIsBranchMenuOpen(false); - onComposerFocusRequest?.(); - return; - } - - checkoutMutation.mutate(branch.name, { - onSuccess: () => { - setThreadError(null); - setThreadBranch(branch.name, activeWorktreePath); - setIsBranchMenuOpen(false); - onComposerFocusRequest?.(); - }, - }); - }; - - const createBranch = (rawName: string) => { - const name = rawName.trim(); - if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return; - createBranchMutation.mutate(name, { - onSuccess: () => { - setThreadError(null); - setThreadBranch(name, activeWorktreePath); - setBranchQuery(""); - setIsBranchMenuOpen(false); - onComposerFocusRequest?.(); - }, - }); - }; - - if (!activeThread || !activeProject) return null; + if (!activeThreadId || !activeProject) return null; return (
-
- {envLocked || activeWorktreePath ? ( - - {activeWorktreePath ? "Worktree" : "Local"} - - ) : ( - - )} -
- - setIsBranchMenuOpen(open)} - open={isBranchMenuOpen} - value={activeThread.branch} - > - } - className="text-muted-foreground/70 hover:text-foreground/80" - disabled={branchesQuery.isLoading} + {envLocked || activeWorktreePath ? ( + + {activeWorktreePath ? ( + <> + + Worktree + + ) : ( + <> + + Local + + )} + + ) : ( + + )} - - {(itemValue) => { - if (createBranchItemValue && itemValue === createBranchItemValue) { - return ( - createBranch(trimmedBranchQuery)} - > - Create new branch "{trimmedBranchQuery}" - - ); - } - - const branch = branchByName.get(itemValue); - if (!branch) return null; - - const hasSecondaryWorktree = - branch.worktreePath && branch.worktreePath !== activeProject.cwd; - return ( - selectBranch(branch)} - > -
- {itemValue} - {(branch.current || branch.isDefault || hasSecondaryWorktree) && ( - - {branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"} - - )} -
-
- ); - }} -
- -
+
); } diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx new file mode 100644 index 0000000000..e1dbb8756c --- /dev/null +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -0,0 +1,550 @@ +import type { GitBranch } from "@t3tools/contracts"; +import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useVirtualizer } from "@tanstack/react-virtual"; +import { ChevronDownIcon } from "lucide-react"; +import { + type CSSProperties, + useCallback, + useDeferredValue, + useEffect, + useMemo, + useOptimistic, + useRef, + useState, + useTransition, +} from "react"; + +import { + gitBranchSearchInfiniteQueryOptions, + gitQueryKeys, + gitStatusQueryOptions, + invalidateGitQueries, +} from "../lib/gitReactQuery"; +import { readNativeApi } from "../nativeApi"; +import { parsePullRequestReference } from "../pullRequestReference"; +import { + deriveLocalBranchNameFromRemoteRef, + EnvMode, + resolveBranchSelectionTarget, + resolveBranchToolbarValue, + shouldIncludeBranchPickerItem, +} from "./BranchToolbar.logic"; +import { Button } from "./ui/button"; +import { + Combobox, + ComboboxEmpty, + ComboboxInput, + ComboboxItem, + ComboboxList, + ComboboxPopup, + ComboboxStatus, + ComboboxTrigger, +} from "./ui/combobox"; +import { toastManager } from "./ui/toast"; + +interface BranchToolbarBranchSelectorProps { + activeProjectCwd: string; + activeThreadBranch: string | null; + activeWorktreePath: string | null; + branchCwd: string | null; + effectiveEnvMode: EnvMode; + envLocked: boolean; + onSetThreadBranch: (branch: string | null, worktreePath: string | null) => void; + onCheckoutPullRequestRequest?: (reference: string) => void; + onComposerFocusRequest?: () => void; +} + +function toBranchActionErrorMessage(error: unknown): string { + return error instanceof Error ? error.message : "An error occurred."; +} + +function getBranchTriggerLabel(input: { + activeWorktreePath: string | null; + effectiveEnvMode: EnvMode; + resolvedActiveBranch: string | null; +}): string { + const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input; + if (!resolvedActiveBranch) { + return "Select branch"; + } + if (effectiveEnvMode === "worktree" && !activeWorktreePath) { + return `From ${resolvedActiveBranch}`; + } + return resolvedActiveBranch; +} + +export function BranchToolbarBranchSelector({ + activeProjectCwd, + activeThreadBranch, + activeWorktreePath, + branchCwd, + effectiveEnvMode, + envLocked, + onSetThreadBranch, + onCheckoutPullRequestRequest, + onComposerFocusRequest, +}: BranchToolbarBranchSelectorProps) { + const queryClient = useQueryClient(); + const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false); + const [branchQuery, setBranchQuery] = useState(""); + const deferredBranchQuery = useDeferredValue(branchQuery); + + const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd)); + const trimmedBranchQuery = branchQuery.trim(); + const deferredTrimmedBranchQuery = deferredBranchQuery.trim(); + + useEffect(() => { + if (!branchCwd) return; + void queryClient.prefetchInfiniteQuery( + gitBranchSearchInfiniteQueryOptions({ cwd: branchCwd, query: "" }), + ); + }, [branchCwd, queryClient]); + + const { + data: branchesSearchData, + fetchNextPage, + hasNextPage, + isFetchingNextPage, + isPending: isBranchesSearchPending, + } = useInfiniteQuery( + gitBranchSearchInfiniteQueryOptions({ + cwd: branchCwd, + query: deferredTrimmedBranchQuery, + enabled: isBranchMenuOpen, + }), + ); + const branches = useMemo( + () => branchesSearchData?.pages.flatMap((page) => page.branches) ?? [], + [branchesSearchData?.pages], + ); + const currentGitBranch = + branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null; + const canonicalActiveBranch = resolveBranchToolbarValue({ + envMode: effectiveEnvMode, + activeWorktreePath, + activeThreadBranch, + currentGitBranch, + }); + const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]); + const branchByName = useMemo( + () => new Map(branches.map((branch) => [branch.name, branch] as const)), + [branches], + ); + const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase(); + const prReference = parsePullRequestReference(trimmedBranchQuery); + const isSelectingWorktreeBase = + effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath; + const checkoutPullRequestItemValue = + prReference && onCheckoutPullRequestRequest ? `__checkout_pull_request__:${prReference}` : null; + const canCreateBranch = !isSelectingWorktreeBase && trimmedBranchQuery.length > 0; + const hasExactBranchMatch = branchByName.has(trimmedBranchQuery); + const createBranchItemValue = canCreateBranch + ? `__create_new_branch__:${trimmedBranchQuery}` + : null; + const branchPickerItems = useMemo(() => { + const items = [...branchNames]; + if (createBranchItemValue && !hasExactBranchMatch) { + items.push(createBranchItemValue); + } + if (checkoutPullRequestItemValue) { + items.unshift(checkoutPullRequestItemValue); + } + return items; + }, [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch]); + const filteredBranchPickerItems = useMemo( + () => + normalizedDeferredBranchQuery.length === 0 + ? branchPickerItems + : branchPickerItems.filter((itemValue) => + shouldIncludeBranchPickerItem({ + itemValue, + normalizedQuery: normalizedDeferredBranchQuery, + createBranchItemValue, + checkoutPullRequestItemValue, + }), + ), + [ + branchPickerItems, + checkoutPullRequestItemValue, + createBranchItemValue, + normalizedDeferredBranchQuery, + ], + ); + const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic( + canonicalActiveBranch, + (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch, + ); + const [isBranchActionPending, startBranchActionTransition] = useTransition(); + const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40; + const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0; + const branchStatusText = isBranchesSearchPending + ? "Loading branches..." + : isFetchingNextPage + ? "Loading more branches..." + : hasNextPage + ? `Showing ${branches.length} of ${totalBranchCount} branches` + : null; + + const runBranchAction = (action: () => Promise) => { + startBranchActionTransition(async () => { + await action().catch(() => undefined); + await invalidateGitQueries(queryClient).catch(() => undefined); + }); + }; + + const selectBranch = (branch: GitBranch) => { + const api = readNativeApi(); + if (!api || !branchCwd || isBranchActionPending) return; + + // In new-worktree mode, selecting a branch sets the base branch. + if (isSelectingWorktreeBase) { + onSetThreadBranch(branch.name, null); + setIsBranchMenuOpen(false); + onComposerFocusRequest?.(); + return; + } + + const selectionTarget = resolveBranchSelectionTarget({ + activeProjectCwd, + activeWorktreePath, + branch, + }); + + // If the branch already lives in a worktree, point the thread there. + if (selectionTarget.reuseExistingWorktree) { + onSetThreadBranch(branch.name, selectionTarget.nextWorktreePath); + setIsBranchMenuOpen(false); + onComposerFocusRequest?.(); + return; + } + + const selectedBranchName = branch.isRemote + ? deriveLocalBranchNameFromRemoteRef(branch.name) + : branch.name; + + setIsBranchMenuOpen(false); + onComposerFocusRequest?.(); + + runBranchAction(async () => { + setOptimisticBranch(selectedBranchName); + try { + await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name }); + await invalidateGitQueries(queryClient); + } catch (error) { + toastManager.add({ + type: "error", + title: "Failed to checkout branch.", + description: toBranchActionErrorMessage(error), + }); + return; + } + + let nextBranchName = selectedBranchName; + if (branch.isRemote) { + const status = await api.git.status({ cwd: selectionTarget.checkoutCwd }).catch(() => null); + if (status?.branch) { + nextBranchName = status.branch; + } + } + + setOptimisticBranch(nextBranchName); + onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath); + }); + }; + + const createBranch = (rawName: string) => { + const name = rawName.trim(); + const api = readNativeApi(); + if (!api || !branchCwd || !name || isBranchActionPending) return; + + setIsBranchMenuOpen(false); + onComposerFocusRequest?.(); + + runBranchAction(async () => { + setOptimisticBranch(name); + + try { + await api.git.createBranch({ cwd: branchCwd, branch: name }); + try { + await api.git.checkout({ cwd: branchCwd, branch: name }); + } catch (error) { + toastManager.add({ + type: "error", + title: "Failed to checkout branch.", + description: toBranchActionErrorMessage(error), + }); + return; + } + } catch (error) { + toastManager.add({ + type: "error", + title: "Failed to create branch.", + description: toBranchActionErrorMessage(error), + }); + return; + } + + setOptimisticBranch(name); + onSetThreadBranch(name, activeWorktreePath); + setBranchQuery(""); + }); + }; + + useEffect(() => { + if ( + effectiveEnvMode !== "worktree" || + activeWorktreePath || + activeThreadBranch || + !currentGitBranch + ) { + return; + } + onSetThreadBranch(currentGitBranch, null); + }, [ + activeThreadBranch, + activeWorktreePath, + currentGitBranch, + effectiveEnvMode, + onSetThreadBranch, + ]); + + const handleOpenChange = useCallback( + (open: boolean) => { + setIsBranchMenuOpen(open); + if (!open) { + setBranchQuery(""); + return; + } + void queryClient.invalidateQueries({ + queryKey: gitQueryKeys.branches(branchCwd), + }); + }, + [branchCwd, queryClient], + ); + + const branchListScrollElementRef = useRef(null); + const maybeFetchNextBranchPage = useCallback(() => { + if (!isBranchMenuOpen || !hasNextPage || isFetchingNextPage) { + return; + } + + const scrollElement = branchListScrollElementRef.current; + if (!scrollElement) { + return; + } + + const distanceFromBottom = + scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight; + if (distanceFromBottom > 96) { + return; + } + + void fetchNextPage().catch(() => undefined); + }, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]); + const branchListVirtualizer = useVirtualizer({ + count: filteredBranchPickerItems.length, + estimateSize: (index) => + filteredBranchPickerItems[index] === checkoutPullRequestItemValue ? 44 : 28, + getScrollElement: () => branchListScrollElementRef.current, + overscan: 12, + enabled: isBranchMenuOpen && shouldVirtualizeBranchList, + initialRect: { + height: 224, + width: 0, + }, + }); + const virtualBranchRows = branchListVirtualizer.getVirtualItems(); + const setBranchListRef = useCallback( + (element: HTMLDivElement | null) => { + branchListScrollElementRef.current = + (element?.parentElement as HTMLDivElement | null) ?? null; + if (element) { + branchListVirtualizer.measure(); + } + }, + [branchListVirtualizer], + ); + + useEffect(() => { + if (!isBranchMenuOpen || !shouldVirtualizeBranchList) return; + queueMicrotask(() => { + branchListVirtualizer.measure(); + }); + }, [ + branchListVirtualizer, + filteredBranchPickerItems.length, + isBranchMenuOpen, + shouldVirtualizeBranchList, + ]); + + useEffect(() => { + if (!isBranchMenuOpen) { + return; + } + + branchListScrollElementRef.current?.scrollTo({ top: 0 }); + }, [deferredTrimmedBranchQuery, isBranchMenuOpen]); + + useEffect(() => { + const scrollElement = branchListScrollElementRef.current; + if (!scrollElement || !isBranchMenuOpen) { + return; + } + + const handleScroll = () => { + maybeFetchNextBranchPage(); + }; + + scrollElement.addEventListener("scroll", handleScroll, { passive: true }); + handleScroll(); + return () => { + scrollElement.removeEventListener("scroll", handleScroll); + }; + }, [isBranchMenuOpen, maybeFetchNextBranchPage]); + + useEffect(() => { + maybeFetchNextBranchPage(); + }, [branches.length, maybeFetchNextBranchPage]); + + const triggerLabel = getBranchTriggerLabel({ + activeWorktreePath, + effectiveEnvMode, + resolvedActiveBranch, + }); + + function renderPickerItem(itemValue: string, index: number, style?: CSSProperties) { + if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) { + return ( + { + if (!prReference || !onCheckoutPullRequestRequest) { + return; + } + setIsBranchMenuOpen(false); + setBranchQuery(""); + onComposerFocusRequest?.(); + onCheckoutPullRequestRequest(prReference); + }} + > +
+ Checkout Pull Request + {prReference} +
+
+ ); + } + if (createBranchItemValue && itemValue === createBranchItemValue) { + return ( + createBranch(trimmedBranchQuery)} + > + Create new branch "{trimmedBranchQuery}" + + ); + } + + const branch = branchByName.get(itemValue); + if (!branch) return null; + + const hasSecondaryWorktree = branch.worktreePath && branch.worktreePath !== activeProjectCwd; + const badge = branch.current + ? "current" + : hasSecondaryWorktree + ? "worktree" + : branch.isRemote + ? "remote" + : branch.isDefault + ? "default" + : null; + return ( + selectBranch(branch)} + > +
+ {itemValue} + {badge && {badge}} +
+
+ ); + } + + return ( + { + if (!isBranchMenuOpen || eventDetails.index < 0) return; + branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" }); + }} + onOpenChange={handleOpenChange} + open={isBranchMenuOpen} + value={resolvedActiveBranch} + > + } + className="text-muted-foreground/70 hover:text-foreground/80" + disabled={(isBranchesSearchPending && branches.length === 0) || isBranchActionPending} + > + {triggerLabel} + + + +
+ setBranchQuery(event.target.value)} + /> +
+ No branches found. + + + {shouldVirtualizeBranchList ? ( +
+ {virtualBranchRows.map((virtualRow) => { + const itemValue = filteredBranchPickerItems[virtualRow.index]; + if (!itemValue) return null; + return renderPickerItem(itemValue, virtualRow.index, { + position: "absolute", + top: 0, + left: 0, + width: "100%", + transform: `translateY(${virtualRow.start}px)`, + }); + })} +
+ ) : ( + filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index)) + )} +
+ {branchStatusText ? {branchStatusText} : null} +
+
+ ); +} diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index e16d09e2a3..b364a8e3a1 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -1,27 +1,296 @@ -import { memo } from "react"; +import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs"; +import { CheckIcon, CopyIcon } from "lucide-react"; +import React, { + Children, + Suspense, + isValidElement, + use, + useCallback, + memo, + useEffect, + useMemo, + useRef, + useState, + type ReactNode, +} from "react"; import type { Components } from "react-markdown"; import ReactMarkdown from "react-markdown"; -import rehypeHighlight from "rehype-highlight"; import remarkGfm from "remark-gfm"; +import { openInPreferredEditor } from "../editorPreferences"; +import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering"; +import { fnv1a32 } from "../lib/diffRendering"; +import { LRUCache } from "../lib/lruCache"; +import { useTheme } from "../hooks/useTheme"; +import { resolveMarkdownFileLinkTarget } from "../markdown-links"; +import { readNativeApi } from "../nativeApi"; + +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; + isStreaming?: boolean; } -const markdownComponents: Components = { - a({ node: _node, ...props }) { - return
; - }, -}; +const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/; +const MAX_HIGHLIGHT_CACHE_ENTRIES = 500; +const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024; +const highlightedCodeCache = new LRUCache( + MAX_HIGHLIGHT_CACHE_ENTRIES, + MAX_HIGHLIGHT_CACHE_MEMORY_BYTES, +); +const highlighterPromiseCache = new Map>(); + +function extractFenceLanguage(className: string | undefined): string { + const match = className?.match(CODE_FENCE_LANGUAGE_REGEX); + const raw = match?.[1] ?? "text"; + // Shiki doesn't bundle a gitignore grammar; ini is a close match (#685) + return raw === "gitignore" ? "ini" : raw; +} + +function nodeToPlainText(node: ReactNode): string { + if (typeof node === "string" || typeof node === "number") { + return String(node); + } + if (Array.isArray(node)) { + return node.map((child) => nodeToPlainText(child)).join(""); + } + if (isValidElement<{ children?: ReactNode }>(node)) { + return nodeToPlainText(node.props.children); + } + return ""; +} + +function extractCodeBlock( + children: ReactNode, +): { className: string | undefined; code: string } | null { + const childNodes = Children.toArray(children); + if (childNodes.length !== 1) { + return null; + } + + const onlyChild = childNodes[0]; + if ( + !isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) || + onlyChild.type !== "code" + ) { + return null; + } + + return { + className: onlyChild.props.className, + code: nodeToPlainText(onlyChild.props.children), + }; +} + +function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string { + return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`; +} + +function estimateHighlightedSize(html: string, code: string): number { + return Math.max(html.length * 2, code.length * 3); +} + +function getHighlighterPromise(language: string): Promise { + const cached = highlighterPromiseCache.get(language); + if (cached) return cached; + + const promise = getSharedHighlighter({ + 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; +} + +function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) { + const [copied, setCopied] = useState(false); + const copiedTimerRef = useRef | null>(null); + const handleCopy = useCallback(() => { + if (typeof navigator === "undefined" || navigator.clipboard == null) { + return; + } + void navigator.clipboard + .writeText(code) + .then(() => { + if (copiedTimerRef.current != null) { + clearTimeout(copiedTimerRef.current); + } + setCopied(true); + copiedTimerRef.current = setTimeout(() => { + setCopied(false); + copiedTimerRef.current = null; + }, 1200); + }) + .catch(() => undefined); + }, [code]); + + useEffect( + () => () => { + if (copiedTimerRef.current != null) { + clearTimeout(copiedTimerRef.current); + copiedTimerRef.current = null; + } + }, + [], + ); -function ChatMarkdown({ text }: ChatMarkdownProps) { return ( -
- + + {children} +
+ ); +} + +interface SuspenseShikiCodeBlockProps { + className: string | undefined; + code: string; + themeName: DiffThemeName; + isStreaming: boolean; +} + +function SuspenseShikiCodeBlock({ + className, + code, + themeName, + isStreaming, +}: SuspenseShikiCodeBlockProps) { + const language = extractFenceLanguage(className); + const cacheKey = createHighlightCacheKey(code, language, themeName); + const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null; + + if (cachedHighlightedHtml != null) { + return ( +
+ ); + } + + const highlighter = use(getHighlighterPromise(language)); + const highlightedHtml = useMemo(() => { + try { + return highlighter.codeToHtml(code, { lang: language, theme: themeName }); + } catch (error) { + // Log highlighting failures for debugging while falling back to plain text + console.warn( + `Code highlighting failed for language "${language}", falling back to plain text.`, + error instanceof Error ? error.message : error, + ); + // 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) { + highlightedCodeCache.set( + cacheKey, + highlightedHtml, + estimateHighlightedSize(highlightedHtml, code), + ); + } + }, [cacheKey, code, highlightedHtml, isStreaming]); + + return ( +
+ ); +} + +function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) { + const { resolvedTheme } = useTheme(); + const diffThemeName = resolveDiffThemeName(resolvedTheme); + const markdownComponents = useMemo( + () => ({ + a({ node: _node, href, ...props }) { + const targetPath = resolveMarkdownFileLinkTarget(href, cwd); + if (!targetPath) { + return ; + } + + return ( + { + event.preventDefault(); + event.stopPropagation(); + const api = readNativeApi(); + if (api) { + void openInPreferredEditor(api, targetPath); + } else { + console.warn("Native API not found. Unable to open file in editor."); + } + }} + /> + ); + }, + pre({ node: _node, children, ...props }) { + const codeBlock = extractCodeBlock(children); + if (!codeBlock) { + return
{children}
; + } + + return ( + + {children}}> + {children}}> + + + + + ); + }, + }), + [cwd, diffThemeName, isStreaming], + ); + + return ( +
+ {text}
diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx new file mode 100644 index 0000000000..8df17b3996 --- /dev/null +++ b/apps/web/src/components/ChatView.browser.tsx @@ -0,0 +1,2942 @@ +// Production CSS is part of the behavior under test because row height depends on it. +import "../index.css"; + +import { + EventId, + ORCHESTRATION_WS_METHODS, + type MessageId, + type OrchestrationEvent, + type OrchestrationReadModel, + type ProjectId, + type ServerConfig, + type ServerLifecycleWelcomePayload, + type ThreadId, + type TurnId, + WS_METHODS, + OrchestrationSessionStatus, + DEFAULT_SERVER_SETTINGS, +} from "@t3tools/contracts"; +import { RouterProvider, createMemoryHistory } from "@tanstack/react-router"; +import { HttpResponse, http, ws } from "msw"; +import { setupWorker } from "msw/browser"; +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 { + INLINE_TERMINAL_CONTEXT_PLACEHOLDER, + type TerminalContextDraft, + removeInlineTerminalContextPlaceholder, +} from "../lib/terminalContext"; +import { isMacPlatform } from "../lib/utils"; +import { __resetNativeApiForTests } from "../nativeApi"; +import { getRouter } from "../router"; +import { useStore } from "../store"; +import { useTerminalStateStore } from "../terminalStateStore"; +import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness"; +import { estimateTimelineMessageHeight } from "./timelineHeight"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; + +const THREAD_ID = "thread-browser-test" as ThreadId; +const UUID_ROUTE_RE = /^\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +const PROJECT_ID = "project-1" as ProjectId; +const NOW_ISO = "2026-03-04T12:00:00.000Z"; +const BASE_TIME_MS = Date.parse(NOW_ISO); +const ATTACHMENT_SVG = ""; + +interface TestFixture { + snapshot: OrchestrationReadModel; + serverConfig: ServerConfig; + welcome: ServerLifecycleWelcomePayload; +} + +let fixture: TestFixture; +const rpcHarness = new BrowserWsRpcHarness(); +const wsRequests = rpcHarness.requests; +let customWsRpcResolver: ((body: NormalizedWsRpcRequestBody) => unknown | undefined) | null = null; +const wsLink = ws.link(/ws(s)?:\/\/.*/); + +interface ViewportSpec { + name: string; + width: number; + height: number; + textTolerancePx: number; + attachmentTolerancePx: number; +} + +const DEFAULT_VIEWPORT: ViewportSpec = { + name: "desktop", + width: 960, + height: 1_100, + textTolerancePx: 44, + attachmentTolerancePx: 56, +}; +const WIDE_FOOTER_VIEWPORT: ViewportSpec = { + name: "wide-footer", + width: 1_400, + height: 1_100, + textTolerancePx: 44, + attachmentTolerancePx: 56, +}; +const COMPACT_FOOTER_VIEWPORT: ViewportSpec = { + name: "compact-footer", + width: 430, + height: 932, + textTolerancePx: 56, + attachmentTolerancePx: 56, +}; +const TEXT_VIEWPORT_MATRIX = [ + DEFAULT_VIEWPORT, + { name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 }, + { name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 }, + { name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 }, +] as const satisfies readonly ViewportSpec[]; +const ATTACHMENT_VIEWPORT_MATRIX = [ + DEFAULT_VIEWPORT, + { name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 }, + { name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 }, +] as const satisfies readonly ViewportSpec[]; + +interface UserRowMeasurement { + measuredRowHeightPx: number; + timelineWidthMeasuredPx: number; + renderedInVirtualizedRegion: boolean; +} + +interface MountedChatView { + [Symbol.asyncDispose]: () => Promise; + cleanup: () => Promise; + measureUserRow: (targetMessageId: MessageId) => Promise; + setViewport: (viewport: ViewportSpec) => Promise; + setContainerSize: (viewport: Pick) => Promise; + router: ReturnType; +} + +function isoAt(offsetSeconds: number): string { + return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString(); +} + +function createBaseServerConfig(): ServerConfig { + return { + cwd: "/repo/project", + keybindingsConfigPath: "/repo/project/.t3code-keybindings.json", + keybindings: [], + issues: [], + providers: [ + { + provider: "codex", + enabled: true, + installed: true, + version: "0.116.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: NOW_ISO, + models: [], + }, + ], + availableEditors: [], + observability: { + logsDirectoryPath: "/repo/project/.t3/logs", + localTracingEnabled: true, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + }, + settings: { + ...DEFAULT_SERVER_SETTINGS, + ...DEFAULT_CLIENT_SETTINGS, + }, + }; +} + +function createUserMessage(options: { + id: MessageId; + text: string; + offsetSeconds: number; + attachments?: Array<{ + type: "image"; + id: string; + name: string; + mimeType: string; + sizeBytes: number; + }>; +}) { + return { + id: options.id, + role: "user" as const, + text: options.text, + ...(options.attachments ? { attachments: options.attachments } : {}), + turnId: null, + streaming: false, + createdAt: isoAt(options.offsetSeconds), + updatedAt: isoAt(options.offsetSeconds + 1), + }; +} + +function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) { + return { + id: options.id, + role: "assistant" as const, + text: options.text, + turnId: null, + streaming: false, + createdAt: isoAt(options.offsetSeconds), + updatedAt: isoAt(options.offsetSeconds + 1), + }; +} + +function createTerminalContext(input: { + id: string; + terminalLabel: string; + lineStart: number; + lineEnd: number; + text: string; +}): TerminalContextDraft { + return { + id: input.id, + threadId: THREAD_ID, + terminalId: `terminal-${input.id}`, + terminalLabel: input.terminalLabel, + lineStart: input.lineStart, + lineEnd: input.lineEnd, + text: input.text, + createdAt: NOW_ISO, + }; +} + +function createSnapshotForTargetUser(options: { + targetMessageId: MessageId; + targetText: string; + targetAttachmentCount?: number; + sessionStatus?: OrchestrationSessionStatus; +}): OrchestrationReadModel { + const messages: Array = []; + + for (let index = 0; index < 22; index += 1) { + const isTarget = index === 3; + const userId = `msg-user-${index}` as MessageId; + const assistantId = `msg-assistant-${index}` as MessageId; + const attachments = + isTarget && (options.targetAttachmentCount ?? 0) > 0 + ? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({ + type: "image" as const, + id: `attachment-${attachmentIndex + 1}`, + name: `attachment-${attachmentIndex + 1}.png`, + mimeType: "image/png", + sizeBytes: 128, + })) + : undefined; + + messages.push( + createUserMessage({ + id: isTarget ? options.targetMessageId : userId, + text: isTarget ? options.targetText : `filler user message ${index}`, + offsetSeconds: messages.length * 3, + ...(attachments ? { attachments } : {}), + }), + ); + messages.push( + createAssistantMessage({ + id: assistantId, + text: `assistant filler ${index}`, + offsetSeconds: messages.length * 3, + }), + ); + } + + return { + snapshotSequence: 1, + projects: [ + { + id: PROJECT_ID, + title: "Project", + workspaceRoot: "/repo/project", + defaultModelSelection: { + provider: "codex", + model: "gpt-5", + }, + scripts: [], + createdAt: NOW_ISO, + updatedAt: NOW_ISO, + deletedAt: null, + }, + ], + threads: [ + { + id: THREAD_ID, + projectId: PROJECT_ID, + title: "Browser test thread", + modelSelection: { + provider: "codex", + model: "gpt-5", + }, + interactionMode: "default", + runtimeMode: "full-access", + branch: "main", + worktreePath: null, + latestTurn: null, + createdAt: NOW_ISO, + updatedAt: NOW_ISO, + archivedAt: null, + deletedAt: null, + messages, + activities: [], + proposedPlans: [], + checkpoints: [], + session: { + threadId: THREAD_ID, + status: options.sessionStatus ?? "ready", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: NOW_ISO, + }, + }, + ], + updatedAt: NOW_ISO, + }; +} + +function buildFixture(snapshot: OrchestrationReadModel): TestFixture { + return { + snapshot, + serverConfig: createBaseServerConfig(), + welcome: { + cwd: "/repo/project", + projectName: "Project", + bootstrapProjectId: PROJECT_ID, + bootstrapThreadId: THREAD_ID, + }, + }; +} + +function addThreadToSnapshot( + snapshot: OrchestrationReadModel, + threadId: ThreadId, +): OrchestrationReadModel { + return { + ...snapshot, + snapshotSequence: snapshot.snapshotSequence + 1, + threads: [ + ...snapshot.threads, + { + id: threadId, + projectId: PROJECT_ID, + title: "New thread", + modelSelection: { + provider: "codex", + model: "gpt-5", + }, + interactionMode: "default", + runtimeMode: "full-access", + branch: "main", + worktreePath: null, + latestTurn: null, + createdAt: NOW_ISO, + updatedAt: NOW_ISO, + archivedAt: null, + deletedAt: null, + messages: [], + activities: [], + proposedPlans: [], + checkpoints: [], + session: { + threadId, + status: "ready", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: NOW_ISO, + }, + }, + ], + }; +} + +function createThreadCreatedEvent(threadId: ThreadId, sequence: number): OrchestrationEvent { + return { + sequence, + eventId: EventId.makeUnsafe(`event-thread-created-${sequence}`), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: NOW_ISO, + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "thread.created", + payload: { + threadId, + projectId: PROJECT_ID, + title: "New thread", + modelSelection: { + provider: "codex", + model: "gpt-5", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt: NOW_ISO, + updatedAt: NOW_ISO, + }, + }; +} + +function sendOrchestrationDomainEvent(event: OrchestrationEvent): void { + rpcHarness.emitStreamValue(WS_METHODS.subscribeOrchestrationDomainEvents, event); +} + +async function waitForWsClient(): Promise { + await vi.waitFor( + () => { + expect( + wsRequests.some( + (request) => request._tag === WS_METHODS.subscribeOrchestrationDomainEvents, + ), + ).toBe(true); + }, + { timeout: 8_000, interval: 16 }, + ); +} + +async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise { + await waitForWsClient(); + fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId); + sendOrchestrationDomainEvent( + createThreadCreatedEvent(threadId, fixture.snapshot.snapshotSequence), + ); + await vi.waitFor( + () => { + expect(useComposerDraftStore.getState().draftThreadsByThreadId[threadId]).toBeUndefined(); + }, + { timeout: 8_000, interval: 16 }, + ); +} + +function createDraftOnlySnapshot(): OrchestrationReadModel { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-draft-target" as MessageId, + targetText: "draft thread", + }); + return { + ...snapshot, + threads: [], + }; +} + +function withProjectScripts( + snapshot: OrchestrationReadModel, + scripts: OrchestrationReadModel["projects"][number]["scripts"], +): OrchestrationReadModel { + return { + ...snapshot, + projects: snapshot.projects.map((project) => + project.id === PROJECT_ID ? { ...project, scripts: Array.from(scripts) } : project, + ), + }; +} + +function setDraftThreadWithoutWorktree(): void { + 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, + }, + }); +} + +function createSnapshotWithLongProposedPlan(): OrchestrationReadModel { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-plan-target" as MessageId, + targetText: "plan thread", + }); + const planMarkdown = [ + "# Ship plan mode follow-up", + "", + "- Step 1: capture the thread-open trace", + "- Step 2: identify the main-thread bottleneck", + "- Step 3: keep collapsed cards cheap", + "- Step 4: render the full markdown only on demand", + "- Step 5: preserve export and save actions", + "- Step 6: add regression coverage", + "- Step 7: verify route transitions stay responsive", + "- Step 8: confirm no server-side work changed", + "- Step 9: confirm short plans still render normally", + "- Step 10: confirm long plans stay collapsed by default", + "- Step 11: confirm preview text is still useful", + "- Step 12: confirm plan follow-up flow still works", + "- Step 13: confirm timeline virtualization still behaves", + "- Step 14: confirm theme styling still looks correct", + "- Step 15: confirm save dialog behavior is unchanged", + "- Step 16: confirm download behavior is unchanged", + "- Step 17: confirm code fences do not parse until expand", + "- Step 18: confirm preview truncation ends cleanly", + "- Step 19: confirm markdown links still open in editor after expand", + "- Step 20: confirm deep hidden detail only appears after expand", + "", + "```ts", + "export const hiddenPlanImplementationDetail = 'deep hidden detail only after expand';", + "```", + ].join("\n"); + + return { + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID + ? Object.assign({}, thread, { + proposedPlans: [ + { + id: "plan-browser-test", + turnId: null, + planMarkdown, + implementedAt: null, + implementationThreadId: null, + createdAt: isoAt(1_000), + updatedAt: isoAt(1_001), + }, + ], + updatedAt: isoAt(1_001), + }) + : thread, + ), + }; +} + +function createSnapshotWithPendingUserInput(): OrchestrationReadModel { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-pending-input-target" as MessageId, + targetText: "question thread", + }); + + return { + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID + ? Object.assign({}, thread, { + interactionMode: "plan", + activities: [ + { + id: EventId.makeUnsafe("activity-user-input-requested"), + tone: "info", + kind: "user-input.requested", + summary: "User input requested", + payload: { + requestId: "req-browser-user-input", + questions: [ + { + id: "scope", + header: "Scope", + question: "What should this change cover?", + options: [ + { + label: "Tight", + description: "Touch only the footer layout logic.", + }, + { + label: "Broad", + description: "Also adjust the related composer controls.", + }, + ], + }, + { + id: "risk", + header: "Risk", + question: "How aggressive should the imaginary plan be?", + options: [ + { + label: "Conservative", + description: "Favor reliability and low-risk changes.", + }, + { + label: "Balanced", + description: "Mix quick wins with one structural improvement.", + }, + ], + }, + ], + }, + turnId: null, + sequence: 1, + createdAt: isoAt(1_000), + }, + ], + updatedAt: isoAt(1_000), + }) + : thread, + ), + }; +} + +function createSnapshotWithPlanFollowUpPrompt(): OrchestrationReadModel { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-plan-follow-up-target" as MessageId, + targetText: "plan follow-up thread", + }); + + return { + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID + ? Object.assign({}, thread, { + interactionMode: "plan", + latestTurn: { + turnId: "turn-plan-follow-up" as TurnId, + state: "completed", + requestedAt: isoAt(1_000), + startedAt: isoAt(1_001), + completedAt: isoAt(1_010), + assistantMessageId: null, + }, + proposedPlans: [ + { + id: "plan-follow-up-browser-test", + turnId: "turn-plan-follow-up" as TurnId, + planMarkdown: "# Follow-up plan\n\n- Keep the composer footer stable on resize.", + implementedAt: null, + implementationThreadId: null, + createdAt: isoAt(1_002), + updatedAt: isoAt(1_003), + }, + ], + session: { + ...thread.session, + status: "ready", + updatedAt: isoAt(1_010), + }, + updatedAt: isoAt(1_010), + }) + : thread, + ), + }; +} + +function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown { + const customResult = customWsRpcResolver?.(body); + if (customResult !== undefined) { + return customResult; + } + const tag = body._tag; + if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) { + return fixture.snapshot; + } + if (tag === WS_METHODS.serverGetConfig) { + return fixture.serverConfig; + } + if (tag === WS_METHODS.gitListBranches) { + return { + isRepo: true, + hasOriginRemote: true, + nextCursor: null, + totalCount: 1, + branches: [ + { + name: "main", + current: true, + isDefault: true, + worktreePath: null, + }, + ], + }; + } + if (tag === WS_METHODS.gitStatus) { + return { + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: true, + branch: "main", + hasWorkingTreeChanges: false, + workingTree: { + files: [], + insertions: 0, + deletions: 0, + }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }; + } + if (tag === WS_METHODS.projectsSearchEntries) { + return { + entries: [], + truncated: false, + }; + } + if (tag === WS_METHODS.shellOpenInEditor) { + return null; + } + if (tag === WS_METHODS.terminalOpen) { + return { + threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID, + terminalId: typeof body.terminalId === "string" ? body.terminalId : "default", + cwd: typeof body.cwd === "string" ? body.cwd : "/repo/project", + worktreePath: + typeof body.worktreePath === "string" + ? body.worktreePath + : body.worktreePath === null + ? null + : null, + status: "running", + pid: 123, + history: "", + exitCode: null, + exitSignal: null, + updatedAt: NOW_ISO, + }; + } + return {}; +} + +const worker = setupWorker( + wsLink.addEventListener("connection", ({ client }) => { + void rpcHarness.connect(client); + client.addEventListener("message", (event) => { + const rawData = event.data; + if (typeof rawData !== "string") return; + void rpcHarness.onMessage(rawData); + }); + }), + http.get("*/attachments/:attachmentId", () => + HttpResponse.text(ATTACHMENT_SVG, { + headers: { + "Content-Type": "image/svg+xml", + }, + }), + ), + http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })), +); + +async function nextFrame(): Promise { + await new Promise((resolve) => { + window.requestAnimationFrame(() => resolve()); + }); +} + +async function waitForLayout(): Promise { + await nextFrame(); + await nextFrame(); + await nextFrame(); +} + +async function setViewport(viewport: ViewportSpec): Promise { + await page.viewport(viewport.width, viewport.height); + await waitForLayout(); +} + +async function waitForProductionStyles(): Promise { + await vi.waitFor( + () => { + expect( + getComputedStyle(document.documentElement).getPropertyValue("--background").trim(), + ).not.toBe(""); + expect(getComputedStyle(document.body).marginTop).toBe("0px"); + }, + { + timeout: 4_000, + interval: 16, + }, + ); +} + +async function waitForElement( + query: () => T | null, + errorMessage: string, +): Promise { + let element: T | null = null; + await vi.waitFor( + () => { + element = query(); + expect(element, errorMessage).toBeTruthy(); + }, + { + timeout: 8_000, + interval: 16, + }, + ); + if (!element) { + throw new Error(errorMessage); + } + return element; +} + +async function waitForURL( + router: ReturnType, + predicate: (pathname: string) => boolean, + errorMessage: string, +): Promise { + let pathname = ""; + await vi.waitFor( + () => { + pathname = router.state.location.pathname; + expect(predicate(pathname), errorMessage).toBe(true); + }, + { timeout: 8_000, interval: 16 }, + ); + return pathname; +} + +async function waitForComposerEditor(): Promise { + return waitForElement( + () => document.querySelector('[contenteditable="true"]'), + "Unable to find composer editor.", + ); +} + +async function waitForComposerMenuItem(itemId: string): Promise { + return waitForElement( + () => document.querySelector(`[data-composer-item-id="${itemId}"]`), + `Unable to find composer menu item "${itemId}".`, + ); +} + +async function waitForSendButton(): Promise { + return waitForElement( + () => document.querySelector('button[aria-label="Send message"]'), + "Unable to find send button.", + ); +} + +function findComposerProviderModelPicker(): HTMLButtonElement | null { + return document.querySelector('[data-chat-provider-model-picker="true"]'); +} + +function findButtonByText(text: string): HTMLButtonElement | null { + return (Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === text, + ) ?? null) as HTMLButtonElement | null; +} + +async function waitForButtonByText(text: string): Promise { + return waitForElement(() => findButtonByText(text), `Unable to find "${text}" button.`); +} + +function findButtonContainingText(text: string): HTMLButtonElement | null { + return (Array.from(document.querySelectorAll("button")).find((button) => + button.textContent?.includes(text), + ) ?? null) as HTMLButtonElement | null; +} + +async function waitForButtonContainingText(text: string): Promise { + return waitForElement( + () => findButtonContainingText(text), + `Unable to find button containing "${text}".`, + ); +} + +async function expectComposerActionsContained(): Promise { + const footer = await waitForElement( + () => document.querySelector('[data-chat-composer-footer="true"]'), + "Unable to find composer footer.", + ); + const actions = await waitForElement( + () => document.querySelector('[data-chat-composer-actions="right"]'), + "Unable to find composer actions container.", + ); + + await vi.waitFor( + () => { + const footerRect = footer.getBoundingClientRect(); + const actionButtons = Array.from(actions.querySelectorAll("button")); + expect(actionButtons.length).toBeGreaterThanOrEqual(1); + + const buttonRects = actionButtons.map((button) => button.getBoundingClientRect()); + const firstTop = buttonRects[0]?.top ?? 0; + + for (const rect of buttonRects) { + expect(rect.right).toBeLessThanOrEqual(footerRect.right + 0.5); + expect(rect.bottom).toBeLessThanOrEqual(footerRect.bottom + 0.5); + expect(Math.abs(rect.top - firstTop)).toBeLessThanOrEqual(1.5); + } + }, + { timeout: 8_000, interval: 16 }, + ); +} + +async function waitForInteractionModeButton( + expectedLabel: "Chat" | "Plan", +): Promise { + 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 waitForServerConfigToApply(): Promise { + await vi.waitFor( + () => { + expect(wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerConfig)).toBe( + true, + ); + }, + { timeout: 8_000, interval: 16 }, + ); + await waitForLayout(); +} + +function dispatchChatNewShortcut(): void { + const useMetaForMod = isMacPlatform(navigator.platform); + window.dispatchEvent( + new KeyboardEvent("keydown", { + key: "o", + shiftKey: true, + metaKey: useMetaForMod, + ctrlKey: !useMetaForMod, + bubbles: true, + cancelable: true, + }), + ); +} + +async function triggerChatNewShortcutUntilPath( + router: ReturnType, + predicate: (pathname: string) => boolean, + errorMessage: string, +): Promise { + let pathname = router.state.location.pathname; + const deadline = Date.now() + 8_000; + while (Date.now() < deadline) { + dispatchChatNewShortcut(); + await waitForLayout(); + pathname = router.state.location.pathname; + if (predicate(pathname)) { + return pathname; + } + } + throw new Error(`${errorMessage} Last path: ${pathname}`); +} + +async function waitForNewThreadShortcutLabel(): Promise { + const newThreadButton = page.getByTestId("new-thread-button"); + await expect.element(newThreadButton).toBeInTheDocument(); + await newThreadButton.hover(); + const shortcutLabel = isMacPlatform(navigator.platform) + ? "New thread (⇧⌘O)" + : "New thread (Ctrl+Shift+O)"; + await expect.element(page.getByText(shortcutLabel)).toBeInTheDocument(); +} + +async function waitForImagesToLoad(scope: ParentNode): Promise { + const images = Array.from(scope.querySelectorAll("img")); + if (images.length === 0) { + return; + } + await Promise.all( + images.map( + (image) => + new Promise((resolve) => { + if (image.complete) { + resolve(); + return; + } + image.addEventListener("load", () => resolve(), { once: true }); + image.addEventListener("error", () => resolve(), { once: true }); + }), + ), + ); + await waitForLayout(); +} + +async function measureUserRow(options: { + host: HTMLElement; + targetMessageId: MessageId; +}): Promise { + const { host, targetMessageId } = options; + const rowSelector = `[data-message-id="${targetMessageId}"][data-message-role="user"]`; + + const scrollContainer = await waitForElement( + () => host.querySelector("div.overflow-y-auto.overscroll-y-contain"), + "Unable to find ChatView message scroll container.", + ); + + let row: HTMLElement | null = null; + await vi.waitFor( + async () => { + scrollContainer.scrollTop = 0; + scrollContainer.dispatchEvent(new Event("scroll")); + await waitForLayout(); + row = host.querySelector(rowSelector); + expect(row, "Unable to locate targeted user message row.").toBeTruthy(); + }, + { + timeout: 8_000, + interval: 16, + }, + ); + + await waitForImagesToLoad(row!); + scrollContainer.scrollTop = 0; + scrollContainer.dispatchEvent(new Event("scroll")); + await nextFrame(); + + const timelineRoot = + row!.closest('[data-timeline-root="true"]') ?? + host.querySelector('[data-timeline-root="true"]'); + if (!(timelineRoot instanceof HTMLElement)) { + throw new Error("Unable to locate timeline root container."); + } + + let timelineWidthMeasuredPx = 0; + let measuredRowHeightPx = 0; + let renderedInVirtualizedRegion = false; + await vi.waitFor( + async () => { + scrollContainer.scrollTop = 0; + scrollContainer.dispatchEvent(new Event("scroll")); + await nextFrame(); + const measuredRow = host.querySelector(rowSelector); + expect(measuredRow, "Unable to measure targeted user row height.").toBeTruthy(); + timelineWidthMeasuredPx = timelineRoot.getBoundingClientRect().width; + measuredRowHeightPx = measuredRow!.getBoundingClientRect().height; + renderedInVirtualizedRegion = measuredRow!.closest("[data-index]") instanceof HTMLElement; + expect(timelineWidthMeasuredPx, "Unable to measure timeline width.").toBeGreaterThan(0); + expect(measuredRowHeightPx, "Unable to measure targeted user row height.").toBeGreaterThan(0); + }, + { + timeout: 4_000, + interval: 16, + }, + ); + + return { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion }; +} + +async function mountChatView(options: { + viewport: ViewportSpec; + snapshot: OrchestrationReadModel; + configureFixture?: (fixture: TestFixture) => void; + resolveRpc?: (body: NormalizedWsRpcRequestBody) => unknown | undefined; +}): Promise { + fixture = buildFixture(options.snapshot); + options.configureFixture?.(fixture); + customWsRpcResolver = options.resolveRpc ?? null; + await setViewport(options.viewport); + await waitForProductionStyles(); + + const host = document.createElement("div"); + host.style.position = "fixed"; + host.style.top = "0"; + host.style.left = "0"; + host.style.width = "100vw"; + host.style.height = "100vh"; + host.style.display = "grid"; + host.style.overflow = "hidden"; + document.body.append(host); + + const router = getRouter( + createMemoryHistory({ + initialEntries: [`/${THREAD_ID}`], + }), + ); + + const screen = await render(, { + container: host, + }); + + await waitForLayout(); + + const cleanup = async () => { + customWsRpcResolver = null; + await screen.unmount(); + host.remove(); + }; + + return { + [Symbol.asyncDispose]: cleanup, + cleanup, + measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }), + setViewport: async (viewport: ViewportSpec) => { + await setViewport(viewport); + await waitForProductionStyles(); + }, + setContainerSize: async (viewport) => { + host.style.width = `${viewport.width}px`; + host.style.height = `${viewport.height}px`; + await waitForLayout(); + }, + router, + }; +} + +async function measureUserRowAtViewport(options: { + snapshot: OrchestrationReadModel; + targetMessageId: MessageId; + viewport: ViewportSpec; +}): Promise { + const mounted = await mountChatView({ + viewport: options.viewport, + snapshot: options.snapshot, + }); + + try { + return await mounted.measureUserRow(options.targetMessageId); + } finally { + await mounted.cleanup(); + } +} + +describe("ChatView timeline estimator parity (full app)", () => { + beforeAll(async () => { + fixture = buildFixture( + createSnapshotForTargetUser({ + targetMessageId: "msg-user-bootstrap" as MessageId, + targetText: "bootstrap", + }), + ); + await worker.start({ + onUnhandledRequest: "bypass", + quiet: true, + serviceWorker: { + url: "/mockServiceWorker.js", + }, + }); + }); + + afterAll(async () => { + await rpcHarness.disconnect(); + await worker.stop(); + }); + + beforeEach(async () => { + await rpcHarness.reset({ + resolveUnary: resolveWsRpc, + getInitialStreamValues: (request) => { + if (request._tag === WS_METHODS.subscribeServerLifecycle) { + return [ + { + version: 1, + sequence: 1, + type: "welcome", + payload: fixture.welcome, + }, + ]; + } + if (request._tag === WS_METHODS.subscribeServerConfig) { + return [ + { + version: 1, + type: "snapshot", + config: fixture.serverConfig, + }, + ]; + } + return []; + }, + }); + __resetNativeApiForTests(); + await setViewport(DEFAULT_VIEWPORT); + localStorage.clear(); + document.body.innerHTML = ""; + wsRequests.length = 0; + customWsRpcResolver = null; + useComposerDraftStore.setState({ + draftsByThreadId: {}, + draftThreadsByThreadId: {}, + projectDraftThreadIdByProjectId: {}, + stickyModelSelectionByProvider: {}, + stickyActiveProvider: null, + }); + useStore.setState({ + projects: [], + threads: [], + bootstrapComplete: false, + }); + useTerminalStateStore.persist.clearStorage(); + useTerminalStateStore.setState({ + terminalStateByThreadId: {}, + terminalLaunchContextByThreadId: {}, + terminalEventEntriesByKey: {}, + nextTerminalEventId: 1, + }); + }); + + afterEach(() => { + customWsRpcResolver = null; + document.body.innerHTML = ""; + }); + + it.each(TEXT_VIEWPORT_MATRIX)( + "keeps long user message estimate close at the $name viewport", + async (viewport) => { + const userText = "x".repeat(3_200); + const targetMessageId = `msg-user-target-long-${viewport.name}` as MessageId; + const mounted = await mountChatView({ + viewport, + snapshot: createSnapshotForTargetUser({ + targetMessageId, + targetText: userText, + }), + }); + + try { + const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } = + await mounted.measureUserRow(targetMessageId); + + expect(renderedInVirtualizedRegion).toBe(true); + + const estimatedHeightPx = estimateTimelineMessageHeight( + { role: "user", text: userText, attachments: [] }, + { timelineWidthPx: timelineWidthMeasuredPx }, + ); + + expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual( + viewport.textTolerancePx, + ); + } finally { + await mounted.cleanup(); + } + }, + ); + + it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => { + const userText = "x".repeat(3_200); + const targetMessageId = "msg-user-target-resize" as MessageId; + const mounted = await mountChatView({ + viewport: TEXT_VIEWPORT_MATRIX[0], + snapshot: createSnapshotForTargetUser({ + targetMessageId, + targetText: userText, + }), + }); + + try { + const measurements: Array< + UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number } + > = []; + + for (const viewport of TEXT_VIEWPORT_MATRIX) { + await mounted.setViewport(viewport); + const measurement = await mounted.measureUserRow(targetMessageId); + const estimatedHeightPx = estimateTimelineMessageHeight( + { role: "user", text: userText, attachments: [] }, + { timelineWidthPx: measurement.timelineWidthMeasuredPx }, + ); + + expect(measurement.renderedInVirtualizedRegion).toBe(true); + expect(Math.abs(measurement.measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual( + viewport.textTolerancePx, + ); + measurements.push({ ...measurement, viewport, estimatedHeightPx }); + } + + expect( + new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx))) + .size, + ).toBeGreaterThanOrEqual(3); + + const byMeasuredWidth = measurements.toSorted( + (left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx, + ); + const narrowest = byMeasuredWidth[0]!; + const widest = byMeasuredWidth.at(-1)!; + expect(narrowest.timelineWidthMeasuredPx).toBeLessThan(widest.timelineWidthMeasuredPx); + expect(narrowest.measuredRowHeightPx).toBeGreaterThan(widest.measuredRowHeightPx); + expect(narrowest.estimatedHeightPx).toBeGreaterThan(widest.estimatedHeightPx); + } finally { + await mounted.cleanup(); + } + }); + + it("tracks additional rendered wrapping when ChatView width narrows between desktop and mobile viewports", async () => { + const userText = "x".repeat(2_400); + const targetMessageId = "msg-user-target-wrap" as MessageId; + const snapshot = createSnapshotForTargetUser({ + targetMessageId, + targetText: userText, + }); + const desktopMeasurement = await measureUserRowAtViewport({ + viewport: TEXT_VIEWPORT_MATRIX[0], + snapshot, + targetMessageId, + }); + const mobileMeasurement = await measureUserRowAtViewport({ + viewport: TEXT_VIEWPORT_MATRIX[2], + snapshot, + targetMessageId, + }); + + const estimatedDesktopPx = estimateTimelineMessageHeight( + { role: "user", text: userText, attachments: [] }, + { timelineWidthPx: desktopMeasurement.timelineWidthMeasuredPx }, + ); + const estimatedMobilePx = estimateTimelineMessageHeight( + { role: "user", text: userText, attachments: [] }, + { timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx }, + ); + + const measuredDeltaPx = + mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx; + const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx; + expect(measuredDeltaPx).toBeGreaterThan(0); + expect(estimatedDeltaPx).toBeGreaterThan(0); + const ratio = estimatedDeltaPx / measuredDeltaPx; + expect(ratio).toBeGreaterThan(0.65); + expect(ratio).toBeLessThan(1.35); + }); + + it.each(ATTACHMENT_VIEWPORT_MATRIX)( + "keeps user attachment estimate close at the $name viewport", + async (viewport) => { + const targetMessageId = `msg-user-target-attachments-${viewport.name}` as MessageId; + const userText = "message with image attachments"; + const mounted = await mountChatView({ + viewport, + snapshot: createSnapshotForTargetUser({ + targetMessageId, + targetText: userText, + targetAttachmentCount: 3, + }), + }); + + try { + const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } = + await mounted.measureUserRow(targetMessageId); + + expect(renderedInVirtualizedRegion).toBe(true); + + const estimatedHeightPx = estimateTimelineMessageHeight( + { + role: "user", + text: userText, + attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }], + }, + { timelineWidthPx: timelineWidthMeasuredPx }, + ); + + expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual( + viewport.attachmentTolerancePx, + ); + } finally { + await mounted.cleanup(); + } + }, + ); + + it("shows an explicit empty state for projects without threads in the sidebar", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + }); + + try { + await expect.element(page.getByText("No threads yet")).toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); + + it("opens the project cwd for draft threads without a worktree path", async () => { + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["vscode"], + }; + }, + }); + + try { + await waitForServerConfigToApply(); + const openButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Open", + ) as HTMLButtonElement | null, + "Unable to find Open button.", + ); + await vi.waitFor(() => { + expect(openButton.disabled).toBe(false); + }); + 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("does not leak a server worktree path into drawer runtime env when launch context clears it", async () => { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-launch-context-target" as MessageId, + targetText: "launch context worktree override", + }); + const targetThread = snapshot.threads.find((thread) => thread.id === THREAD_ID); + if (targetThread) { + Object.assign(targetThread, { + branch: "feature/branch", + worktreePath: "/repo/worktrees/feature-branch", + }); + } + + useTerminalStateStore.setState({ + terminalStateByThreadId: { + [THREAD_ID]: { + terminalOpen: true, + terminalHeight: 280, + terminalIds: ["default"], + runningTerminalIds: [], + runningTerminalPorts: {}, + activeTerminalId: "default", + terminalGroups: [{ id: "group-default", terminalIds: ["default"] }], + activeTerminalGroupId: "group-default", + }, + }, + terminalLaunchContextByThreadId: { + [THREAD_ID]: { + cwd: "/repo/project", + worktreePath: null, + }, + }, + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot, + }); + + try { + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.terminalOpen, + ) as + | { + _tag: string; + cwd?: string; + worktreePath?: string | null; + env?: Record; + } + | undefined; + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.terminalOpen, + cwd: "/repo/project", + worktreePath: null, + env: { + T3CODE_PROJECT_ROOT: "/repo/project", + }, + }); + expect(openRequest?.env?.T3CODE_WORKTREE_PATH).toBeUndefined(); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => { + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["vscode-insiders"], + }; + }, + }); + + try { + await waitForServerConfigToApply(); + const openButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Open", + ) as HTMLButtonElement | null, + "Unable to find Open button.", + ); + await vi.waitFor(() => { + expect(openButton.disabled).toBe(false); + }); + 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-insiders", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("opens the project cwd with Trae when it is the only available editor", async () => { + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["trae"], + }; + }, + }); + + try { + await waitForServerConfigToApply(); + const openButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Open", + ) as HTMLButtonElement | null, + "Unable to find Open button.", + ); + await vi.waitFor(() => { + expect(openButton.disabled).toBe(false); + }); + 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: "trae", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("filters the open picker menu and opens VSCodium from the menu", async () => { + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["vscode-insiders", "vscodium"], + }; + }, + }); + + try { + await waitForServerConfigToApply(); + const menuButton = await waitForElement( + () => document.querySelector('button[aria-label="Copy options"]'), + "Unable to find Open picker button.", + ); + (menuButton as HTMLButtonElement).click(); + + await waitForElement( + () => + Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => + item.textContent?.includes("VS Code Insiders"), + ) ?? null, + "Unable to find VS Code Insiders menu item.", + ); + + expect( + Array.from(document.querySelectorAll('[data-slot="menu-item"]')).some((item) => + item.textContent?.includes("Zed"), + ), + ).toBe(false); + + const vscodiumItem = await waitForElement( + () => + Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => + item.textContent?.includes("VSCodium"), + ) ?? null, + "Unable to find VSCodium menu item.", + ); + (vscodiumItem as HTMLElement).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: "vscodium", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("falls back to the first installed editor when the stored favorite is unavailable", async () => { + localStorage.setItem("t3code:last-editor", JSON.stringify("vscodium")); + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["vscode-insiders"], + }; + }, + }); + + try { + await waitForServerConfigToApply(); + const openButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Open", + ) as HTMLButtonElement | null, + "Unable to find Open button.", + ); + await vi.waitFor(() => { + expect(openButton.disabled).toBe(false); + }); + 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-insiders", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("runs project scripts from local draft threads at the project cwd", 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: withProjectScripts(createDraftOnlySnapshot(), [ + { + id: "lint", + name: "Lint", + command: "bun run lint", + icon: "lint", + runOnWorktreeCreate: false, + }, + ]), + }); + + try { + const runButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.title === "Run Lint", + ) as HTMLButtonElement | null, + "Unable to find Run Lint button.", + ); + runButton.click(); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.terminalOpen, + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.terminalOpen, + threadId: THREAD_ID, + cwd: "/repo/project", + env: { + T3CODE_PROJECT_ROOT: "/repo/project", + }, + }); + }, + { timeout: 8_000, interval: 16 }, + ); + + await vi.waitFor( + () => { + const writeRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.terminalWrite, + ); + expect(writeRequest).toMatchObject({ + _tag: WS_METHODS.terminalWrite, + threadId: THREAD_ID, + data: "bun run lint\r", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("runs project scripts from worktree draft threads at the worktree cwd", async () => { + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: "feature/draft", + worktreePath: "/repo/worktrees/feature-draft", + envMode: "worktree", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: withProjectScripts(createDraftOnlySnapshot(), [ + { + id: "test", + name: "Test", + command: "bun run test", + icon: "test", + runOnWorktreeCreate: false, + }, + ]), + }); + + try { + const runButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.title === "Run Test", + ) as HTMLButtonElement | null, + "Unable to find Run Test button.", + ); + runButton.click(); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.terminalOpen, + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.terminalOpen, + threadId: THREAD_ID, + cwd: "/repo/worktrees/feature-draft", + env: { + T3CODE_PROJECT_ROOT: "/repo/project", + T3CODE_WORKTREE_PATH: "/repo/worktrees/feature-draft", + }, + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("lets the server own setup after preparing a pull request worktree thread", 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: withProjectScripts(createDraftOnlySnapshot(), [ + { + id: "setup", + name: "Setup", + command: "bun install", + icon: "configure", + runOnWorktreeCreate: true, + }, + ]), + resolveRpc: (body) => { + if (body._tag === WS_METHODS.gitResolvePullRequest) { + return { + pullRequest: { + number: 1359, + title: "Add thread archiving and settings navigation", + url: "https://github.com/pingdotgg/t3code/pull/1359", + baseBranch: "main", + headBranch: "archive-settings-overhaul", + state: "open", + }, + }; + } + if (body._tag === WS_METHODS.gitPreparePullRequestThread) { + return { + pullRequest: { + number: 1359, + title: "Add thread archiving and settings navigation", + url: "https://github.com/pingdotgg/t3code/pull/1359", + baseBranch: "main", + headBranch: "archive-settings-overhaul", + state: "open", + }, + branch: "archive-settings-overhaul", + worktreePath: "/repo/worktrees/pr-1359", + }; + } + return undefined; + }, + }); + + try { + const branchButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "main", + ) as HTMLButtonElement | null, + "Unable to find branch selector button.", + ); + branchButton.click(); + + const branchInput = await waitForElement( + () => document.querySelector('input[placeholder="Search branches..."]'), + "Unable to find branch search input.", + ); + branchInput.focus(); + await page.getByPlaceholder("Search branches...").fill("1359"); + + const checkoutItem = await waitForElement( + () => + Array.from(document.querySelectorAll("span")).find( + (element) => element.textContent?.trim() === "Checkout Pull Request", + ) as HTMLSpanElement | null, + "Unable to find checkout pull request option.", + ); + checkoutItem.click(); + + const worktreeButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Worktree", + ) as HTMLButtonElement | null, + "Unable to find Worktree button.", + ); + worktreeButton.click(); + + await vi.waitFor( + () => { + const prepareRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.gitPreparePullRequestThread, + ); + expect(prepareRequest).toMatchObject({ + _tag: WS_METHODS.gitPreparePullRequestThread, + cwd: "/repo/project", + reference: "1359", + mode: "worktree", + threadId: THREAD_ID, + }); + }, + { timeout: 8_000, interval: 16 }, + ); + + expect( + wsRequests.some( + (request) => + request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r", + ), + ).toBe(false); + } finally { + await mounted.cleanup(); + } + }); + + it("sends bootstrap turn-starts and waits for server setup on first-send worktree drafts", async () => { + useTerminalStateStore.setState({ + terminalStateByThreadId: {}, + }); + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + envMode: "worktree", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: withProjectScripts(createDraftOnlySnapshot(), [ + { + id: "setup", + name: "Setup", + command: "bun install", + icon: "configure", + runOnWorktreeCreate: true, + }, + ]), + resolveRpc: (body) => { + if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { + return { + sequence: fixture.snapshot.snapshotSequence + 1, + }; + } + return undefined; + }, + }); + + try { + useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it"); + await waitForLayout(); + + const sendButton = await waitForSendButton(); + expect(sendButton.disabled).toBe(false); + sendButton.click(); + + await vi.waitFor( + () => { + const dispatchRequest = wsRequests.find( + (request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand, + ) as + | { + _tag: string; + type?: string; + bootstrap?: { + createThread?: { projectId?: string }; + prepareWorktree?: { projectCwd?: string; baseBranch?: string; branch?: string }; + runSetupScript?: boolean; + }; + } + | undefined; + expect(dispatchRequest).toMatchObject({ + _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, + type: "thread.turn.start", + bootstrap: { + createThread: { + projectId: PROJECT_ID, + }, + prepareWorktree: { + projectCwd: "/repo/project", + baseBranch: "main", + branch: expect.stringMatching(/^t3code\/[0-9a-f]{8}$/), + }, + runSetupScript: true, + }, + }); + }, + { timeout: 8_000, interval: 16 }, + ); + + expect(wsRequests.some((request) => request._tag === WS_METHODS.gitCreateWorktree)).toBe( + false, + ); + expect( + wsRequests.some( + (request) => + request._tag === WS_METHODS.terminalWrite && + request.threadId === THREAD_ID && + request.data === "bun install\r", + ), + ).toBe(false); + } finally { + await mounted.cleanup(); + } + }); + + it("shows the send state once bootstrap dispatch is in flight", async () => { + useTerminalStateStore.setState({ + terminalStateByThreadId: {}, + }); + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + envMode: "worktree", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); + + let resolveDispatch!: (value: { sequence: number }) => void; + const dispatchPromise = new Promise<{ sequence: number }>((resolve) => { + resolveDispatch = resolve; + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: withProjectScripts(createDraftOnlySnapshot(), [ + { + id: "setup", + name: "Setup", + command: "bun install", + icon: "configure", + runOnWorktreeCreate: true, + }, + ]), + resolveRpc: (body) => { + if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { + return dispatchPromise; + } + return undefined; + }, + }); + + try { + useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it"); + await waitForLayout(); + + const sendButton = await waitForSendButton(); + expect(sendButton.disabled).toBe(false); + sendButton.click(); + + await vi.waitFor( + () => { + expect( + wsRequests.some((request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand), + ).toBe(true); + expect(document.querySelector('button[aria-label="Sending"]')).toBeTruthy(); + expect(document.querySelector('button[aria-label="Preparing worktree"]')).toBeNull(); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + resolveDispatch({ sequence: fixture.snapshot.snapshotSequence + 1 }); + 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(); + } + }); + + it("keeps removed terminal context pills removed when a new one is added", async () => { + const removedLabel = "Terminal 1 lines 1-2"; + const addedLabel = "Terminal 2 lines 9-10"; + useComposerDraftStore.getState().addTerminalContext( + THREAD_ID, + createTerminalContext({ + id: "ctx-removed", + terminalLabel: "Terminal 1", + lineStart: 1, + lineEnd: 2, + text: "bun i\nno changes", + }), + ); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-terminal-pill-backspace" as MessageId, + targetText: "terminal pill backspace target", + }), + }); + + try { + await vi.waitFor( + () => { + expect(document.body.textContent).toContain(removedLabel); + }, + { timeout: 8_000, interval: 16 }, + ); + + const store = useComposerDraftStore.getState(); + const currentPrompt = store.draftsByThreadId[THREAD_ID]?.prompt ?? ""; + const nextPrompt = removeInlineTerminalContextPlaceholder(currentPrompt, 0); + store.setPrompt(THREAD_ID, nextPrompt.prompt); + store.removeTerminalContext(THREAD_ID, "ctx-removed"); + + await vi.waitFor( + () => { + expect(useComposerDraftStore.getState().draftsByThreadId[THREAD_ID]).toBeUndefined(); + expect(document.body.textContent).not.toContain(removedLabel); + }, + { timeout: 8_000, interval: 16 }, + ); + + useComposerDraftStore.getState().addTerminalContext( + THREAD_ID, + createTerminalContext({ + id: "ctx-added", + terminalLabel: "Terminal 2", + lineStart: 9, + lineEnd: 10, + text: "git status\nOn branch main", + }), + ); + + await vi.waitFor( + () => { + const draft = useComposerDraftStore.getState().draftsByThreadId[THREAD_ID]; + expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-added"]); + expect(document.body.textContent).toContain(addedLabel); + expect(document.body.textContent).not.toContain(removedLabel); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("disables send when the composer only contains an expired terminal pill", async () => { + const expiredLabel = "Terminal 1 line 4"; + useComposerDraftStore.getState().addTerminalContext( + THREAD_ID, + createTerminalContext({ + id: "ctx-expired-only", + terminalLabel: "Terminal 1", + lineStart: 4, + lineEnd: 4, + text: "", + }), + ); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-expired-pill-disabled" as MessageId, + targetText: "expired pill disabled target", + }), + }); + + try { + await vi.waitFor( + () => { + expect(document.body.textContent).toContain(expiredLabel); + }, + { timeout: 8_000, interval: 16 }, + ); + + const sendButton = await waitForSendButton(); + expect(sendButton.disabled).toBe(true); + } finally { + await mounted.cleanup(); + } + }); + + it("warns when sending text while omitting expired terminal pills", async () => { + const expiredLabel = "Terminal 1 line 4"; + useComposerDraftStore.getState().addTerminalContext( + THREAD_ID, + createTerminalContext({ + id: "ctx-expired-send-warning", + terminalLabel: "Terminal 1", + lineStart: 4, + lineEnd: 4, + text: "", + }), + ); + useComposerDraftStore + .getState() + .setPrompt(THREAD_ID, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-expired-pill-warning" as MessageId, + targetText: "expired pill warning target", + }), + }); + + try { + await vi.waitFor( + () => { + expect(document.body.textContent).toContain(expiredLabel); + }, + { timeout: 8_000, interval: 16 }, + ); + + const sendButton = await waitForSendButton(); + expect(sendButton.disabled).toBe(false); + sendButton.click(); + + await vi.waitFor( + () => { + expect(document.body.textContent).toContain( + "Expired terminal context omitted from message", + ); + expect(document.body.textContent).not.toContain(expiredLabel); + expect(document.body.textContent).toContain("yoowaddup"); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("shows a pointer cursor for the running stop button", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-stop-button-cursor" as MessageId, + targetText: "stop button cursor target", + sessionStatus: "running", + }), + }); + + try { + const stopButton = await waitForElement( + () => document.querySelector('button[aria-label="Stop generation"]'), + "Unable to find stop generation button.", + ); + + expect(getComputedStyle(stopButton).cursor).toBe("pointer"); + } finally { + await mounted.cleanup(); + } + }); + + it("hides the archive action when the pointer leaves a thread row", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-archive-hover-test" as MessageId, + targetText: "archive hover target", + }), + }); + + try { + const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`); + + await expect.element(threadRow).toBeInTheDocument(); + const archiveButton = await waitForElement( + () => + document.querySelector(`[data-testid="thread-archive-${THREAD_ID}"]`), + "Unable to find archive button.", + ); + const archiveAction = archiveButton.parentElement; + expect( + archiveAction, + "Archive button should render inside a visibility wrapper.", + ).not.toBeNull(); + expect(getComputedStyle(archiveAction!).opacity).toBe("0"); + + await threadRow.hover(); + await vi.waitFor( + () => { + expect(getComputedStyle(archiveAction!).opacity).toBe("1"); + }, + { timeout: 4_000, interval: 16 }, + ); + + await page.getByTestId("composer-editor").hover(); + await vi.waitFor( + () => { + expect(getComputedStyle(archiveAction!).opacity).toBe("0"); + }, + { timeout: 4_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("shows the confirm archive action after clicking the archive button", async () => { + localStorage.setItem( + "t3code:client-settings:v1", + JSON.stringify({ + ...DEFAULT_CLIENT_SETTINGS, + confirmThreadArchive: true, + }), + ); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-archive-confirm-test" as MessageId, + targetText: "archive confirm target", + }), + }); + + try { + const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`); + + await expect.element(threadRow).toBeInTheDocument(); + await threadRow.hover(); + + const archiveButton = page.getByTestId(`thread-archive-${THREAD_ID}`); + await expect.element(archiveButton).toBeInTheDocument(); + await archiveButton.click(); + + const confirmButton = page.getByTestId(`thread-archive-confirm-${THREAD_ID}`); + await expect.element(confirmButton).toBeInTheDocument(); + await expect.element(confirmButton).toBeVisible(); + } finally { + localStorage.removeItem("t3code:client-settings:v1"); + await mounted.cleanup(); + } + }); + + it("keeps the new thread selected after clicking the new-thread button", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-new-thread-test" as MessageId, + targetText: "new thread selection test", + }), + }); + + try { + // Wait for the sidebar to render with the project. + const newThreadButton = page.getByTestId("new-thread-button"); + await expect.element(newThreadButton).toBeInTheDocument(); + + await newThreadButton.click(); + + // The route should change to a new draft thread ID. + const newThreadPath = await waitForURL( + mounted.router, + (path) => UUID_ROUTE_RE.test(path), + "Route should have changed to a new draft thread UUID.", + ); + const newThreadId = newThreadPath.slice(1) as ThreadId; + + // The composer editor should be present for the new draft thread. + await waitForComposerEditor(); + + // Simulate the steady-state promotion path: the server emits + // `thread.created`, the client materializes the thread incrementally, + // and the draft is cleared by live batch effects. + await promoteDraftThreadViaDomainEvent(newThreadId); + + // The route should still be on the new thread — not redirected away. + await waitForURL( + mounted.router, + (path) => path === newThreadPath, + "New thread should remain selected after server thread promotion clears the draft.", + ); + + // The empty thread view and composer should still be visible. + await expect + .element(page.getByText("Send a message to start the conversation.")) + .toBeInTheDocument(); + await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); + + it("snapshots sticky codex settings into a new draft thread", async () => { + useComposerDraftStore.setState({ + stickyModelSelectionByProvider: { + codex: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + reasoningEffort: "medium", + fastMode: true, + }, + }, + }, + stickyActiveProvider: "codex", + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-sticky-codex-traits-test" as MessageId, + targetText: "sticky codex traits test", + }), + }); + + try { + const newThreadButton = page.getByTestId("new-thread-button"); + await expect.element(newThreadButton).toBeInTheDocument(); + + await newThreadButton.click(); + + const newThreadPath = await waitForURL( + mounted.router, + (path) => UUID_ROUTE_RE.test(path), + "Route should have changed to a new draft thread UUID.", + ); + const newThreadId = newThreadPath.slice(1) as ThreadId; + + expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({ + modelSelectionByProvider: { + codex: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + fastMode: true, + }, + }, + }, + activeProvider: "codex", + }); + } finally { + await mounted.cleanup(); + } + }); + + it("hydrates the provider alongside a sticky claude model", async () => { + useComposerDraftStore.setState({ + stickyModelSelectionByProvider: { + claudeAgent: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + effort: "max", + fastMode: true, + }, + }, + }, + stickyActiveProvider: "claudeAgent", + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-sticky-claude-model-test" as MessageId, + targetText: "sticky claude model test", + }), + }); + + try { + const newThreadButton = page.getByTestId("new-thread-button"); + await expect.element(newThreadButton).toBeInTheDocument(); + + await newThreadButton.click(); + + const newThreadPath = await waitForURL( + mounted.router, + (path) => UUID_ROUTE_RE.test(path), + "Route should have changed to a new sticky claude draft thread UUID.", + ); + const newThreadId = newThreadPath.slice(1) as ThreadId; + + expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({ + modelSelectionByProvider: { + claudeAgent: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + effort: "max", + fastMode: true, + }, + }, + }, + activeProvider: "claudeAgent", + }); + } finally { + await mounted.cleanup(); + } + }); + + it("falls back to defaults when no sticky composer settings exist", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-default-codex-traits-test" as MessageId, + targetText: "default codex traits test", + }), + }); + + try { + const newThreadButton = page.getByTestId("new-thread-button"); + await expect.element(newThreadButton).toBeInTheDocument(); + + await newThreadButton.click(); + + const newThreadPath = await waitForURL( + mounted.router, + (path) => UUID_ROUTE_RE.test(path), + "Route should have changed to a new draft thread UUID.", + ); + const newThreadId = newThreadPath.slice(1) as ThreadId; + + expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toBeUndefined(); + } finally { + await mounted.cleanup(); + } + }); + + it("prefers draft state over sticky composer settings and defaults", async () => { + useComposerDraftStore.setState({ + stickyModelSelectionByProvider: { + codex: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + reasoningEffort: "medium", + fastMode: true, + }, + }, + }, + stickyActiveProvider: "codex", + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-draft-codex-traits-precedence-test" as MessageId, + targetText: "draft codex traits precedence test", + }), + }); + + try { + const newThreadButton = page.getByTestId("new-thread-button"); + await expect.element(newThreadButton).toBeInTheDocument(); + + await newThreadButton.click(); + + const threadPath = await waitForURL( + mounted.router, + (path) => UUID_ROUTE_RE.test(path), + "Route should have changed to a sticky draft thread UUID.", + ); + const threadId = threadPath.slice(1) as ThreadId; + + expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({ + modelSelectionByProvider: { + codex: { + provider: "codex", + model: "gpt-5.3-codex", + options: { + fastMode: true, + }, + }, + }, + activeProvider: "codex", + }); + + useComposerDraftStore.getState().setModelSelection(threadId, { + provider: "codex", + model: "gpt-5.4", + options: { + reasoningEffort: "low", + fastMode: true, + }, + }); + + await newThreadButton.click(); + + await waitForURL( + mounted.router, + (path) => path === threadPath, + "New-thread should reuse the existing project draft thread.", + ); + expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({ + modelSelectionByProvider: { + codex: { + provider: "codex", + model: "gpt-5.4", + options: { + reasoningEffort: "low", + fastMode: true, + }, + }, + }, + activeProvider: "codex", + }); + } finally { + await mounted.cleanup(); + } + }); + + it("creates a new thread from the global chat.new shortcut", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-chat-shortcut-test" as MessageId, + targetText: "chat shortcut test", + }), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + keybindings: [ + { + command: "chat.new", + shortcut: { + key: "o", + metaKey: false, + ctrlKey: false, + shiftKey: true, + altKey: false, + modKey: true, + }, + whenAst: { + type: "not", + node: { type: "identifier", name: "terminalFocus" }, + }, + }, + ], + }; + }, + }); + + try { + await waitForNewThreadShortcutLabel(); + await waitForServerConfigToApply(); + const composerEditor = await waitForComposerEditor(); + composerEditor.focus(); + await waitForLayout(); + await triggerChatNewShortcutUntilPath( + mounted.router, + (path) => UUID_ROUTE_RE.test(path), + "Route should have changed to a new draft thread UUID from the shortcut.", + ); + } finally { + await mounted.cleanup(); + } + }); + it("creates a fresh draft after the previous draft thread is promoted", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-promoted-draft-shortcut-test" as MessageId, + targetText: "promoted draft shortcut test", + }), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + keybindings: [ + { + command: "chat.new", + shortcut: { + key: "o", + metaKey: false, + ctrlKey: false, + shiftKey: true, + altKey: false, + modKey: true, + }, + whenAst: { + type: "not", + node: { type: "identifier", name: "terminalFocus" }, + }, + }, + ], + }; + }, + }); + + try { + const newThreadButton = page.getByTestId("new-thread-button"); + await expect.element(newThreadButton).toBeInTheDocument(); + await waitForNewThreadShortcutLabel(); + await waitForServerConfigToApply(); + await newThreadButton.click(); + + const promotedThreadPath = await waitForURL( + mounted.router, + (path) => UUID_ROUTE_RE.test(path), + "Route should have changed to a promoted draft thread UUID.", + ); + const promotedThreadId = promotedThreadPath.slice(1) as ThreadId; + + await promoteDraftThreadViaDomainEvent(promotedThreadId); + + const freshThreadPath = await triggerChatNewShortcutUntilPath( + mounted.router, + (path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath, + "Shortcut should create a fresh draft instead of reusing the promoted thread.", + ); + expect(freshThreadPath).not.toBe(promotedThreadPath); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps long proposed plans lightweight until the user expands them", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotWithLongProposedPlan(), + }); + + try { + await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Expand plan", + ) as HTMLButtonElement | null, + "Unable to find Expand plan button.", + ); + + expect(document.body.textContent).not.toContain("deep hidden detail only after expand"); + + const expandButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Expand plan", + ) as HTMLButtonElement | null, + "Unable to find Expand plan button.", + ); + expandButton.click(); + + await vi.waitFor( + () => { + expect(document.body.textContent).toContain("deep hidden detail only after expand"); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps pending-question footer actions inside the composer after a real resize", async () => { + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: createSnapshotWithPendingUserInput(), + }); + + try { + const firstOption = await waitForButtonContainingText("Tight"); + firstOption.click(); + + await waitForButtonByText("Previous"); + await waitForButtonByText("Submit answers"); + + await mounted.setContainerSize(COMPACT_FOOTER_VIEWPORT); + await expectComposerActionsContained(); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps plan follow-up footer actions fused and aligned after a real resize", async () => { + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: createSnapshotWithPlanFollowUpPrompt(), + }); + + try { + const footer = await waitForElement( + () => document.querySelector('[data-chat-composer-footer="true"]'), + "Unable to find composer footer.", + ); + const initialModelPicker = await waitForElement( + findComposerProviderModelPicker, + "Unable to find provider model picker.", + ); + const initialModelPickerOffset = + initialModelPicker.getBoundingClientRect().left - footer.getBoundingClientRect().left; + + await waitForButtonByText("Implement"); + await waitForElement( + () => + document.querySelector('button[aria-label="Implementation actions"]'), + "Unable to find implementation actions trigger.", + ); + + await mounted.setContainerSize({ + width: 440, + height: WIDE_FOOTER_VIEWPORT.height, + }); + await expectComposerActionsContained(); + + const implementButton = await waitForButtonByText("Implement"); + const implementActionsButton = await waitForElement( + () => + document.querySelector('button[aria-label="Implementation actions"]'), + "Unable to find implementation actions trigger.", + ); + + await vi.waitFor( + () => { + const implementRect = implementButton.getBoundingClientRect(); + const implementActionsRect = implementActionsButton.getBoundingClientRect(); + const compactModelPicker = findComposerProviderModelPicker(); + expect(compactModelPicker).toBeTruthy(); + + const compactModelPickerOffset = + compactModelPicker!.getBoundingClientRect().left - footer.getBoundingClientRect().left; + + expect(Math.abs(implementRect.right - implementActionsRect.left)).toBeLessThanOrEqual(1); + expect(Math.abs(implementRect.top - implementActionsRect.top)).toBeLessThanOrEqual(1); + expect(Math.abs(compactModelPickerOffset - initialModelPickerOffset)).toBeLessThanOrEqual( + 1, + ); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps the slash-command menu visible above the composer", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-command-menu-target" as MessageId, + targetText: "command menu thread", + }), + }); + + try { + await waitForComposerEditor(); + await page.getByTestId("composer-editor").fill("/"); + + const menuItem = await waitForComposerMenuItem("slash:model"); + const composerForm = await waitForElement( + () => document.querySelector('[data-chat-composer-form="true"]'), + "Unable to find composer form.", + ); + + await vi.waitFor( + () => { + const menuRect = menuItem.getBoundingClientRect(); + const composerRect = composerForm.getBoundingClientRect(); + const hitTarget = document.elementFromPoint( + menuRect.left + menuRect.width / 2, + menuRect.top + menuRect.height / 2, + ); + + expect(menuRect.width).toBeGreaterThan(0); + expect(menuRect.height).toBeGreaterThan(0); + expect(menuRect.bottom).toBeLessThanOrEqual(composerRect.bottom); + expect(hitTarget instanceof Element && menuItem.contains(hitTarget)).toBe(true); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); +}); diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts new file mode 100644 index 0000000000..8d49bc07f2 --- /dev/null +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -0,0 +1,457 @@ +import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { useStore } from "../store"; + +import { + MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, + buildExpiredTerminalContextToastCopy, + createLocalDispatchSnapshot, + deriveComposerSendState, + hasServerAcknowledgedLocalDispatch, + reconcileMountedTerminalThreadIds, + waitForStartedServerThread, +} from "./ChatView.logic"; + +describe("deriveComposerSendState", () => { + it("treats expired terminal pills as non-sendable content", () => { + const state = deriveComposerSendState({ + prompt: "\uFFFC", + imageCount: 0, + terminalContexts: [ + { + id: "ctx-expired", + threadId: ThreadId.makeUnsafe("thread-1"), + terminalId: "default", + terminalLabel: "Terminal 1", + lineStart: 4, + lineEnd: 4, + text: "", + createdAt: "2026-03-17T12:52:29.000Z", + }, + ], + }); + + expect(state.trimmedPrompt).toBe(""); + expect(state.sendableTerminalContexts).toEqual([]); + expect(state.expiredTerminalContextCount).toBe(1); + expect(state.hasSendableContent).toBe(false); + }); + + it("keeps text sendable while excluding expired terminal pills", () => { + const state = deriveComposerSendState({ + prompt: `yoo \uFFFC waddup`, + imageCount: 0, + terminalContexts: [ + { + id: "ctx-expired", + threadId: ThreadId.makeUnsafe("thread-1"), + terminalId: "default", + terminalLabel: "Terminal 1", + lineStart: 4, + lineEnd: 4, + text: "", + createdAt: "2026-03-17T12:52:29.000Z", + }, + ], + }); + + expect(state.trimmedPrompt).toBe("yoo waddup"); + expect(state.expiredTerminalContextCount).toBe(1); + expect(state.hasSendableContent).toBe(true); + }); +}); + +describe("buildExpiredTerminalContextToastCopy", () => { + it("formats clear empty-state guidance", () => { + expect(buildExpiredTerminalContextToastCopy(1, "empty")).toEqual({ + title: "Expired terminal context won't be sent", + description: "Remove it or re-add it to include terminal output.", + }); + }); + + it("formats omission guidance for sent messages", () => { + expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({ + title: "Expired terminal contexts omitted from message", + description: "Re-add it if you want that terminal output included.", + }); + }); +}); + +describe("reconcileMountedTerminalThreadIds", () => { + it("keeps previously mounted open threads and adds the active open thread", () => { + expect( + reconcileMountedTerminalThreadIds({ + currentThreadIds: [ + ThreadId.makeUnsafe("thread-hidden"), + ThreadId.makeUnsafe("thread-stale"), + ], + openThreadIds: [ThreadId.makeUnsafe("thread-hidden"), ThreadId.makeUnsafe("thread-active")], + activeThreadId: ThreadId.makeUnsafe("thread-active"), + activeThreadTerminalOpen: true, + }), + ).toEqual([ThreadId.makeUnsafe("thread-hidden"), ThreadId.makeUnsafe("thread-active")]); + }); + + it("drops mounted threads once their terminal drawer is no longer open", () => { + expect( + reconcileMountedTerminalThreadIds({ + currentThreadIds: [ThreadId.makeUnsafe("thread-closed")], + openThreadIds: [], + activeThreadId: ThreadId.makeUnsafe("thread-closed"), + activeThreadTerminalOpen: false, + }), + ).toEqual([]); + }); + + it("keeps only the most recently active hidden terminal threads", () => { + expect( + reconcileMountedTerminalThreadIds({ + currentThreadIds: [ + ThreadId.makeUnsafe("thread-1"), + ThreadId.makeUnsafe("thread-2"), + ThreadId.makeUnsafe("thread-3"), + ], + openThreadIds: [ + ThreadId.makeUnsafe("thread-1"), + ThreadId.makeUnsafe("thread-2"), + ThreadId.makeUnsafe("thread-3"), + ThreadId.makeUnsafe("thread-4"), + ], + activeThreadId: ThreadId.makeUnsafe("thread-4"), + activeThreadTerminalOpen: true, + maxHiddenThreadCount: 2, + }), + ).toEqual([ + ThreadId.makeUnsafe("thread-2"), + ThreadId.makeUnsafe("thread-3"), + ThreadId.makeUnsafe("thread-4"), + ]); + }); + + it("moves the active thread to the end so it is treated as most recently used", () => { + expect( + reconcileMountedTerminalThreadIds({ + currentThreadIds: [ + ThreadId.makeUnsafe("thread-a"), + ThreadId.makeUnsafe("thread-b"), + ThreadId.makeUnsafe("thread-c"), + ], + openThreadIds: [ + ThreadId.makeUnsafe("thread-a"), + ThreadId.makeUnsafe("thread-b"), + ThreadId.makeUnsafe("thread-c"), + ], + activeThreadId: ThreadId.makeUnsafe("thread-a"), + activeThreadTerminalOpen: true, + maxHiddenThreadCount: 2, + }), + ).toEqual([ + ThreadId.makeUnsafe("thread-b"), + ThreadId.makeUnsafe("thread-c"), + ThreadId.makeUnsafe("thread-a"), + ]); + }); + + it("defaults to the hidden mounted terminal cap", () => { + const currentThreadIds = Array.from( + { length: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS + 2 }, + (_, index) => ThreadId.makeUnsafe(`thread-${index + 1}`), + ); + + expect( + reconcileMountedTerminalThreadIds({ + currentThreadIds, + openThreadIds: currentThreadIds, + activeThreadId: null, + activeThreadTerminalOpen: false, + }), + ).toEqual(currentThreadIds.slice(-MAX_HIDDEN_MOUNTED_TERMINAL_THREADS)); + }); +}); + +const makeThread = (input?: { + id?: ThreadId; + latestTurn?: { + turnId: TurnId; + state: "running" | "completed"; + requestedAt: string; + startedAt: string | null; + completedAt: string | null; + } | null; +}) => ({ + id: input?.id ?? ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId: ProjectId.makeUnsafe("project-1"), + title: "Thread", + modelSelection: { provider: "codex" as const, model: "gpt-5.4" }, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + session: null, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:00.000Z", + latestTurn: input?.latestTurn + ? { + ...input.latestTurn, + assistantMessageId: null, + } + : null, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], +}); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + useStore.setState((state) => ({ + ...state, + projects: [], + threads: [], + bootstrapComplete: true, + })); +}); + +describe("waitForStartedServerThread", () => { + it("resolves immediately when the thread is already started", async () => { + const threadId = ThreadId.makeUnsafe("thread-started"); + useStore.setState((state) => ({ + ...state, + threads: [ + makeThread({ + id: threadId, + latestTurn: { + turnId: TurnId.makeUnsafe("turn-started"), + state: "running", + requestedAt: "2026-03-29T00:00:01.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: null, + }, + }), + ], + })); + + await expect(waitForStartedServerThread(threadId)).resolves.toBe(true); + }); + + it("waits for the thread to start via subscription updates", async () => { + const threadId = ThreadId.makeUnsafe("thread-wait"); + useStore.setState((state) => ({ + ...state, + threads: [makeThread({ id: threadId })], + })); + + const promise = waitForStartedServerThread(threadId, 500); + + useStore.setState((state) => ({ + ...state, + threads: [ + makeThread({ + id: threadId, + latestTurn: { + turnId: TurnId.makeUnsafe("turn-started"), + state: "running", + requestedAt: "2026-03-29T00:00:01.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: null, + }, + }), + ], + })); + + await expect(promise).resolves.toBe(true); + }); + + it("handles the thread starting between the initial read and subscription setup", async () => { + const threadId = ThreadId.makeUnsafe("thread-race"); + useStore.setState((state) => ({ + ...state, + threads: [makeThread({ id: threadId })], + })); + + const originalSubscribe = useStore.subscribe.bind(useStore); + let raced = false; + vi.spyOn(useStore, "subscribe").mockImplementation((listener) => { + if (!raced) { + raced = true; + useStore.setState((state) => ({ + ...state, + threads: [ + makeThread({ + id: threadId, + latestTurn: { + turnId: TurnId.makeUnsafe("turn-race"), + state: "running", + requestedAt: "2026-03-29T00:00:01.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: null, + }, + }), + ], + })); + } + return originalSubscribe(listener); + }); + + await expect(waitForStartedServerThread(threadId, 500)).resolves.toBe(true); + }); + + it("returns false after the timeout when the thread never starts", async () => { + vi.useFakeTimers(); + + const threadId = ThreadId.makeUnsafe("thread-timeout"); + useStore.setState((state) => ({ + ...state, + threads: [makeThread({ id: threadId })], + })); + const promise = waitForStartedServerThread(threadId, 500); + + await vi.advanceTimersByTimeAsync(500); + + await expect(promise).resolves.toBe(false); + }); +}); + +describe("hasServerAcknowledgedLocalDispatch", () => { + const projectId = ProjectId.makeUnsafe("project-1"); + const previousLatestTurn = { + turnId: TurnId.makeUnsafe("turn-1"), + state: "completed" as const, + requestedAt: "2026-03-29T00:00:00.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: "2026-03-29T00:00:10.000Z", + assistantMessageId: null, + }; + + const previousSession = { + provider: "codex" as const, + status: "ready" as const, + createdAt: "2026-03-29T00:00:00.000Z", + updatedAt: "2026-03-29T00:00:10.000Z", + orchestrationStatus: "idle" as const, + }; + + it("does not clear local dispatch before server state changes", () => { + const localDispatch = createLocalDispatchSnapshot({ + id: ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId, + title: "Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + session: previousSession, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:10.000Z", + latestTurn: previousLatestTurn, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], + }); + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "ready", + latestTurn: previousLatestTurn, + session: previousSession, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(false); + }); + + it("clears local dispatch when a new turn is already settled", () => { + const localDispatch = createLocalDispatchSnapshot({ + id: ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId, + title: "Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + session: previousSession, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:10.000Z", + latestTurn: previousLatestTurn, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], + }); + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "ready", + latestTurn: { + ...previousLatestTurn, + turnId: TurnId.makeUnsafe("turn-2"), + requestedAt: "2026-03-29T00:01:00.000Z", + startedAt: "2026-03-29T00:01:01.000Z", + completedAt: "2026-03-29T00:01:30.000Z", + }, + session: { + ...previousSession, + updatedAt: "2026-03-29T00:01:30.000Z", + }, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(true); + }); + + it("clears local dispatch when the session changes without an observed running phase", () => { + const localDispatch = createLocalDispatchSnapshot({ + id: ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId, + title: "Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + session: previousSession, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:10.000Z", + latestTurn: previousLatestTurn, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], + }); + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "ready", + latestTurn: previousLatestTurn, + session: { + ...previousSession, + updatedAt: "2026-03-29T00:00:11.000Z", + }, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(true); + }); +}); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts new file mode 100644 index 0000000000..ca2a671c11 --- /dev/null +++ b/apps/web/src/components/ChatView.logic.ts @@ -0,0 +1,306 @@ +import { ProjectId, type ModelSelection, type ThreadId, type TurnId } from "@t3tools/contracts"; +import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types"; +import { randomUUID } from "~/lib/utils"; +import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore"; +import { Schema } from "effect"; +import { useStore } from "../store"; +import { + filterTerminalContextsWithText, + stripInlineTerminalContextPlaceholders, + type TerminalContextDraft, +} from "../lib/terminalContext"; + +export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project"; +export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10; +const WORKTREE_BRANCH_PREFIX = "t3code"; + +export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String); + +export function buildLocalDraftThread( + threadId: ThreadId, + draftThread: DraftThreadState, + fallbackModelSelection: ModelSelection, + error: string | null, +): Thread { + return { + id: threadId, + codexThreadId: null, + projectId: draftThread.projectId, + title: "New thread", + modelSelection: fallbackModelSelection, + runtimeMode: draftThread.runtimeMode, + interactionMode: draftThread.interactionMode, + session: null, + messages: [], + error, + createdAt: draftThread.createdAt, + archivedAt: null, + latestTurn: null, + branch: draftThread.branch, + worktreePath: draftThread.worktreePath, + turnDiffSummaries: [], + activities: [], + proposedPlans: [], + }; +} + +export function reconcileMountedTerminalThreadIds(input: { + currentThreadIds: ReadonlyArray; + openThreadIds: ReadonlyArray; + activeThreadId: ThreadId | null; + activeThreadTerminalOpen: boolean; + maxHiddenThreadCount?: number; +}): ThreadId[] { + const openThreadIdSet = new Set(input.openThreadIds); + const hiddenThreadIds = input.currentThreadIds.filter( + (threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId), + ); + const maxHiddenThreadCount = Math.max( + 0, + input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, + ); + const nextThreadIds = + hiddenThreadIds.length > maxHiddenThreadCount + ? hiddenThreadIds.slice(-maxHiddenThreadCount) + : hiddenThreadIds; + + if ( + input.activeThreadId && + input.activeThreadTerminalOpen && + !nextThreadIds.includes(input.activeThreadId) + ) { + nextThreadIds.push(input.activeThreadId); + } + + return nextThreadIds; +} + +export function revokeBlobPreviewUrl(previewUrl: string | undefined): void { + if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) { + return; + } + URL.revokeObjectURL(previewUrl); +} + +export function revokeUserMessagePreviewUrls(message: ChatMessage): void { + if (message.role !== "user" || !message.attachments) { + return; + } + for (const attachment of message.attachments) { + if (attachment.type !== "image") { + continue; + } + revokeBlobPreviewUrl(attachment.previewUrl); + } +} + +export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] { + if (message.role !== "user" || !message.attachments) { + return []; + } + const previewUrls: string[] = []; + for (const attachment of message.attachments) { + if (attachment.type !== "image") continue; + if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue; + previewUrls.push(attachment.previewUrl); + } + return previewUrls; +} + +export interface PullRequestDialogState { + initialReference: string | null; + key: number; +} + +export function readFileAsDataUrl(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.addEventListener("load", () => { + if (typeof reader.result === "string") { + resolve(reader.result); + return; + } + reject(new Error("Could not read image data.")); + }); + reader.addEventListener("error", () => { + reject(reader.error ?? new Error("Failed to read image.")); + }); + reader.readAsDataURL(file); + }); +} + +export function buildTemporaryWorktreeBranchName(): string { + // Keep the 8-hex suffix shape for backend temporary-branch detection. + const token = randomUUID().slice(0, 8).toLowerCase(); + return `${WORKTREE_BRANCH_PREFIX}/${token}`; +} + +export function cloneComposerImageForRetry( + image: ComposerImageAttachment, +): ComposerImageAttachment { + if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) { + return image; + } + try { + return { + ...image, + previewUrl: URL.createObjectURL(image.file), + }; + } catch { + return image; + } +} + +export function deriveComposerSendState(options: { + prompt: string; + imageCount: number; + terminalContexts: ReadonlyArray; +}): { + trimmedPrompt: string; + sendableTerminalContexts: TerminalContextDraft[]; + expiredTerminalContextCount: number; + hasSendableContent: boolean; +} { + const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim(); + const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts); + const expiredTerminalContextCount = + options.terminalContexts.length - sendableTerminalContexts.length; + return { + trimmedPrompt, + sendableTerminalContexts, + expiredTerminalContextCount, + hasSendableContent: + trimmedPrompt.length > 0 || options.imageCount > 0 || sendableTerminalContexts.length > 0, + }; +} + +export function buildExpiredTerminalContextToastCopy( + expiredTerminalContextCount: number, + variant: "omitted" | "empty", +): { title: string; description: string } { + const count = Math.max(1, Math.floor(expiredTerminalContextCount)); + const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts"; + if (variant === "empty") { + return { + title: `${noun} won't be sent`, + description: "Remove it or re-add it to include terminal output.", + }; + } + return { + title: `${noun} omitted from message`, + description: "Re-add it if you want that terminal output included.", + }; +} + +export function threadHasStarted(thread: Thread | null | undefined): boolean { + return Boolean( + thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null), + ); +} + +export async function waitForStartedServerThread( + threadId: ThreadId, + timeoutMs = 1_000, +): Promise { + const getThread = () => useStore.getState().threads.find((thread) => thread.id === threadId); + const thread = getThread(); + + if (threadHasStarted(thread)) { + return true; + } + + return await new Promise((resolve) => { + let settled = false; + let timeoutId: ReturnType | null = null; + const finish = (result: boolean) => { + if (settled) { + return; + } + settled = true; + if (timeoutId !== null) { + globalThis.clearTimeout(timeoutId); + } + unsubscribe(); + resolve(result); + }; + + const unsubscribe = useStore.subscribe((state) => { + if (!threadHasStarted(state.threads.find((thread) => thread.id === threadId))) { + return; + } + finish(true); + }); + + if (threadHasStarted(getThread())) { + finish(true); + return; + } + + timeoutId = globalThis.setTimeout(() => { + finish(false); + }, timeoutMs); + }); +} + +export interface LocalDispatchSnapshot { + startedAt: string; + preparingWorktree: boolean; + latestTurnTurnId: TurnId | null; + latestTurnRequestedAt: string | null; + latestTurnStartedAt: string | null; + latestTurnCompletedAt: string | null; + sessionOrchestrationStatus: ThreadSession["orchestrationStatus"] | null; + sessionUpdatedAt: string | null; +} + +export function createLocalDispatchSnapshot( + activeThread: Thread | undefined, + options?: { preparingWorktree?: boolean }, +): LocalDispatchSnapshot { + const latestTurn = activeThread?.latestTurn ?? null; + const session = activeThread?.session ?? null; + return { + startedAt: new Date().toISOString(), + preparingWorktree: Boolean(options?.preparingWorktree), + latestTurnTurnId: latestTurn?.turnId ?? null, + latestTurnRequestedAt: latestTurn?.requestedAt ?? null, + latestTurnStartedAt: latestTurn?.startedAt ?? null, + latestTurnCompletedAt: latestTurn?.completedAt ?? null, + sessionOrchestrationStatus: session?.orchestrationStatus ?? null, + sessionUpdatedAt: session?.updatedAt ?? null, + }; +} + +export function hasServerAcknowledgedLocalDispatch(input: { + localDispatch: LocalDispatchSnapshot | null; + phase: SessionPhase; + latestTurn: Thread["latestTurn"] | null; + session: Thread["session"] | null; + hasPendingApproval: boolean; + hasPendingUserInput: boolean; + threadError: string | null | undefined; +}): boolean { + if (!input.localDispatch) { + return false; + } + if ( + input.phase === "running" || + input.hasPendingApproval || + input.hasPendingUserInput || + Boolean(input.threadError) + ) { + return true; + } + + const latestTurn = input.latestTurn ?? null; + const session = input.session ?? null; + + return ( + input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) || + input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) || + input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) || + input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) || + input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) || + input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null) + ); +} diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 3a54834d61..8d60d5e128 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,360 +1,1701 @@ import { - EDITORS, - type EditorId, - ModelSlug, - type NativeApi, - PROVIDER_SEND_TURN_MAX_INPUT_CHARS, + type ApprovalRequestId, + DEFAULT_MODEL_BY_PROVIDER, + type ClaudeCodeEffort, + type MessageId, + type ModelSelection, + type ProjectScript, + type ProviderKind, + type ProjectEntry, + type ProjectId, + type ProviderApprovalDecision, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, - type ResolvedKeybindingsConfig, - type ProviderApprovalDecision, - type ProviderSendTurnAttachmentInput, + type ServerProvider, + type ThreadId, + type TurnId, + type KeybindingCommand, + OrchestrationThreadActivity, + ProviderInteractionMode, + RuntimeMode, + TerminalOpenInput, } from "@t3tools/contracts"; -import { - type ClipboardEvent, - type DragEvent, - type FormEvent, - Fragment, - type KeyboardEvent, - memo, - type RefObject, - useCallback, - useEffect, - useLayoutEffect, - useMemo, - useRef, - useState, -} from "react"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery"; -import { serverConfigQueryOptions } from "~/lib/serverReactQuery"; - +import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model"; +import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts"; +import { truncate } from "@t3tools/shared/String"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { useDebouncedValue } from "@tanstack/react-pacer"; +import { useNavigate, useSearch } from "@tanstack/react-router"; +import { gitStatusQueryOptions } from "~/lib/gitReactQuery"; +import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery"; import { isElectron } from "../env"; -import { buildBootstrapInput } from "../historyBootstrap"; +import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"; import { - DEFAULT_MODEL, - DEFAULT_REASONING, - MODEL_OPTIONS, - REASONING_OPTIONS, - ReasoningEffort, - resolveModelSlug, -} from "../model-logic"; + clampCollapsedComposerCursor, + type ComposerTrigger, + collapseExpandedComposerCursor, + detectComposerTrigger, + expandCollapsedComposerCursor, + parseStandaloneComposerSlashCommand, + replaceTextRange, +} from "../composer-logic"; import { + deriveCompletionDividerBeforeEntryId, derivePendingApprovals, + derivePendingUserInputs, derivePhase, deriveTimelineEntries, - type PendingApproval, + deriveActiveWorkStartedAt, + deriveActivePlanState, + findSidebarProposedPlan, + findLatestProposedPlan, deriveWorkLogEntries, - formatDuration, + hasActionableProposedPlan, + hasToolActivityForTurn, + isLatestTurnSettled, formatElapsed, - formatTimestamp, } from "../session-logic"; import { isScrollContainerNearBottom } from "../chat-scroll"; +import { + buildPendingUserInputAnswers, + derivePendingUserInputProgress, + setPendingUserInputCustomAnswer, + type PendingUserInputDraftAnswer, +} from "../pendingUserInput"; import { useStore } from "../store"; -import type { ChatImageAttachment } from "../types"; +import { useProjectById, useThreadById } from "../storeSelectors"; +import { useUiStateStore } from "../uiStateStore"; +import { + buildPlanImplementationThreadTitle, + buildPlanImplementationPrompt, + proposedPlanTitle, + resolvePlanFollowUpSubmission, +} from "../proposedPlan"; +import { + DEFAULT_INTERACTION_MODE, + DEFAULT_RUNTIME_MODE, + DEFAULT_THREAD_TERMINAL_ID, + MAX_TERMINALS_PER_GROUP, + type ChatMessage, + type SessionPhase, + type Thread, + type TurnDiffSummary, +} from "../types"; +import { LRUCache } from "../lib/lruCache"; + +import { basenameOfPath } from "../vscode-icons"; +import { useTheme } from "../hooks/useTheme"; +import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; import BranchToolbar from "./BranchToolbar"; -import GitActionsControl from "./GitActionsControl"; -import { - isOpenFavoriteEditorShortcut, - isTerminalCloseShortcut, - isTerminalNewShortcut, - isTerminalSplitShortcut, - isTerminalToggleShortcut, - shortcutLabelForCommand, -} from "../keybindings"; -import ChatMarkdown from "./ChatMarkdown"; +import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; +import PlanSidebar from "./PlanSidebar"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; -import { useNativeApi } from "../hooks/useNativeApi"; -import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert"; import { + BotIcon, ChevronDownIcon, + ChevronLeftIcon, + ChevronRightIcon, CircleAlertIcon, - FolderClosedIcon, - InfoIcon, + ListTodoIcon, LockIcon, LockOpenIcon, XIcon, } from "lucide-react"; import { Button } from "./ui/button"; -import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; import { Separator } from "./ui/separator"; -import { Group, GroupSeparator } from "./ui/group"; -import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu"; -import { CursorIcon, Icon } from "./Icons"; -import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils"; -import { Badge } from "./ui/badge"; +import { cn, randomUUID } from "~/lib/utils"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { toastManager } from "./ui/toast"; +import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings"; +import { type NewProjectScriptInput } from "./ProjectScriptsControl"; +import { + commandForProjectScript, + nextProjectScriptId, + projectScriptIdFromCommand, +} from "~/projectScripts"; +import { SidebarTrigger } from "./ui/sidebar"; +import { newCommandId, newMessageId, newThreadId } from "~/lib/utils"; +import { readNativeApi } from "~/nativeApi"; +import { + getProviderModelCapabilities, + getProviderModels, + resolveSelectableProvider, +} from "../providerModels"; +import { useSettings } from "../hooks/useSettings"; +import { resolveAppModelSelection } from "../modelSelection"; +import { isTerminalFocused } from "../lib/terminalFocus"; +import { + type ComposerImageAttachment, + type DraftThreadEnvMode, + type PersistedComposerImageAttachment, + useComposerDraftStore, + useEffectiveComposerModelState, + useComposerThreadDraft, +} from "../composerDraftStore"; +import { + appendTerminalContextsToPrompt, + formatTerminalContextLabel, + insertInlineTerminalContextPlaceholder, + removeInlineTerminalContextPlaceholder, + type TerminalContextDraft, + type TerminalContextSelection, +} from "../lib/terminalContext"; +import { deriveLatestContextWindowSnapshot } from "../lib/contextWindow"; +import { + resolveComposerFooterContentWidth, + shouldForceCompactComposerFooterForFit, + shouldUseCompactComposerPrimaryActions, + shouldUseCompactComposerFooter, +} from "./composerFooterLayout"; +import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore"; +import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor"; +import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; +import { MessagesTimeline } from "./chat/MessagesTimeline"; +import { ChatHeader } from "./chat/ChatHeader"; +import { ContextWindowMeter } from "./chat/ContextWindowMeter"; +import { buildExpandedImagePreview, ExpandedImagePreview } from "./chat/ExpandedImagePreview"; +import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./chat/ProviderModelPicker"; +import { ComposerCommandItem, ComposerCommandMenu } from "./chat/ComposerCommandMenu"; +import { ComposerPendingApprovalActions } from "./chat/ComposerPendingApprovalActions"; +import { CompactComposerControlsMenu } from "./chat/CompactComposerControlsMenu"; +import { ComposerPrimaryActions } from "./chat/ComposerPrimaryActions"; +import { ComposerPendingApprovalPanel } from "./chat/ComposerPendingApprovalPanel"; +import { ComposerPendingUserInputPanel } from "./chat/ComposerPendingUserInputPanel"; +import { ComposerPlanFollowUpBanner } from "./chat/ComposerPlanFollowUpBanner"; +import { + getComposerProviderState, + renderProviderTraitsMenuContent, + renderProviderTraitsPicker, +} from "./chat/composerProviderRegistry"; +import { ProviderStatusBanner } from "./chat/ProviderStatusBanner"; +import { ThreadErrorBanner } from "./chat/ThreadErrorBanner"; +import { + MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, + buildExpiredTerminalContextToastCopy, + buildLocalDraftThread, + buildTemporaryWorktreeBranchName, + cloneComposerImageForRetry, + collectUserMessageBlobPreviewUrls, + createLocalDispatchSnapshot, + deriveComposerSendState, + hasServerAcknowledgedLocalDispatch, + LAST_INVOKED_SCRIPT_BY_PROJECT_KEY, + LastInvokedScriptByProjectSchema, + type LocalDispatchSnapshot, + PullRequestDialogState, + readFileAsDataUrl, + reconcileMountedTerminalThreadIds, + revokeBlobPreviewUrl, + revokeUserMessagePreviewUrls, + threadHasStarted, + waitForStartedServerThread, +} from "./ChatView.logic"; +import { useLocalStorage } from "~/hooks/useLocalStorage"; +import { + useServerAvailableEditors, + useServerConfig, + useServerKeybindings, +} from "~/rpc/serverState"; -function formatMessageMeta(createdAt: string, duration: string | null): string { - if (!duration) return formatTimestamp(createdAt); - return `${formatTimestamp(createdAt)} • ${duration}`; -} - -const LAST_EDITOR_KEY = "t3code:last-editor"; -const MAX_VISIBLE_WORK_LOG_ENTRIES = 6; +const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000; const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; const IMAGE_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]"; -const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = []; +const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = []; +const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = []; +const EMPTY_PROVIDERS: ServerProvider[] = []; +const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; -function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string { - if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50"; - if (tone === "tool") return "text-muted-foreground/70"; - if (tone === "thinking") return "text-muted-foreground/50"; - return "text-muted-foreground/40"; +type ThreadPlanCatalogEntry = Pick; + +const MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES = 500; +const MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES = 512 * 1024; +const threadPlanCatalogCache = new LRUCache<{ + proposedPlans: Thread["proposedPlans"]; + entry: ThreadPlanCatalogEntry; +}>(MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES, MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES); + +function estimateThreadPlanCatalogEntrySize(thread: Thread): number { + return Math.max( + 64, + thread.id.length + + thread.proposedPlans.reduce( + (total, plan) => + total + + plan.id.length + + plan.planMarkdown.length + + plan.updatedAt.length + + (plan.turnId?.length ?? 0), + 0, + ), + ); } -type SessionContinuityState = "resumed" | "new" | "fallback_new"; +function toThreadPlanCatalogEntry(thread: Thread): ThreadPlanCatalogEntry { + const cached = threadPlanCatalogCache.get(thread.id); + if (cached && cached.proposedPlans === thread.proposedPlans) { + return cached.entry; + } -interface EnsuredSessionInfo { - sessionId: string; - resolvedThreadId: string | null; - continuityState: SessionContinuityState; + const entry: ThreadPlanCatalogEntry = { + id: thread.id, + proposedPlans: thread.proposedPlans, + }; + threadPlanCatalogCache.set( + thread.id, + { + proposedPlans: thread.proposedPlans, + entry, + }, + estimateThreadPlanCatalogEntrySize(thread), + ); + return entry; } -interface ComposerImageAttachment extends Omit { - previewUrl: string; - file: File; +function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] { + const selector = useMemo(() => { + let previousThreads: Array | null = null; + let previousEntries: ThreadPlanCatalogEntry[] = []; + + return (state: { threads: Thread[] }): ThreadPlanCatalogEntry[] => { + const nextThreads = threadIds.map((threadId) => + state.threads.find((thread) => thread.id === threadId), + ); + const cachedThreads = previousThreads; + if ( + cachedThreads && + nextThreads.length === cachedThreads.length && + nextThreads.every((thread, index) => thread === cachedThreads[index]) + ) { + return previousEntries; + } + + previousThreads = nextThreads; + previousEntries = nextThreads.flatMap((thread) => + thread ? [toThreadPlanCatalogEntry(thread)] : [], + ); + return previousEntries; + }; + }, [threadIds]); + + return useStore(selector); } -interface ExpandedImagePreview { - src: string; - name: string; +function formatOutgoingPrompt(params: { + provider: ProviderKind; + model: string | null; + models: ReadonlyArray; + effort: string | null; + text: string; +}): string { + const caps = getProviderModelCapabilities(params.models, params.model, params.provider); + if (params.effort && caps.promptInjectedEffortLevels.includes(params.effort)) { + return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null); + } + return params.text; +} +const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120; +const SCRIPT_TERMINAL_COLS = 120; +const SCRIPT_TERMINAL_ROWS = 30; + +const extendReplacementRangeForTrailingSpace = ( + text: string, + rangeEnd: number, + replacement: string, +): number => { + if (!replacement.endsWith(" ")) { + return rangeEnd; + } + return text[rangeEnd] === " " ? rangeEnd + 1 : rangeEnd; +}; + +const syncTerminalContextsByIds = ( + contexts: ReadonlyArray, + ids: ReadonlyArray, +): TerminalContextDraft[] => { + const contextsById = new Map(contexts.map((context) => [context.id, context])); + return ids.flatMap((id) => { + const context = contextsById.get(id); + return context ? [context] : []; + }); +}; + +const terminalContextIdListsEqual = ( + contexts: ReadonlyArray, + ids: ReadonlyArray, +): boolean => + contexts.length === ids.length && contexts.every((context, index) => context.id === ids[index]); + +interface ChatViewProps { + threadId: ThreadId; } -function readFileAsDataUrl(file: File): Promise { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.addEventListener("load", () => { - if (typeof reader.result === "string") { - resolve(reader.result); +interface TerminalLaunchContext { + threadId: ThreadId; + cwd: string; + worktreePath: string | null; +} + +type PersistentTerminalLaunchContext = Pick; + +function useLocalDispatchState(input: { + activeThread: Thread | undefined; + activeLatestTurn: Thread["latestTurn"] | null; + phase: SessionPhase; + activePendingApproval: ApprovalRequestId | null; + activePendingUserInput: ApprovalRequestId | null; + threadError: string | null | undefined; +}) { + const [localDispatch, setLocalDispatch] = useState(null); + + const beginLocalDispatch = useCallback( + (options?: { preparingWorktree?: boolean }) => { + const preparingWorktree = Boolean(options?.preparingWorktree); + setLocalDispatch((current) => { + if (current) { + return current.preparingWorktree === preparingWorktree + ? current + : { ...current, preparingWorktree }; + } + return createLocalDispatchSnapshot(input.activeThread, options); + }); + }, + [input.activeThread], + ); + + const resetLocalDispatch = useCallback(() => { + setLocalDispatch(null); + }, []); + + const serverAcknowledgedLocalDispatch = useMemo( + () => + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: input.phase, + latestTurn: input.activeLatestTurn, + session: input.activeThread?.session ?? null, + hasPendingApproval: input.activePendingApproval !== null, + hasPendingUserInput: input.activePendingUserInput !== null, + threadError: input.threadError, + }), + [ + input.activeLatestTurn, + input.activePendingApproval, + input.activePendingUserInput, + input.activeThread?.session, + input.phase, + input.threadError, + localDispatch, + ], + ); + + useEffect(() => { + if (!serverAcknowledgedLocalDispatch) { + return; + } + resetLocalDispatch(); + }, [resetLocalDispatch, serverAcknowledgedLocalDispatch]); + + return { + beginLocalDispatch, + resetLocalDispatch, + localDispatchStartedAt: localDispatch?.startedAt ?? null, + isPreparingWorktree: localDispatch?.preparingWorktree ?? false, + isSendBusy: localDispatch !== null && !serverAcknowledgedLocalDispatch, + }; +} + +interface PersistentThreadTerminalDrawerProps { + threadId: ThreadId; + visible: boolean; + launchContext: PersistentTerminalLaunchContext | null; + focusRequestId: number; + splitShortcutLabel: string | undefined; + newShortcutLabel: string | undefined; + closeShortcutLabel: string | undefined; + onAddTerminalContext: (selection: TerminalContextSelection) => void; +} + +function PersistentThreadTerminalDrawer({ + threadId, + visible, + launchContext, + focusRequestId, + splitShortcutLabel, + newShortcutLabel, + closeShortcutLabel, + onAddTerminalContext, +}: PersistentThreadTerminalDrawerProps) { + const serverThread = useThreadById(threadId); + const draftThread = useComposerDraftStore( + (store) => store.draftThreadsByThreadId[threadId] ?? null, + ); + const project = useProjectById(serverThread?.projectId ?? draftThread?.projectId); + const terminalState = useTerminalStateStore((state) => + selectThreadTerminalState(state.terminalStateByThreadId, threadId), + ); + const storeSetTerminalHeight = useTerminalStateStore((state) => state.setTerminalHeight); + const storeSplitTerminal = useTerminalStateStore((state) => state.splitTerminal); + const storeNewTerminal = useTerminalStateStore((state) => state.newTerminal); + const storeSetActiveTerminal = useTerminalStateStore((state) => state.setActiveTerminal); + const storeCloseTerminal = useTerminalStateStore((state) => state.closeTerminal); + const [localFocusRequestId, setLocalFocusRequestId] = useState(0); + const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; + const effectiveWorktreePath = useMemo(() => { + if (launchContext !== null) { + return launchContext.worktreePath; + } + return worktreePath; + }, [launchContext, worktreePath]); + const cwd = useMemo( + () => + launchContext?.cwd ?? + (project + ? projectScriptCwd({ + project: { cwd: project.cwd }, + worktreePath: effectiveWorktreePath, + }) + : null), + [effectiveWorktreePath, launchContext?.cwd, project], + ); + const runtimeEnv = useMemo( + () => + project + ? projectScriptRuntimeEnv({ + project: { cwd: project.cwd }, + worktreePath: effectiveWorktreePath, + }) + : {}, + [effectiveWorktreePath, project], + ); + + const bumpFocusRequestId = useCallback(() => { + if (!visible) { + return; + } + setLocalFocusRequestId((value) => value + 1); + }, [visible]); + + const setTerminalHeight = useCallback( + (height: number) => { + storeSetTerminalHeight(threadId, height); + }, + [storeSetTerminalHeight, threadId], + ); + + const splitTerminal = useCallback(() => { + storeSplitTerminal(threadId, `terminal-${randomUUID()}`); + bumpFocusRequestId(); + }, [bumpFocusRequestId, storeSplitTerminal, threadId]); + + const createNewTerminal = useCallback(() => { + storeNewTerminal(threadId, `terminal-${randomUUID()}`); + bumpFocusRequestId(); + }, [bumpFocusRequestId, storeNewTerminal, threadId]); + + const activateTerminal = useCallback( + (terminalId: string) => { + storeSetActiveTerminal(threadId, terminalId); + bumpFocusRequestId(); + }, + [bumpFocusRequestId, storeSetActiveTerminal, threadId], + ); + + const closeTerminal = useCallback( + (terminalId: string) => { + const api = readNativeApi(); + if (!api) return; + const isFinalTerminal = terminalState.terminalIds.length <= 1; + const fallbackExitWrite = () => + api.terminal.write({ threadId, terminalId, data: "exit\n" }).catch(() => undefined); + + if ("close" in api.terminal && typeof api.terminal.close === "function") { + void (async () => { + if (isFinalTerminal) { + await api.terminal.clear({ threadId, terminalId }).catch(() => undefined); + } + await api.terminal.close({ + threadId, + terminalId, + deleteHistory: true, + }); + })().catch(() => fallbackExitWrite()); + } else { + void fallbackExitWrite(); + } + + storeCloseTerminal(threadId, terminalId); + bumpFocusRequestId(); + }, + [bumpFocusRequestId, storeCloseTerminal, terminalState.terminalIds.length, threadId], + ); + + const handleAddTerminalContext = useCallback( + (selection: TerminalContextSelection) => { + if (!visible) { return; } - reject(new Error("Could not read image data.")); - }); - reader.addEventListener("error", () => { - reject(reader.error ?? new Error("Failed to read image.")); - }); - reader.readAsDataURL(file); - }); + onAddTerminalContext(selection); + }, + [onAddTerminalContext, visible], + ); + + if (!project || !terminalState.terminalOpen || !cwd) { + return null; + } + + return ( +
+ +
+ ); } -export default function ChatView() { - const { state, dispatch } = useStore(); - const api = useNativeApi(); - const queryClient = useQueryClient(); - const createWorktreeMutation = useMutation( - gitCreateWorktreeMutationOptions({ api, queryClient }), +export default function ChatView({ threadId }: ChatViewProps) { + const serverThread = useThreadById(threadId); + const setStoreThreadError = useStore((store) => store.setError); + const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); + const activeThreadLastVisitedAt = useUiStateStore( + (store) => store.threadLastVisitedAtById[threadId], ); - const [prompt, setPrompt] = useState(""); - const [composerImages, setComposerImages] = useState([]); + const settings = useSettings(); + const setStickyComposerModelSelection = useComposerDraftStore( + (store) => store.setStickyModelSelection, + ); + const timestampFormat = settings.timestampFormat; + const navigate = useNavigate(); + const rawSearch = useSearch({ + strict: false, + select: (params) => parseDiffRouteSearch(params), + }); + const { resolvedTheme } = useTheme(); + const composerDraft = useComposerThreadDraft(threadId); + const prompt = composerDraft.prompt; + const composerImages = composerDraft.images; + const composerTerminalContexts = composerDraft.terminalContexts; + const composerSendState = useMemo( + () => + deriveComposerSendState({ + prompt, + imageCount: composerImages.length, + terminalContexts: composerTerminalContexts, + }), + [composerImages.length, composerTerminalContexts, prompt], + ); + const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds; + const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt); + const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection); + const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode); + const setComposerDraftInteractionMode = useComposerDraftStore( + (store) => store.setInteractionMode, + ); + const addComposerDraftImage = useComposerDraftStore((store) => store.addImage); + const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); + const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage); + const insertComposerDraftTerminalContext = useComposerDraftStore( + (store) => store.insertTerminalContext, + ); + const addComposerDraftTerminalContexts = useComposerDraftStore( + (store) => store.addTerminalContexts, + ); + const removeComposerDraftTerminalContext = useComposerDraftStore( + (store) => store.removeTerminalContext, + ); + const setComposerDraftTerminalContexts = useComposerDraftStore( + (store) => store.setTerminalContexts, + ); + const clearComposerDraftPersistedAttachments = useComposerDraftStore( + (store) => store.clearPersistedAttachments, + ); + const syncComposerDraftPersistedAttachments = useComposerDraftStore( + (store) => store.syncPersistedAttachments, + ); + const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent); + const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); + const getDraftThreadByProjectId = useComposerDraftStore( + (store) => store.getDraftThreadByProjectId, + ); + const getDraftThread = useComposerDraftStore((store) => store.getDraftThread); + const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId); + const clearProjectDraftThreadId = useComposerDraftStore( + (store) => store.clearProjectDraftThreadId, + ); + const draftThread = useComposerDraftStore( + (store) => store.draftThreadsByThreadId[threadId] ?? null, + ); + const promptRef = useRef(prompt); + const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [isDragOverComposer, setIsDragOverComposer] = useState(false); const [expandedImage, setExpandedImage] = useState(null); - const [isSending, setIsSending] = useState(false); - const [isConnecting, setIsConnecting] = useState(false); - const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING); - const [envMode, setEnvMode] = useState<"local" | "worktree">("local"); - const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false); - const [respondingRequestIds, setRespondingRequestIds] = useState([]); + const [optimisticUserMessages, setOptimisticUserMessages] = useState([]); + const optimisticUserMessagesRef = useRef(optimisticUserMessages); + optimisticUserMessagesRef.current = optimisticUserMessages; + const composerTerminalContextsRef = useRef(composerTerminalContexts); + const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState< + Record + >({}); + const [isConnecting, _setIsConnecting] = useState(false); + const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false); + const [respondingRequestIds, setRespondingRequestIds] = useState([]); + const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState< + ApprovalRequestId[] + >([]); + const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState< + Record> + >({}); + const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] = + useState>({}); const [expandedWorkGroups, setExpandedWorkGroups] = useState>({}); + const [planSidebarOpen, setPlanSidebarOpen] = useState(false); + const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false); + const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false); + // Tracks whether the user explicitly dismissed the sidebar for the active turn. + const planSidebarDismissedForTurnRef = useRef(null); + // When set, the thread-change reset effect will open the sidebar instead of closing it. + // Used by "Implement in a new thread" to carry the sidebar-open intent across navigation. + const planSidebarOpenOnNextThreadRef = useRef(false); const [nowTick, setNowTick] = useState(() => Date.now()); const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0); + const [composerHighlightedItemId, setComposerHighlightedItemId] = useState(null); + const [pullRequestDialogState, setPullRequestDialogState] = + useState(null); + const [terminalLaunchContext, setTerminalLaunchContext] = useState( + null, + ); + const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState< + Record + >({}); + const [composerCursor, setComposerCursor] = useState(() => + collapseExpandedComposerCursor(prompt, prompt.length), + ); + const [composerTrigger, setComposerTrigger] = useState(() => + detectComposerTrigger(prompt, prompt.length), + ); + const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage( + LAST_INVOKED_SCRIPT_BY_PROJECT_KEY, + {}, + LastInvokedScriptByProjectSchema, + ); const messagesScrollRef = useRef(null); - const messagesEndRef = useRef(null); + const [messagesScrollElement, setMessagesScrollElement] = useState(null); const shouldAutoScrollRef = useRef(true); - const textareaRef = useRef(null); + const lastKnownScrollTopRef = useRef(0); + const isPointerScrollActiveRef = useRef(false); + const lastTouchClientYRef = useRef(null); + const pendingUserScrollUpIntentRef = useRef(false); + const pendingAutoScrollFrameRef = useRef(null); + const pendingInteractionAnchorRef = useRef<{ + element: HTMLElement; + top: number; + } | null>(null); + const pendingInteractionAnchorFrameRef = useRef(null); + const composerEditorRef = useRef(null); + const composerFormRef = useRef(null); + const composerFormHeightRef = useRef(0); + const composerFooterRef = useRef(null); + const composerFooterLeadingRef = useRef(null); + const composerFooterActionsRef = useRef(null); const composerImagesRef = useRef([]); + const composerSelectLockRef = useRef(false); + const composerMenuOpenRef = useRef(false); + const composerMenuItemsRef = useRef([]); + const activeComposerMenuItemRef = useRef(null); + const attachmentPreviewHandoffByMessageIdRef = useRef>({}); + const attachmentPreviewHandoffTimeoutByMessageIdRef = useRef>({}); + const sendInFlightRef = useRef(false); const dragDepthRef = useRef(0); const terminalOpenByThreadRef = useRef>({}); + const setMessagesScrollContainerRef = useCallback((element: HTMLDivElement | null) => { + messagesScrollRef.current = element; + setMessagesScrollElement(element); + }, []); - const activeThread = state.threads.find((t) => t.id === state.activeThreadId); + const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId); + const terminalState = useMemo( + () => selectThreadTerminalState(terminalStateByThreadId, threadId), + [terminalStateByThreadId, threadId], + ); + const openTerminalThreadIds = useMemo( + () => + Object.entries(terminalStateByThreadId).flatMap(([nextThreadId, nextTerminalState]) => + nextTerminalState.terminalOpen ? [nextThreadId as ThreadId] : [], + ), + [terminalStateByThreadId], + ); + const storeSetTerminalOpen = useTerminalStateStore((s) => s.setTerminalOpen); + const storeSplitTerminal = useTerminalStateStore((s) => s.splitTerminal); + const storeNewTerminal = useTerminalStateStore((s) => s.newTerminal); + const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal); + const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal); + const storeServerTerminalLaunchContext = useTerminalStateStore( + (s) => s.terminalLaunchContextByThreadId[threadId] ?? null, + ); + const storeClearTerminalLaunchContext = useTerminalStateStore( + (s) => s.clearTerminalLaunchContext, + ); + const threads = useStore((state) => state.threads); + const serverThreadIds = useMemo(() => threads.map((thread) => thread.id), [threads]); + const draftThreadsByThreadId = useComposerDraftStore((store) => store.draftThreadsByThreadId); + const draftThreadIds = useMemo( + () => Object.keys(draftThreadsByThreadId) as ThreadId[], + [draftThreadsByThreadId], + ); + const [mountedTerminalThreadIds, setMountedTerminalThreadIds] = useState([]); + + const setPrompt = useCallback( + (nextPrompt: string) => { + setComposerDraftPrompt(threadId, nextPrompt); + }, + [setComposerDraftPrompt, threadId], + ); + const addComposerImage = useCallback( + (image: ComposerImageAttachment) => { + addComposerDraftImage(threadId, image); + }, + [addComposerDraftImage, threadId], + ); + const addComposerImagesToDraft = useCallback( + (images: ComposerImageAttachment[]) => { + addComposerDraftImages(threadId, images); + }, + [addComposerDraftImages, threadId], + ); + const addComposerTerminalContextsToDraft = useCallback( + (contexts: TerminalContextDraft[]) => { + addComposerDraftTerminalContexts(threadId, contexts); + }, + [addComposerDraftTerminalContexts, threadId], + ); + const removeComposerImageFromDraft = useCallback( + (imageId: string) => { + removeComposerDraftImage(threadId, imageId); + }, + [removeComposerDraftImage, threadId], + ); + const removeComposerTerminalContextFromDraft = useCallback( + (contextId: string) => { + const contextIndex = composerTerminalContexts.findIndex( + (context) => context.id === contextId, + ); + if (contextIndex < 0) { + return; + } + const nextPrompt = removeInlineTerminalContextPlaceholder(promptRef.current, contextIndex); + promptRef.current = nextPrompt.prompt; + setPrompt(nextPrompt.prompt); + removeComposerDraftTerminalContext(threadId, contextId); + setComposerCursor(nextPrompt.cursor); + setComposerTrigger( + detectComposerTrigger( + nextPrompt.prompt, + expandCollapsedComposerCursor(nextPrompt.prompt, nextPrompt.cursor), + ), + ); + }, + [composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId], + ); + + const fallbackDraftProject = useProjectById(draftThread?.projectId); + const localDraftError = serverThread ? null : (localDraftErrorsByThreadId[threadId] ?? null); + const localDraftThread = useMemo( + () => + draftThread + ? buildLocalDraftThread( + threadId, + draftThread, + fallbackDraftProject?.defaultModelSelection ?? { + provider: "codex", + model: DEFAULT_MODEL_BY_PROVIDER.codex, + }, + localDraftError, + ) + : undefined, + [draftThread, fallbackDraftProject?.defaultModelSelection, localDraftError, threadId], + ); + const activeThread = serverThread ?? localDraftThread; + const runtimeMode = + composerDraft.runtimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE; + const interactionMode = + composerDraft.interactionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE; + const isServerThread = serverThread !== undefined; + const isLocalDraftThread = !isServerThread && localDraftThread !== undefined; + const canCheckoutPullRequestIntoThread = isLocalDraftThread; + const diffOpen = rawSearch.diff === "1"; const activeThreadId = activeThread?.id ?? null; - const activeSessionId = activeThread?.session?.sessionId; - const activeProject = state.projects.find((p) => p.id === activeThread?.projectId); - const selectedModel = resolveModelSlug( - activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL, + const existingOpenTerminalThreadIds = useMemo(() => { + const existingThreadIds = new Set([...serverThreadIds, ...draftThreadIds]); + return openTerminalThreadIds.filter((nextThreadId) => existingThreadIds.has(nextThreadId)); + }, [draftThreadIds, openTerminalThreadIds, serverThreadIds]); + const activeLatestTurn = activeThread?.latestTurn ?? null; + const threadPlanCatalog = useThreadPlanCatalog( + useMemo(() => { + const threadIds: ThreadId[] = []; + if (activeThread?.id) { + threadIds.push(activeThread.id); + } + const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId; + if (sourceThreadId && sourceThreadId !== activeThread?.id) { + threadIds.push(sourceThreadId); + } + return threadIds; + }, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]), ); + const activeContextWindow = useMemo( + () => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []), + [activeThread?.activities], + ); + useEffect(() => { + setMountedTerminalThreadIds((currentThreadIds) => { + const nextThreadIds = reconcileMountedTerminalThreadIds({ + currentThreadIds, + openThreadIds: existingOpenTerminalThreadIds, + activeThreadId, + activeThreadTerminalOpen: Boolean(activeThreadId && terminalState.terminalOpen), + maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, + }); + return currentThreadIds.length === nextThreadIds.length && + currentThreadIds.every((nextThreadId, index) => nextThreadId === nextThreadIds[index]) + ? currentThreadIds + : nextThreadIds; + }); + }, [activeThreadId, existingOpenTerminalThreadIds, terminalState.terminalOpen]); + const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null); + const activeProject = useProjectById(activeThread?.projectId); + + const openPullRequestDialog = useCallback( + (reference?: string) => { + if (!canCheckoutPullRequestIntoThread) { + return; + } + setPullRequestDialogState({ + initialReference: reference ?? null, + key: Date.now(), + }); + setComposerHighlightedItemId(null); + }, + [canCheckoutPullRequestIntoThread], + ); + + const closePullRequestDialog = useCallback(() => { + setPullRequestDialogState(null); + }, []); + + const openOrReuseProjectDraftThread = useCallback( + async (input: { branch: string; worktreePath: string | null; envMode: DraftThreadEnvMode }) => { + if (!activeProject) { + throw new Error("No active project is available for this pull request."); + } + const storedDraftThread = getDraftThreadByProjectId(activeProject.id); + if (storedDraftThread) { + setDraftThreadContext(storedDraftThread.threadId, input); + setProjectDraftThreadId(activeProject.id, storedDraftThread.threadId, input); + if (storedDraftThread.threadId !== threadId) { + await navigate({ + to: "/$threadId", + params: { threadId: storedDraftThread.threadId }, + }); + } + return storedDraftThread.threadId; + } + + const activeDraftThread = getDraftThread(threadId); + if (!isServerThread && activeDraftThread?.projectId === activeProject.id) { + setDraftThreadContext(threadId, input); + setProjectDraftThreadId(activeProject.id, threadId, input); + return threadId; + } + + clearProjectDraftThreadId(activeProject.id); + const nextThreadId = newThreadId(); + setProjectDraftThreadId(activeProject.id, nextThreadId, { + createdAt: new Date().toISOString(), + runtimeMode: DEFAULT_RUNTIME_MODE, + interactionMode: DEFAULT_INTERACTION_MODE, + ...input, + }); + await navigate({ + to: "/$threadId", + params: { threadId: nextThreadId }, + }); + return nextThreadId; + }, + [ + activeProject, + clearProjectDraftThreadId, + getDraftThread, + getDraftThreadByProjectId, + isServerThread, + navigate, + setDraftThreadContext, + setProjectDraftThreadId, + threadId, + ], + ); + + const handlePreparedPullRequestThread = useCallback( + async (input: { branch: string; worktreePath: string | null }) => { + await openOrReuseProjectDraftThread({ + branch: input.branch, + worktreePath: input.worktreePath, + envMode: input.worktreePath ? "worktree" : "local", + }); + }, + [openOrReuseProjectDraftThread], + ); + + useEffect(() => { + if (!serverThread?.id) return; + if (!latestTurnSettled) return; + if (!activeLatestTurn?.completedAt) return; + const turnCompletedAt = Date.parse(activeLatestTurn.completedAt); + if (Number.isNaN(turnCompletedAt)) return; + const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN; + if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return; + + markThreadVisited(serverThread.id); + }, [ + activeLatestTurn?.completedAt, + activeThreadLastVisitedAt, + latestTurnSettled, + markThreadVisited, + serverThread?.id, + ]); + + const sessionProvider = activeThread?.session?.provider ?? null; + const selectedProviderByThreadId = composerDraft.activeProvider ?? null; + const threadProvider = + activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null; + const hasThreadStarted = threadHasStarted(activeThread); + const lockedProvider: ProviderKind | null = hasThreadStarted + ? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null) + : null; + const serverConfig = useServerConfig(); + const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS; + const unlockedSelectedProvider = resolveSelectableProvider( + providerStatuses, + selectedProviderByThreadId ?? threadProvider ?? "codex", + ); + const selectedProvider: ProviderKind = lockedProvider ?? unlockedSelectedProvider; + const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({ + threadId, + providers: providerStatuses, + selectedProvider, + threadModelSelection: activeThread?.modelSelection, + projectModelSelection: activeProject?.defaultModelSelection, + settings, + }); + const selectedProviderModels = getProviderModels(providerStatuses, selectedProvider); + const composerProviderState = useMemo( + () => + getComposerProviderState({ + provider: selectedProvider, + model: selectedModel, + models: selectedProviderModels, + prompt, + modelOptions: composerModelOptions, + }), + [composerModelOptions, prompt, selectedModel, selectedProvider, selectedProviderModels], + ); + const selectedPromptEffort = composerProviderState.promptEffort; + const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch; + const selectedModelSelection = useMemo( + () => ({ + provider: selectedProvider, + model: selectedModel, + ...(selectedModelOptionsForDispatch ? { options: selectedModelOptionsForDispatch } : {}), + }), + [selectedModel, selectedModelOptionsForDispatch, selectedProvider], + ); + const selectedModelForPicker = selectedModel; const phase = derivePhase(activeThread?.session ?? null); - const isWorking = phase === "running" || isSending || isConnecting; - const nowIso = new Date(nowTick).toISOString(); + const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; const workLogEntries = useMemo( - () => deriveWorkLogEntries(activeThread?.events ?? [], undefined), - [activeThread?.events], + () => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined), + [activeLatestTurn?.turnId, threadActivities], ); - const latestTurnWorkEntries = useMemo( - () => deriveWorkLogEntries(activeThread?.events ?? [], activeThread?.latestTurnId), - [activeThread?.events, activeThread?.latestTurnId], + const latestTurnHasToolActivity = useMemo( + () => hasToolActivityForTurn(threadActivities, activeLatestTurn?.turnId), + [activeLatestTurn?.turnId, threadActivities], ); const pendingApprovals = useMemo( - () => derivePendingApprovals(activeThread?.events ?? []), - [activeThread?.events], + () => derivePendingApprovals(threadActivities), + [threadActivities], ); - const assistantCompletionByItemId = useMemo(() => { - const map = new Map(); - const ordered = [...(activeThread?.events ?? [])].toReversed(); - for (const event of ordered) { - if (event.method !== "item/completed") continue; - if (!event.itemId) continue; - map.set(event.itemId, event.createdAt); - } - return map; - }, [activeThread?.events]); - const timelineEntries = useMemo( - () => deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries), - [activeThread?.messages, workLogEntries], + const pendingUserInputs = useMemo( + () => derivePendingUserInputs(threadActivities), + [threadActivities], ); - const completionSummary = useMemo(() => { - if (!activeThread?.latestTurnStartedAt) return null; - if (!activeThread.latestTurnCompletedAt) return null; - if (!latestTurnWorkEntries.some((entry) => entry.tone === "tool")) { + const activePendingUserInput = pendingUserInputs[0] ?? null; + const activePendingDraftAnswers = useMemo( + () => + activePendingUserInput + ? (pendingUserInputAnswersByRequestId[activePendingUserInput.requestId] ?? + EMPTY_PENDING_USER_INPUT_ANSWERS) + : EMPTY_PENDING_USER_INPUT_ANSWERS, + [activePendingUserInput, pendingUserInputAnswersByRequestId], + ); + const activePendingQuestionIndex = activePendingUserInput + ? (pendingUserInputQuestionIndexByRequestId[activePendingUserInput.requestId] ?? 0) + : 0; + const activePendingProgress = useMemo( + () => + activePendingUserInput + ? derivePendingUserInputProgress( + activePendingUserInput.questions, + activePendingDraftAnswers, + activePendingQuestionIndex, + ) + : null, + [activePendingDraftAnswers, activePendingQuestionIndex, activePendingUserInput], + ); + const activePendingResolvedAnswers = useMemo( + () => + activePendingUserInput + ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingDraftAnswers) + : null, + [activePendingDraftAnswers, activePendingUserInput], + ); + const activePendingIsResponding = activePendingUserInput + ? respondingUserInputRequestIds.includes(activePendingUserInput.requestId) + : false; + const activeProposedPlan = useMemo(() => { + if (!latestTurnSettled) { return null; } + return findLatestProposedPlan( + activeThread?.proposedPlans ?? [], + activeLatestTurn?.turnId ?? null, + ); + }, [activeLatestTurn?.turnId, activeThread?.proposedPlans, latestTurnSettled]); + const sidebarProposedPlan = useMemo( + () => + findSidebarProposedPlan({ + threads: threadPlanCatalog, + latestTurn: activeLatestTurn, + latestTurnSettled, + threadId: activeThread?.id ?? null, + }), + [activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog], + ); + const activePlan = useMemo( + () => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined), + [activeLatestTurn?.turnId, threadActivities], + ); + const showPlanFollowUpPrompt = + pendingUserInputs.length === 0 && + interactionMode === "plan" && + latestTurnSettled && + hasActionableProposedPlan(activeProposedPlan); + const activePendingApproval = pendingApprovals[0] ?? null; + const { + beginLocalDispatch, + resetLocalDispatch, + localDispatchStartedAt, + isPreparingWorktree, + isSendBusy, + } = useLocalDispatchState({ + activeThread, + activeLatestTurn, + phase, + activePendingApproval: activePendingApproval?.requestId ?? null, + activePendingUserInput: activePendingUserInput?.requestId ?? null, + threadError: activeThread?.error, + }); + const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint; + const nowIso = new Date(nowTick).toISOString(); + const activeWorkStartedAt = deriveActiveWorkStartedAt( + activeLatestTurn, + activeThread?.session ?? null, + localDispatchStartedAt, + ); + const isComposerApprovalState = activePendingApproval !== null; + const hasComposerHeader = + isComposerApprovalState || + pendingUserInputs.length > 0 || + (showPlanFollowUpPrompt && activeProposedPlan !== null); + const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; + const composerFooterActionLayoutKey = useMemo(() => { + if (activePendingProgress) { + return `pending:${activePendingProgress.questionIndex}:${activePendingProgress.isLastQuestion}:${activePendingIsResponding}`; + } + if (phase === "running") { + return "running"; + } + if (showPlanFollowUpPrompt) { + return prompt.trim().length > 0 ? "plan:refine" : "plan:implement"; + } + return `idle:${composerSendState.hasSendableContent}:${isSendBusy}:${isConnecting}:${isPreparingWorktree}`; + }, [ + activePendingIsResponding, + activePendingProgress, + composerSendState.hasSendableContent, + isConnecting, + isPreparingWorktree, + isSendBusy, + phase, + prompt, + showPlanFollowUpPrompt, + ]); + const lastSyncedPendingInputRef = useRef<{ + requestId: string | null; + questionId: string | null; + } | null>(null); + useEffect(() => { + const nextCustomAnswer = activePendingProgress?.customAnswer; + if (typeof nextCustomAnswer !== "string") { + lastSyncedPendingInputRef.current = null; + return; + } + const nextRequestId = activePendingUserInput?.requestId ?? null; + const nextQuestionId = activePendingProgress?.activeQuestion?.id ?? null; + const questionChanged = + lastSyncedPendingInputRef.current?.requestId !== nextRequestId || + lastSyncedPendingInputRef.current?.questionId !== nextQuestionId; + const textChangedExternally = promptRef.current !== nextCustomAnswer; - if ( - typeof activeThread.latestTurnDurationMs === "number" && - Number.isFinite(activeThread.latestTurnDurationMs) && - activeThread.latestTurnDurationMs >= 0 - ) { - return `Worked for ${formatDuration(activeThread.latestTurnDurationMs)}`; + lastSyncedPendingInputRef.current = { + requestId: nextRequestId, + questionId: nextQuestionId, + }; + + if (!questionChanged && !textChangedExternally) { + return; } - const elapsed = formatElapsed( - activeThread.latestTurnStartedAt, - activeThread.latestTurnCompletedAt, + promptRef.current = nextCustomAnswer; + const nextCursor = collapseExpandedComposerCursor(nextCustomAnswer, nextCustomAnswer.length); + setComposerCursor(nextCursor); + setComposerTrigger( + detectComposerTrigger( + nextCustomAnswer, + expandCollapsedComposerCursor(nextCustomAnswer, nextCursor), + ), ); - return elapsed ? `Worked for ${elapsed}` : null; + setComposerHighlightedItemId(null); }, [ - activeThread?.latestTurnStartedAt, - activeThread?.latestTurnCompletedAt, - activeThread?.latestTurnDurationMs, - latestTurnWorkEntries, + activePendingProgress?.customAnswer, + activePendingUserInput?.requestId, + activePendingProgress?.activeQuestion?.id, ]); - const completionDividerBeforeEntryId = useMemo(() => { - if (!activeThread?.latestTurnStartedAt) return null; - if (!activeThread.latestTurnCompletedAt) return null; - if (!completionSummary) return null; - - const turnStartedAt = Date.parse(activeThread.latestTurnStartedAt); - const turnCompletedAt = Date.parse(activeThread.latestTurnCompletedAt); - if (Number.isNaN(turnStartedAt)) return null; - if (Number.isNaN(turnCompletedAt)) return null; - - let inRangeMatch: string | null = null; - let fallbackMatch: string | null = null; - for (const timelineEntry of timelineEntries) { - if (timelineEntry.kind !== "message") continue; - if (timelineEntry.message.role !== "assistant") continue; - const messageAt = Date.parse(timelineEntry.message.createdAt); - if (Number.isNaN(messageAt) || messageAt < turnStartedAt) continue; - fallbackMatch = timelineEntry.id; - if (messageAt <= turnCompletedAt) { - inRangeMatch = timelineEntry.id; + useEffect(() => { + attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId; + }, [attachmentPreviewHandoffByMessageId]); + const clearAttachmentPreviewHandoffs = useCallback(() => { + for (const timeoutId of Object.values(attachmentPreviewHandoffTimeoutByMessageIdRef.current)) { + window.clearTimeout(timeoutId); + } + attachmentPreviewHandoffTimeoutByMessageIdRef.current = {}; + for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) { + for (const previewUrl of previewUrls) { + revokeBlobPreviewUrl(previewUrl); } } - return inRangeMatch ?? fallbackMatch; + attachmentPreviewHandoffByMessageIdRef.current = {}; + setAttachmentPreviewHandoffByMessageId({}); + }, []); + useEffect(() => { + return () => { + clearAttachmentPreviewHandoffs(); + for (const message of optimisticUserMessagesRef.current) { + revokeUserMessagePreviewUrls(message); + } + }; + }, [clearAttachmentPreviewHandoffs]); + const handoffAttachmentPreviews = useCallback((messageId: MessageId, previewUrls: string[]) => { + if (previewUrls.length === 0) return; + + const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? []; + for (const previewUrl of previousPreviewUrls) { + if (!previewUrls.includes(previewUrl)) { + revokeBlobPreviewUrl(previewUrl); + } + } + setAttachmentPreviewHandoffByMessageId((existing) => { + const next = { + ...existing, + [messageId]: previewUrls, + }; + attachmentPreviewHandoffByMessageIdRef.current = next; + return next; + }); + + const existingTimeout = attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId]; + if (typeof existingTimeout === "number") { + window.clearTimeout(existingTimeout); + } + attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId] = window.setTimeout(() => { + const currentPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId]; + if (currentPreviewUrls) { + for (const previewUrl of currentPreviewUrls) { + revokeBlobPreviewUrl(previewUrl); + } + } + setAttachmentPreviewHandoffByMessageId((existing) => { + if (!(messageId in existing)) return existing; + const next = { ...existing }; + delete next[messageId]; + attachmentPreviewHandoffByMessageIdRef.current = next; + return next; + }); + delete attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId]; + }, ATTACHMENT_PREVIEW_HANDOFF_TTL_MS); + }, []); + const serverMessages = activeThread?.messages; + const timelineMessages = useMemo(() => { + const messages = serverMessages ?? []; + const serverMessagesWithPreviewHandoff = + Object.keys(attachmentPreviewHandoffByMessageId).length === 0 + ? messages + : // Spread only fires for the few messages that actually changed; + // unchanged ones early-return their original reference. + // In-place mutation would break React's immutable state contract. + // oxlint-disable-next-line no-map-spread + messages.map((message) => { + if ( + message.role !== "user" || + !message.attachments || + message.attachments.length === 0 + ) { + return message; + } + const handoffPreviewUrls = attachmentPreviewHandoffByMessageId[message.id]; + if (!handoffPreviewUrls || handoffPreviewUrls.length === 0) { + return message; + } + + let changed = false; + let imageIndex = 0; + const attachments = message.attachments.map((attachment) => { + if (attachment.type !== "image") { + return attachment; + } + const handoffPreviewUrl = handoffPreviewUrls[imageIndex]; + imageIndex += 1; + if (!handoffPreviewUrl || attachment.previewUrl === handoffPreviewUrl) { + return attachment; + } + changed = true; + return { + ...attachment, + previewUrl: handoffPreviewUrl, + }; + }); + + return changed ? { ...message, attachments } : message; + }); + + if (optimisticUserMessages.length === 0) { + return serverMessagesWithPreviewHandoff; + } + const serverIds = new Set(serverMessagesWithPreviewHandoff.map((message) => message.id)); + const pendingMessages = optimisticUserMessages.filter((message) => !serverIds.has(message.id)); + if (pendingMessages.length === 0) { + return serverMessagesWithPreviewHandoff; + } + return [...serverMessagesWithPreviewHandoff, ...pendingMessages]; + }, [serverMessages, attachmentPreviewHandoffByMessageId, optimisticUserMessages]); + const timelineEntries = useMemo( + () => + deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries), + [activeThread?.proposedPlans, timelineMessages, workLogEntries], + ); + const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } = + useTurnDiffSummaries(activeThread); + const turnDiffSummaryByAssistantMessageId = useMemo(() => { + const byMessageId = new Map(); + for (const summary of turnDiffSummaries) { + if (!summary.assistantMessageId) continue; + byMessageId.set(summary.assistantMessageId, summary); + } + return byMessageId; + }, [turnDiffSummaries]); + const revertTurnCountByUserMessageId = useMemo(() => { + const byUserMessageId = new Map(); + for (let index = 0; index < timelineEntries.length; index += 1) { + const entry = timelineEntries[index]; + if (!entry || entry.kind !== "message" || entry.message.role !== "user") { + continue; + } + + for (let nextIndex = index + 1; nextIndex < timelineEntries.length; nextIndex += 1) { + const nextEntry = timelineEntries[nextIndex]; + if (!nextEntry || nextEntry.kind !== "message") { + continue; + } + if (nextEntry.message.role === "user") { + break; + } + const summary = turnDiffSummaryByAssistantMessageId.get(nextEntry.message.id); + if (!summary) { + continue; + } + const turnCount = + summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId]; + if (typeof turnCount !== "number") { + break; + } + byUserMessageId.set(entry.message.id, Math.max(0, turnCount - 1)); + break; + } + } + + return byUserMessageId; + }, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]); + + const completionSummary = useMemo(() => { + if (!latestTurnSettled) return null; + if (!activeLatestTurn?.startedAt) return null; + if (!activeLatestTurn.completedAt) return null; + if (!latestTurnHasToolActivity) return null; + + const elapsed = formatElapsed(activeLatestTurn.startedAt, activeLatestTurn.completedAt); + return elapsed ? `Worked for ${elapsed}` : null; }, [ - activeThread?.latestTurnCompletedAt, - activeThread?.latestTurnStartedAt, - completionSummary, - timelineEntries, + activeLatestTurn?.completedAt, + activeLatestTurn?.startedAt, + latestTurnHasToolActivity, + latestTurnSettled, ]); - const runtimeSessionConfig = - state.runtimeMode === "full-access" - ? ({ - approvalPolicy: "never", - sandboxMode: "danger-full-access", - } as const) - : ({ - approvalPolicy: "on-request", - sandboxMode: "workspace-write", - } as const); - const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null; - const branchesQuery = useQuery(gitBranchesQueryOptions(api, gitCwd)); - const keybindingsQuery = useQuery({ - ...serverConfigQueryOptions(api), - select: (config) => config.keybindings, - }); - const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS; + const completionDividerBeforeEntryId = useMemo(() => { + if (!latestTurnSettled) return null; + if (!completionSummary) return null; + return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn); + }, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]); + const gitCwd = activeProject + ? projectScriptCwd({ + project: { cwd: activeProject.cwd }, + worktreePath: activeThread?.worktreePath ?? null, + }) + : null; + const composerTriggerKind = composerTrigger?.kind ?? null; + const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : ""; + const isPathTrigger = composerTriggerKind === "path"; + const [debouncedPathQuery, composerPathQueryDebouncer] = useDebouncedValue( + pathTriggerQuery, + { wait: COMPOSER_PATH_QUERY_DEBOUNCE_MS }, + (debouncerState) => ({ isPending: debouncerState.isPending }), + ); + const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : ""; + const gitStatusQuery = useQuery(gitStatusQueryOptions(gitCwd)); + const keybindings = useServerKeybindings(); + const availableEditors = useServerAvailableEditors(); + const modelOptionsByProvider = useMemo( + () => ({ + codex: providerStatuses.find((provider) => provider.provider === "codex")?.models ?? [], + claudeAgent: + providerStatuses.find((provider) => provider.provider === "claudeAgent")?.models ?? [], + }), + [providerStatuses], + ); + const selectedModelForPickerWithCustomFallback = useMemo(() => { + const currentOptions = modelOptionsByProvider[selectedProvider]; + return currentOptions.some((option) => option.slug === selectedModelForPicker) + ? selectedModelForPicker + : (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker); + }, [modelOptionsByProvider, selectedModelForPicker, selectedProvider]); + const searchableModelOptions = useMemo( + () => + AVAILABLE_PROVIDER_OPTIONS.filter( + (option) => lockedProvider === null || option.value === lockedProvider, + ).flatMap((option) => + modelOptionsByProvider[option.value].map(({ slug, name }) => ({ + provider: option.value, + providerLabel: option.label, + slug, + name, + searchSlug: slug.toLowerCase(), + searchName: name.toLowerCase(), + searchProvider: option.label.toLowerCase(), + })), + ), + [lockedProvider, modelOptionsByProvider], + ); + const workspaceEntriesQuery = useQuery( + projectSearchEntriesQueryOptions({ + cwd: gitCwd, + query: effectivePathQuery, + enabled: isPathTrigger, + limit: 80, + }), + ); + const workspaceEntries = workspaceEntriesQuery.data?.entries ?? EMPTY_PROJECT_ENTRIES; + const composerMenuItems = useMemo(() => { + if (!composerTrigger) return []; + if (composerTrigger.kind === "path") { + return workspaceEntries.map((entry) => ({ + id: `path:${entry.kind}:${entry.path}`, + type: "path", + path: entry.path, + pathKind: entry.kind, + label: basenameOfPath(entry.path), + description: entry.parentPath ?? "", + })); + } + + if (composerTrigger.kind === "slash-command") { + const slashCommandItems = [ + { + id: "slash:model", + type: "slash-command", + command: "model", + label: "/model", + description: "Switch response model for this thread", + }, + { + id: "slash:plan", + type: "slash-command", + command: "plan", + label: "/plan", + description: "Switch this thread into plan mode", + }, + { + id: "slash:default", + type: "slash-command", + command: "default", + label: "/default", + description: "Switch this thread back to normal chat mode", + }, + ] satisfies ReadonlyArray>; + const query = composerTrigger.query.trim().toLowerCase(); + if (!query) { + return [...slashCommandItems]; + } + return slashCommandItems.filter( + (item) => item.command.includes(query) || item.label.slice(1).includes(query), + ); + } + + return searchableModelOptions + .filter(({ searchSlug, searchName, searchProvider }) => { + const query = composerTrigger.query.trim().toLowerCase(); + if (!query) return true; + return ( + searchSlug.includes(query) || searchName.includes(query) || searchProvider.includes(query) + ); + }) + .map(({ provider, providerLabel, slug, name }) => ({ + id: `model:${provider}:${slug}`, + type: "model", + provider, + model: slug, + label: name, + description: `${providerLabel} · ${slug}`, + })); + }, [composerTrigger, searchableModelOptions, workspaceEntries]); + const composerMenuOpen = Boolean(composerTrigger); + const activeComposerMenuItem = useMemo( + () => + composerMenuItems.find((item) => item.id === composerHighlightedItemId) ?? + composerMenuItems[0] ?? + null, + [composerHighlightedItemId, composerMenuItems], + ); + composerMenuOpenRef.current = composerMenuOpen; + composerMenuItemsRef.current = composerMenuItems; + activeComposerMenuItemRef.current = activeComposerMenuItem; + const nonPersistedComposerImageIdSet = useMemo( + () => new Set(nonPersistedComposerImageIds), + [nonPersistedComposerImageIds], + ); + const activeProviderStatus = useMemo( + () => providerStatuses.find((status) => status.provider === selectedProvider) ?? null, + [selectedProvider, providerStatuses], + ); + const activeProjectCwd = activeProject?.cwd ?? null; + const activeThreadWorktreePath = activeThread?.worktreePath ?? null; + const activeTerminalLaunchContext = + terminalLaunchContext?.threadId === activeThreadId + ? terminalLaunchContext + : (storeServerTerminalLaunchContext ?? null); // Default true while loading to avoid toolbar flicker. - const isGitRepo = branchesQuery.data?.isRepo ?? true; - const splitTerminalShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "terminal.split"), + const isGitRepo = gitStatusQuery.data?.isRepo ?? true; + const terminalShortcutLabelOptions = useMemo( + () => ({ + context: { + terminalFocus: true, + terminalOpen: Boolean(terminalState.terminalOpen), + }, + }), + [terminalState.terminalOpen], + ); + const nonTerminalShortcutLabelOptions = useMemo( + () => ({ + context: { + terminalFocus: false, + terminalOpen: Boolean(terminalState.terminalOpen), + }, + }), + [terminalState.terminalOpen], + ); + const terminalToggleShortcutLabel = useMemo( + () => shortcutLabelForCommand(keybindings, "terminal.toggle"), [keybindings], ); + const splitTerminalShortcutLabel = useMemo( + () => shortcutLabelForCommand(keybindings, "terminal.split", terminalShortcutLabelOptions), + [keybindings, terminalShortcutLabelOptions], + ); const newTerminalShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "terminal.new"), - [keybindings], + () => shortcutLabelForCommand(keybindings, "terminal.new", terminalShortcutLabelOptions), + [keybindings, terminalShortcutLabelOptions], ); const closeTerminalShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "terminal.close"), - [keybindings], + () => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions), + [keybindings, terminalShortcutLabelOptions], ); + const diffPanelShortcutLabel = useMemo( + () => shortcutLabelForCommand(keybindings, "diff.toggle", nonTerminalShortcutLabelOptions), + [keybindings, nonTerminalShortcutLabelOptions], + ); + const onToggleDiff = useCallback(() => { + void navigate({ + to: "/$threadId", + params: { threadId }, + replace: true, + search: (previous) => { + const rest = stripDiffSearchParams(previous); + return diffOpen ? { ...rest, diff: undefined } : { ...rest, diff: "1" }; + }, + }); + }, [diffOpen, navigate, threadId]); const envLocked = Boolean( activeThread && (activeThread.messages.length > 0 || (activeThread.session !== null && activeThread.session.status !== "closed")), ); + const activeTerminalGroup = + terminalState.terminalGroups.find( + (group) => group.id === terminalState.activeTerminalGroupId, + ) ?? + terminalState.terminalGroups.find((group) => + group.terminalIds.includes(terminalState.activeTerminalId), + ) ?? + null; + const hasReachedSplitLimit = + (activeTerminalGroup?.terminalIds.length ?? 0) >= MAX_TERMINALS_PER_GROUP; + const setThreadError = useCallback( + (targetThreadId: ThreadId | null, error: string | null) => { + if (!targetThreadId) return; + if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) { + setStoreThreadError(targetThreadId, error); + return; + } + setLocalDraftErrorsByThreadId((existing) => { + if ((existing[targetThreadId] ?? null) === error) { + return existing; + } + return { + ...existing, + [targetThreadId]: error, + }; + }); + }, + [setStoreThreadError], + ); - const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => { - for (const image of images) { - if (!image.previewUrl) continue; - URL.revokeObjectURL(image.previewUrl); - } - }, []); const focusComposer = useCallback(() => { - const textarea = textareaRef.current; - if (!textarea) return; - textarea.focus(); - const cursor = textarea.value.length; - textarea.setSelectionRange(cursor, cursor); + composerEditorRef.current?.focusAtEnd(); }, []); const scheduleComposerFocus = useCallback(() => { window.requestAnimationFrame(() => { focusComposer(); }); }, [focusComposer]); + const addTerminalContextToDraft = useCallback( + (selection: TerminalContextSelection) => { + if (!activeThread) { + return; + } + const snapshot = composerEditorRef.current?.readSnapshot() ?? { + value: promptRef.current, + cursor: composerCursor, + expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor), + terminalContextIds: composerTerminalContexts.map((context) => context.id), + }; + const insertion = insertInlineTerminalContextPlaceholder( + snapshot.value, + snapshot.expandedCursor, + ); + const nextCollapsedCursor = collapseExpandedComposerCursor( + insertion.prompt, + insertion.cursor, + ); + const inserted = insertComposerDraftTerminalContext( + activeThread.id, + insertion.prompt, + { + id: randomUUID(), + threadId: activeThread.id, + createdAt: new Date().toISOString(), + ...selection, + }, + insertion.contextIndex, + ); + if (!inserted) { + return; + } + promptRef.current = insertion.prompt; + setComposerCursor(nextCollapsedCursor); + setComposerTrigger(detectComposerTrigger(insertion.prompt, insertion.cursor)); + window.requestAnimationFrame(() => { + composerEditorRef.current?.focusAt(nextCollapsedCursor); + }); + }, + [activeThread, composerCursor, composerTerminalContexts, insertComposerDraftTerminalContext], + ); + const setTerminalOpen = useCallback( + (open: boolean) => { + if (!activeThreadId) return; + storeSetTerminalOpen(activeThreadId, open); + }, + [activeThreadId, storeSetTerminalOpen], + ); const toggleTerminalVisibility = useCallback(() => { if (!activeThreadId) return; - dispatch({ - type: "SET_THREAD_TERMINAL_OPEN", - threadId: activeThreadId, - open: !activeThread?.terminalOpen, - }); - }, [activeThread?.terminalOpen, activeThreadId, dispatch]); + setTerminalOpen(!terminalState.terminalOpen); + }, [activeThreadId, setTerminalOpen, terminalState.terminalOpen]); const splitTerminal = useCallback(() => { - if (!activeThreadId) return; - dispatch({ - type: "SPLIT_THREAD_TERMINAL", - threadId: activeThreadId, - terminalId: `terminal-${crypto.randomUUID()}`, - }); + if (!activeThreadId || hasReachedSplitLimit) return; + const terminalId = `terminal-${randomUUID()}`; + storeSplitTerminal(activeThreadId, terminalId); setTerminalFocusRequestId((value) => value + 1); - }, [activeThreadId, dispatch]); + }, [activeThreadId, hasReachedSplitLimit, storeSplitTerminal]); const createNewTerminal = useCallback(() => { if (!activeThreadId) return; - dispatch({ - type: "NEW_THREAD_TERMINAL", - threadId: activeThreadId, - terminalId: `terminal-${crypto.randomUUID()}`, - }); + const terminalId = `terminal-${randomUUID()}`; + storeNewTerminal(activeThreadId, terminalId); setTerminalFocusRequestId((value) => value + 1); - }, [activeThreadId, dispatch]); - const activateTerminal = useCallback( - (terminalId: string) => { - if (!activeThreadId) return; - dispatch({ - type: "SET_THREAD_ACTIVE_TERMINAL", - threadId: activeThreadId, - terminalId, - }); - setTerminalFocusRequestId((value) => value + 1); - }, - [activeThreadId, dispatch], - ); + }, [activeThreadId, storeNewTerminal]); const closeTerminal = useCallback( (terminalId: string) => { + const api = readNativeApi(); if (!activeThreadId || !api) return; - const isFinalTerminal = (activeThread?.terminalIds.length ?? 0) <= 1; + const isFinalTerminal = terminalState.terminalIds.length <= 1; const fallbackExitWrite = () => api.terminal .write({ threadId: activeThreadId, terminalId, data: "exit\n" }) @@ -366,137 +1707,879 @@ export default function ChatView() { .clear({ threadId: activeThreadId, terminalId }) .catch(() => undefined); } - await api.terminal.close({ threadId: activeThreadId, terminalId, deleteHistory: true }); + await api.terminal.close({ + threadId: activeThreadId, + terminalId, + deleteHistory: true, + }); })().catch(() => fallbackExitWrite()); } else { void fallbackExitWrite(); } - dispatch({ - type: "CLOSE_THREAD_TERMINAL", - threadId: activeThreadId, - terminalId, - }); + storeCloseTerminal(activeThreadId, terminalId); setTerminalFocusRequestId((value) => value + 1); }, - [activeThread?.terminalIds.length, activeThreadId, api, dispatch], + [activeThreadId, storeCloseTerminal, terminalState.terminalIds.length], + ); + const runProjectScript = useCallback( + async ( + script: ProjectScript, + options?: { + cwd?: string; + env?: Record; + worktreePath?: string | null; + preferNewTerminal?: boolean; + rememberAsLastInvoked?: boolean; + }, + ) => { + const api = readNativeApi(); + if (!api || !activeThreadId || !activeProject || !activeThread) return; + if (options?.rememberAsLastInvoked !== false) { + setLastInvokedScriptByProjectId((current) => { + if (current[activeProject.id] === script.id) return current; + return { ...current, [activeProject.id]: script.id }; + }); + } + const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd; + const baseTerminalId = + terminalState.activeTerminalId || + terminalState.terminalIds[0] || + DEFAULT_THREAD_TERMINAL_ID; + const isBaseTerminalBusy = terminalState.runningTerminalIds.includes(baseTerminalId); + const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy; + const shouldCreateNewTerminal = wantsNewTerminal; + const targetTerminalId = shouldCreateNewTerminal + ? `terminal-${randomUUID()}` + : baseTerminalId; + const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null; + + setTerminalLaunchContext({ + threadId: activeThreadId, + cwd: targetCwd, + worktreePath: targetWorktreePath, + }); + setTerminalOpen(true); + if (shouldCreateNewTerminal) { + storeNewTerminal(activeThreadId, targetTerminalId); + } else { + storeSetActiveTerminal(activeThreadId, targetTerminalId); + } + setTerminalFocusRequestId((value) => value + 1); + + const runtimeEnv = projectScriptRuntimeEnv({ + project: { + cwd: activeProject.cwd, + }, + worktreePath: targetWorktreePath, + ...(options?.env ? { extraEnv: options.env } : {}), + }); + const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal + ? { + threadId: activeThreadId, + terminalId: targetTerminalId, + cwd: targetCwd, + ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}), + env: runtimeEnv, + cols: SCRIPT_TERMINAL_COLS, + rows: SCRIPT_TERMINAL_ROWS, + } + : { + threadId: activeThreadId, + terminalId: targetTerminalId, + cwd: targetCwd, + ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}), + env: runtimeEnv, + }; + + try { + await api.terminal.open(openTerminalInput); + await api.terminal.write({ + threadId: activeThreadId, + terminalId: targetTerminalId, + data: `${script.command}\r`, + }); + } catch (error) { + setThreadError( + activeThreadId, + error instanceof Error ? error.message : `Failed to run script "${script.name}".`, + ); + } + }, + [ + activeProject, + activeThread, + activeThreadId, + gitCwd, + setTerminalOpen, + setThreadError, + storeNewTerminal, + storeSetActiveTerminal, + setLastInvokedScriptByProjectId, + terminalState.activeTerminalId, + terminalState.runningTerminalIds, + terminalState.terminalIds, + ], ); - const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => { - if (mode === state.runtimeMode) return; - dispatch({ type: "SET_RUNTIME_MODE", mode }); - scheduleComposerFocus(); - if (!api) return; + const persistProjectScripts = useCallback( + async (input: { + projectId: ProjectId; + projectCwd: string; + previousScripts: ProjectScript[]; + nextScripts: ProjectScript[]; + keybinding?: string | null; + keybindingCommand: KeybindingCommand; + }) => { + const api = readNativeApi(); + if (!api) return; - const sessionIds = state.threads - .map((t) => t.session) - .filter((s): s is NonNullable => s !== null && s.status !== "closed") - .map((s) => s.sessionId); + await api.orchestration.dispatchCommand({ + type: "project.meta.update", + commandId: newCommandId(), + projectId: input.projectId, + scripts: input.nextScripts, + }); - if (sessionIds.length === 0) return; + const keybindingRule = decodeProjectScriptKeybindingRule({ + keybinding: input.keybinding, + command: input.keybindingCommand, + }); - setIsSwitchingRuntimeMode(true); - try { - await Promise.all( - sessionIds.map((id) => api.providers.stopSession({ sessionId: id }).catch(() => undefined)), + if (isElectron && keybindingRule) { + await api.server.upsertKeybinding(keybindingRule); + } + }, + [], + ); + const saveProjectScript = useCallback( + async (input: NewProjectScriptInput) => { + if (!activeProject) return; + const nextId = nextProjectScriptId( + input.name, + activeProject.scripts.map((script) => script.id), ); - } finally { - setIsSwitchingRuntimeMode(false); - } - }; + const nextScript: ProjectScript = { + id: nextId, + name: input.name, + command: input.command, + icon: input.icon, + runOnWorktreeCreate: input.runOnWorktreeCreate, + }; + const nextScripts = input.runOnWorktreeCreate + ? [ + ...activeProject.scripts.map((script) => + script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script, + ), + nextScript, + ] + : [...activeProject.scripts, nextScript]; + + await persistProjectScripts({ + projectId: activeProject.id, + projectCwd: activeProject.cwd, + previousScripts: activeProject.scripts, + nextScripts, + keybinding: input.keybinding, + keybindingCommand: commandForProjectScript(nextId), + }); + }, + [activeProject, persistProjectScripts], + ); + const updateProjectScript = useCallback( + async (scriptId: string, input: NewProjectScriptInput) => { + if (!activeProject) return; + const existingScript = activeProject.scripts.find((script) => script.id === scriptId); + if (!existingScript) { + throw new Error("Script not found."); + } + + const updatedScript: ProjectScript = { + ...existingScript, + name: input.name, + command: input.command, + icon: input.icon, + runOnWorktreeCreate: input.runOnWorktreeCreate, + }; + const nextScripts = activeProject.scripts.map((script) => + script.id === scriptId + ? updatedScript + : input.runOnWorktreeCreate + ? { ...script, runOnWorktreeCreate: false } + : script, + ); + + await persistProjectScripts({ + projectId: activeProject.id, + projectCwd: activeProject.cwd, + previousScripts: activeProject.scripts, + nextScripts, + keybinding: input.keybinding, + keybindingCommand: commandForProjectScript(scriptId), + }); + }, + [activeProject, persistProjectScripts], + ); + const deleteProjectScript = useCallback( + async (scriptId: string) => { + if (!activeProject) return; + const nextScripts = activeProject.scripts.filter((script) => script.id !== scriptId); + + const deletedName = activeProject.scripts.find((s) => s.id === scriptId)?.name; + + try { + await persistProjectScripts({ + projectId: activeProject.id, + projectCwd: activeProject.cwd, + previousScripts: activeProject.scripts, + nextScripts, + keybinding: null, + keybindingCommand: commandForProjectScript(scriptId), + }); + toastManager.add({ + type: "success", + title: `Deleted action "${deletedName ?? "Unknown"}"`, + }); + } catch (error) { + toastManager.add({ + type: "error", + title: "Could not delete action", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }); + } + }, + [activeProject, persistProjectScripts], + ); + + const handleRuntimeModeChange = useCallback( + (mode: RuntimeMode) => { + if (mode === runtimeMode) return; + setComposerDraftRuntimeMode(threadId, mode); + if (isLocalDraftThread) { + setDraftThreadContext(threadId, { runtimeMode: mode }); + } + scheduleComposerFocus(); + }, + [ + isLocalDraftThread, + runtimeMode, + scheduleComposerFocus, + setComposerDraftRuntimeMode, + setDraftThreadContext, + threadId, + ], + ); + + const handleInteractionModeChange = useCallback( + (mode: ProviderInteractionMode) => { + if (mode === interactionMode) return; + setComposerDraftInteractionMode(threadId, mode); + if (isLocalDraftThread) { + setDraftThreadContext(threadId, { interactionMode: mode }); + } + scheduleComposerFocus(); + }, + [ + interactionMode, + isLocalDraftThread, + scheduleComposerFocus, + setComposerDraftInteractionMode, + setDraftThreadContext, + threadId, + ], + ); + const toggleInteractionMode = useCallback(() => { + handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan"); + }, [handleInteractionModeChange, interactionMode]); + const toggleRuntimeMode = useCallback(() => { + void handleRuntimeModeChange( + runtimeMode === "full-access" ? "approval-required" : "full-access", + ); + }, [handleRuntimeModeChange, runtimeMode]); + const togglePlanSidebar = useCallback(() => { + setPlanSidebarOpen((open) => { + if (open) { + const turnKey = activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? null; + if (turnKey) { + planSidebarDismissedForTurnRef.current = turnKey; + } + } else { + planSidebarDismissedForTurnRef.current = null; + } + return !open; + }); + }, [activePlan?.turnId, sidebarProposedPlan?.turnId]); + + const persistThreadSettingsForNextTurn = useCallback( + async (input: { + threadId: ThreadId; + createdAt: string; + modelSelection?: ModelSelection; + runtimeMode: RuntimeMode; + interactionMode: ProviderInteractionMode; + }) => { + if (!serverThread) { + return; + } + const api = readNativeApi(); + if (!api) { + return; + } + + if ( + input.modelSelection !== undefined && + (input.modelSelection.model !== serverThread.modelSelection.model || + input.modelSelection.provider !== serverThread.modelSelection.provider || + JSON.stringify(input.modelSelection.options ?? null) !== + JSON.stringify(serverThread.modelSelection.options ?? null)) + ) { + await api.orchestration.dispatchCommand({ + type: "thread.meta.update", + commandId: newCommandId(), + threadId: input.threadId, + modelSelection: input.modelSelection, + }); + } + + if (input.runtimeMode !== serverThread.runtimeMode) { + await api.orchestration.dispatchCommand({ + type: "thread.runtime-mode.set", + commandId: newCommandId(), + threadId: input.threadId, + runtimeMode: input.runtimeMode, + createdAt: input.createdAt, + }); + } + + if (input.interactionMode !== serverThread.interactionMode) { + await api.orchestration.dispatchCommand({ + type: "thread.interaction-mode.set", + commandId: newCommandId(), + threadId: input.threadId, + interactionMode: input.interactionMode, + createdAt: input.createdAt, + }); + } + }, + [serverThread], + ); // Auto-scroll on new messages - const messageCount = activeThread?.messages.length ?? 0; - const workLogCount = workLogEntries.length; + const messageCount = timelineMessages.length; const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => { const scrollContainer = messagesScrollRef.current; if (!scrollContainer) return; scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior }); + lastKnownScrollTopRef.current = scrollContainer.scrollTop; shouldAutoScrollRef.current = true; }, []); + const cancelPendingStickToBottom = useCallback(() => { + const pendingFrame = pendingAutoScrollFrameRef.current; + if (pendingFrame === null) return; + pendingAutoScrollFrameRef.current = null; + window.cancelAnimationFrame(pendingFrame); + }, []); + const cancelPendingInteractionAnchorAdjustment = useCallback(() => { + const pendingFrame = pendingInteractionAnchorFrameRef.current; + if (pendingFrame === null) return; + pendingInteractionAnchorFrameRef.current = null; + window.cancelAnimationFrame(pendingFrame); + }, []); + const scheduleStickToBottom = useCallback(() => { + if (pendingAutoScrollFrameRef.current !== null) return; + pendingAutoScrollFrameRef.current = window.requestAnimationFrame(() => { + pendingAutoScrollFrameRef.current = null; + scrollMessagesToBottom(); + }); + }, [scrollMessagesToBottom]); + const onMessagesClickCapture = useCallback( + (event: React.MouseEvent) => { + const scrollContainer = messagesScrollRef.current; + if (!scrollContainer || !(event.target instanceof Element)) return; + + const trigger = event.target.closest( + "button, summary, [role='button'], [data-scroll-anchor-target]", + ); + if (!trigger || !scrollContainer.contains(trigger)) return; + if (trigger.closest("[data-scroll-anchor-ignore]")) return; + + pendingInteractionAnchorRef.current = { + element: trigger, + top: trigger.getBoundingClientRect().top, + }; + + cancelPendingInteractionAnchorAdjustment(); + pendingInteractionAnchorFrameRef.current = window.requestAnimationFrame(() => { + pendingInteractionAnchorFrameRef.current = null; + const anchor = pendingInteractionAnchorRef.current; + pendingInteractionAnchorRef.current = null; + const activeScrollContainer = messagesScrollRef.current; + if (!anchor || !activeScrollContainer) return; + if (!anchor.element.isConnected || !activeScrollContainer.contains(anchor.element)) return; + + const nextTop = anchor.element.getBoundingClientRect().top; + const delta = nextTop - anchor.top; + if (Math.abs(delta) < 0.5) return; + + activeScrollContainer.scrollTop += delta; + lastKnownScrollTopRef.current = activeScrollContainer.scrollTop; + }); + }, + [cancelPendingInteractionAnchorAdjustment], + ); + const forceStickToBottom = useCallback(() => { + cancelPendingStickToBottom(); + scrollMessagesToBottom(); + scheduleStickToBottom(); + }, [cancelPendingStickToBottom, scheduleStickToBottom, scrollMessagesToBottom]); const onMessagesScroll = useCallback(() => { const scrollContainer = messagesScrollRef.current; if (!scrollContainer) return; - shouldAutoScrollRef.current = isScrollContainerNearBottom(scrollContainer); + const currentScrollTop = scrollContainer.scrollTop; + const isNearBottom = isScrollContainerNearBottom(scrollContainer); + + if (!shouldAutoScrollRef.current && isNearBottom) { + shouldAutoScrollRef.current = true; + pendingUserScrollUpIntentRef.current = false; + } else if (shouldAutoScrollRef.current && pendingUserScrollUpIntentRef.current) { + const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1; + if (scrolledUp && !isNearBottom) { + shouldAutoScrollRef.current = false; + } + pendingUserScrollUpIntentRef.current = false; + } else if (shouldAutoScrollRef.current && isPointerScrollActiveRef.current) { + const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1; + if (scrolledUp && !isNearBottom) { + shouldAutoScrollRef.current = false; + } + } else if (shouldAutoScrollRef.current && !isNearBottom) { + // Catch-all for keyboard/assistive scroll interactions. + const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1; + if (scrolledUp) { + shouldAutoScrollRef.current = false; + } + } + + setShowScrollToBottom(!shouldAutoScrollRef.current); + lastKnownScrollTopRef.current = currentScrollTop; }, []); + const onMessagesWheel = useCallback((event: React.WheelEvent) => { + if (event.deltaY < 0) { + pendingUserScrollUpIntentRef.current = true; + } + }, []); + const onMessagesPointerDown = useCallback((_event: React.PointerEvent) => { + isPointerScrollActiveRef.current = true; + }, []); + const onMessagesPointerUp = useCallback((_event: React.PointerEvent) => { + isPointerScrollActiveRef.current = false; + }, []); + const onMessagesPointerCancel = useCallback((_event: React.PointerEvent) => { + isPointerScrollActiveRef.current = false; + }, []); + const onMessagesTouchStart = useCallback((event: React.TouchEvent) => { + const touch = event.touches[0]; + if (!touch) return; + lastTouchClientYRef.current = touch.clientY; + }, []); + const onMessagesTouchMove = useCallback((event: React.TouchEvent) => { + const touch = event.touches[0]; + if (!touch) return; + const previousTouchY = lastTouchClientYRef.current; + if (previousTouchY !== null && touch.clientY > previousTouchY + 1) { + pendingUserScrollUpIntentRef.current = true; + } + lastTouchClientYRef.current = touch.clientY; + }, []); + const onMessagesTouchEnd = useCallback((_event: React.TouchEvent) => { + lastTouchClientYRef.current = null; + }, []); + useEffect(() => { + return () => { + cancelPendingStickToBottom(); + cancelPendingInteractionAnchorAdjustment(); + }; + }, [cancelPendingInteractionAnchorAdjustment, cancelPendingStickToBottom]); useLayoutEffect(() => { if (!activeThread?.id) return; - scrollMessagesToBottom(); - }, [activeThread?.id, scrollMessagesToBottom]); + shouldAutoScrollRef.current = true; + scheduleStickToBottom(); + const timeout = window.setTimeout(() => { + const scrollContainer = messagesScrollRef.current; + if (!scrollContainer) return; + if (isScrollContainerNearBottom(scrollContainer)) return; + scheduleStickToBottom(); + }, 96); + return () => { + window.clearTimeout(timeout); + }; + }, [activeThread?.id, scheduleStickToBottom]); + useLayoutEffect(() => { + const composerForm = composerFormRef.current; + if (!composerForm) return; + const measureComposerFormWidth = () => composerForm.clientWidth; + const measureFooterCompactness = () => { + const composerFormWidth = measureComposerFormWidth(); + const heuristicFooterCompact = shouldUseCompactComposerFooter(composerFormWidth, { + hasWideActions: composerFooterHasWideActions, + }); + const footer = composerFooterRef.current; + const footerStyle = footer ? window.getComputedStyle(footer) : null; + const footerContentWidth = resolveComposerFooterContentWidth({ + footerWidth: footer?.clientWidth ?? null, + paddingLeft: footerStyle ? Number.parseFloat(footerStyle.paddingLeft) : null, + paddingRight: footerStyle ? Number.parseFloat(footerStyle.paddingRight) : null, + }); + const fitInput = { + footerContentWidth, + leadingContentWidth: composerFooterLeadingRef.current?.scrollWidth ?? null, + actionsWidth: composerFooterActionsRef.current?.scrollWidth ?? null, + }; + const nextFooterCompact = + heuristicFooterCompact || shouldForceCompactComposerFooterForFit(fitInput); + const nextPrimaryActionsCompact = + nextFooterCompact && + shouldUseCompactComposerPrimaryActions(composerFormWidth, { + hasWideActions: composerFooterHasWideActions, + }); + + return { + primaryActionsCompact: nextPrimaryActionsCompact, + footerCompact: nextFooterCompact, + }; + }; + + composerFormHeightRef.current = composerForm.getBoundingClientRect().height; + const initialCompactness = measureFooterCompactness(); + setIsComposerPrimaryActionsCompact(initialCompactness.primaryActionsCompact); + setIsComposerFooterCompact(initialCompactness.footerCompact); + if (typeof ResizeObserver === "undefined") return; + + const observer = new ResizeObserver((entries) => { + const [entry] = entries; + if (!entry) return; + + const nextCompactness = measureFooterCompactness(); + setIsComposerPrimaryActionsCompact((previous) => + previous === nextCompactness.primaryActionsCompact + ? previous + : nextCompactness.primaryActionsCompact, + ); + setIsComposerFooterCompact((previous) => + previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact, + ); + + const nextHeight = entry.contentRect.height; + const previousHeight = composerFormHeightRef.current; + composerFormHeightRef.current = nextHeight; + + if (previousHeight > 0 && Math.abs(nextHeight - previousHeight) < 0.5) return; + if (!shouldAutoScrollRef.current) return; + scheduleStickToBottom(); + }); + + observer.observe(composerForm); + return () => { + observer.disconnect(); + }; + }, [ + activeThread?.id, + composerFooterActionLayoutKey, + composerFooterHasWideActions, + scheduleStickToBottom, + ]); useEffect(() => { if (!shouldAutoScrollRef.current) return; - scrollMessagesToBottom("smooth"); - }, [messageCount, scrollMessagesToBottom]); + scheduleStickToBottom(); + }, [messageCount, scheduleStickToBottom]); useEffect(() => { if (phase !== "running") return; if (!shouldAutoScrollRef.current) return; - scrollMessagesToBottom("smooth"); - }, [phase, workLogCount, scrollMessagesToBottom]); + scheduleStickToBottom(); + }, [phase, scheduleStickToBottom, timelineEntries]); useEffect(() => { setExpandedWorkGroups({}); + setPullRequestDialogState(null); + if (planSidebarOpenOnNextThreadRef.current) { + planSidebarOpenOnNextThreadRef.current = false; + setPlanSidebarOpen(true); + } else { + setPlanSidebarOpen(false); + } + planSidebarDismissedForTurnRef.current = null; }, [activeThread?.id]); useEffect(() => { - if (!activeThread?.id || activeThread.terminalOpen) return; + if (!composerMenuOpen) { + setComposerHighlightedItemId(null); + return; + } + setComposerHighlightedItemId((existing) => + existing && composerMenuItems.some((item) => item.id === existing) + ? existing + : (composerMenuItems[0]?.id ?? null), + ); + }, [composerMenuItems, composerMenuOpen]); + + useEffect(() => { + setIsRevertingCheckpoint(false); + }, [activeThread?.id]); + + useEffect(() => { + if (!activeThread?.id || terminalState.terminalOpen) return; const frame = window.requestAnimationFrame(() => { focusComposer(); }); return () => { window.cancelAnimationFrame(frame); }; - }, [activeThread?.id, activeThread?.terminalOpen, focusComposer]); + }, [activeThread?.id, focusComposer, terminalState.terminalOpen]); useEffect(() => { composerImagesRef.current = composerImages; }, [composerImages]); useEffect(() => { - setComposerImages((existing) => { - revokePreviewUrls(existing); + composerTerminalContextsRef.current = composerTerminalContexts; + }, [composerTerminalContexts]); + + useEffect(() => { + if (!activeThread?.id) return; + if (activeThread.messages.length === 0) { + return; + } + const serverIds = new Set(activeThread.messages.map((message) => message.id)); + const removedMessages = optimisticUserMessages.filter((message) => serverIds.has(message.id)); + if (removedMessages.length === 0) { + return; + } + const timer = window.setTimeout(() => { + setOptimisticUserMessages((existing) => + existing.filter((message) => !serverIds.has(message.id)), + ); + }, 0); + for (const removedMessage of removedMessages) { + const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage); + if (previewUrls.length > 0) { + handoffAttachmentPreviews(removedMessage.id, previewUrls); + continue; + } + revokeUserMessagePreviewUrls(removedMessage); + } + return () => { + window.clearTimeout(timer); + }; + }, [activeThread?.id, activeThread?.messages, handoffAttachmentPreviews, optimisticUserMessages]); + + useEffect(() => { + promptRef.current = prompt; + setComposerCursor((existing) => clampCollapsedComposerCursor(prompt, existing)); + }, [prompt]); + + useEffect(() => { + setOptimisticUserMessages((existing) => { + for (const message of existing) { + revokeUserMessagePreviewUrls(message); + } return []; }); + resetLocalDispatch(); + setComposerHighlightedItemId(null); + setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length)); + setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length)); dragDepthRef.current = 0; setIsDragOverComposer(false); setExpandedImage(null); - }, [activeThread?.id, revokePreviewUrls]); + }, [resetLocalDispatch, threadId]); useEffect(() => { + let cancelled = false; + void (async () => { + if (composerImages.length === 0) { + clearComposerDraftPersistedAttachments(threadId); + return; + } + const getPersistedAttachmentsForThread = () => + useComposerDraftStore.getState().draftsByThreadId[threadId]?.persistedAttachments ?? []; + try { + const currentPersistedAttachments = getPersistedAttachmentsForThread(); + const existingPersistedById = new Map( + currentPersistedAttachments.map((attachment) => [attachment.id, attachment]), + ); + const stagedAttachmentById = new Map(); + await Promise.all( + composerImages.map(async (image) => { + try { + const dataUrl = await readFileAsDataUrl(image.file); + stagedAttachmentById.set(image.id, { + id: image.id, + name: image.name, + mimeType: image.mimeType, + sizeBytes: image.sizeBytes, + dataUrl, + }); + } catch { + const existingPersisted = existingPersistedById.get(image.id); + if (existingPersisted) { + stagedAttachmentById.set(image.id, existingPersisted); + } + } + }), + ); + const serialized = Array.from(stagedAttachmentById.values()); + if (cancelled) { + return; + } + // Stage attachments in persisted draft state first so persist middleware can write them. + syncComposerDraftPersistedAttachments(threadId, serialized); + } catch { + const currentImageIds = new Set(composerImages.map((image) => image.id)); + const fallbackPersistedAttachments = getPersistedAttachmentsForThread(); + const fallbackPersistedIds = fallbackPersistedAttachments + .map((attachment) => attachment.id) + .filter((id) => currentImageIds.has(id)); + const fallbackPersistedIdSet = new Set(fallbackPersistedIds); + const fallbackAttachments = fallbackPersistedAttachments.filter((attachment) => + fallbackPersistedIdSet.has(attachment.id), + ); + if (cancelled) { + return; + } + syncComposerDraftPersistedAttachments(threadId, fallbackAttachments); + } + })(); return () => { - revokePreviewUrls(composerImagesRef.current); + cancelled = true; }; - }, [revokePreviewUrls]); + }, [ + clearComposerDraftPersistedAttachments, + composerImages, + syncComposerDraftPersistedAttachments, + threadId, + ]); + + const closeExpandedImage = useCallback(() => { + setExpandedImage(null); + }, []); + const navigateExpandedImage = useCallback((direction: -1 | 1) => { + setExpandedImage((existing) => { + if (!existing || existing.images.length <= 1) { + return existing; + } + const nextIndex = + (existing.index + direction + existing.images.length) % existing.images.length; + if (nextIndex === existing.index) { + return existing; + } + return { ...existing, index: nextIndex }; + }); + }, []); - /** - * Close expanded image on Escape key - */ useEffect(() => { if (!expandedImage) { return; } const onKeyDown = (event: globalThis.KeyboardEvent) => { - if (event.key !== "Escape") return; - setExpandedImage(null); + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + closeExpandedImage(); + return; + } + if (expandedImage.images.length <= 1) { + return; + } + if (event.key === "ArrowLeft") { + event.preventDefault(); + event.stopPropagation(); + navigateExpandedImage(-1); + return; + } + if (event.key !== "ArrowRight") return; + event.preventDefault(); + event.stopPropagation(); + navigateExpandedImage(1); }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [expandedImage]); + }, [closeExpandedImage, expandedImage, navigateExpandedImage]); const activeWorktreePath = activeThread?.worktreePath; + const envMode: DraftThreadEnvMode = activeWorktreePath + ? "worktree" + : isLocalDraftThread + ? (draftThread?.envMode ?? "local") + : "local"; useEffect(() => { - if (!activeThread?.id) return; - setEnvMode(activeWorktreePath ? "worktree" : "local"); - }, [activeThread?.id, activeWorktreePath]); + if (!activeThreadId) { + setTerminalLaunchContext(null); + storeClearTerminalLaunchContext(threadId); + return; + } + setTerminalLaunchContext((current) => { + if (!current) return current; + if (current.threadId === activeThreadId) return current; + return null; + }); + }, [activeThreadId, storeClearTerminalLaunchContext, threadId]); - // Auto-resize textarea useEffect(() => { - const ta = textareaRef.current; - if (!ta) return; - ta.style.height = "auto"; - ta.style.height = `${Math.min(ta.scrollHeight, 200)}px`; - }, [prompt]); + if (!activeThreadId || !activeProjectCwd) { + return; + } + setTerminalLaunchContext((current) => { + if (!current || current.threadId !== activeThreadId) { + return current; + } + const settledCwd = projectScriptCwd({ + project: { cwd: activeProjectCwd }, + worktreePath: activeThreadWorktreePath, + }); + if ( + settledCwd === current.cwd && + (activeThreadWorktreePath ?? null) === current.worktreePath + ) { + storeClearTerminalLaunchContext(activeThreadId); + return null; + } + return current; + }); + }, [activeProjectCwd, activeThreadId, activeThreadWorktreePath, storeClearTerminalLaunchContext]); + + useEffect(() => { + if (!activeThreadId || !activeProjectCwd || !storeServerTerminalLaunchContext) { + return; + } + const settledCwd = projectScriptCwd({ + project: { cwd: activeProjectCwd }, + worktreePath: activeThreadWorktreePath, + }); + if ( + settledCwd === storeServerTerminalLaunchContext.cwd && + (activeThreadWorktreePath ?? null) === storeServerTerminalLaunchContext.worktreePath + ) { + storeClearTerminalLaunchContext(activeThreadId); + } + }, [ + activeProjectCwd, + activeThreadId, + activeThreadWorktreePath, + storeClearTerminalLaunchContext, + storeServerTerminalLaunchContext, + ]); + + useEffect(() => { + if (terminalState.terminalOpen) { + return; + } + if (activeThreadId) { + storeClearTerminalLaunchContext(activeThreadId); + } + setTerminalLaunchContext((current) => (current?.threadId === activeThreadId ? null : current)); + }, [activeThreadId, storeClearTerminalLaunchContext, terminalState.terminalOpen]); useEffect(() => { if (phase !== "running") return; @@ -511,10 +2594,12 @@ export default function ChatView() { useEffect(() => { if (!activeThreadId) return; const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false; - const current = Boolean(activeThread?.terminalOpen); + const current = Boolean(terminalState.terminalOpen); if (!previous && current) { + terminalOpenByThreadRef.current[activeThreadId] = current; setTerminalFocusRequestId((value) => value + 1); + return; } else if (previous && !current) { terminalOpenByThreadRef.current[activeThreadId] = current; const frame = window.requestAnimationFrame(() => { @@ -526,91 +2611,101 @@ export default function ChatView() { } terminalOpenByThreadRef.current[activeThreadId] = current; - }, [activeThread?.terminalOpen, activeThreadId, focusComposer]); + }, [activeThreadId, focusComposer, terminalState.terminalOpen]); useEffect(() => { - const isTerminalFocused = (): boolean => { - const activeElement = document.activeElement; - if (!(activeElement instanceof HTMLElement)) return false; - if (activeElement.classList.contains("xterm-helper-textarea")) return true; - return activeElement.closest(".thread-terminal-drawer .xterm") !== null; - }; - const handler = (event: globalThis.KeyboardEvent) => { if (!activeThreadId || event.defaultPrevented) return; const shortcutContext = { terminalFocus: isTerminalFocused(), - terminalOpen: Boolean(activeThread?.terminalOpen), + terminalOpen: Boolean(terminalState.terminalOpen), }; - if (isTerminalToggleShortcut(event, keybindings, { context: shortcutContext })) { + const command = resolveShortcutCommand(event, keybindings, { + context: shortcutContext, + }); + if (!command) return; + + if (command === "terminal.toggle") { event.preventDefault(); event.stopPropagation(); toggleTerminalVisibility(); return; } - if (isTerminalSplitShortcut(event, keybindings, { context: shortcutContext })) { + if (command === "terminal.split") { event.preventDefault(); event.stopPropagation(); - if (!activeThread?.terminalOpen) { - dispatch({ - type: "SET_THREAD_TERMINAL_OPEN", - threadId: activeThreadId, - open: true, - }); + if (!terminalState.terminalOpen) { + setTerminalOpen(true); } splitTerminal(); return; } - if (isTerminalCloseShortcut(event, keybindings, { context: shortcutContext })) { + if (command === "terminal.close") { event.preventDefault(); event.stopPropagation(); - if (!activeThread?.terminalOpen) return; - closeTerminal(activeThread.activeTerminalId); + if (!terminalState.terminalOpen) return; + closeTerminal(terminalState.activeTerminalId); return; } - if (!isTerminalNewShortcut(event, keybindings, { context: shortcutContext })) return; + if (command === "terminal.new") { + event.preventDefault(); + event.stopPropagation(); + if (!terminalState.terminalOpen) { + setTerminalOpen(true); + } + createNewTerminal(); + return; + } + + if (command === "diff.toggle") { + event.preventDefault(); + event.stopPropagation(); + onToggleDiff(); + return; + } + + const scriptId = projectScriptIdFromCommand(command); + if (!scriptId || !activeProject) return; + const script = activeProject.scripts.find((entry) => entry.id === scriptId); + if (!script) return; event.preventDefault(); event.stopPropagation(); - if (!activeThread?.terminalOpen) { - dispatch({ - type: "SET_THREAD_TERMINAL_OPEN", - threadId: activeThreadId, - open: true, - }); - } - createNewTerminal(); + void runProjectScript(script); }; window.addEventListener("keydown", handler); return () => window.removeEventListener("keydown", handler); }, [ - activeThread?.terminalOpen, - activeThread?.activeTerminalId, + activeProject, + terminalState.terminalOpen, + terminalState.activeTerminalId, activeThreadId, closeTerminal, createNewTerminal, - dispatch, + setTerminalOpen, + runProjectScript, splitTerminal, keybindings, + onToggleDiff, toggleTerminalVisibility, ]); - const setThreadError = (threadId: string | null, error: string | null) => { - if (!threadId) return; - dispatch({ - type: "SET_ERROR", - threadId, - error, - }); - }; - const addComposerImages = (files: File[]) => { if (!activeThreadId || files.length === 0) return; - const nextImages = [...composerImagesRef.current]; + if (pendingUserInputs.length > 0) { + toastManager.add({ + type: "error", + title: "Attach images after answering plan questions.", + }); + return; + } + + const nextImages: ComposerImageAttachment[] = []; + let nextImageCount = composerImagesRef.current.length; let error: string | null = null; for (const file of files) { if (!file.type.startsWith("image/")) { @@ -621,7 +2716,7 @@ export default function ChatView() { error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`; continue; } - if (nextImages.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { + if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`; break; } @@ -629,30 +2724,29 @@ export default function ChatView() { const previewUrl = URL.createObjectURL(file); nextImages.push({ type: "image", - id: crypto.randomUUID(), + id: randomUUID(), name: file.name || "image", mimeType: file.type, sizeBytes: file.size, previewUrl, file, }); + nextImageCount += 1; } - setComposerImages(nextImages); + if (nextImages.length === 1 && nextImages[0]) { + addComposerImage(nextImages[0]); + } else if (nextImages.length > 1) { + addComposerImagesToDraft(nextImages); + } setThreadError(activeThreadId, error); }; const removeComposerImage = (imageId: string) => { - setComposerImages((existing) => { - const match = existing.find((image) => image.id === imageId); - if (match?.previewUrl) { - URL.revokeObjectURL(match.previewUrl); - } - return existing.filter((image) => image.id !== imageId); - }); + removeComposerImageFromDraft(imageId); }; - const onComposerPaste = (event: ClipboardEvent) => { + const onComposerPaste = (event: React.ClipboardEvent) => { const files = Array.from(event.clipboardData.files); if (files.length === 0) { return; @@ -665,7 +2759,7 @@ export default function ChatView() { addComposerImages(imageFiles); }; - const onComposerDragEnter = (event: DragEvent) => { + const onComposerDragEnter = (event: React.DragEvent) => { if (!event.dataTransfer.types.includes("Files")) { return; } @@ -674,7 +2768,7 @@ export default function ChatView() { setIsDragOverComposer(true); }; - const onComposerDragOver = (event: DragEvent) => { + const onComposerDragOver = (event: React.DragEvent) => { if (!event.dataTransfer.types.includes("Files")) { return; } @@ -683,7 +2777,7 @@ export default function ChatView() { setIsDragOverComposer(true); }; - const onComposerDragLeave = (event: DragEvent) => { + const onComposerDragLeave = (event: React.DragEvent) => { if (!event.dataTransfer.types.includes("Files")) { return; } @@ -698,7 +2792,7 @@ export default function ChatView() { } }; - const onComposerDrop = (event: DragEvent) => { + const onComposerDrop = (event: React.DragEvent) => { if (!event.dataTransfer.types.includes("Files")) { return; } @@ -710,248 +2804,1059 @@ export default function ChatView() { focusComposer(); }; - const ensureSession = async (cwdOverride?: string): Promise => { - if (!api || !activeThread || !activeProject) return null; - if (activeThread.session && activeThread.session.status !== "closed") { - const sessionThreadId = activeThread.session.threadId ?? null; - const continuityState: SessionContinuityState = - activeThread.codexThreadId === null - ? "new" - : sessionThreadId === activeThread.codexThreadId - ? "resumed" - : "fallback_new"; - return { - sessionId: activeThread.session.sessionId, - resolvedThreadId: sessionThreadId, - continuityState, - } satisfies EnsuredSessionInfo; - } + const onRevertToTurnCount = useCallback( + async (turnCount: number) => { + const api = readNativeApi(); + if (!api || !activeThread || isRevertingCheckpoint) return; - const priorCodexThreadId = activeThread.codexThreadId; - setIsConnecting(true); - try { - const session = await api.providers.startSession({ - provider: "codex", - cwd: cwdOverride ?? activeThread.worktreePath ?? activeProject.cwd, - model: selectedModel || undefined, - resumeThreadId: priorCodexThreadId ?? undefined, - approvalPolicy: runtimeSessionConfig.approvalPolicy, - sandboxMode: runtimeSessionConfig.sandboxMode, - }); - dispatch({ - type: "UPDATE_SESSION", - threadId: activeThread.id, - session, - }); - const resolvedThreadId = session.threadId ?? null; - const continuityState: SessionContinuityState = - priorCodexThreadId === null - ? "new" - : resolvedThreadId === priorCodexThreadId - ? "resumed" - : "fallback_new"; - return { - sessionId: session.sessionId, - resolvedThreadId, - continuityState, - }; - } catch (err) { - dispatch({ - type: "SET_ERROR", - threadId: activeThread.id, - error: err instanceof Error ? err.message : "Failed to connect.", - }); - return null; - } finally { - setIsConnecting(false); - } - }; - - const onSend = async (e: FormEvent) => { - e.preventDefault(); - if (!api || !activeThread || isSending || isConnecting) return; - const trimmed = prompt.trim(); - if (!trimmed && composerImages.length === 0) return; - if (!activeProject) return; - const composerImagesSnapshot = [...composerImages]; - - // On first message: lock in branch + create worktree if needed. - let sessionCwd: string | undefined; - if ( - activeThread.messages.length === 0 && - activeThread.branch && - envMode === "worktree" && - !activeThread.worktreePath - ) { - try { - const newBranch = `codething/${crypto.randomUUID().slice(0, 8)}`; - const result = await createWorktreeMutation.mutateAsync({ - cwd: activeProject.cwd, - branch: activeThread.branch, - newBranch, - }); - sessionCwd = result.worktree.path; - dispatch({ - type: "SET_THREAD_BRANCH", - threadId: activeThread.id, - branch: result.worktree.branch, - worktreePath: result.worktree.path, - }); - } catch (err) { - dispatch({ - type: "SET_ERROR", - threadId: activeThread.id, - error: err instanceof Error ? err.message : "Failed to create worktree", - }); + if (phase === "running" || isSendBusy || isConnecting) { + setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); + return; + } + const confirmed = await api.dialogs.confirm( + [ + `Revert this thread to checkpoint ${turnCount}?`, + "This will discard newer messages and turn diffs in this thread.", + "This action cannot be undone.", + ].join("\n"), + ); + if (!confirmed) { return; } - } - // Auto-title from first message - if (activeThread.messages.length === 0) { - const titleSeed = - trimmed || - (composerImagesSnapshot.length > 0 - ? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}` - : "New thread"); - const title = titleSeed.length > 50 ? `${titleSeed.slice(0, 50)}...` : titleSeed; - dispatch({ - type: "SET_THREAD_TITLE", - threadId: activeThread.id, - title, + setIsRevertingCheckpoint(true); + setThreadError(activeThread.id, null); + try { + await api.orchestration.dispatchCommand({ + type: "thread.checkpoint.revert", + commandId: newCommandId(), + threadId: activeThread.id, + turnCount, + createdAt: new Date().toISOString(), + }); + } catch (err) { + setThreadError( + activeThread.id, + err instanceof Error ? err.message : "Failed to revert thread state.", + ); + } + setIsRevertingCheckpoint(false); + }, + [activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError], + ); + + const onSend = async (e?: { preventDefault: () => void }) => { + e?.preventDefault(); + const api = readNativeApi(); + if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return; + if (activePendingProgress) { + onAdvanceActivePendingUserInput(); + return; + } + const promptForSend = promptRef.current; + const { + trimmedPrompt: trimmed, + sendableTerminalContexts: sendableComposerTerminalContexts, + expiredTerminalContextCount, + hasSendableContent, + } = deriveComposerSendState({ + prompt: promptForSend, + imageCount: composerImages.length, + terminalContexts: composerTerminalContexts, + }); + if (showPlanFollowUpPrompt && activeProposedPlan) { + const followUp = resolvePlanFollowUpSubmission({ + draftText: trimmed, + planMarkdown: activeProposedPlan.planMarkdown, }); + promptRef.current = ""; + clearComposerDraftContent(activeThread.id); + setComposerHighlightedItemId(null); + setComposerCursor(0); + setComposerTrigger(null); + await onSubmitPlanFollowUp({ + text: followUp.text, + interactionMode: followUp.interactionMode, + }); + return; + } + const standaloneSlashCommand = + composerImages.length === 0 && sendableComposerTerminalContexts.length === 0 + ? parseStandaloneComposerSlashCommand(trimmed) + : null; + if (standaloneSlashCommand) { + handleInteractionModeChange(standaloneSlashCommand); + promptRef.current = ""; + clearComposerDraftContent(activeThread.id); + setComposerHighlightedItemId(null); + setComposerCursor(0); + setComposerTrigger(null); + return; + } + if (!hasSendableContent) { + if (expiredTerminalContextCount > 0) { + const toastCopy = buildExpiredTerminalContextToastCopy( + expiredTerminalContextCount, + "empty", + ); + toastManager.add({ + type: "warning", + title: toastCopy.title, + description: toastCopy.description, + }); + } + return; + } + if (!activeProject) return; + const threadIdForSend = activeThread.id; + const isFirstMessage = !isServerThread || activeThread.messages.length === 0; + const baseBranchForWorktree = + isFirstMessage && envMode === "worktree" && !activeThread.worktreePath + ? activeThread.branch + : null; + + // In worktree mode, require an explicit base branch so we don't silently + // fall back to local execution when branch selection is missing. + const shouldCreateWorktree = + isFirstMessage && envMode === "worktree" && !activeThread.worktreePath; + if (shouldCreateWorktree && !activeThread.branch) { + setStoreThreadError( + threadIdForSend, + "Select a base branch before sending in New worktree mode.", + ); + return; } - setThreadError(activeThread.id, null); - const messageAttachments: ChatImageAttachment[] = composerImagesSnapshot.map((image) => ({ - type: "image", + sendInFlightRef.current = true; + beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) }); + + const composerImagesSnapshot = [...composerImages]; + const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts]; + const messageTextForSend = appendTerminalContextsToPrompt( + promptForSend, + composerTerminalContextsSnapshot, + ); + const messageIdForSend = newMessageId(); + const messageCreatedAt = new Date().toISOString(); + const outgoingMessageText = formatOutgoingPrompt({ + provider: selectedProvider, + model: selectedModel, + models: selectedProviderModels, + effort: selectedPromptEffort, + text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT, + }); + const turnAttachmentsPromise = Promise.all( + composerImagesSnapshot.map(async (image) => ({ + type: "image" as const, + name: image.name, + mimeType: image.mimeType, + sizeBytes: image.sizeBytes, + dataUrl: await readFileAsDataUrl(image.file), + })), + ); + const optimisticAttachments = composerImagesSnapshot.map((image) => ({ + type: "image" as const, id: image.id, name: image.name, mimeType: image.mimeType, sizeBytes: image.sizeBytes, previewUrl: image.previewUrl, })); - dispatch({ - type: "PUSH_USER_MESSAGE", - threadId: activeThread.id, - id: crypto.randomUUID(), - text: trimmed, - ...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}), - }); - const previousMessages = activeThread.messages; - setPrompt(""); - setComposerImages([]); + setOptimisticUserMessages((existing) => [ + ...existing, + { + id: messageIdForSend, + role: "user", + text: outgoingMessageText, + ...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}), + createdAt: messageCreatedAt, + streaming: false, + }, + ]); + // Sending a message should always bring the latest user turn into view. + shouldAutoScrollRef.current = true; + forceStickToBottom(); - const sessionInfo = await ensureSession(sessionCwd); - if (!sessionInfo) return; - - setIsSending(true); - try { - const turnAttachments = await Promise.all( - composerImagesSnapshot.map( - async (image): Promise => ({ - type: "image", - name: image.name, - mimeType: image.mimeType, - sizeBytes: image.sizeBytes, - dataUrl: await readFileAsDataUrl(image.file), - }), - ), + setThreadError(threadIdForSend, null); + if (expiredTerminalContextCount > 0) { + const toastCopy = buildExpiredTerminalContextToastCopy( + expiredTerminalContextCount, + "omitted", ); - const shouldBootstrap = - previousMessages.length > 0 && - (sessionInfo.continuityState === "new" || sessionInfo.continuityState === "fallback_new"); - const latestPromptForBootstrap = trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT; - const input = shouldBootstrap - ? buildBootstrapInput( - previousMessages, - latestPromptForBootstrap, - PROVIDER_SEND_TURN_MAX_INPUT_CHARS, - ).text - : trimmed || undefined; - await api.providers.sendTurn({ - sessionId: sessionInfo.sessionId, - ...(input ? { input } : {}), - ...(turnAttachments.length > 0 ? { attachments: turnAttachments } : {}), - model: selectedModel || undefined, - effort: selectedEffort || undefined, + toastManager.add({ + type: "warning", + title: toastCopy.title, + description: toastCopy.description, }); - } catch (err) { + } + promptRef.current = ""; + clearComposerDraftContent(threadIdForSend); + setComposerHighlightedItemId(null); + setComposerCursor(0); + setComposerTrigger(null); + + let turnStartSucceeded = false; + await (async () => { + let firstComposerImageName: string | null = null; + if (composerImagesSnapshot.length > 0) { + const firstComposerImage = composerImagesSnapshot[0]; + if (firstComposerImage) { + firstComposerImageName = firstComposerImage.name; + } + } + let titleSeed = trimmed; + if (!titleSeed) { + if (firstComposerImageName) { + titleSeed = `Image: ${firstComposerImageName}`; + } else if (composerTerminalContextsSnapshot.length > 0) { + titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!); + } else { + titleSeed = "New thread"; + } + } + const title = truncate(titleSeed); + const threadCreateModelSelection: ModelSelection = { + provider: selectedProvider, + model: + selectedModel || + activeProject.defaultModelSelection?.model || + DEFAULT_MODEL_BY_PROVIDER.codex, + ...(selectedModelSelection.options ? { options: selectedModelSelection.options } : {}), + }; + + // Auto-title from first message + if (isFirstMessage && isServerThread) { + await api.orchestration.dispatchCommand({ + type: "thread.meta.update", + commandId: newCommandId(), + threadId: threadIdForSend, + title, + }); + } + + if (isServerThread) { + await persistThreadSettingsForNextTurn({ + threadId: threadIdForSend, + createdAt: messageCreatedAt, + ...(selectedModel ? { modelSelection: selectedModelSelection } : {}), + runtimeMode, + interactionMode, + }); + } + + const turnAttachments = await turnAttachmentsPromise; + const bootstrap = + isLocalDraftThread || baseBranchForWorktree + ? { + ...(isLocalDraftThread + ? { + createThread: { + projectId: activeProject.id, + title, + modelSelection: threadCreateModelSelection, + runtimeMode, + interactionMode, + branch: activeThread.branch, + worktreePath: activeThread.worktreePath, + createdAt: activeThread.createdAt, + }, + } + : {}), + ...(baseBranchForWorktree + ? { + prepareWorktree: { + projectCwd: activeProject.cwd, + baseBranch: baseBranchForWorktree, + branch: buildTemporaryWorktreeBranchName(), + }, + runSetupScript: true, + } + : {}), + } + : undefined; + beginLocalDispatch({ preparingWorktree: false }); + await api.orchestration.dispatchCommand({ + type: "thread.turn.start", + commandId: newCommandId(), + threadId: threadIdForSend, + message: { + messageId: messageIdForSend, + role: "user", + text: outgoingMessageText, + attachments: turnAttachments, + }, + modelSelection: selectedModelSelection, + titleSeed: title, + runtimeMode, + interactionMode, + ...(bootstrap ? { bootstrap } : {}), + createdAt: messageCreatedAt, + }); + turnStartSucceeded = true; + })().catch(async (err: unknown) => { + if ( + !turnStartSucceeded && + promptRef.current.length === 0 && + composerImagesRef.current.length === 0 && + composerTerminalContextsRef.current.length === 0 + ) { + setOptimisticUserMessages((existing) => { + const removed = existing.filter((message) => message.id === messageIdForSend); + for (const message of removed) { + revokeUserMessagePreviewUrls(message); + } + const next = existing.filter((message) => message.id !== messageIdForSend); + return next.length === existing.length ? existing : next; + }); + promptRef.current = promptForSend; + setPrompt(promptForSend); + setComposerCursor(collapseExpandedComposerCursor(promptForSend, promptForSend.length)); + addComposerImagesToDraft(composerImagesSnapshot.map(cloneComposerImageForRetry)); + addComposerTerminalContextsToDraft(composerTerminalContextsSnapshot); + setComposerTrigger(detectComposerTrigger(promptForSend, promptForSend.length)); + } setThreadError( - activeThread.id, + threadIdForSend, err instanceof Error ? err.message : "Failed to send message.", ); - } finally { - setIsSending(false); + }); + sendInFlightRef.current = false; + if (!turnStartSucceeded) { + resetLocalDispatch(); } }; const onInterrupt = async () => { - if (!api || !activeThread?.session) return; - await api.providers.interruptTurn({ - sessionId: activeThread.session.sessionId, - turnId: activeThread.session.activeTurnId, + const api = readNativeApi(); + if (!api || !activeThread) return; + await api.orchestration.dispatchCommand({ + type: "thread.turn.interrupt", + commandId: newCommandId(), + threadId: activeThread.id, + createdAt: new Date().toISOString(), }); }; const onRespondToApproval = useCallback( - async (requestId: string, decision: ProviderApprovalDecision) => { - if (!api || !activeSessionId || !activeThreadId) return; + async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => { + const api = readNativeApi(); + if (!api || !activeThreadId) return; setRespondingRequestIds((existing) => existing.includes(requestId) ? existing : [...existing, requestId], ); - try { - await api.providers.respondToRequest({ - sessionId: activeSessionId, + await api.orchestration + .dispatchCommand({ + type: "thread.approval.respond", + commandId: newCommandId(), + threadId: activeThreadId, requestId, decision, + createdAt: new Date().toISOString(), + }) + .catch((err: unknown) => { + setStoreThreadError( + activeThreadId, + err instanceof Error ? err.message : "Failed to submit approval decision.", + ); }); - } catch (err) { - dispatch({ - type: "SET_ERROR", + setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); + }, + [activeThreadId, setStoreThreadError], + ); + + const onRespondToUserInput = useCallback( + async (requestId: ApprovalRequestId, answers: Record) => { + const api = readNativeApi(); + if (!api || !activeThreadId) return; + + setRespondingUserInputRequestIds((existing) => + existing.includes(requestId) ? existing : [...existing, requestId], + ); + await api.orchestration + .dispatchCommand({ + type: "thread.user-input.respond", + commandId: newCommandId(), threadId: activeThreadId, - error: err instanceof Error ? err.message : "Failed to submit approval decision.", + requestId, + answers, + createdAt: new Date().toISOString(), + }) + .catch((err: unknown) => { + setStoreThreadError( + activeThreadId, + err instanceof Error ? err.message : "Failed to submit user input.", + ); }); - } finally { - setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); + setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); + }, + [activeThreadId, setStoreThreadError], + ); + + const setActivePendingUserInputQuestionIndex = useCallback( + (nextQuestionIndex: number) => { + if (!activePendingUserInput) { + return; + } + setPendingUserInputQuestionIndexByRequestId((existing) => ({ + ...existing, + [activePendingUserInput.requestId]: nextQuestionIndex, + })); + }, + [activePendingUserInput], + ); + + const onSelectActivePendingUserInputOption = useCallback( + (questionId: string, optionLabel: string) => { + if (!activePendingUserInput) { + return; + } + setPendingUserInputAnswersByRequestId((existing) => ({ + ...existing, + [activePendingUserInput.requestId]: { + ...existing[activePendingUserInput.requestId], + [questionId]: { + selectedOptionLabel: optionLabel, + customAnswer: "", + }, + }, + })); + promptRef.current = ""; + setComposerCursor(0); + setComposerTrigger(null); + }, + [activePendingUserInput], + ); + + const onChangeActivePendingUserInputCustomAnswer = useCallback( + ( + questionId: string, + value: string, + nextCursor: number, + expandedCursor: number, + cursorAdjacentToMention: boolean, + ) => { + if (!activePendingUserInput) { + return; + } + promptRef.current = value; + setPendingUserInputAnswersByRequestId((existing) => ({ + ...existing, + [activePendingUserInput.requestId]: { + ...existing[activePendingUserInput.requestId], + [questionId]: setPendingUserInputCustomAnswer( + existing[activePendingUserInput.requestId]?.[questionId], + value, + ), + }, + })); + setComposerCursor(nextCursor); + setComposerTrigger( + cursorAdjacentToMention ? null : detectComposerTrigger(value, expandedCursor), + ); + }, + [activePendingUserInput], + ); + + const onAdvanceActivePendingUserInput = useCallback(() => { + if (!activePendingUserInput || !activePendingProgress) { + return; + } + if (activePendingProgress.isLastQuestion) { + if (activePendingResolvedAnswers) { + void onRespondToUserInput(activePendingUserInput.requestId, activePendingResolvedAnswers); + } + return; + } + setActivePendingUserInputQuestionIndex(activePendingProgress.questionIndex + 1); + }, [ + activePendingProgress, + activePendingResolvedAnswers, + activePendingUserInput, + onRespondToUserInput, + setActivePendingUserInputQuestionIndex, + ]); + + const onPreviousActivePendingUserInputQuestion = useCallback(() => { + if (!activePendingProgress) { + return; + } + setActivePendingUserInputQuestionIndex(Math.max(activePendingProgress.questionIndex - 1, 0)); + }, [activePendingProgress, setActivePendingUserInputQuestionIndex]); + + const onSubmitPlanFollowUp = useCallback( + async ({ + text, + interactionMode: nextInteractionMode, + }: { + text: string; + interactionMode: "default" | "plan"; + }) => { + const api = readNativeApi(); + if ( + !api || + !activeThread || + !isServerThread || + isSendBusy || + isConnecting || + sendInFlightRef.current + ) { + return; + } + + const trimmed = text.trim(); + if (!trimmed) { + return; + } + + const threadIdForSend = activeThread.id; + const messageIdForSend = newMessageId(); + const messageCreatedAt = new Date().toISOString(); + const outgoingMessageText = formatOutgoingPrompt({ + provider: selectedProvider, + model: selectedModel, + models: selectedProviderModels, + effort: selectedPromptEffort, + text: trimmed, + }); + + sendInFlightRef.current = true; + beginLocalDispatch({ preparingWorktree: false }); + setThreadError(threadIdForSend, null); + setOptimisticUserMessages((existing) => [ + ...existing, + { + id: messageIdForSend, + role: "user", + text: outgoingMessageText, + createdAt: messageCreatedAt, + streaming: false, + }, + ]); + shouldAutoScrollRef.current = true; + forceStickToBottom(); + + try { + await persistThreadSettingsForNextTurn({ + threadId: threadIdForSend, + createdAt: messageCreatedAt, + modelSelection: selectedModelSelection, + runtimeMode, + interactionMode: nextInteractionMode, + }); + + // Keep the mode toggle and plan-follow-up banner in sync immediately + // while the same-thread implementation turn is starting. + setComposerDraftInteractionMode(threadIdForSend, nextInteractionMode); + + await api.orchestration.dispatchCommand({ + type: "thread.turn.start", + commandId: newCommandId(), + threadId: threadIdForSend, + message: { + messageId: messageIdForSend, + role: "user", + text: outgoingMessageText, + attachments: [], + }, + modelSelection: selectedModelSelection, + titleSeed: activeThread.title, + runtimeMode, + interactionMode: nextInteractionMode, + ...(nextInteractionMode === "default" && activeProposedPlan + ? { + sourceProposedPlan: { + threadId: activeThread.id, + planId: activeProposedPlan.id, + }, + } + : {}), + createdAt: messageCreatedAt, + }); + // Optimistically open the plan sidebar when implementing (not refining). + // "default" mode here means the agent is executing the plan, which produces + // step-tracking activities that the sidebar will display. + if (nextInteractionMode === "default") { + planSidebarDismissedForTurnRef.current = null; + setPlanSidebarOpen(true); + } + sendInFlightRef.current = false; + } catch (err) { + setOptimisticUserMessages((existing) => + existing.filter((message) => message.id !== messageIdForSend), + ); + setThreadError( + threadIdForSend, + err instanceof Error ? err.message : "Failed to send plan follow-up.", + ); + sendInFlightRef.current = false; + resetLocalDispatch(); } }, - [activeSessionId, activeThreadId, api, dispatch], + [ + activeThread, + activeProposedPlan, + beginLocalDispatch, + forceStickToBottom, + isConnecting, + isSendBusy, + isServerThread, + persistThreadSettingsForNextTurn, + resetLocalDispatch, + runtimeMode, + selectedPromptEffort, + selectedModelSelection, + selectedProvider, + selectedProviderModels, + setComposerDraftInteractionMode, + setThreadError, + selectedModel, + ], ); - const onModelSelect = useCallback( - (model: ModelSlug) => { - if (!activeThread) return; - dispatch({ - type: "SET_THREAD_MODEL", - threadId: activeThread.id, - model: resolveModelSlug(model), - }); - scheduleComposerFocus(); - }, - [activeThread, dispatch, scheduleComposerFocus], - ); - const onEffortSelect = useCallback( - (effort: ReasoningEffort) => { - setSelectedEffort(effort); - scheduleComposerFocus(); - }, - [scheduleComposerFocus], - ); - const onEnvModeChange = useCallback( - (mode: "local" | "worktree") => { - setEnvMode(mode); - scheduleComposerFocus(); - }, - [scheduleComposerFocus], - ); - - const onKeyDown = (e: KeyboardEvent) => { - if (e.key === "Enter" && !e.shiftKey) { - e.preventDefault(); - void onSend(e as unknown as FormEvent); + const onImplementPlanInNewThread = useCallback(async () => { + const api = readNativeApi(); + if ( + !api || + !activeThread || + !activeProject || + !activeProposedPlan || + !isServerThread || + isSendBusy || + isConnecting || + sendInFlightRef.current + ) { + return; } + + const createdAt = new Date().toISOString(); + const nextThreadId = newThreadId(); + const planMarkdown = activeProposedPlan.planMarkdown; + const implementationPrompt = buildPlanImplementationPrompt(planMarkdown); + const outgoingImplementationPrompt = formatOutgoingPrompt({ + provider: selectedProvider, + model: selectedModel, + models: selectedProviderModels, + effort: selectedPromptEffort, + text: implementationPrompt, + }); + const nextThreadTitle = truncate(buildPlanImplementationThreadTitle(planMarkdown)); + const nextThreadModelSelection: ModelSelection = selectedModelSelection; + + sendInFlightRef.current = true; + beginLocalDispatch({ preparingWorktree: false }); + const finish = () => { + sendInFlightRef.current = false; + resetLocalDispatch(); + }; + + await api.orchestration + .dispatchCommand({ + type: "thread.create", + commandId: newCommandId(), + threadId: nextThreadId, + projectId: activeProject.id, + title: nextThreadTitle, + modelSelection: nextThreadModelSelection, + runtimeMode, + interactionMode: "default", + branch: activeThread.branch, + worktreePath: activeThread.worktreePath, + createdAt, + }) + .then(() => { + return api.orchestration.dispatchCommand({ + type: "thread.turn.start", + commandId: newCommandId(), + threadId: nextThreadId, + message: { + messageId: newMessageId(), + role: "user", + text: outgoingImplementationPrompt, + attachments: [], + }, + modelSelection: selectedModelSelection, + titleSeed: nextThreadTitle, + runtimeMode, + interactionMode: "default", + sourceProposedPlan: { + threadId: activeThread.id, + planId: activeProposedPlan.id, + }, + createdAt, + }); + }) + .then(() => { + return waitForStartedServerThread(nextThreadId); + }) + .then(() => { + // Signal that the plan sidebar should open on the new thread. + planSidebarOpenOnNextThreadRef.current = true; + return navigate({ + to: "/$threadId", + params: { threadId: nextThreadId }, + }); + }) + .catch(async (err) => { + await api.orchestration + .dispatchCommand({ + type: "thread.delete", + commandId: newCommandId(), + threadId: nextThreadId, + }) + .catch(() => undefined); + toastManager.add({ + type: "error", + title: "Could not start implementation thread", + description: + err instanceof Error ? err.message : "An error occurred while creating the new thread.", + }); + }) + .then(finish, finish); + }, [ + activeProject, + activeProposedPlan, + activeThread, + beginLocalDispatch, + isConnecting, + isSendBusy, + isServerThread, + navigate, + resetLocalDispatch, + runtimeMode, + selectedPromptEffort, + selectedModelSelection, + selectedProvider, + selectedProviderModels, + selectedModel, + ]); + + const onProviderModelSelect = useCallback( + (provider: ProviderKind, model: string) => { + if (!activeThread) return; + if (lockedProvider !== null && provider !== lockedProvider) { + scheduleComposerFocus(); + return; + } + const resolvedProvider = resolveSelectableProvider(providerStatuses, provider); + const resolvedModel = resolveAppModelSelection( + resolvedProvider, + settings, + providerStatuses, + model, + ); + const nextModelSelection: ModelSelection = { + provider: resolvedProvider, + model: resolvedModel, + }; + setComposerDraftModelSelection(activeThread.id, nextModelSelection); + setStickyComposerModelSelection(nextModelSelection); + scheduleComposerFocus(); + }, + [ + activeThread, + lockedProvider, + scheduleComposerFocus, + setComposerDraftModelSelection, + setStickyComposerModelSelection, + providerStatuses, + settings, + ], + ); + const setPromptFromTraits = useCallback( + (nextPrompt: string) => { + const currentPrompt = promptRef.current; + if (nextPrompt === currentPrompt) { + scheduleComposerFocus(); + return; + } + promptRef.current = nextPrompt; + setPrompt(nextPrompt); + const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length); + setComposerCursor(nextCursor); + setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length)); + scheduleComposerFocus(); + }, + [scheduleComposerFocus, setPrompt], + ); + const providerTraitsMenuContent = renderProviderTraitsMenuContent({ + provider: selectedProvider, + threadId, + model: selectedModel, + models: selectedProviderModels, + modelOptions: composerModelOptions?.[selectedProvider], + prompt, + onPromptChange: setPromptFromTraits, + }); + const providerTraitsPicker = renderProviderTraitsPicker({ + provider: selectedProvider, + threadId, + model: selectedModel, + models: selectedProviderModels, + modelOptions: composerModelOptions?.[selectedProvider], + prompt, + onPromptChange: setPromptFromTraits, + }); + const onEnvModeChange = useCallback( + (mode: DraftThreadEnvMode) => { + if (isLocalDraftThread) { + setDraftThreadContext(threadId, { envMode: mode }); + } + scheduleComposerFocus(); + }, + [isLocalDraftThread, scheduleComposerFocus, setDraftThreadContext, threadId], + ); + + const applyPromptReplacement = useCallback( + ( + rangeStart: number, + rangeEnd: number, + replacement: string, + options?: { expectedText?: string }, + ): boolean => { + const currentText = promptRef.current; + const safeStart = Math.max(0, Math.min(currentText.length, rangeStart)); + const safeEnd = Math.max(safeStart, Math.min(currentText.length, rangeEnd)); + if ( + options?.expectedText !== undefined && + currentText.slice(safeStart, safeEnd) !== options.expectedText + ) { + return false; + } + const next = replaceTextRange(promptRef.current, rangeStart, rangeEnd, replacement); + const nextCursor = collapseExpandedComposerCursor(next.text, next.cursor); + promptRef.current = next.text; + const activePendingQuestion = activePendingProgress?.activeQuestion; + if (activePendingQuestion && activePendingUserInput) { + setPendingUserInputAnswersByRequestId((existing) => ({ + ...existing, + [activePendingUserInput.requestId]: { + ...existing[activePendingUserInput.requestId], + [activePendingQuestion.id]: setPendingUserInputCustomAnswer( + existing[activePendingUserInput.requestId]?.[activePendingQuestion.id], + next.text, + ), + }, + })); + } else { + setPrompt(next.text); + } + setComposerCursor(nextCursor); + setComposerTrigger( + detectComposerTrigger(next.text, expandCollapsedComposerCursor(next.text, nextCursor)), + ); + window.requestAnimationFrame(() => { + composerEditorRef.current?.focusAt(nextCursor); + }); + return true; + }, + [activePendingProgress?.activeQuestion, activePendingUserInput, setPrompt], + ); + + const readComposerSnapshot = useCallback((): { + value: string; + cursor: number; + expandedCursor: number; + terminalContextIds: string[]; + } => { + const editorSnapshot = composerEditorRef.current?.readSnapshot(); + if (editorSnapshot) { + return editorSnapshot; + } + return { + value: promptRef.current, + cursor: composerCursor, + expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor), + terminalContextIds: composerTerminalContexts.map((context) => context.id), + }; + }, [composerCursor, composerTerminalContexts]); + + const resolveActiveComposerTrigger = useCallback((): { + snapshot: { value: string; cursor: number; expandedCursor: number }; + trigger: ComposerTrigger | null; + } => { + const snapshot = readComposerSnapshot(); + return { + snapshot, + trigger: detectComposerTrigger(snapshot.value, snapshot.expandedCursor), + }; + }, [readComposerSnapshot]); + + const onSelectComposerItem = useCallback( + (item: ComposerCommandItem) => { + if (composerSelectLockRef.current) return; + composerSelectLockRef.current = true; + window.requestAnimationFrame(() => { + composerSelectLockRef.current = false; + }); + const { snapshot, trigger } = resolveActiveComposerTrigger(); + if (!trigger) return; + if (item.type === "path") { + const replacement = `@${item.path} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement( + trigger.rangeStart, + replacementRangeEnd, + replacement, + { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, + ); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } + if (item.type === "slash-command") { + if (item.command === "model") { + const replacement = "/model "; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement( + trigger.rangeStart, + replacementRangeEnd, + replacement, + { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, + ); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } + void handleInteractionModeChange(item.command === "plan" ? "plan" : "default"); + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), + }); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } + onProviderModelSelect(item.provider, item.model); + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), + }); + if (applied) { + setComposerHighlightedItemId(null); + } + }, + [ + applyPromptReplacement, + handleInteractionModeChange, + onProviderModelSelect, + resolveActiveComposerTrigger, + ], + ); + const onComposerMenuItemHighlighted = useCallback((itemId: string | null) => { + setComposerHighlightedItemId(itemId); + }, []); + const nudgeComposerMenuHighlight = useCallback( + (key: "ArrowDown" | "ArrowUp") => { + if (composerMenuItems.length === 0) { + return; + } + const highlightedIndex = composerMenuItems.findIndex( + (item) => item.id === composerHighlightedItemId, + ); + const normalizedIndex = + highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0; + const offset = key === "ArrowDown" ? 1 : -1; + const nextIndex = + (normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length; + const nextItem = composerMenuItems[nextIndex]; + setComposerHighlightedItemId(nextItem?.id ?? null); + }, + [composerHighlightedItemId, composerMenuItems], + ); + const isComposerMenuLoading = + composerTriggerKind === "path" && + ((pathTriggerQuery.length > 0 && composerPathQueryDebouncer.state.isPending) || + workspaceEntriesQuery.isLoading || + workspaceEntriesQuery.isFetching); + + const onPromptChange = useCallback( + ( + nextPrompt: string, + nextCursor: number, + expandedCursor: number, + cursorAdjacentToMention: boolean, + terminalContextIds: string[], + ) => { + if (activePendingProgress?.activeQuestion && activePendingUserInput) { + onChangeActivePendingUserInputCustomAnswer( + activePendingProgress.activeQuestion.id, + nextPrompt, + nextCursor, + expandedCursor, + cursorAdjacentToMention, + ); + return; + } + promptRef.current = nextPrompt; + setPrompt(nextPrompt); + if (!terminalContextIdListsEqual(composerTerminalContexts, terminalContextIds)) { + setComposerDraftTerminalContexts( + threadId, + syncTerminalContextsByIds(composerTerminalContexts, terminalContextIds), + ); + } + setComposerCursor(nextCursor); + setComposerTrigger( + cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor), + ); + }, + [ + activePendingProgress?.activeQuestion, + activePendingUserInput, + composerTerminalContexts, + onChangeActivePendingUserInputCustomAnswer, + setPrompt, + setComposerDraftTerminalContexts, + threadId, + ], + ); + + const onComposerCommandKey = ( + key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab", + event: KeyboardEvent, + ) => { + if (key === "Tab" && event.shiftKey) { + toggleInteractionMode(); + return true; + } + + const { trigger } = resolveActiveComposerTrigger(); + const menuIsActive = composerMenuOpenRef.current || trigger !== null; + + if (menuIsActive) { + const currentItems = composerMenuItemsRef.current; + if (key === "ArrowDown" && currentItems.length > 0) { + nudgeComposerMenuHighlight("ArrowDown"); + return true; + } + if (key === "ArrowUp" && currentItems.length > 0) { + nudgeComposerMenuHighlight("ArrowUp"); + return true; + } + if (key === "Tab" || key === "Enter") { + const selectedItem = activeComposerMenuItemRef.current ?? currentItems[0]; + if (selectedItem) { + onSelectComposerItem(selectedItem); + return true; + } + } + } + + if (key === "Enter" && !event.shiftKey) { + void onSend(); + return true; + } + return false; }; const onToggleWorkGroup = useCallback((groupId: string) => { setExpandedWorkGroups((existing) => ({ @@ -959,17 +3864,45 @@ export default function ChatView() { [groupId]: !existing[groupId], })); }, []); - const onExpandTimelineImage = useCallback((image: ExpandedImagePreview) => { - setExpandedImage(image); + const onExpandTimelineImage = useCallback((preview: ExpandedImagePreview) => { + setExpandedImage(preview); }, []); - const onToggleDiff = useCallback(() => { - dispatch({ type: "TOGGLE_DIFF" }); - }, [dispatch]); + const expandedImageItem = expandedImage ? expandedImage.images[expandedImage.index] : null; + const onOpenTurnDiff = useCallback( + (turnId: TurnId, filePath?: string) => { + void navigate({ + to: "/$threadId", + params: { threadId }, + search: (previous) => { + const rest = stripDiffSearchParams(previous); + return filePath + ? { ...rest, diff: "1", diffTurnId: turnId, diffFilePath: filePath } + : { ...rest, diff: "1", diffTurnId: turnId }; + }, + }); + }, + [navigate, threadId], + ); + const onRevertUserMessage = (messageId: MessageId) => { + const targetTurnCount = revertTurnCountByUserMessageId.get(messageId); + if (typeof targetTurnCount !== "number") { + return; + } + void onRevertToTurnCount(targetTurnCount); + }; // Empty state: no active thread if (!activeThread) { return ( -
+
+ {!isElectron && ( +
+
+ + Threads +
+
+ )} {isElectron && (
No active thread @@ -985,785 +3918,624 @@ export default function ChatView() { } return ( -
+
{/* Top bar */}
{ + void runProjectScript(script); + }} + onAddProjectScript={saveProjectScript} + onUpdateProjectScript={updateProjectScript} + onDeleteProjectScript={deleteProjectScript} + onToggleTerminal={toggleTerminalVisibility} onToggleDiff={onToggleDiff} />
{/* Error banner */} - - + setThreadError(activeThread.id, null)} /> - - {/* Messages */} -
- 0} - isWorking={isWorking} - timelineEntries={timelineEntries} - completionDividerBeforeEntryId={completionDividerBeforeEntryId} - completionSummary={completionSummary} - assistantCompletionByItemId={assistantCompletionByItemId} - nowIso={nowIso} - expandedWorkGroups={expandedWorkGroups} - onToggleWorkGroup={onToggleWorkGroup} - onImageExpand={onExpandTimelineImage} - messagesEndRef={messagesEndRef} - /> -
- - {/* Input bar */} -
-
-
- {/* Textarea area */} -
- {composerImages.length > 0 && ( -
- {composerImages.map((image) => ( -
- {image.previewUrl ? ( - {image.name} - setExpandedImage({ src: image.previewUrl, name: image.name }) - } - /> - ) : ( -
- {image.name} -
- )} - -
- ))} -
- )} -