Compare commits

..
18 Commits
Author SHA1 Message Date
Julius Marminge 0d4a38f079 kewl 2026-02-14 23:33:58 -08:00
Julius Marminge f3b65dbedf Polish action button icons and hover tooltips
- Standardize quick action icon sizing and label spacing in chat and git controls
- Replace manual popover hover state handling with `openOnHover` triggers
- Add reusable terminal action button wrapper with hover tooltips for split/new/close controls
2026-02-14 23:31:20 -08:00
Julius Marminge 38667d323c Add inline branch creation to branch picker search
- let users create a new local branch directly from the branch combobox search
- remove separate "New branch" form/button flow in `BranchToolbar`
- add `inputClassName` support to `ComboboxInput` for native input styling control
2026-02-14 23:20:45 -08:00
Julius Marminge e829f971ce Use action maps for Git dialog title and description
- Replace nested conditional strings with action-to-copy lookup objects
- Keep commit/push/create PR dialog text centralized and easier to maintain
2026-02-14 23:08:05 -08:00
Julius Marminge 37cd7be09b Close git action toast before triggering follow-up action
- Dismiss the success toast before handling Push/Open PR/Create PR CTA clicks
- Prevent stale result toasts from lingering while starting the next git action
2026-02-14 23:04:34 -08:00
Julius Marminge aa6412c3ba Keep git action success toast visible until dismissed
- set success toast timeout in `GitActionsControl` from `5_000` to `0`
- keeps post-action feedback and push CTA available until user closes it
2026-02-14 23:02:58 -08:00
Julius Marminge 04d86b0559 Skip commit progress stages when no files changed
- Only include commit-related progress steps for stacked actions when there are working tree changes
- Prevents showing "Generating commit message"/"Committing" during pure push or PR flows
2026-02-14 23:02:37 -08:00
Julius Marminge d4447da322 Streamline git action flow and improve changed-files dialog
- Trigger `commit_push` directly from primary Push actions
- Simplify push confirmation copy and dialog descriptions
- Replace 6-file cap with a scrollable full changed-files list plus totals
2026-02-14 23:00:53 -08:00
Julius Marminge 2512721b13 fmt 2026-02-14 22:54:58 -08:00
Julius Marminge 07d5dc1f25 kewl 2026-02-14 22:49:16 -08:00
Julius Marminge 3125dd80a7 Reduce git action success toast duration
- Shorten success notification timeout in `GitActionsControl` from 10s to 5s
2026-02-14 22:47:21 -08:00
Julius Marminge 25579c9942 Prefer upstream branch in push result summary
- show push target as `origin/<branch>` when available
- update summarizeGitResult test expectation accordingly
2026-02-14 22:44:22 -08:00
Julius Marminge 5caae992e3 Refine git action success toasts with contextual summaries
- replace generic success text with action-specific toast titles/descriptions
- include short SHA/branch details for push and commit outcomes
- add tests for PR/commit/push summaries and description truncation
2026-02-14 22:43:27 -08:00
Julius Marminge beb9201f5d Fix disabled git action tooltip hover handling
- Use the quick action button itself as the popover trigger
- Keep hover tooltips working on disabled controls via pointer-events override
- Remove focus/blur tab-stop handlers from disabled tooltip wrappers
2026-02-14 22:38:54 -08:00
Julius Marminge c129be5e21 Improve git status details and streamline quick action flows
- add working-tree file/line stats to git status contracts, server responses, and tests
- refactor web git queries/mutations into shared React Query helpers
- update git quick-action logic/UI to prefer commit/push/PR flows and clearer disabled states
- hide branch toolbar for non-repos and tighten related chat/toolbar behavior
2026-02-14 22:36:16 -08:00
Julius Marminge 5aaae6cb60 git actions 2026-02-14 21:40:42 -08:00
Julius Marminge 8b94f007f2 Use outline styling for Git action buttons
- Change primary Git action button from ghost to outline
- Update Git action options trigger button to outline for consistent affordance
2026-02-14 10:17:14 -08:00
Julius Marminge 80ce01b8e6 Adopt Base UI components and improve editor open behavior
- migrate web UI to shared Base UI primitives (alerts, buttons, combobox, toast, etc.)
- refactor chat and branch toolbars to use new components and cleaner interactions
- add cross-platform file-manager fallback in `openInEditor` server handling
- update model contracts/tests and web dependencies to support new UI flow
2026-02-14 10:16:31 -08:00
459 changed files with 11882 additions and 92451 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
---
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
```
@@ -0,0 +1,3 @@
interface:
display_name: "BTCA CLI"
short_description: "Help with BTCA CLI setup and usage workflows"
-143
View File
@@ -1,143 +0,0 @@
# Architecture
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ 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
-6
View File
@@ -1,6 +0,0 @@
# CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
-5
View File
@@ -1,5 +0,0 @@
# Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
-180
View File
@@ -1,180 +0,0 @@
# 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
-30
View File
@@ -1,30 +0,0 @@
# Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: 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.
-22
View File
@@ -1,22 +0,0 @@
# Quick start
```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
# Build a shareable macOS .dmg (arm64 by default)
bun run dist:desktop:dmg
# Or from any project directory after publishing:
npx t3
```
-6
View File
@@ -1,6 +0,0 @@
# Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
-42
View File
@@ -1,42 +0,0 @@
# Scripts
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
## Desktop `.dmg` packaging notes
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
## Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
-7
View File
@@ -1,7 +0,0 @@
# Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared 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.
-28
View File
@@ -1,28 +0,0 @@
# 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:nmggithub
github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
-33
View File
@@ -1,33 +0,0 @@
<!--
⚠️ READ BEFORE OPENING ⚠️
We are not actively accepting contributions right now.
You can still open a PR, but please do so knowing there is a high chance
we may close it without merging it, or never review it.
- Small, focused PRs are strongly preferred. Bug fixes are most likely to be merged.
- New features will most likely just annoy us.
- 1,000+ line PRs with a bunch of new features will probably get you banned from the repo.
-->
## What Changed
<!-- Describe the change clearly and keep scope tight. -->
## Why
<!-- Explain the problem being solved and why this approach is the right one. -->
## UI Changes
<!-- If this PR changes UI, include clear before/after screenshots.
If the change involves motion or interaction, include a short video.
Delete this section if not applicable. -->
## 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
+3 -44
View File
@@ -8,8 +8,8 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
name: Lint, Typecheck, Test, Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -17,12 +17,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
bun-version: 1.3.9
- name: Cache Bun and Turbo
uses: actions/cache@v4
@@ -34,14 +29,6 @@ jobs:
restore-keys: |
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v4
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
@@ -54,14 +41,6 @@ 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
@@ -69,23 +48,3 @@ 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@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
-175
View File
@@ -1,175 +0,0 @@
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@v7
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@v7
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 = 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;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
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,
});
const preservedLabels = currentLabels
.map((label) => label.name)
.filter((name) => !managedLabelNames.includes(name));
await github.rest.issues.setLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [...preservedLabels, nextLabelName],
});
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
-351
View File
@@ -1,351 +0,0 @@
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@v4
- 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@v4
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@v4
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@v4
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- 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@v4
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@v4
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@v4
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: bun install --frozen-lockfile
- 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@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Download all desktop artifacts
uses: actions/download-artifact@v4
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:
- name: Checkout
uses: actions/checkout@v4
with:
ref: main
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@v4
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 "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
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
-6
View File
@@ -5,14 +5,8 @@ node_modules
*.log
*.tsbuildinfo
apps/*/dist
.astro
packages/*/dist
.env
.env.local
build/
.logs/
release/
.t3
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
-3
View File
@@ -1,3 +0,0 @@
[tools]
node = "24.13.1"
bun = "1.3.9"
+1 -2
View File
@@ -6,8 +6,7 @@
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
"*.tsbuildinfo"
],
"experimentalSortPackageJson": {}
}
+2 -11
View File
@@ -1,13 +1,6 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
],
"ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
"correctness": "warn",
@@ -15,8 +8,6 @@
"perf": "warn"
},
"rules": {
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
"react-in-jsx-scope": "off"
}
}
-42
View File
@@ -1,42 +0,0 @@
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.
-58
View File
@@ -1,58 +0,0 @@
# 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.
@@ -1,110 +0,0 @@
# 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<ProviderAdapterError>`.
- 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.
@@ -1,215 +0,0 @@
# 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.
-10
View File
@@ -1,10 +0,0 @@
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)
- ...
-145
View File
@@ -1,145 +0,0 @@
# 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.
-477
View File
@@ -1,477 +0,0 @@
# 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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")`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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 === ''`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- 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.
@@ -1,88 +0,0 @@
# 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.
## Key Changes
### 1. Strengthen the generic boundaries, not the Codex boundary
- Keep `ProviderRuntimeEvent` as the canonical provider event contract and `ProviderService` as the only cross-provider facade.
- Do not expose raw Codex payloads or Codex event ordering outside `CodexAdapter.ts` and `codexAppServerManager.ts`.
- Do not expand `ProviderKind` in this change. The runtime stays provider-neutral by contract, while the product remains Codex-only in concrete support.
### 2. Replace loose websocket envelopes with channel-indexed typed pushes
- Refactor `packages/contracts/src/ws.ts` so push messages are derived from a channel-to-schema map instead of `channel: string` plus `data: unknown`.
- Add `sequence: number` to every server push. Ordering becomes explicit and testable.
- Add structured decode diagnostics with stable machine fields: `code`, `reason`, `expected`, `actual`, `path`, optional `jsonOffset`.
- Remove runtime/test dependence on engine-specific pretty strings. Human-readable formatting remains a logging helper only.
### 3. Introduce explicit server readiness and a single push pipeline
- Add a `ServerPushBus` service in `apps/server` backed by one ordered queue/pubsub path. All pushes go through it: `server.welcome`, `server.configUpdated`, terminal events, orchestration domain events.
- Add a `ServerReadiness` service with explicit barriers for:
- HTTP listening
- push bus ready
- keybindings runtime ready
- terminal subscriptions ready
- orchestration subscriptions ready
- Strengthen `server.welcome` semantics: it is emitted only after connection-scoped and server-scoped readiness is complete.
- `wsServer` should never publish directly from ad hoc background streams once the bus exists.
### 4. Turn background watchers into explicit runtimes
- Extract keybindings watching into a `KeybindingsRuntime` service with `start`, `ready`, `snapshot`, and `changes`.
- Initial config load, startup sync, cache warmup, and watcher attachment complete before `ready` resolves.
- Keep the real `fs.watch` adapter thin. Most behavior tests use a fake watch source and deterministic change stream.
### 5. Replace polling-based orchestration waiting with receipts
- Add server-owned completion receipts for operations that tests currently infer by polling:
- checkpoint capture complete
- checkpoint diff finalized
- turn processing quiesced
- A receipt means append, projection, and required side effects are complete. It must not mean the provider emitted a certain event sequence.
- Update the orchestration harness and checkpoint tests to await receipts/barriers instead of polling snapshots and git refs.
### 6. Centralize client transport state and decoding
- Refactor `apps/web/src/wsTransport.ts` into an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Decode and validate typed push payloads at the transport boundary, not downstream in `apps/web/src/wsNativeApi.ts`.
- Keep cached latest welcome/config behavior only if it is modeled as explicit state, not as a late-subscriber race workaround.
### 7. Replace ad hoc test helpers with semantic test clients
- Add a shared `WsTestClient` for server/websocket tests:
- connect
- await semantic welcome
- await typed push by channel and optional predicate
- track `sequence`
- match RPC responses by id
- Add one orchestration test harness that waits on receipts/barriers instead of custom `waitForThread`, `waitForGitRef`, and arbitrary retry loops.
- Keep only a narrow set of integration tests for real filesystem/watch/socket behavior. Move behavioral assertions to deterministic unit-style harnesses.
## 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.
-201
View File
@@ -1,201 +0,0 @@
# 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.
-401
View File
@@ -1,401 +0,0 @@
# 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`.
+1 -2
View File
@@ -4,6 +4,5 @@
"editor.codeActionsOnSave": {
"source.fixAll.oxc": "always"
},
"oxc.unusedDisableDirectives": "warn",
"typescript.tsdk": "node_modules/typescript/lib"
"oxc.unusedDisableDirectives": "warn"
}
+3 -13
View File
@@ -1,9 +1,4 @@
# AGENTS.md
## Task Completion Requirements
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
# CLAUDE.md
## Project Snapshot
@@ -19,16 +14,11 @@ 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 are shared logic that can be extracted to a separate module. Duplicate logic across mulitple 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 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.
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Codex App Server (Important)
@@ -39,7 +29,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 orchestration domain events via WebSocket push on channel `orchestration.domainEvent` (provider runtime activity is projected into orchestration events server-side).
- Web app consumes provider event streams via WebSocket push on channel `providers.event`.
Docs:
-65
View File
@@ -1,65 +0,0 @@
# 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.
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.
-101
View File
@@ -1,101 +0,0 @@
# Keybindings
T3 Code reads keybindings from:
- `~/.t3/keybindings.json`
The file must be a JSON array of rules:
```json
[
{ "key": "mod+g", "command": "terminal.toggle" },
{ "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" }
]
```
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
## Defaults
```json
[
{ "key": "mod+j", "command": "terminal.toggle" },
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
{ "key": "mod+o", "command": "editor.openFavorite" }
]
```
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
## Configuration
### Rule Shape
Each entry supports:
- `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d`
- `command` (required): action ID
- `when` (optional): boolean expression controlling when the shortcut is active
Invalid rules are ignored. Invalid config files are ignored. Warnings are logged by the server.
### Available Commands
- `terminal.toggle`: open/close terminal drawer
- `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `editor.openFavorite`: open current project/worktree in the last-used editor
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
### Key Syntax
Supported modifiers:
- `mod` (`cmd` on macOS, `ctrl` on non-macOS)
- `cmd` / `meta`
- `ctrl` / `control`
- `shift`
- `alt` / `option`
Examples:
- `mod+j`
- `mod+shift+d`
- `ctrl+l`
- `cmd+k`
### `when` Conditions
Currently available context keys:
- `terminalFocus`
- `terminalOpen`
Supported operators:
- `!` (not)
- `&&` (and)
- `||` (or)
- parentheses: `(` `)`
Examples:
- `"when": "terminalFocus"`
- `"when": "terminalOpen && !terminalFocus"`
- `"when": "terminalFocus || terminalOpen"`
Unknown condition keys evaluate to `false`.
### Precedence
- Rules are evaluated in array order.
- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
- That means precedence is across commands, not only within the same command.
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 T3 Tools Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+90 -11
View File
@@ -2,27 +2,106 @@
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
## How to use
Run `npx t3` in any project directory to launch the web interface.
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
> [!WARNING]
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
## Architecture
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
```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
```
You can also just install the desktop app. It's cooler.
## Scripts
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
- `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.
## Some notes
### Running multiple dev instances
We are very very early in this project. Expect bugs.
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
We are not accepting contributions yet.
- 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`
## If you REALLY want to contribute still.... read this first
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
## Runtime modes
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
T3 Code has a global runtime mode switch in the chat toolbar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
## Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for streaming provider events
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
## CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
-65
View File
@@ -1,65 +0,0 @@
# 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 <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
> 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.
- 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://<your-machine-ip>: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://<tailnet-ip>: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.
+11 -1
View File
@@ -2,12 +2,22 @@
## Small things
- [ ] Submitting new messages should scroll to bottom
- [ ] 1 click copy in codeblocks
- [x] Pasting/adding images to submit with prompts
- [ ] Only show last 10 threads for a given project
- [ ] Thread archiving
- [x] Selecting folder should instantly create project
- [ ] New projects should go on top
- [ ] Projects should be sorted by latest thread update
- [x] "Response" bar should ONLY appear on work completed
- [x] "Response" bar should ONLY appear above the FINAL message in a series
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
- [ ] 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)
-1
View File
@@ -1,2 +1 @@
dist-electron/
.electron-runtime/
+9 -13
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.9",
"version": "0.0.0",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
@@ -8,24 +8,20 @@
"dev:bundle": "tsdown --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "tsdown",
"start": "bun run scripts/start-electron.mjs",
"start": "electron dist-electron/main.js",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"effect": "catalog:",
"electron": "40.6.0",
"electron-updater": "^6.6.2"
"electron": "33.4.11"
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
"@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"
},
"productName": "T3 Code (Alpha)"
}
}
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 313 KiB

+19 -195
View File
@@ -1,207 +1,31 @@
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import { spawn } from "node:child_process";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
const devServerUrl = `http://localhost:${port}`;
const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
await waitOn({
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
resources: [
`tcp:${port}`,
"file:dist-electron/main.js",
"file:dist-electron/preload.js",
"file:../server/dist/index.mjs",
],
});
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
let shuttingDown = false;
let restartTimer = null;
let currentApp = null;
let restartQueue = Promise.resolve();
const expectedExits = new WeakSet();
const watchers = [];
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", () => {
if (currentApp === app) {
currentApp = null;
}
if (!shuttingDown && !expectedExits.has(app)) {
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);
const child = spawn(command, ["dist-electron/main.js"], {
stdio: "inherit",
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
});
process.once("SIGTERM", () => {
void shutdown(143);
});
process.once("SIGHUP", () => {
void shutdown(129);
child.on("exit", (code) => {
process.exit(code ?? 0);
});
-144
View File
@@ -1,144 +0,0 @@
// 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);
}
-20
View File
@@ -1,20 +0,0 @@
import { spawn } from "node:child_process";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
});
child.on("exit", (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 0);
});
+5 -2
View File
@@ -1,11 +1,14 @@
import { readPathFromLoginShell } from "@t3tools/shared/shell";
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 = readPathFromLoginShell(shell);
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
encoding: "utf8",
timeout: 5000,
});
if (result) {
process.env.PATH = result;
}
+75 -1115
View File
File diff suppressed because it is too large. Load diff
+6 -36
View File
@@ -1,46 +1,16 @@
import { contextBridge, ipcRenderer } from "electron";
import type { DesktopBridge } from "@t3tools/contracts";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const 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 wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
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),
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<typeof listener>[0]);
};
ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
};
},
} satisfies DesktopBridge);
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
confirm: (message: string) => ipcRenderer.invoke(CONFIRM_CHANNEL, message) as Promise<boolean>,
showContextMenu: (items: { id: string; label: string }[]) =>
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
});
-74
View File
@@ -1,74 +0,0 @@
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);
});
});
-49
View File
@@ -1,49 +0,0 @@
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,
});
});
});
-40
View File
@@ -1,40 +0,0 @@
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";
}
-136
View File
@@ -1,136 +0,0 @@
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();
});
});
-160
View File
@@ -1,160 +0,0 @@
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,
};
}
-145
View File
@@ -1,145 +0,0 @@
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);
});
});
-48
View File
@@ -1,48 +0,0 @@
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;
}
+1 -1
View File
@@ -12,7 +12,7 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
noExternal: ["@t3tools/contracts"],
},
{
...shared,
-7
View File
@@ -1,7 +0,0 @@
import { defineConfig } from "astro/config";
export default defineConfig({
server: {
port: Number(process.env.PORT ?? 4173),
},
});
-19
View File
@@ -1,19 +0,0 @@
{
"name": "@t3tools/marketing",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"typecheck": "astro check"
},
"dependencies": {
"astro": "^5.7.13"
},
"devDependencies": {
"@astrojs/check": "^0.9.4",
"typescript": "catalog:"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 662 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 652 KiB

-433
View File
@@ -1,433 +0,0 @@
---
---
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="T3 Code — The best way to code with AI." />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>T3 Code</title>
</head>
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
</nav>
<main class="main">
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<a
id="download-btn"
href="https://github.com/pingdotgg/t3code/releases"
class="hero-button"
>
<svg class="hero-button-icon hero-button-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="hero-button-icon hero-button-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="hero-button-icon hero-button-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<span id="download-label">Download now</span>
</a>
<div class="screenshot-wrap">
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
</div>
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
</body>
</html>
<script>
const REPO = "pingdotgg/t3code";
const RELEASES_URL = `https://github.com/${REPO}/releases`;
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
type Platform = { os: "mac" | "win" | "linux"; label: string; arch?: string };
function detectPlatform(): Platform | null {
const ua = navigator.userAgent;
if (/Win/i.test(ua)) return { os: "win", label: "Download for Windows" };
if (/Mac/i.test(ua)) {
return {
os: "mac",
label: `Download for macOS`,
arch: "arm64",
};
}
if (/Linux/i.test(ua)) return { os: "linux", label: "Download for Linux" };
return null;
}
function pickAsset(
assets: Array<{ name: string; browser_download_url: string }>,
platform: Platform,
): string | null {
if (platform.os === "win") {
return (
assets.find((a) => a.name.endsWith("-x64.exe"))
?.browser_download_url ?? null
);
}
if (platform.os === "mac") {
const preferred = assets.find((a) =>
a.name.endsWith(`-${platform.arch}.dmg`),
);
const fallback = assets.find((a) => a.name.endsWith(".dmg"));
return (preferred ?? fallback)?.browser_download_url ?? null;
}
if (platform.os === "linux") {
return (
assets.find((a) => a.name.endsWith(".AppImage"))
?.browser_download_url ?? null
);
}
return null;
}
async function init() {
const btn = document.getElementById("download-btn") as HTMLAnchorElement | null;
const label = document.getElementById("download-label");
if (!btn || !label) return;
const platform = detectPlatform();
if (!platform) return;
document.documentElement.dataset.platform = platform.os;
label.textContent = platform.label;
try {
const cached = sessionStorage.getItem("t3code-latest-release");
const data = cached
? JSON.parse(cached)
: await fetch(API_URL).then((r) => r.json());
if (!cached && data?.assets) {
sessionStorage.setItem("t3code-latest-release", JSON.stringify(data));
}
const url = pickAsset(data.assets ?? [], platform);
if (url) {
btn.href = url;
btn.removeAttribute("target");
btn.removeAttribute("rel");
}
} catch {
btn.href = RELEASES_URL;
}
}
init();
</script>
<style>
:root {
--bg: #09090b;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--border: rgba(255, 255, 255, 0.08);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
color-scheme: dark;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
z-index: 9999;
}
a {
color: inherit;
text-decoration: none;
}
img {
display: block;
max-width: 100%;
}
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
}
.nav-brand {
display: flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
}
/* ── Main content ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding-top: 10vh;
}
/* ── Tagline ── */
.tagline {
font-weight: 500;
font-size: clamp(2rem, 5vw, 3.5rem);
letter-spacing: -0.035em;
line-height: 1.15;
text-align: center;
margin: 0 0 6vh;
opacity: 0;
animation: fade-in 1s ease-out forwards;
}
/* ── Hero button ── */
.hero-button {
display: inline-flex;
align-items: center;
gap: 0.55rem;
background: #fafafa;
color: #09090b;
padding: 0.75rem 2rem;
border-radius: 999px;
font-weight: 600;
font-size: 0.9rem;
margin-bottom: 5vh;
opacity: 0;
animation: fade-in 1s ease-out 0.15s forwards;
transition: transform 0.25s ease, box-shadow 0.25s ease;
}
.hero-button:hover {
transform: scale(1.03);
box-shadow: 0 0 24px rgba(255, 255, 255, 0.08);
}
.hero-button:active {
transform: scale(0.98);
}
.hero-button-icon {
display: none;
width: 1em;
height: 1em;
flex-shrink: 0;
}
:global([data-platform="mac"]) .hero-button-icon--apple {
display: block;
}
:global([data-platform="win"]) .hero-button-icon--windows {
display: block;
}
:global([data-platform="linux"]) .hero-button-icon--linux {
display: block;
}
/* ── Screenshot ── */
.screenshot-wrap {
margin: 0 auto;
width: min(95vw, 1400px);
opacity: 0;
transform: scale(0.98);
animation: screenshot-in 1s ease-out 0.15s forwards;
}
.screenshot {
width: 100%;
display: block;
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.06);
mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
-webkit-mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
}
.screenshot-wrap::after {
content: "";
display: block;
width: 100%;
height: 120px;
background: inherit;
margin-top: -1px;
opacity: 0.04;
transform: scaleY(-1);
mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
-webkit-mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
pointer-events: none;
}
/* ── Footer ── */
.footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
color: var(--fg-dim);
}
.footer-links {
display: flex;
gap: 1.25rem;
}
.footer-links a {
color: var(--fg-dim);
transition: color 0.3s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Animations ── */
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes screenshot-in {
from {
opacity: 0;
transform: scale(0.98);
}
to {
opacity: 1;
transform: scale(1);
}
}
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem 1.25rem;
}
.main {
padding-top: 7vh;
}
.tagline {
margin-bottom: 4vh;
}
.screenshot-wrap {
width: 95vw;
}
.footer {
padding: 1.25rem;
}
}
</style>
-3
View File
@@ -1,3 +0,0 @@
{
"extends": "astro/tsconfigs/strict"
}
@@ -1,499 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import {
Effect,
Exit,
Layer,
ManagedRuntime,
Option,
Ref,
Schedule,
Schema,
Scope,
Stream,
} from "effect";
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.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 { 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 { ServerConfig } from "../src/config.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
cwd,
stdio: ["ignore", "pipe", "pipe"],
encoding: "utf8",
});
}
function initializeGitWorkspace(cwd: string) {
runGit(cwd, ["init", "--initial-branch=main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
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"]);
}
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>()(
"WaitForTimeoutError",
{
description: Schema.String,
},
) {}
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs?: number,
): Effect.Effect<A, never>;
function waitFor<A, B extends A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => value is B,
description: string,
timeoutMs?: number,
): Effect.Effect<B, never>;
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 10_000,
): Effect.Effect<A, never> {
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>()(
"OrchestrationHarnessRuntimeError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
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<OrchestrationThread, never>;
readonly waitForDomainEvent: (
predicate: (event: OrchestrationEvent) => boolean,
timeoutMs?: number,
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, 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<OrchestrationRuntimeReceipt, never>;
<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
};
readonly dispose: Effect.Effect<void, never>;
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: "codex";
readonly realCodex?: boolean;
}
export const makeOrchestrationIntegrationHarness = (
options?: MakeOrchestrationIntegrationHarnessOptions,
) =>
Effect.gen(function* () {
const sleep = (ms: number) => Effect.sleep(ms);
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 = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
const workspaceDir = path.join(rootDir, "workspace");
const stateDir = path.join(rootDir, "state");
const dbPath = path.join(stateDir, "state.sqlite");
fs.mkdirSync(workspaceDir, { recursive: true });
fs.mkdirSync(stateDir, { recursive: true });
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, stateDir)),
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 runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
CheckpointStoreLive,
providerLayer,
RuntimeReceiptBusLive,
);
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
);
const gitCoreLayer = Layer.succeed(GitCore, {
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
} as unknown as GitCoreShape);
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: null }),
} as unknown as TextGenerationShape);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(textGenerationLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
);
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
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<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* 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<OrchestrationThread, never>;
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
predicate,
timeoutMs,
) =>
waitFor(
Stream.runCollect(engine.readEvents(0)).pipe(
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => 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<OrchestrationRuntimeReceipt, never>;
function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
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.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
),
);
});
return {
rootDir,
workspaceDir,
dbPath,
adapterHarness,
engine,
snapshotQuery,
providerService,
checkpointStore,
checkpointRepository,
pendingApprovalRepository,
waitForThread,
waitForDomainEvent,
waitForPendingApproval,
waitForReceipt,
dispose,
} satisfies OrchestrationIntegrationHarness;
});
@@ -1,561 +0,0 @@
import { randomUUID } from "node:crypto";
import {
ApprovalRequestId,
EventId,
ProviderApprovalDecision,
ProviderRuntimeEvent,
RuntimeSessionId,
ProviderSession,
ProviderTurnStartResult,
ThreadId,
TurnId,
} 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<FixtureProviderRuntimeEvent>;
readonly mutateWorkspace?: (input: {
readonly cwd: string;
readonly turnCount: number;
}) => Effect.Effect<void, never>;
}
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
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<TestTurnResponse>;
readonly rollbackCalls: Array<number>;
}
function isRecord(value: unknown): value is Record<string, unknown> {
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<string, unknown>): 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<ProviderAdapterError>;
readonly provider: "codex";
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
readonly queueTurnResponseForNextSession: (
response: TestTurnResponse,
) => Effect.Effect<void, never>;
readonly getStartCount: () => number;
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
readonly listActiveSessionIds: () => ReadonlyArray<ThreadId>;
readonly getApprovalResponses: (threadId: ThreadId) => ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}>;
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: "codex";
}
function nowIso(): string {
return new Date().toISOString();
}
function sessionNotFound(
provider: "codex",
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
provider,
threadId: String(threadId),
});
}
function missingSessionEffect(
provider: "codex",
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
}
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
Effect.gen(function* () {
const provider = options?.provider ?? "codex";
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
const sessions = new Map<ThreadId, SessionState>();
const queuedResponsesForNextSession: TestTurnResponse[] = [];
const interruptCallsBySession = new Map<ThreadId, Array<TurnId | undefined>>();
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<ProviderAdapterError>["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<ProviderAdapterError>["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<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
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<unknown> =
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<ProviderAdapterError>["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<ProviderAdapterError>["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<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["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<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
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<void, ProviderAdapterSessionNotFoundError> =>
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<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
const getStartCount = (): number => sessionCount;
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
const calls = interruptCallsBySession.get(threadId);
if (!calls) {
return [];
}
return [...calls];
};
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
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;
});
@@ -1,162 +0,0 @@
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<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
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<LegacyProviderRuntimeEvent>;
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: "Command run",
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: "Command run",
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<LegacyProviderRuntimeEvent>;
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<LegacyProviderRuntimeEvent>;
@@ -1,884 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
ThreadId,
} 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";
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 = "codex";
function nowIso() {
return new Date().toISOString();
}
class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWaitTimeoutError>()(
"IntegrationWaitTimeoutError",
{
description: Schema.String,
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
function waitForSync<A>(
read: () => A,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 3000,
): Effect.Effect<A, never> {
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* sleep(10);
}
});
}
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
return {
eventId: asEventId(eventId),
provider,
createdAt,
};
}
function withHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
provider: IntegrationProvider = "codex",
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider }),
use,
(harness) => harness.dispose,
);
}
function withRealCodexHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
use,
(harness) => harness.dispose,
);
}
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
yield* harness.engine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe("cmd-project-create"),
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModel: "gpt-5-codex",
createdAt,
});
yield* harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create"),
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
model: "gpt-5-codex",
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 provider?: IntegrationProvider;
}) =>
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.provider !== undefined ? { provider: input.provider } : {}),
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,
defaultModel: "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",
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,
);
}),
),
);
@@ -1,297 +0,0 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
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 { 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<ProviderService, unknown, never>;
}
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),
AnalyticsService.layerTest,
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
return {
cwd,
harness,
layer,
} satisfies IntegrationFixture;
});
const collectEventsDuring = <A, E, R>(
stream: Stream.Stream<ProviderRuntimeEvent>,
count: number,
action: Effect.Effect<A, E, R>,
) =>
Effect.gen(function* () {
const queue = yield* Queue.unbounded<ProviderRuntimeEvent>();
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)),
);
+7 -24
View File
@@ -1,11 +1,6 @@
{
"name": "t3",
"version": "0.0.9",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
"directory": "apps/server"
},
"version": "0.1.0",
"bin": {
"t3": "./dist/index.mjs"
},
@@ -13,37 +8,25 @@
"dist"
],
"type": "module",
"main": "./dist/index.mjs",
"scripts": {
"dev": "bun run src/index.ts",
"build": "node scripts/cli.ts build",
"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",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@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"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"engines": {
"node": "^22.13 || ^23.4 || >=24.10"
"tsdown": "^0.20.3",
"typescript": "^5.7.3"
}
}
+21
View File
@@ -0,0 +1,21 @@
/**
* 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");
-265
View File
@@ -1,265 +0,0 @@
#!/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<PublishIconBackup>;
});
const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
backups: ReadonlyArray<PublishIconBackup>,
) {
const fs = yield* FileSystem.FileSystem;
for (const backup of backups) {
if (!(yield* fs.exists(backup.backupPath))) {
continue;
}
yield* fs.rename(backup.backupPath, backup.targetPath);
}
});
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
repoRoot: string,
serverDir: string,
) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
for (const override of DEVELOPMENT_ICON_OVERRIDES) {
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
const targetPath = path.join(serverDir, override.targetRelativePath);
if (!(yield* fs.exists(sourcePath))) {
return yield* new CliError({
message: `Missing development icon source: ${sourcePath}`,
});
}
if (!(yield* fs.exists(targetPath))) {
return yield* new CliError({
message: `Missing development icon target: ${targetPath}. Build web first.`,
});
}
yield* fs.copyFile(sourcePath, targetPath);
}
yield* Effect.log("[cli] Applied development icon overrides to dist/client");
});
// ---------------------------------------------------------------------------
// build subcommand
// ---------------------------------------------------------------------------
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<string, unknown>,
};
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<PublishIconBackup> }) =>
Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(
`[cli] Failed to restore publish icon overrides: ${String(error)}`,
),
),
);
yield* fs.rename(backupPath, packageJsonPath);
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
}),
);
}),
).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,
);
-28
View File
@@ -1,28 +0,0 @@
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 stateDir: string;
readonly relativePath: string;
}): string | null {
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
if (!normalizedRelativePath) {
return null;
}
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
return null;
}
return filePath;
}
-77
View File
@@ -1,77 +0,0 @@
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 stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const attachmentId = "thread-1-attachment";
const attachmentsDir = path.join(stateDir, "attachments");
fs.mkdirSync(attachmentsDir, { recursive: true });
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
fs.writeFileSync(pngPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
stateDir,
attachmentId,
});
expect(resolved).toBe(pngPath);
} finally {
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
it("returns null when no attachment file exists for the id", () => {
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const resolved = resolveAttachmentPathById({
stateDir,
attachmentId: "thread-1-missing",
});
expect(resolved).toBeNull();
} finally {
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
});
-110
View File
@@ -1,110 +0,0 @@
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 stateDir: string;
readonly attachment: ChatAttachment;
}): string | null {
return resolveAttachmentRelativePath({
stateDir: input.stateDir,
relativePath: attachmentRelativePath(input.attachment),
});
}
export function resolveAttachmentPathById(input: {
readonly stateDir: 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({
stateDir: input.stateDir,
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;
}
@@ -1,68 +0,0 @@
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 },
]);
});
});
-27
View File
@@ -1,27 +0,0 @@
import { parsePatchFiles } from "@pierre/diffs";
export interface TurnDiffFileSummary {
readonly path: string;
readonly additions: number;
readonly deletions: number;
}
export function parseTurnDiffFilesFromUnifiedDiff(
diff: string,
): ReadonlyArray<TurnDiffFileSummary> {
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));
}
-43
View File
@@ -1,43 +0,0 @@
import { Schema } from "effect";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import { GitCommandError } from "../git/Errors.ts";
/**
* CheckpointUnavailableError - Expected checkpoint does not exist.
*/
export class CheckpointUnavailableError extends Schema.TaggedErrorClass<CheckpointUnavailableError>()(
"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>()(
"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;
@@ -1,197 +0,0 @@
import {
CheckpointRef,
DEFAULT_PROVIDER_INTERACTION_MODE,
ProjectId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { describe, expect, it } from "vitest";
import { ProjectionSnapshotQuery } 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 makeSnapshot(input: {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpointTurnCount: number;
readonly checkpointRef: CheckpointRef;
}): OrchestrationReadModel {
return {
snapshotSequence: 0,
updatedAt: "2026-01-01T00:00:00.000Z",
projects: [
{
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
defaultModel: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
},
],
threads: [
{
id: input.threadId,
projectId: input.projectId,
title: "Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: input.worktreePath,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-01-01T00:00:00.000Z",
startedAt: "2026-01-01T00:00:00.000Z",
completedAt: "2026-01-01T00:00:00.000Z",
assistantMessageId: null,
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
messages: [],
activities: [],
proposedPlans: [],
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
},
],
session: null,
},
],
};
}
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<CheckpointRef> = [];
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
}> = [];
const snapshot = makeSnapshot({
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.succeed(snapshot),
}),
),
);
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.succeed({
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "2026-01-01T00:00:00.000Z",
} satisfies OrchestrationReadModel),
}),
),
);
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.");
});
});
@@ -1,169 +0,0 @@
import {
OrchestrationGetTurnDiffResult,
type OrchestrationGetFullThreadDiffInput,
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
import { Effect, Layer, Schema } from "effect";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } 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"] = (input) =>
Effect.gen(function* () {
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 snapshot = yield* projectionSnapshotQuery.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
if (!thread) {
return yield* new CheckpointInvariantError({
operation,
detail: `Thread '${input.threadId}' not found.`,
});
}
const maxTurnCount = thread.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 = resolveThreadWorkspaceCwd({
thread,
projects: snapshot.projects,
});
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)
: thread.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 = thread.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);
@@ -1,282 +0,0 @@
/**
* 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 "../../git/Errors.ts";
import { GitServiceLive } from "../../git/Layers/GitService.ts";
import { GitService } from "../../git/Services/GitService.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* GitService;
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
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<boolean, GitCommandError> =>
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<string | null, GitCommandError> =>
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"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.captureCheckpoint";
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
(tempDir) =>
Effect.gen(function* () {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const 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"] = (input) =>
Effect.gen(function* () {
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"] = (input) =>
Effect.gen(function* () {
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"] = (input) =>
Effect.gen(function* () {
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).pipe(
Layer.provideMerge(GitServiceLive),
);
@@ -1,49 +0,0 @@
/**
* 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<OrchestrationGetTurnDiffResult, CheckpointServiceError>;
/**
* Read the full patch diff across a thread range of checkpoints.
*
* Delegates to turn diff with `fromTurnCount = 0`.
*/
readonly getFullThreadDiff: (
input: OrchestrationGetFullThreadDiffInput,
) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
}
/**
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
*/
export class CheckpointDiffQuery extends ServiceMap.Service<
CheckpointDiffQuery,
CheckpointDiffQueryShape
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
@@ -1,100 +0,0 @@
/**
* 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<CheckpointRef>;
}
/**
* 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<boolean, CheckpointStoreError>;
/**
* 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<void, CheckpointStoreError>;
/**
* Check whether a checkpoint ref exists.
*/
readonly hasCheckpointRef: (
input: Omit<RestoreCheckpointInput, "fallbackToHead">,
) => Effect.Effect<boolean, CheckpointStoreError>;
/**
* 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<boolean, CheckpointStoreError>;
/**
* Compute patch diff between two checkpoint refs.
*
* Can optionally treat missing "from" ref as `HEAD`.
*/
readonly diffCheckpoints: (
input: DiffCheckpointsInput,
) => Effect.Effect<string, CheckpointStoreError>;
/**
* Delete the provided checkpoint refs.
*
* Best-effort delete: missing refs are tolerated.
*/
readonly deleteCheckpointRefs: (
input: DeleteCheckpointRefsInput,
) => Effect.Effect<void, CheckpointStoreError>;
}
/**
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
*/
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
"t3/checkpointing/Services/CheckpointStore",
) {}
-28
View File
@@ -1,28 +0,0 @@
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;
}
+13 -649
View File
@@ -1,42 +1,23 @@
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,
},
};
const requireSession = vi
@@ -62,79 +43,6 @@ 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",
},
};
const requireSession = vi
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
);
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, requireSession, sendRequest, updateSession };
}
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"),
},
],
]),
};
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 };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -205,197 +113,32 @@ describe("isRecoverableThreadResumeError", () => {
});
});
describe("readCodexAccountSnapshot", () => {
it("disables spark for chatgpt plus accounts", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
planType: "plus",
}),
).toEqual({
type: "chatgpt",
planType: "plus",
sparkEnabled: false,
});
});
it("keeps spark enabled for chatgpt pro accounts", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
planType: "pro",
}),
).toEqual({
type: "chatgpt",
planType: "pro",
sparkEnabled: true,
});
});
it("keeps spark enabled for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
}),
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: true,
});
});
});
describe("resolveCodexModelForAccount", () => {
it("falls back from spark to default for unsupported chatgpt plans", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "chatgpt",
planType: "plus",
sparkEnabled: false,
}),
).toBe("gpt-5.3-codex");
});
it("keeps spark for supported plans", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "chatgpt",
planType: "pro",
sparkEnabled: true,
}),
).toBe("gpt-5.3-codex-spark");
});
});
describe("startSession", () => {
it("enables Codex experimental api capabilities during initialize", () => {
expect(buildCodexInitializeParams()).toEqual({
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",
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",
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({
threadId: asThreadId("thread_1"),
sessionId: "sess_1",
input: "Inspect this image",
attachments: [
{
type: "image",
url: "data:image/png;base64,AAAA",
name: "error.png",
mimeType: "image/png",
sizeBytes: 1_024,
dataUrl: "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("thread_1");
expect(requireSession).toHaveBeenCalledWith("sess_1");
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
@@ -410,13 +153,11 @@ describe("sendTurn", () => {
},
],
model: "gpt-5.3-codex",
serviceTier: "fast",
effort: "high",
});
expect(updateSession).toHaveBeenCalledWith(context, {
status: "running",
activeTurnId: "turn_1",
resumeCursor: { threadId: "thread_1" },
});
});
@@ -424,11 +165,14 @@ describe("sendTurn", () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
threadId: asThreadId("thread_1"),
sessionId: "sess_1",
attachments: [
{
type: "image",
url: "data:image/png;base64,BBBB",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 256,
dataUrl: "data:image/png;base64,BBBB",
},
],
});
@@ -441,98 +185,6 @@ 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,
},
},
});
});
@@ -541,296 +193,8 @@ describe("sendTurn", () => {
await expect(
manager.sendTurn({
threadId: asThreadId("thread_1"),
sessionId: "sess_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(),
};
type ApprovalRequestContext = {
session: typeof context.session;
pendingApprovals: typeof context.pendingApprovals;
pendingUserInputs: typeof context.pendingUserInputs;
};
(
manager as unknown as {
handleServerRequest: (
context: ApprovalRequestContext,
request: Record<string, unknown>,
) => void;
}
).handleServerRequest(context, {
jsonrpc: "2.0",
id: 42,
method: "item/fileRead/requestApproval",
params: {},
});
const request = Array.from(context.pendingApprovals.values())[0];
expect(request?.requestKind).toBe("file-read");
expect(request?.method).toBe("item/fileRead/requestApproval");
});
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
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",
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH
? { 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,
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH
? { 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,
);
});
File diff suppressed because it is too large. Load diff
+252
View File
@@ -0,0 +1,252 @@
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<ProcessRunResult>;
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<string, unknown>;
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<string, unknown>;
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<string> {
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<void> {
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<T>({
cwd,
prompt,
outputSchemaJson,
parse,
run,
}: {
cwd: string;
prompt: string;
outputSchemaJson: object;
parse: (raw: unknown) => T;
run: ProcessRunner;
}): Promise<T> {
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<CommitMessageGenerationResult> {
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<PrContentGenerationResult> {
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(),
};
}
}
-81
View File
@@ -1,81 +0,0 @@
/**
* ServerConfig - Runtime configuration services.
*
* Defines process-level server configuration and networking helpers used by
* startup and runtime layers.
*
* @module ServerConfig
*/
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
export const DEFAULT_PORT = 3773;
export type RuntimeMode = "web" | "desktop";
/**
* ServerConfigShape - Process/runtime configuration required by the server.
*/
export interface ServerConfigShape {
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
readonly cwd: string;
readonly keybindingsConfigPath: string;
readonly stateDir: string;
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
readonly noBrowser: boolean;
readonly authToken: string | undefined;
readonly autoBootstrapProjectFromCwd: boolean;
readonly logWebSocketEvents: boolean;
}
/**
* ServerConfig - Service tag for server runtime configuration.
*/
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
"t3/config/ServerConfig",
) {
static readonly layerTest = (cwd: string, statedir: string) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const path = yield* Path.Path;
return {
cwd,
stateDir: statedir,
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
port: 0,
host: undefined,
authToken: undefined,
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
staticDir: undefined,
devUrl: undefined,
noBrowser: false,
};
}),
);
}
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;
});
+32
View File
@@ -0,0 +1,32 @@
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<CommitMessageGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}
+18
View File
@@ -0,0 +1,18 @@
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
}
}
+656
View File
@@ -0,0 +1,656 @@
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<string> {
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<void> {
await initGitRepo({ cwd });
await git(cwd, "config user.email '[email protected]'");
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<void> {
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("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 '[email protected]'");
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 '[email protected]'");
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();
});
});
});
+641
View File
@@ -0,0 +1,641 @@
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<GitStatusResult, "openPr"> {
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<ProcessRunResult> {
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<TerminalCommandResult> {
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<TerminalCommandResult> {
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<GitStatusResult> {
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<GitStatusDetails> {
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<string>();
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<string, { insertions: number; deletions: number }>();
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<GitPreparedCommitContext | null> {
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<GitPushResult> {
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<GitPullResult> {
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<GitRangeContext> {
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<string | null> {
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<Map<string, number>> {
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<string, number>();
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<GitListBranchesResult> {
const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
() => new Map<string, number>(),
);
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<string, string>();
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<GitCreateWorktreeResult> {
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<void> {
await executeGit(input.cwd, ["worktree", "remove", input.path], {
timeoutMs: 15_000,
fallbackErrorMessage: "git worktree remove failed",
});
}
async createBranch(input: GitCreateBranchInput): Promise<void> {
await executeGit(input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git branch create failed",
});
}
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
await executeGit(input.cwd, ["checkout", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
}
async initRepo(input: GitInitInput): Promise<void> {
await executeGit(input.cwd, ["init"], {
timeoutMs: 10_000,
fallbackErrorMessage: "git init failed",
});
}
async git(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<void> {
await executeGit(cwd, args, { allowNonZeroExit });
}
async gitStdout(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<string> {
const result = await executeGit(cwd, args, { allowNonZeroExit });
return result.stdout;
}
}
const defaultGitCoreService = new GitCoreService();
export async function runTerminalCommand(
input: TerminalCommandInput,
): Promise<TerminalCommandResult> {
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<GitListBranchesResult> {
return defaultGitCoreService.listBranches(input);
}
export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
}
export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
return defaultGitCoreService.createWorktree(input);
}
export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise<void> {
await defaultGitCoreService.removeWorktree(input);
}
export async function createGitBranch(input: GitCreateBranchInput): Promise<void> {
await defaultGitCoreService.createBranch(input);
}
export async function checkoutGitBranch(input: GitCheckoutInput): Promise<void> {
await defaultGitCoreService.checkoutBranch(input);
}
export async function initGitRepo(input: GitInitInput): Promise<void> {
await defaultGitCoreService.initRepo(input);
}
-67
View File
@@ -1,67 +0,0 @@
import { Schema } from "effect";
/**
* GitCommandError - Git command execution failed.
*/
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
}
}
/**
* GitHubCliError - GitHub CLI execution or authentication failed.
*/
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
}
/**
* TextGenerationError - Commit or PR text generation failed.
*/
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
"TextGenerationError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Text generation failed in ${this.operation}: ${this.detail}`;
}
}
/**
* GitManagerError - Stacked Git workflow orchestration failed.
*/
export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `Git manager failed in ${this.operation}: ${this.detail}`;
}
}
/**
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
*/
export type GitManagerServiceError =
| GitManagerError
| GitCommandError
| GitHubCliError
| TextGenerationError;
@@ -1,516 +0,0 @@
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 { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "../Errors.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
CodexTextGenerationLive.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeCodexBinary(dir: 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=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--image" ]; then',
" shift",
' if [ -n "$1" ]; then',
' seen_image="1"',
" fi",
" continue",
" fi",
' if [ "$1" = "--output-last-message" ]; then',
" shift",
' output_path="$1"',
" fi",
" shift",
"done",
'stdin_content="$(cat)"',
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
' printf "%s\\n" "missing --image input" >&2',
" exit 2",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 3",
" }",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "stdin contained forbidden content" >&2',
" exit 4",
" fi",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
"fi",
'if [ -n "$output_path" ]; then',
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
"fi",
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
"",
].join("\n"),
);
yield* fs.chmod(codexPath, 0o755);
return binDir;
});
}
function withFakeCodexEnv<A, E, R>(
input: {
output: string;
exitCode?: number;
stderr?: string;
requireImage?: boolean;
stdinMustContain?: string;
stdinMustNotContain?: string;
},
effect: Effect.Effect<A, E, R>,
) {
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const binDir = yield* makeFakeCodexBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
if (input.exitCode !== undefined) {
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
} else {
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
}
if (input.stderr !== undefined) {
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
} else {
delete process.env.T3_FAKE_CODEX_STDERR;
}
if (input.requireImage) {
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
} else {
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
}
if (input.stdinMustContain !== undefined) {
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
} else {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
}
if (input.stdinMustNotContain !== undefined) {
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
} else {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
}
});
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
previousRequireImage,
previousStdinMustContain,
previousStdinMustNotContain,
};
}),
() => effect,
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
} else {
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
} else {
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CODEX_STDERR;
} else {
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
}
if (previous.previousRequireImage === undefined) {
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
} else {
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
if (previous.previousStdinMustNotContain === undefined) {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
}
}),
);
}
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
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",
});
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("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,
});
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",
});
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.",
});
expect(generated.branch).toBe("feat/session");
}),
),
);
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.",
});
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 attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
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 attachmentId =
`thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration
.generateBranchName({
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 missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: missingAttachmentId,
name: "outside.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.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",
})
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.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",
})
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
}
}),
),
);
});
@@ -1,467 +0,0 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../Errors.ts";
import {
type BranchNameGenerationInput,
type BranchNameGenerationResult,
type CommitMessageGenerationResult,
type PrContentGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
function toCodexOutputJsonSchema(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;
}
function normalizeCodexError(
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: codex") ||
lower.includes("spawn codex") ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: "Codex CLI (`codex`) 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,
});
}
function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
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";
}
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);
type MaterializedImageAttachments = {
readonly imagePaths: ReadonlyArray<string>;
};
const readStreamAsString = <E>(
operation: string,
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, TextGenerationError> =>
Effect.gen(function* () {
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.sync(() => {
text += Buffer.from(chunk).toString("utf8");
}),
).pipe(
Effect.mapError((cause) =>
normalizeCodexError(operation, cause, "Failed to collect process output"),
),
);
return text;
});
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const writeTempFile = (
operation: string,
prefix: string,
content: string,
): Effect.Effect<string, TextGenerationError> => {
const filePath = path.join(tempDir, `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
return fileSystem.writeFileString(filePath, content).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file at ${filePath}.`,
cause,
}),
),
Effect.as(filePath),
);
};
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const materializeImageAttachments = (
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
attachments: BranchNameGenerationInput["attachments"],
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
Effect.gen(function* () {
if (!attachments || attachments.length === 0) {
return { imagePaths: [] };
}
const imagePaths: string[] = [];
for (const attachment of attachments) {
if (attachment.type !== "image") {
continue;
}
const resolvedPath = resolveAttachmentPath({
stateDir: serverConfig.stateDir,
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 = <S extends Schema.Top>({
operation,
cwd,
prompt,
outputSchemaJson,
imagePaths = [],
cleanupPaths = [],
}: {
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
cwd: string;
prompt: string;
outputSchemaJson: S;
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const runCodexCommand = Effect.gen(function* () {
const command = ChildProcess.make(
"codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
CODEX_MODEL,
"--config",
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
"-",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.make(new TextEncoder().encode(prompt)),
},
},
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCodexError(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.map((value) => Number(value)),
Effect.mapError((cause) =>
normalizeCodexError(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"] = (input) => {
const wantsBranch = input.includeBranch === true;
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");
const outputSchemaJson = wantsBranch
? Schema.Struct({
subject: Schema.String,
body: Schema.String,
branch: Schema.String,
})
: Schema.Struct({
subject: Schema.String,
body: Schema.String,
});
return runCodexJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson,
}).pipe(
Effect.map(
(generated) =>
({
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
}) satisfies CommitMessageGenerationResult,
),
);
};
const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
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");
return runCodexJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: Schema.Struct({
title: Schema.String,
body: Schema.String,
}),
}).pipe(
Effect.map(
(generated) =>
({
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
}) satisfies PrContentGenerationResult,
),
);
};
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
return Effect.gen(function* () {
const { imagePaths } = yield* materializeImageAttachments(
"generateBranchName",
input.attachments,
);
const attachmentLines = (input.attachments ?? []).map(
(attachment) =>
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
);
const promptSections = [
"You generate concise git branch names.",
"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.",
"",
"User message:",
limitSection(input.message, 8_000),
];
if (attachmentLines.length > 0) {
promptSections.push(
"",
"Attachment metadata:",
limitSection(attachmentLines.join("\n"), 4_000),
);
}
const prompt = promptSections.join("\n");
const generated = yield* runCodexJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: Schema.Struct({
branch: Schema.String,
}),
imagePaths,
});
return {
branch: sanitizeBranchFragment(generated.branch),
} satisfies BranchNameGenerationResult;
});
};
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
} satisfies TextGenerationShape;
});
export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Loaded 100 of 459 files, more files were not shown because too many files have changed in this diff. Show more