Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex 7333863065 Merge remote-tracking branch 'origin/main' into t3code/pr-649/fix/skip-auth-check-custom-model-providers
Co-authored-by: codex <[email protected]>
2026-03-10 01:18:30 -07:00
BinBandit 9dc1b8153b fix(server): skip auth check when Codex CLI uses a custom model provider
When the Codex CLI is configured with a custom model_provider in
~/.codex/config.toml (e.g. Portkey, Azure OpenAI proxy), authentication
is handled via provider-specific environment variables rather than
`codex login`. The `codex login status` probe would report 'not logged
in' and t3code would treat this as a blocking error, even though the CLI
works perfectly fine.

This change reads the model_provider key from the Codex CLI config file
at startup. When a non-OpenAI provider is detected, the auth probe is
skipped and the provider health check returns ready with authStatus
'unknown' instead of erroring out.

Fixes #644
2026-03-09 20:44:39 +11:00
193 changed files with 5262 additions and 15432 deletions

No files matched your search

+3 -125
View File
@@ -5,139 +5,17 @@ T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JS
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ wsTransport (state machine) │
│ Typed push decode at boundary │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ServerPushBus (ordered pushes) │
│ ServerReadiness (startup gate) │
│ OrchestrationEngine │
│ ProviderService │
│ CheckpointReactor │
│ RuntimeReceiptBus │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ 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
+1 -17
View File
@@ -3,9 +3,7 @@
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.
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
@@ -14,17 +12,3 @@ Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `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.
+1 -2
View File
@@ -3,5 +3,4 @@
- `/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.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
-117
View File
@@ -1,117 +0,0 @@
name: Bug report
description: Report broken behavior, regressions, crashes, or reliability issues.
title: "[Bug]: "
labels:
- bug
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for broken behavior, regressions, crashes, or reliability problems.
Search existing issues first and keep the report focused on one problem.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I included enough detail to reproduce or investigate the problem.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project is affected?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: Provide a minimal, deterministic repro.
placeholder: |
1. Start the app with ...
2. Open ...
3. Disconnect the network
4. Reconnect and send another prompt
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
placeholder: The thread should resume normally and accept the new message.
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual behavior
placeholder: The composer clears, no new turn starts, and the session stays in a pending state.
validations:
required: true
- type: dropdown
id: impact
attributes:
label: Impact
description: How bad is this in practice?
options:
- Blocks work completely
- Major degradation or frequent failure
- Minor bug or occasional failure
- Cosmetic issue
validations:
required: true
- type: input
id: version
attributes:
label: Version or commit
description: Release version, commit SHA, or branch name if known.
placeholder: main @ abc1234
- type: input
id: environment
attributes:
label: Environment
description: OS, browser or desktop app version, Node/Bun version, provider/model if relevant.
placeholder: macOS 15.3, Chrome 135, Bun 1.3.9, Codex app-server ...
- type: textarea
id: logs
attributes:
label: Logs or stack traces
description: Paste the most relevant output only. Redact secrets.
render: shell
- type: upload
id: attachments
attributes:
label: Screenshots, recordings, or supporting files
description: Upload screenshots, short recordings, repro archives, or log files. Redact secrets before uploading.
validations:
required: false
accept: ".png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.mov,.webm,.log,.txt,.json,.zip"
- type: textarea
id: workaround
attributes:
label: Workaround
description: If you found a temporary workaround, include it.
placeholder: Restarting the provider session clears the stuck state.
-101
View File
@@ -1,101 +0,0 @@
name: Feature request
description: Propose a scoped improvement or new capability.
title: "[Feature]: "
labels:
- enhancement
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for new capabilities or meaningful improvements to existing behavior.
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I am describing a concrete problem or use case, not just a vague idea.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project would this change affect?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem or use case
description: What are you trying to do? What is hard, slow, or impossible today?
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: Describe the behavior, API, or UX you want.
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
validations:
required: true
- type: textarea
id: value
attributes:
label: Why this matters
description: Who benefits, and what outcome does this unlock?
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
validations:
required: true
- type: textarea
id: scope
attributes:
label: Smallest useful scope
description: What is the narrowest version of this request that would still solve your problem?
placeholder: A first pass only needs to support restoring the active session for the current thread.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: Workarounds, prior art, or other approaches you considered.
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
- type: textarea
id: tradeoffs
attributes:
label: Risks or tradeoffs
description: What costs, complexity, or edge cases should be considered?
placeholder: This may require careful handling when the underlying provider session has already exited.
- type: textarea
id: references
attributes:
label: Examples or references
description: Links, screenshots, mockups, or comparable tools.
- type: checkboxes
id: contribution
attributes:
label: Contribution
options:
- label: I would be open to helping implement this.
-3
View File
@@ -19,7 +19,6 @@ github:hwanseoc
github:jamesx0416
github:jasonLaster
github:JoeEverest
github:maria-rcks
github:nmggithub
github:Noojuno
github:notkainoa
@@ -27,5 +26,3 @@ github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
+6 -6
View File
@@ -12,7 +12,7 @@ jobs:
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -20,12 +20,12 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Cache Bun and Turbo
uses: actions/cache@v5
uses: actions/cache@v4
with:
path: |
~/.bun/install/cache
@@ -35,7 +35,7 @@ jobs:
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v5
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
@@ -78,7 +78,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -86,7 +86,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
-75
View File
@@ -1,75 +0,0 @@
name: Issue Labels
on:
push:
branches:
- main
paths:
- .github/ISSUE_TEMPLATE/**
- .github/workflows/issue-labels.yml
workflow_dispatch:
permissions:
issues: write
jobs:
sync:
name: Sync issue labels
runs-on: ubuntu-24.04
steps:
- name: Ensure managed issue labels exist
uses: actions/github-script@v7
with:
script: |
const managedLabels = [
{
name: "bug",
color: "d73a4a",
description: "Something is broken or behaving incorrectly.",
},
{
name: "enhancement",
color: "a2eeef",
description: "Requested improvement or new capability.",
},
{
name: "needs-triage",
color: "fbca04",
description: "Issue needs maintainer review and initial categorization.",
},
];
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
-202
View File
@@ -1,202 +0,0 @@
name: PR Size
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
permissions:
contents: read
jobs:
prepare-config:
name: Prepare PR size config
runs-on: ubuntu-24.04
outputs:
labels_json: ${{ steps.config.outputs.labels_json }}
steps:
- id: config
name: Build PR size label config
uses: actions/github-script@v8
with:
result-encoding: string
script: |
const managedLabels = [
{
name: "size:XS",
color: "0e8a16",
description: "0-9 changed lines (additions + deletions).",
},
{
name: "size:S",
color: "5ebd3e",
description: "10-29 changed lines (additions + deletions).",
},
{
name: "size:M",
color: "fbca04",
description: "30-99 changed lines (additions + deletions).",
},
{
name: "size:L",
color: "fe7d37",
description: "100-499 changed lines (additions + deletions).",
},
{
name: "size:XL",
color: "d93f0b",
description: "500-999 changed lines (additions + deletions).",
},
{
name: "size:XXL",
color: "b60205",
description: "1,000+ changed lines (additions + deletions).",
},
];
core.setOutput("labels_json", JSON.stringify(managedLabels));
sync-label-definitions:
name: Sync PR size label definitions
needs: prepare-config
if: github.event_name != 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: write
steps:
- name: Ensure PR size labels exist
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
}
label:
name: Label PR size
needs: prepare-config
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: read
pull-requests: write
concurrency:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
- name: Sync PR size label
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const issueNumber = context.payload.pull_request.number;
const additions = context.payload.pull_request.additions ?? 0;
const deletions = context.payload.pull_request.deletions ?? 0;
const changedLines = additions + deletions;
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
const resolveSizeLabel = (totalChangedLines) => {
if (totalChangedLines < 10) {
return "size:XS";
}
if (totalChangedLines < 30) {
return "size:S";
}
if (totalChangedLines < 100) {
return "size:M";
}
if (totalChangedLines < 500) {
return "size:L";
}
if (totalChangedLines < 1000) {
return "size:XL";
}
return "size:XXL";
};
const nextLabelName = resolveSizeLabel(changedLines);
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
core.info(`PR #${issueNumber}: ${changedLines} changed lines -> ${nextLabelName}`);
+19 -43
View File
@@ -25,7 +25,7 @@ jobs:
targets: ${{ steps.collect.outputs.targets }}
steps:
- id: collect
uses: actions/github-script@v8
uses: actions/github-script@v7
with:
script: |
if (context.eventName === "pull_request_target") {
@@ -85,7 +85,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Sync PR labels
uses: actions/github-script@v8
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ matrix.target.number }}
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
@@ -111,7 +111,7 @@ jobs:
},
];
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
const managedLabelNames = managedLabels.map((label) => label.name);
for (const label of managedLabels) {
try {
@@ -138,19 +138,13 @@ jobs:
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
@@ -165,35 +159,17 @@ jobs:
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
const preservedLabels = currentLabels
.map((label) => label.name)
.filter((name) => !managedLabelNames.includes(name));
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
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}`);
+12 -18
View File
@@ -27,7 +27,7 @@ jobs:
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- id: release_meta
name: Resolve release version
@@ -61,7 +61,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
@@ -107,7 +107,7 @@ jobs:
arch: x64
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
@@ -118,16 +118,13 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build desktop artifact
shell: bash
env:
@@ -217,7 +214,7 @@ jobs:
fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release-publish/*
@@ -229,7 +226,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
@@ -239,7 +236,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
@@ -247,9 +244,6 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
@@ -262,17 +256,17 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
pattern: desktop-*
merge-multiple: true
@@ -309,7 +303,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
@@ -320,7 +314,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
-1
View File
@@ -13,7 +13,6 @@ build/
.logs/
release/
.t3
.idea/
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"
-441
View File
@@ -1,441 +0,0 @@
# Plan: Claude Code Integration (Orchestration Architecture)
## Why this plan was rewritten
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
1. `orchestration.dispatchCommand` (client intent)
2. `OrchestrationEngine` (decide + persist + publish domain events)
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
4. `ProviderService` (adapter routing + canonical runtime stream)
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
6. `orchestration.domainEvent` (single push channel consumed by web)
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
---
## Current constraints to design around (post-Stage 1)
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
---
## Architecture target
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
Key decisions:
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
---
## Phase 1: Contracts and command shape updates
### 1.1 Provider-aware model contract
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
Expected outcomes:
1. Introduce provider-scoped model lists (Codex + Claude).
2. Add helpers that resolve model by provider.
3. Preserve backwards compatibility for existing Codex defaults.
### 1.2 Turn-start provider intent
Update `packages/contracts/src/orchestration.ts`:
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
2. Carry provider through `ThreadTurnStartRequestedPayload`.
3. Keep existing command valid when provider is omitted.
This removes the implicit “Codex unless session already exists” behavior as the only path.
### 1.3 Provider session start input for Claude runtime knobs (completed)
Update `packages/contracts/src/provider.ts`:
1. Move provider-specific start fields into typed `providerOptions`:
- `providerOptions.codex`
- `providerOptions.claudeCode`
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
3. Deprecate/remove `resumeThreadId` from the generic start contract.
4. Treat `resumeCursor` as adapter-owned opaque state.
### 1.4 Contract tests (completed)
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Breaking-change expectations for removed top-level provider fields.
---
## Phase 2: Claude adapter implementation
### 2.1 Add adapter service + layer
Create:
1. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts`
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
### 2.1.a SDK dependency and baseline config
Add server dependency:
1. `@anthropic-ai/claude-agent-sdk`
Baseline adapter options to support from day one:
1. `cwd`
2. `model`
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
6. `resume`
7. `resumeSessionAt`
8. `includePartialMessages`
9. `canUseTool`
10. `hooks`
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
### 2.2 Claude runtime bridge
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
Required capabilities:
1. Long-lived session context per adapter session.
2. Multi-turn input queue.
3. Interrupt support.
4. Approval request/response bridge.
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
#### 2.2.a Agent SDK details to preserve
The adapter should explicitly rely on these SDK capabilities:
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
2. Multi-turn input is supported via async-iterable prompt input.
3. Tool approval decisions are provided via `canUseTool`.
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
#### 2.2.b Effect-native session lifecycle skeleton
```ts
import { query } from "@anthropic-ai/claude-agent-sdk";
import { Effect } from "effect";
const acquireSession = (input: ProviderSessionStartInput) =>
Effect.acquireRelease(
Effect.tryPromise({
try: async () => {
const claudeOptions = input.providerOptions?.claudeCode;
const resumeState = readClaudeResumeState(input.resumeCursor);
const abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: claudeOptions?.permissionMode,
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
resume: resumeState?.threadId,
resumeSessionAt: resumeState?.sessionAt,
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(),
hooks: makeClaudeHooks(),
},
});
return { abortController, result };
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId: "pending",
detail: "Failed to start Claude runtime session.",
cause,
}),
}),
({ abortController }) => Effect.sync(() => abortController.abort()),
);
```
#### 2.2.c AsyncIterable -> Effect Stream integration
Preferred when available in the pinned Effect version:
```ts
const sdkMessageStream = Stream.fromAsyncIterable(
session.result,
(cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
```
Portable fallback (already aligned with current server patterns):
```ts
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
let cancelled = false;
void (async () => {
try {
for await (const message of session.result) {
if (cancelled) break;
emit.single(message);
}
emit.end();
} catch (cause) {
emit.fail(
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
}
})();
return Effect.sync(() => {
cancelled = true;
});
});
```
### 2.3 Canonical event mapping
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
Initial mapping target:
1. assistant text deltas -> `content.delta`
2. final assistant text -> `item.completed` and/or `turn.completed`
3. approval requests -> `request.opened`
4. approval results -> `request.resolved`
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
6. errors -> `runtime.error`
7. plan/proposed-plan content when derivable
Implementation note:
1. Keep raw Claude message on `raw` for debugging.
2. Prefer canonical item/request kinds over provider-native enums.
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
### 2.4 Resume cursor strategy
Define Claude-owned opaque resume state, e.g.:
```ts
interface ClaudeResumeCursor {
readonly version: 1;
readonly threadId?: string;
readonly sessionAt?: string;
}
```
Rules:
1. Serialize only adapter-owned state into `resumeCursor`.
2. Parse/validate only inside Claude adapter.
3. Store updated cursor when Claude runtime yields enough data to resume safely.
4. Never overload orchestration thread id as Claude thread id.
### 2.5 Interrupt and stop semantics
Map orchestration stop/interrupt expectations onto SDK controls:
1. `interruptTurn()` -> active query interrupt.
2. `stopSession()` -> close session resources and prevent future sends.
3. `rollbackThread()` -> see Phase 4.
---
## Phase 3: Provider service and composition
### 3.1 Register Claude adapter
Update provider registry layer to include Claude:
1. add `claudeCode` -> `ClaudeCodeAdapter`
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
### 3.2 Persist provider binding
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
Required validation:
1. Claude bindings survive restart.
2. resume cursor remains opaque and round-trips untouched.
3. stopAll + restart can recover Claude sessions when possible.
### 3.3 Provider start routing
Update `ProviderCommandReactor` / orchestration flow:
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
2. If a thread already has Claude session binding, reuse it.
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
---
## Phase 4: Checkpoint and revert strategy
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
Pick one explicit strategy:
### Option A: provider-native rewind
If SDK/runtime supports safe rewind:
1. implement in Claude adapter
2. keep `CheckpointReactor` unchanged
### Option B: session restart + state truncation shim
If no native rewind exists:
1. Claude adapter returns successful rollback by:
- stopping current Claude session
- clearing/rewriting stored Claude resume cursor to last safe resumable point
- forcing next turn to recreate session from persisted orchestration state
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
Whichever option is chosen:
1. behavior must be deterministic
2. checkpoint revert tests must pass under orchestration expectations
3. user-visible activity log should explain failures clearly when provider rollback is impossible
---
## Phase 5: Web integration
### 5.1 Provider picker and model picker
Update web state/UI:
1. allow choosing Claude as thread provider before first turn
2. show Claude model list from provider-aware model helpers
3. preserve existing Codex default behavior when provider omitted
Likely touch points:
1. `apps/web/src/store.ts`
2. `apps/web/src/components/ChatView.tsx`
3. `apps/web/src/types.ts`
4. `packages/shared/src/model.ts`
### 5.2 Settings for Claude executable/options
Add app settings if needed for:
1. Claude binary path
2. default permission mode
3. default max thinking tokens
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
### 5.3 Session rendering
No new WS channel should be needed. Claude should appear through existing:
1. thread messages
2. activities/worklog
3. approvals
4. session state
5. checkpoints/diffs
---
## Phase 6: Testing strategy
### 6.1 Contract tests
Cover:
1. provider-aware model schemas
2. provider field on turn-start command
3. provider-specific start options schema
### 6.2 Adapter layer tests
Add `ClaudeCodeAdapter.test.ts` covering:
1. session start
2. event mapping
3. approval bridge
4. resume cursor parse/serialize
5. interrupt behavior
6. rollback behavior or explicit unsupported error path
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
### 6.3 Provider service integration tests
Extend provider integration coverage so Claude is exercised through `ProviderService`:
1. start Claude session
2. send turn
3. receive canonical runtime events
4. restart/recover using persisted binding
### 6.4 Orchestration integration tests
Add/extend integration tests around:
1. first-turn provider selection
2. Claude approval requests routed through orchestration
3. Claude runtime ingestion -> messages/activities/session updates
4. checkpoint revert behavior under Claude
5. stopAll/restart recovery
These should validate real orchestration flows, not just adapter behavior.
---
## Phase 7: Rollout order
Recommended implementation order:
1. contracts/provider-aware models
2. provider field on turn-start
3. Claude adapter skeleton + start/send/stream
4. canonical event mapping
5. provider registry/service wiring
6. orchestration recovery + checkpoint strategy
7. web provider/model picker
8. full integration tests
---
## Non-goals
1. Reintroducing provider-specific WS methods/channels.
2. Storing provider-native thread ids as orchestration ids.
3. Bypassing orchestration engine for Claude-specific UI flows.
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
@@ -1,109 +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.
## Implementation Status
All 7 sections are implemented. CI passes (format, lint, typecheck, test, browser test, build). One deferred item remains: the shared `WsTestClient` helper from section 7 — tests use direct transport subscription and receipt-based waits instead.
### New files
| File | Purpose |
|------|---------|
| `packages/shared/src/DrainableWorker.ts` | Queue-based Effect worker with deterministic `drain` signal |
| `packages/shared/src/schemaJson.ts` | Two-phase JSON→Schema decode helpers (`decodeJsonResult`, `formatSchemaError`) |
| `apps/server/src/wsServer/pushBus.ts` | `ServerPushBus` — ordered typed push pipeline with auto-incrementing sequence |
| `apps/server/src/wsServer/readiness.ts` | `ServerReadiness` — Deferred-based barriers for startup sequencing |
| `apps/server/src/orchestration/Services/RuntimeReceiptBus.ts` | Receipt schema union: checkpoint captured, diff finalized, turn quiesced |
| `apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts` | PubSub-backed receipt bus implementation |
| `apps/server/src/watchFileWithStatPolling.ts` | Stat-polling file watcher for containers where `fs.watch` is unreliable |
| `apps/server/vitest.config.ts` | Server-specific test config (timeout bumps) |
| `apps/server/src/wsServer/pushBus.test.ts` | Push bus serialization and welcome-gating tests |
| `packages/shared/src/DrainableWorker.test.ts` | Drainable worker enqueue/drain lifecycle tests |
### Key modifications
| File | Change |
|------|--------|
| `packages/contracts/src/ws.ts` | Channel-indexed `WsPushPayloadByChannel` map, `WsPush` union schema, `WsPushSequence` |
| `apps/server/src/wsServer.ts` | Integrated `ServerPushBus` and `ServerReadiness`; welcome gated on readiness |
| `apps/server/src/keybindings.ts` | Explicit runtime with `start`/`ready`/`snapshot`; dual `fs.watch` + stat-polling watcher |
| `apps/web/src/wsTransport.ts` | Connection state machine (`connecting`→`open`→`reconnecting`→`closed`→`disposed`); two-phase decode at boundary; cached latest push by channel |
| `apps/web/src/wsNativeApi.ts` | Removed decode logic; delegates to pre-validated transport messages |
| `apps/server/src/orchestration/Layers/CheckpointReactor.ts` | Uses `DrainableWorker`; publishes completion receipts |
| `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts` | Uses `DrainableWorker` for command processing |
| `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` | Uses `DrainableWorker` for event ingestion |
| `apps/server/integration/OrchestrationEngineHarness.integration.ts` | Receipt-based waits replace polling loops |
## Key Changes
### 1. Strengthen the generic boundaries, not the Codex boundary — DONE
- `ProviderRuntimeEvent` remains the canonical provider event contract; `ProviderService` remains the only cross-provider facade.
- Raw Codex payloads and event ordering stay isolated in `CodexAdapter.ts` and `codexAppServerManager.ts`.
- `ProviderKind` was not expanded. The runtime stays provider-neutral by contract.
### 2. Replace loose websocket envelopes with channel-indexed typed pushes — DONE
- `packages/contracts/src/ws.ts` now derives push messages from a `WsPushPayloadByChannel` channel-to-schema map. `WsPush` is a union schema replacing `channel: string` + `data: unknown`.
- Every server push carries `sequence: number`, auto-incremented in `ServerPushBus`.
- `packages/shared/src/schemaJson.ts` provides structured decode diagnostics via `formatSchemaError`.
- `packages/contracts/src/ws.test.ts` covers typed push envelope validation and channel/payload mismatch rejection.
### 3. Introduce explicit server readiness and a single push pipeline — DONE
- `apps/server/src/wsServer/pushBus.ts`: `ServerPushBus` with `publishAll` (broadcast) and `publishClient` (targeted) methods, backed by one ordered path. All pushes flow through it.
- `apps/server/src/wsServer/readiness.ts`: `ServerReadiness` with Deferred-based barriers for HTTP listening, push bus, keybindings, terminal subscriptions, and orchestration subscriptions.
- `server.welcome` is emitted only after connection-scoped and server-scoped readiness is complete.
- `wsServer.ts` no longer publishes directly from ad hoc background streams.
### 4. Turn background watchers into explicit runtimes — DONE
- `apps/server/src/keybindings.ts` refactored as explicit `KeybindingsShape` service with `start`, `ready`, `snapshot` semantics.
- Initial config load, cache warmup, and dual watcher attachment (`fs.watch` + `watchFileWithStatPolling`) complete before `ready` resolves.
- `watchFileWithStatPolling.ts` is the thin adapter for environments where `fs.watch` is unreliable.
### 5. Replace polling-based orchestration waiting with receipts — DONE
- `RuntimeReceiptBus` service defines three receipt types: `CheckpointBaselineCapturedReceipt`, `CheckpointDiffFinalizedReceipt` (with `status: "ready"|"missing"|"error"`), and `TurnProcessingQuiescedReceipt`.
- `CheckpointReactor`, `ProviderCommandReactor`, and `ProviderRuntimeIngestion` use `DrainableWorker` and publish receipts on completion.
- Integration harness and checkpoint tests await receipts instead of polling snapshots and git refs.
### 6. Centralize client transport state and decoding — DONE
- `apps/web/src/wsTransport.ts` implements an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Two-phase decode (JSON parse → Schema validate) happens at the transport boundary. `wsNativeApi.ts` receives pre-validated messages.
- Cached latest welcome/config modeled as explicit `latestPushByChannel` state.
### 7. Replace ad hoc test helpers with semantic test clients — MOSTLY DONE
- `DrainableWorker` replaces timing-sensitive `Effect.sleep` with deterministic `drain()` across reactor tests.
- Orchestration harness waits on receipts/barriers instead of `waitForThread`, `waitForGitRef`, and retry loops.
- Behavioral assertions moved to deterministic unit-style harnesses; narrow integration tests kept for real filesystem/socket behavior.
- **Deferred:** Shared `WsTestClient` helper (connect, awaitSemanticWelcome, awaitTypedPush, trackSequence, matchRpcResponseById). Tests use direct transport subscription instead.
## Provider-Coupling Guardrails
- No generic runtime API may depend on Codex-native event names, thread IDs, or request payload shapes.
- No readiness barrier may be defined as "Codex has emitted X." Readiness is owned by the server runtime, not by provider event order.
- No websocket channel payload may contain raw provider-native payloads unless the channel is explicitly debug/internal.
- Any provider-specific divergence must be exposed through provider capabilities from `ProviderService.getCapabilities()`, not `if provider === "codex"` branches in shared runtime code.
- Generic tests must use canonical `ProviderRuntimeEvent` fixtures. Codex-specific ordering and translation tests stay in adapter/app-server suites only.
- Keep UI/provider-specific knobs such as Codex-only options scoped to provider UX code. Do not pull them into generic transport or orchestration state.
## Test Plan
- Contracts:
- schema tests for typed push envelopes and structured decode diagnostics
- ordering tests for `sequence`
- Server:
- readiness tests proving `server.welcome` cannot precede runtime readiness
- push bus tests proving terminal/config/orchestration pushes are serialized and typed
- keybindings runtime tests with fake watch source plus one real watcher integration test
- Orchestration:
- receipt tests proving checkpoint refs and projections are complete before completion signals resolve
- replacement of polling-based checkpoint/integration waits with receipt-based waits
- Web:
- transport tests for invalid JSON, invalid envelope, invalid payload, reconnect queue flushing, cached semantic state
- Validation gate:
- `bun run lint`
- `bun run typecheck`
- `mise exec -- bun run test`
- repeated full-suite run after cutover to confirm flake removal
## Assumptions and Defaults
- This remains a single-provider product during the cutover, but the runtime contracts must stay provider-neutral.
- No backward-compatibility layer is required for old websocket push envelopes.
- The goal is deterministic runtime behavior first; reducing retries and sleeps in tests is a consequence, not the primary mechanism.
- If a completion signal cannot be expressed provider-neutrally, it does not belong in the shared runtime layer and must stay adapter-local.
+2 -2
View File
@@ -2,7 +2,7 @@
## Task Completion Requirements
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
## Project Snapshot
@@ -21,7 +21,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
## Maintainability
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
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
+1 -1
View File
@@ -1 +1 @@
AGENTS.md
AGENTS.md
+1 -1
View File
@@ -8,7 +8,7 @@ You can still open an issue or PR, but please do so knowing there is a high chan
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
PRs are automatically labeled with a `vouch:*` trust status and a `size:*` diff size based on changed lines.
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).
+1 -1
View File
@@ -51,7 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
- `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`)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.10",
"version": "0.0.9",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+2 -3
View File
@@ -80,13 +80,12 @@ function startApp() {
}
});
app.once("exit", (code, signal) => {
app.once("exit", () => {
if (currentApp === app) {
currentApp = null;
}
const exitedAbnormally = signal !== null || code !== 0;
if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
if (!shuttingDown && !expectedExits.has(app)) {
scheduleRestart();
}
});
+15
View File
@@ -0,0 +1,15 @@
import { readPathFromLoginShell } from "@t3tools/shared/shell";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = readPathFromLoginShell(shell);
if (result) {
process.env.PATH = result;
}
} catch {
// Keep inherited PATH if shell lookup fails.
}
}
+6 -75
View File
@@ -4,31 +4,17 @@ import * as FS from "node:fs";
import * as OS from "node:os";
import * as Path from "node:path";
import {
app,
BrowserWindow,
dialog,
ipcMain,
Menu,
nativeImage,
nativeTheme,
protocol,
shell,
} from "electron";
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, shell } from "electron";
import type { MenuItemConstructorOptions } from "electron";
import * as Effect from "effect/Effect";
import type {
DesktopTheme,
DesktopUpdateActionResult,
DesktopUpdateState,
} from "@t3tools/contracts";
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { fixPath } from "./fixPath";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import {
createInitialDesktopUpdateState,
@@ -44,11 +30,10 @@ import {
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
syncShellEnvironment();
fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -152,14 +137,6 @@ function getSafeExternalUrl(rawUrl: unknown): string | null {
return parsedUrl.toString();
}
function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
if (rawTheme === "light" || rawTheme === "dark" || rawTheme === "system") {
return rawTheme;
}
return null;
}
function writeDesktopStreamChunk(
streamName: "stdout" | "stderr",
chunk: unknown,
@@ -535,28 +512,7 @@ function handleCheckForUpdatesMenuClick(): void {
if (!BrowserWindow.getAllWindows().length) {
mainWindow = createWindow();
}
void checkForUpdatesFromMenu();
}
async function checkForUpdatesFromMenu(): Promise<void> {
await checkForUpdates("menu");
if (updateState.status === "up-to-date") {
void dialog.showMessageBox({
type: "info",
title: "You're up to date!",
message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
buttons: ["OK"],
});
} else if (updateState.status === "error") {
void dialog.showMessageBox({
type: "warning",
title: "Update check failed",
message: "Could not check for updates.",
detail: updateState.message ?? "An unknown error occurred. Please try again later.",
buttons: ["OK"],
});
}
void checkForUpdates("menu");
}
function configureApplicationMenu(): void {
@@ -607,21 +563,7 @@ function configureApplicationMenu(): void {
],
},
{ role: "editMenu" },
{
label: "View",
submenu: [
{ role: "reload" },
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
],
},
{ role: "viewMenu" },
{ role: "windowMenu" },
{
role: "help",
@@ -640,7 +582,6 @@ function configureApplicationMenu(): void {
function resolveResourcePath(fileName: string): string | null {
const candidates = [
Path.join(__dirname, "../resources", fileName),
Path.join(__dirname, "../prod-resources", fileName),
Path.join(process.resourcesPath, "resources", fileName),
Path.join(process.resourcesPath, fileName),
];
@@ -1096,16 +1037,6 @@ function registerIpcHandlers(): void {
return showDesktopConfirmDialog(message, owner);
});
ipcMain.removeHandler(SET_THEME_CHANNEL);
ipcMain.handle(SET_THEME_CHANNEL, async (_event, rawTheme: unknown) => {
const theme = getSafeTheme(rawTheme);
if (!theme) {
return;
}
nativeTheme.themeSource = theme;
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
-2
View File
@@ -3,7 +3,6 @@ import type { DesktopBridge } from "@t3tools/contracts";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -17,7 +16,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
@@ -1,85 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("preserves an inherited SSH_AUTH_SOCK value", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/login-shell.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("preserves inherited values when the login shell omits them", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("does nothing outside macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "linux",
readEnvironment,
});
expect(readEnvironment).not.toHaveBeenCalled();
expect(env.PATH).toBe("/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
});
-29
View File
@@ -1,29 +0,0 @@
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
export function syncShellEnvironment(
env: NodeJS.ProcessEnv = process.env,
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
} = {},
): void {
if ((options.platform ?? process.platform) !== "darwin") return;
try {
const shell = env.SHELL ?? "/bin/zsh";
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
"PATH",
"SSH_AUTH_SOCK",
]);
if (shellEnvironment.PATH) {
env.PATH = shellEnvironment.PATH;
}
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
} catch {
// Keep inherited environment if shell lookup fails.
}
}
+2 -2
View File
@@ -10,10 +10,10 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^6.0.4"
"astro": "^5.7.13"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
"@astrojs/check": "^0.9.4",
"typescript": "catalog:"
}
}
-228
View File
@@ -1,228 +0,0 @@
---
interface Props {
title?: string;
description?: string;
}
const {
title = "T3 Code",
description = "T3 Code — The best way to code with AI.",
} = Astro.props;
---
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content={description} />
<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>{title}</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">
<slot />
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
</body>
</html>
<style is:global>
: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%;
}
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
<style>
/* ── 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;
}
/* ── 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);
}
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem;
}
.footer {
padding: 1.25rem;
}
}
</style>
-30
View File
@@ -1,30 +0,0 @@
const REPO = "pingdotgg/t3code";
export const RELEASES_URL = `https://github.com/${REPO}/releases`;
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
const CACHE_KEY = "t3code-latest-release";
export interface ReleaseAsset {
name: string;
browser_download_url: string;
}
export interface Release {
tag_name: string;
html_url: string;
assets: ReleaseAsset[];
}
export async function fetchLatestRelease(): Promise<Release> {
const cached = sessionStorage.getItem(CACHE_KEY);
if (cached) return JSON.parse(cached);
const data = await fetch(API_URL).then((r) => r.json());
if (data?.assets) {
sessionStorage.setItem(CACHE_KEY, JSON.stringify(data));
}
return data;
}
-271
View File
@@ -1,271 +0,0 @@
---
import Layout from "../layouts/Layout.astro";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
<h1 class="heading">Download T3 Code</h1>
<p class="subheading">
<span id="version-label">Loading latest release&hellip;</span>
<a id="changelog-link" class="changelog-link" href="#" target="_blank" rel="noopener noreferrer" style="display:none">View changelog<span aria-hidden="true"> &#8599;</span></a>
</p>
<div class="platforms" id="platforms">
<!-- macOS -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" 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>
<h2 class="platform-name">macOS</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="arm64.dmg" href="#">
<span class="card-arch">Apple Silicon (arm64)</span>
<span class="card-format">.dmg</span>
</a>
<a class="download-card" data-asset="x64.dmg" href="#">
<span class="card-arch">Intel (x64)</span>
<span class="card-format">.dmg</span>
</a>
</div>
</section>
<!-- Windows -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" 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>
<h2 class="platform-name">Windows</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x64.exe" href="#">
<span class="card-arch">Windows 10, 11</span>
<span class="card-format">.exe</span>
</a>
</div>
</section>
<!-- Linux -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" 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>
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x86_64.AppImage" href="#">
<span class="card-arch">x86_64</span>
<span class="card-format">AppImage</span>
</a>
</div>
</section>
</div>
<p class="releases-link">
Looking for older versions? Check the
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
GitHub releases page<span aria-hidden="true"> &#8599;</span>
</a>
</p>
</Layout>
<script>
import { fetchLatestRelease, RELEASES_URL } from "../lib/releases";
async function init() {
const versionLabel = document.getElementById("version-label");
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
try {
const release = await fetchLatestRelease();
if (versionLabel && release.tag_name) {
versionLabel.textContent = `Latest (${release.tag_name})`;
}
const changelogLink = document.getElementById("changelog-link") as HTMLAnchorElement | null;
if (changelogLink && release.html_url) {
changelogLink.href = release.html_url;
changelogLink.style.display = "";
}
cards.forEach((card) => {
const suffix = card.dataset.asset;
if (!suffix) return;
const match = (release.assets ?? []).find((a) => a.name.endsWith(`-${suffix}`));
if (match) {
card.href = match.browser_download_url;
} else {
card.href = RELEASES_URL;
}
});
} catch {
if (versionLabel) {
versionLabel.textContent = "Could not load release info.";
}
cards.forEach((card) => {
card.href = RELEASES_URL;
});
}
}
init();
</script>
<style>
.main {
padding: 8vh 1.5rem 4rem;
}
/* ── Heading ── */
.heading {
font-weight: 500;
font-size: clamp(1.75rem, 4vw, 2.75rem);
letter-spacing: -0.035em;
line-height: 1.15;
text-align: center;
margin-bottom: 0.5rem;
opacity: 0;
animation: fade-in 1s ease-out forwards;
}
.subheading {
font-size: 0.9rem;
color: var(--fg-dim);
margin-bottom: 3.5rem;
opacity: 0;
animation: fade-in 1s ease-out 0.1s forwards;
display: flex;
align-items: center;
gap: 0.75rem;
}
.changelog-link {
color: var(--fg-muted);
font-size: 0.8rem;
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.3s ease, text-decoration-color 0.3s ease;
}
.changelog-link:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* ── Platforms ── */
.platforms {
width: 100%;
max-width: 720px;
display: flex;
flex-direction: column;
gap: 2.5rem;
opacity: 0;
animation: fade-in 1s ease-out 0.2s forwards;
}
.platform-section {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.platform-header {
display: flex;
align-items: center;
gap: 0.6rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid var(--border);
}
.platform-icon {
width: 1.15em;
height: 1.15em;
color: var(--fg-muted);
flex-shrink: 0;
}
.platform-name {
font-weight: 500;
font-size: 1.1rem;
letter-spacing: -0.01em;
}
/* ── Download cards ── */
.download-cards {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 0.5rem;
}
.download-card {
display: flex;
flex-direction: column;
gap: 0.2rem;
padding: 0.85rem 1rem;
border-radius: 10px;
border: 1px solid var(--border);
background: rgba(255, 255, 255, 0.02);
transition: background 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
}
.download-card:hover {
background: rgba(255, 255, 255, 0.06);
border-color: rgba(255, 255, 255, 0.15);
transform: translateY(-1px);
}
.download-card:active {
transform: translateY(0);
}
.card-arch {
font-weight: 600;
font-size: 0.95rem;
}
.card-format {
font-size: 0.8rem;
color: var(--fg-dim);
}
/* ── Releases link ── */
.releases-link {
margin-top: 3rem;
font-size: 0.825rem;
color: var(--fg-dim);
opacity: 0;
animation: fade-in 1s ease-out 0.35s forwards;
}
.releases-link a {
color: var(--fg-muted);
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.3s ease, text-decoration-color 0.3s ease;
}
.releases-link a:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* ── Mobile ── */
@media (max-width: 640px) {
.main {
padding: 5vh 1.25rem 4rem;
}
.platforms {
padding: 0 0.25rem;
}
.download-cards {
grid-template-columns: 1fr;
}
}
</style>
+238 -42
View File
@@ -1,30 +1,75 @@
---
import Layout from "../layouts/Layout.astro";
---
<Layout>
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<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>
<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>
<main class="main">
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<a href="/download" class="other-platforms">Other platforms</a>
<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>
</Layout>
<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>
import { fetchLatestRelease, RELEASES_URL, type ReleaseAsset } from "../lib/releases";
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 };
@@ -42,7 +87,10 @@ import Layout from "../layouts/Layout.astro";
return null;
}
function pickAsset(assets: ReleaseAsset[], platform: Platform): string | 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"))
@@ -77,8 +125,16 @@ import Layout from "../layouts/Layout.astro";
label.textContent = platform.label;
try {
const release = await fetchLatestRelease();
const url = pickAsset(release.assets ?? [], platform);
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");
@@ -93,7 +149,120 @@ import Layout from "../layouts/Layout.astro";
</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;
}
@@ -122,7 +291,7 @@ import Layout from "../layouts/Layout.astro";
border-radius: 999px;
font-weight: 600;
font-size: 0.9rem;
margin-bottom: 1.25rem;
margin-bottom: 5vh;
opacity: 0;
animation: fade-in 1s ease-out 0.15s forwards;
transition: transform 0.25s ease, box-shadow 0.25s ease;
@@ -156,25 +325,6 @@ import Layout from "../layouts/Layout.astro";
display: block;
}
/* ── Other platforms link ── */
.other-platforms {
font-size: 0.825rem;
color: var(--fg-dim);
margin-bottom: 5vh;
opacity: 0;
animation: fade-in 1s ease-out 0.3s forwards;
transition: color 0.3s ease;
text-decoration: underline;
text-decoration-color: rgba(113, 113, 122, 0.4);
text-underline-offset: 3px;
}
.other-platforms:hover {
color: var(--fg-muted);
text-decoration-color: var(--fg-muted);
}
/* ── Screenshot ── */
.screenshot-wrap {
@@ -208,6 +358,44 @@ import Layout from "../layouts/Layout.astro";
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;
@@ -222,6 +410,10 @@ import Layout from "../layouts/Layout.astro";
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem 1.25rem;
}
.main {
padding-top: 7vh;
}
@@ -233,5 +425,9 @@ import Layout from "../layouts/Layout.astro";
.screenshot-wrap {
width: 95vw;
}
.footer {
padding: 1.25rem;
}
}
</style>
@@ -15,7 +15,6 @@ import {
Layer,
ManagedRuntime,
Option,
Ref,
Schedule,
Schema,
Scope,
@@ -46,7 +45,6 @@ import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointRea
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";
@@ -56,10 +54,6 @@ import {
} 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,
@@ -120,7 +114,7 @@ function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 10_000,
timeoutMs = 3000,
): Effect.Effect<A, never> {
const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10;
@@ -191,21 +185,11 @@ export interface OrchestrationIntegrationHarness {
},
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" | "claudeCode";
readonly provider?: "codex";
readonly realCodex?: boolean;
}
@@ -284,7 +268,6 @@ export const makeOrchestrationIntegrationHarness = (
ProjectionPendingApprovalRepositoryLive,
CheckpointStoreLive,
providerLayer,
RuntimeReceiptBusLive,
);
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
@@ -339,18 +322,11 @@ export const makeOrchestrationIntegrationHarness = (
"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"] = (
@@ -422,30 +398,6 @@ export const makeOrchestrationIntegrationHarness = (
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) {
@@ -491,7 +443,6 @@ export const makeOrchestrationIntegrationHarness = (
waitForThread,
waitForDomainEvent,
waitForPendingApproval,
waitForReceipt,
dispose,
} satisfies OrchestrationIntegrationHarness;
});
@@ -35,7 +35,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex" | "claudeCode";
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -177,7 +177,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: "codex" | "claudeCode";
readonly provider: "codex";
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -197,7 +197,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: "codex" | "claudeCode";
readonly provider?: "codex";
}
function nowIso(): string {
@@ -205,7 +205,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: "codex" | "claudeCode",
provider: "codex",
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -215,7 +215,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: "codex" | "claudeCode",
provider: "codex",
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -73,7 +73,7 @@ export const codexTurnToolFixture = [
turnId: TURN_ID,
payload: {
itemType: "command_execution",
title: "Ran command",
title: "Command run",
detail: "echo integration",
},
},
@@ -85,7 +85,7 @@ export const codexTurnToolFixture = [
payload: {
itemType: "command_execution",
status: "completed",
title: "Ran command",
title: "Command run",
detail: "echo integration",
},
},
@@ -21,10 +21,6 @@ import {
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);
@@ -36,7 +32,7 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = "codex" | "claudeCode";
type IntegrationProvider = "codex";
function nowIso() {
return new Date().toISOString();
@@ -191,22 +187,6 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
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,
@@ -228,6 +208,8 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
assert.equal(checkpointRows[0]?.status, "ready");
assert.deepEqual(checkpointRows[0]?.files, []);
yield* harness.waitForDomainEvent((event) => event.type === "thread.turn-diff-completed");
const ref0 = checkpointRefForThreadTurn(THREAD_ID, 0);
const ref1 = checkpointRefForThreadTurn(THREAD_ID, 1);
assert.equal(gitRefExists(harness.workspaceDir, ref0), true);
@@ -385,12 +367,6 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
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,
@@ -432,22 +408,6 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
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,
@@ -882,420 +842,3 @@ it.live(
}),
),
);
it.live("starts a claudeCode session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-initial",
messageId: "msg-user-claude-initial",
text: "Use Claude",
provider: "claudeCode",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeCode" &&
entry.session.status === "ready" &&
entry.messages.some(
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
),
);
assert.equal(thread.session?.providerName, "claudeCode");
}),
"claudeCode",
),
);
it.live("recovers claudeCode sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-1",
messageId: "msg-user-claude-recover-1",
text: "Before restart",
provider: "claudeCode",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.adapter.stopAll();
yield* waitForSync(
() => harness.adapterHarness!.listActiveSessionIds(),
(sessionIds) => sessionIds.length === 0,
"provider stopAll",
);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-2",
messageId: "msg-user-claude-recover-2",
text: "After restart",
});
yield* waitForSync(
() => harness.adapterHarness!.getStartCount(),
(count) => count === 2,
"claude provider recovery start",
);
const recoveredThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeCode" &&
entry.messages.some(
(message) => message.role === "user" && message.text === "After restart",
) &&
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
);
assert.equal(recoveredThread.session?.providerName, "claudeCode");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeCode",
),
);
it.live("forwards claudeCode approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
requestKind: "command",
detail: "Approve Claude tool call",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-approval",
messageId: "msg-user-claude-approval",
text: "Need approval",
provider: "claudeCode",
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some((activity) => activity.kind === "approval.requested"),
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
createdAt: nowIso(),
});
yield* harness.waitForPendingApproval(
"req-approval-1",
(row) => row.status === "resolved" && row.decision === "accept",
);
const approvalResponses = yield* waitForSync(
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1,
"claude provider approval response",
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeCode",
),
);
it.live("forwards thread.turn.interrupt to claudeCode provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-interrupt",
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
provider: "claudeCode",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1",
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
threadId: THREAD_ID,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent(
(event) => event.type === "thread.turn-interrupt-requested",
);
const interruptCalls = yield* waitForSync(
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
(calls) => calls.length === 1,
"claude provider interrupt call",
);
assert.equal(interruptCalls.length, 1);
}),
"claudeCode",
),
);
it.live("reverts claudeCode turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
provider: "claudeCode",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeCode",
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeCode",
),
);
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.10",
"version": "0.0.9",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
@@ -22,7 +22,6 @@
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.76",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@pierre/diffs": "^1.1.0-beta.16",
@@ -45,6 +44,6 @@
"vitest": "catalog:"
},
"engines": {
"node": "^22.16 || ^23.11 || >=24.10"
"node": "^22.13 || ^23.4 || >=24.10"
}
}
+1 -190
View File
@@ -97,7 +97,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
return {
status: (input) => core.status(input),
statusDetails: (cwd) => core.statusDetails(cwd),
prepareCommitContext: (cwd, filePaths?) => core.prepareCommitContext(cwd, filePaths),
prepareCommitContext: (cwd) => core.prepareCommitContext(cwd),
commit: (cwd, subject, body) => core.commit(cwd, subject, body),
pushCurrentBranch: (cwd, fallbackBranch) => core.pushCurrentBranch(cwd, fallbackBranch),
pullCurrentBranch: (cwd) => core.pullCurrentBranch(cwd),
@@ -260,7 +260,6 @@ it.layer(TestLayer)("git integration", (it) => {
yield* initRepoWithCommit(tmp);
const result = yield* listGitBranches({ cwd: tmp });
expect(result.isRepo).toBe(true);
expect(result.hasOriginRemote).toBe(false);
expect(result.branches.length).toBeGreaterThanOrEqual(1);
}),
);
@@ -274,7 +273,6 @@ it.layer(TestLayer)("git integration", (it) => {
const tmp = yield* makeTmpDir();
const result = yield* listGitBranches({ cwd: tmp });
expect(result.isRepo).toBe(false);
expect(result.hasOriginRemote).toBe(false);
expect(result.branches).toEqual([]);
}),
);
@@ -433,7 +431,6 @@ it.layer(TestLayer)("git integration", (it) => {
const result = yield* listGitBranches({ cwd: tmp });
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
expect(result.hasOriginRemote).toBe(true);
expect(firstRemoteIndex).toBeGreaterThan(0);
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
true,
@@ -1409,44 +1406,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"computes ahead count against a non-origin remote-prefixed gh-merge-base candidate",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const remoteName = "fork-seed";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", remoteName, remote]);
yield* git(source, ["push", "-u", remoteName, initialBranch]);
yield* git(source, ["checkout", "-b", "feature/non-origin-merge-base"]);
yield* git(source, [
"config",
"branch.feature/non-origin-merge-base.gh-merge-base",
`${remoteName}/${initialBranch}`,
]);
yield* writeTextFile(
path.join(source, "feature.txt"),
`ahead of ${remoteName}/${initialBranch}\n`,
);
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["branch", "-D", initialBranch]);
const core = yield* GitCore;
const details = yield* core.statusDetails(source);
expect(details.branch).toBe("feature/non-origin-merge-base");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
);
it.effect("skips push when no upstream is configured and branch is not ahead of base", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1488,31 +1447,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("pushes with upstream setup to the only configured non-origin remote", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* git(tmp, ["init", "--initial-branch=main"]);
yield* git(tmp, ["config", "user.email", "[email protected]"]);
yield* git(tmp, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(tmp, "README.md"), "hello\n");
yield* git(tmp, ["add", "README.md"]);
yield* git(tmp, ["commit", "-m", "initial"]);
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "fork", remote]);
yield* git(tmp, ["checkout", "-b", "feature/fork-only"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(pushed.upstreamBranch).toBe("fork/feature/fork-only");
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"fork/feature/fork-only",
);
}),
);
it.effect(
"pushes with upstream setup when comparable base exists but remote branch is missing",
() =>
@@ -1549,90 +1483,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("prefers branch pushRemote over origin when setting upstream", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const origin = yield* makeTmpDir();
const fork = yield* makeTmpDir();
yield* git(origin, ["init", "--bare"]);
yield* git(fork, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const initialBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", origin]);
yield* git(tmp, ["remote", "add", "fork", fork]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
const featureBranch = "feature/push-remote";
yield* git(tmp, ["checkout", "-b", featureBranch]);
yield* git(tmp, ["config", `branch.${featureBranch}.pushRemote`, "fork"]);
yield* writeTextFile(path.join(tmp, "feature.txt"), "push to fork\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature commit"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(pushed.upstreamBranch).toBe(`fork/${featureBranch}`);
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
`fork/${featureBranch}`,
);
expect(yield* git(tmp, ["ls-remote", "--heads", "fork", featureBranch])).toContain(
featureBranch,
);
}),
);
it.effect(
"pushes renamed PR worktree branches to their tracked upstream branch even when push.default is current",
() =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const fork = yield* makeTmpDir();
yield* git(fork, ["init", "--bare"]);
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* git(tmp, ["remote", "add", "jasonLaster", fork]);
yield* git(tmp, ["checkout", "-b", "statemachine"]);
yield* writeTextFile(path.join(tmp, "fork.txt"), "fork branch\n");
yield* git(tmp, ["add", "fork.txt"]);
yield* git(tmp, ["commit", "-m", "fork branch"]);
yield* git(tmp, ["push", "-u", "jasonLaster", "statemachine"]);
yield* git(tmp, ["checkout", initialBranch]);
yield* git(tmp, ["branch", "-D", "statemachine"]);
yield* git(tmp, [
"checkout",
"-b",
"t3code/pr-488/statemachine",
"--track",
"jasonLaster/statemachine",
]);
yield* git(tmp, ["config", "push.default", "current"]);
yield* writeTextFile(path.join(tmp, "fork.txt"), "updated fork branch\n");
yield* git(tmp, ["add", "fork.txt"]);
yield* git(tmp, ["commit", "-m", "update reviewed PR branch"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(false);
expect(pushed.upstreamBranch).toBe("jasonLaster/statemachine");
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"jasonLaster/statemachine",
);
expect(
yield* git(tmp, ["ls-remote", "--heads", "jasonLaster", "statemachine"]),
).toContain("statemachine");
expect(
yield* git(tmp, ["ls-remote", "--heads", "jasonLaster", "t3code/pr-488/statemachine"]),
).toBe("");
}),
);
it.effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1711,45 +1561,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("prepareCommitContext stages only selected files when filePaths provided", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* writeTextFile(path.join(tmp, "a.txt"), "file a\n");
yield* writeTextFile(path.join(tmp, "b.txt"), "file b\n");
const context = yield* core.prepareCommitContext(tmp, ["a.txt"]);
expect(context).not.toBeNull();
expect(context!.stagedSummary).toContain("a.txt");
expect(context!.stagedSummary).not.toContain("b.txt");
yield* core.commit(tmp, "Add only a.txt", "");
// b.txt should still be untracked after commit
const statusAfter = yield* git(tmp, ["status", "--porcelain"]);
expect(statusAfter).toContain("b.txt");
expect(statusAfter).not.toContain("a.txt");
}),
);
it.effect("prepareCommitContext stages everything when filePaths is undefined", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* writeTextFile(path.join(tmp, "a.txt"), "file a\n");
yield* writeTextFile(path.join(tmp, "b.txt"), "file b\n");
const context = yield* core.prepareCommitContext(tmp);
expect(context).not.toBeNull();
expect(context!.stagedSummary).toContain("a.txt");
expect(context!.stagedSummary).toContain("b.txt");
}),
);
it.effect("pushes with upstream setup and then skips when up to date", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
+22 -103
View File
@@ -191,9 +191,9 @@ function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null {
function parseDefaultBranchFromRemoteHeadRef(value: string): string | null {
const trimmed = value.trim();
const prefix = `refs/remotes/${remoteName}/`;
const prefix = "refs/remotes/origin/";
if (!trimmed.startsWith(prefix)) {
return null;
}
@@ -417,33 +417,29 @@ const makeGitCore = Effect.gen(function* () {
yield* fetchUpstreamRef(cwd, upstream);
});
const resolveDefaultBranchName = (
cwd: string,
remoteName: string,
): Effect.Effect<string | null, GitCommandError> =>
const resolveDefaultBranchName = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
executeGit(
"GitCore.resolveDefaultBranchName",
cwd,
["symbolic-ref", `refs/remotes/${remoteName}/HEAD`],
["symbolic-ref", "refs/remotes/origin/HEAD"],
{ allowNonZeroExit: true },
).pipe(
Effect.map((result) => {
if (result.code !== 0) {
return null;
}
return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName);
return parseDefaultBranchFromRemoteHeadRef(result.stdout);
}),
);
const remoteBranchExists = (
cwd: string,
remoteName: string,
branch: string,
): Effect.Effect<boolean, GitCommandError> =>
executeGit(
"GitCore.remoteBranchExists",
cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`],
["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`],
{
allowNonZeroExit: true,
},
@@ -477,34 +473,6 @@ const makeGitCore = Effect.gen(function* () {
);
});
const resolvePushRemoteName = (
cwd: string,
branch: string,
): Effect.Effect<string | null, GitCommandError> =>
Effect.gen(function* () {
const branchPushRemote = yield* runGitStdout(
"GitCore.resolvePushRemoteName.branchPushRemote",
cwd,
["config", "--get", `branch.${branch}.pushRemote`],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
if (branchPushRemote.length > 0) {
return branchPushRemote;
}
const pushDefaultRemote = yield* runGitStdout(
"GitCore.resolvePushRemoteName.remotePushDefault",
cwd,
["config", "--get", "remote.pushDefault"],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
if (pushDefaultRemote.length > 0) {
return pushDefaultRemote;
}
return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null)));
});
const ensureRemote: GitCoreShape["ensureRemote"] = (input) =>
Effect.gen(function* () {
const preferredName = sanitizeRemoteName(input.preferredName);
@@ -549,11 +517,7 @@ const makeGitCore = Effect.gen(function* () {
true,
).pipe(Effect.map((stdout) => stdout.trim()));
const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe(
Effect.catch(() => Effect.succeed(null)),
);
const defaultBranch =
primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName);
const defaultBranch = yield* resolveDefaultBranchName(cwd);
const candidates = [
configuredBaseBranch.length > 0 ? configuredBaseBranch : null,
defaultBranch,
@@ -565,13 +529,9 @@ const makeGitCore = Effect.gen(function* () {
continue;
}
const remotePrefix =
primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null;
const normalizedCandidate = candidate.startsWith("origin/")
? candidate.slice("origin/".length)
: remotePrefix && candidate.startsWith(remotePrefix)
? candidate.slice(remotePrefix.length)
: candidate;
: candidate;
if (normalizedCandidate.length === 0 || normalizedCandidate === branch) {
continue;
}
@@ -580,11 +540,8 @@ const makeGitCore = Effect.gen(function* () {
return normalizedCandidate;
}
if (
primaryRemoteName &&
(yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate))
) {
return `${primaryRemoteName}/${normalizedCandidate}`;
if (yield* remoteBranchExists(cwd, normalizedCandidate)) {
return `origin/${normalizedCandidate}`;
}
}
@@ -654,7 +611,7 @@ const makeGitCore = Effect.gen(function* () {
const statusDetails: GitCoreShape["statusDetails"] = (cwd) =>
Effect.gen(function* () {
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.catch(() => Effect.void));
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
[
@@ -766,21 +723,9 @@ const makeGitCore = Effect.gen(function* () {
})),
);
const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd, filePaths) =>
const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd) =>
Effect.gen(function* () {
if (filePaths && filePaths.length > 0) {
yield* runGit("GitCore.prepareCommitContext.reset", cwd, ["reset"]).pipe(
Effect.catch(() => Effect.void),
);
yield* runGit("GitCore.prepareCommitContext.addSelected", cwd, [
"add",
"-A",
"--",
...filePaths,
]);
} else {
yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
}
yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [
"diff",
@@ -847,17 +792,17 @@ const makeGitCore = Effect.gen(function* () {
Effect.catch(() => Effect.succeed(null)),
);
if (comparableBaseBranch) {
const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(null)),
const hasOriginRemote = yield* originRemoteExists(cwd).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (!publishRemoteName) {
if (!hasOriginRemote) {
return {
status: "skipped_up_to_date" as const,
branch,
};
}
const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe(
const hasRemoteBranch = yield* remoteBranchExists(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (hasRemoteBranch) {
@@ -870,46 +815,20 @@ const makeGitCore = Effect.gen(function* () {
}
if (!details.hasUpstream) {
const publishRemoteName = yield* resolvePushRemoteName(cwd, branch);
if (!publishRemoteName) {
return yield* createGitCommandError(
"GitCore.pushCurrentBranch",
cwd,
["push"],
"Cannot push because no git remote is configured for this repository.",
);
}
yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [
"push",
"-u",
publishRemoteName,
"origin",
branch,
]);
return {
status: "pushed" as const,
branch,
upstreamBranch: `${publishRemoteName}/${branch}`,
upstreamBranch: `origin/${branch}`,
setUpstream: true,
};
}
const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe(
Effect.catch(() => Effect.succeed(null)),
);
if (currentUpstream) {
yield* runGit("GitCore.pushCurrentBranch.pushUpstream", cwd, [
"push",
currentUpstream.remoteName,
`HEAD:${currentUpstream.upstreamBranch}`,
]);
return {
status: "pushed" as const,
branch,
upstreamBranch: currentUpstream.upstreamRef,
setUpstream: false,
};
}
yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]);
return {
status: "pushed" as const,
@@ -1012,7 +931,7 @@ const makeGitCore = Effect.gen(function* () {
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false, hasOriginRemote: false };
return { branches: [], isRepo: false };
}
return yield* createGitCommandError(
"GitCore.listBranches",
@@ -1178,7 +1097,7 @@ const makeGitCore = Effect.gen(function* () {
const branches = [...localBranches, ...remoteBranches];
return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") };
return { branches, isRepo: true };
});
const createWorktree: GitCoreShape["createWorktree"] = (input) =>
@@ -1377,7 +1296,7 @@ const makeGitCore = Effect.gen(function* () {
// Refresh upstream refs in the background so checkout remains responsive.
yield* Effect.forkScoped(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })),
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
);
});
+2 -2
View File
@@ -181,7 +181,7 @@ const makeGitHubCli = Effect.sync(() => {
"pr",
"list",
"--head",
input.headSelector,
input.headBranch,
"--state",
"open",
"--limit",
@@ -250,7 +250,7 @@ const makeGitHubCli = Effect.sync(() => {
"--base",
input.baseBranch,
"--head",
input.headSelector,
input.headBranch,
"--title",
input.title,
"--body-file",
+3 -322
View File
@@ -22,7 +22,6 @@ import { makeGitManager } from "./GitManager.ts";
interface FakeGhScenario {
prListSequence?: string[];
prListByHeadSelector?: Record<string, string>;
createdPrUrl?: string;
defaultBranch?: string;
pullRequest?: {
@@ -222,16 +221,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}
if (args[0] === "pr" && args[1] === "list") {
const headSelectorIndex = args.findIndex((value) => value === "--head");
const headSelector =
headSelectorIndex >= 0 && headSelectorIndex < args.length - 1
? args[headSelectorIndex + 1]
: undefined;
const mappedStdout =
typeof headSelector === "string"
? scenario.prListByHeadSelector?.[headSelector]
: undefined;
const stdout = (mappedStdout ?? prListQueue.shift() ?? "[]") + "\n";
const stdout = (prListQueue.shift() ?? "[]") + "\n";
return Effect.succeed({
stdout,
stderr: "",
@@ -379,7 +369,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
"pr",
"list",
"--head",
input.headSelector,
input.headBranch,
"--state",
"open",
"--limit",
@@ -401,7 +391,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
"--base",
input.baseBranch,
"--head",
input.headSelector,
input.headBranch,
"--title",
input.title,
"--body-file",
@@ -451,7 +441,6 @@ function runStackedAction(
action: "commit" | "commit_push" | "commit_push_pr";
commitMessage?: string;
featureBranch?: boolean;
filePaths?: readonly string[];
},
) {
return manager.runStackedAction(input);
@@ -534,64 +523,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"status detects cross-repo PRs from the upstream remote URL owner",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
fs.writeFileSync(path.join(repoDir, "fork-pr.txt"), "fork pr\n");
yield* runGit(repoDir, ["add", "fork-pr.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Fork PR branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-488/statemachine"]);
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
"[email protected]:jasonLaster/codething-mvp.git",
]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([
{
number: 488,
title: "Rebase this PR on latest main",
url: "https://github.com/pingdotgg/codething-mvp/pull/488",
baseRefName: "main",
headRefName: "statemachine",
state: "OPEN",
updatedAt: "2026-03-10T07:00:00Z",
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("t3code/pr-488/statemachine");
expect(status.pr).toEqual({
number: 488,
title: "Rebase this PR on latest main",
url: "https://github.com/pingdotgg/codething-mvp/pull/488",
baseBranch: "main",
headBranch: "statemachine",
state: "open",
});
expect(ghCalls).toContain(
"pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
);
}),
12_000,
);
it.effect("status returns merged PR state when latest PR was merged", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -768,31 +699,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("commits only selected files when filePaths is provided", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "a.txt"), "file a\n");
fs.writeFileSync(path.join(repoDir, "b.txt"), "file b\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit",
filePaths: ["a.txt"],
});
expect(result.commit.status).toBe("created");
// b.txt should remain in the working tree
const statusStdout = yield* runGit(repoDir, ["status", "--porcelain"]).pipe(
Effect.map((r) => r.stdout),
);
expect(statusStdout).toContain("b.txt");
expect(statusStdout).not.toContain("a.txt");
}),
);
it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1058,172 +964,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"returns existing cross-repo PR metadata using the fork owner selector",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
"[email protected]:octocat/codething-mvp.git",
]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([]),
JSON.stringify([
{
number: 142,
title: "Existing fork PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
baseRefName: "main",
headRefName: "statemachine",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(142);
expect(
ghCalls.some((call) =>
call.includes("pr list --head octocat:statemachine --state open --limit 1"),
),
).toBe(true);
expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(false);
}),
12_000,
);
it.effect(
"prefers owner-qualified selectors before bare branch names for cross-repo PRs",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-142/statemachine"]);
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
"[email protected]:octocat/codething-mvp.git",
]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListByHeadSelector: {
"t3code/pr-142/statemachine": JSON.stringify([]),
statemachine: JSON.stringify([
{
number: 41,
title: "Unrelated same-repo PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/41",
baseRefName: "main",
headRefName: "statemachine",
},
]),
"octocat:statemachine": JSON.stringify([
{
number: 142,
title: "Existing fork PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
baseRefName: "main",
headRefName: "statemachine",
},
]),
"fork-seed:statemachine": JSON.stringify([]),
},
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(142);
const ownerSelectorCallIndex = ghCalls.findIndex((call) =>
call.includes("pr list --head octocat:statemachine --state open --limit 1"),
);
expect(ownerSelectorCallIndex).toBeGreaterThanOrEqual(0);
expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(false);
}),
12_000,
);
it.effect(
"stops probing head selectors after finding an existing PR",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-142/statemachine"]);
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
"[email protected]:octocat/codething-mvp.git",
]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListByHeadSelector: {
"octocat:statemachine": JSON.stringify([
{
number: 142,
title: "Existing fork PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
baseRefName: "main",
headRefName: "statemachine",
},
]),
"fork-seed:statemachine": JSON.stringify([]),
"t3code/pr-142/statemachine": JSON.stringify([]),
statemachine: JSON.stringify([]),
},
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(142);
const prListCalls = ghCalls.filter((call) => call.startsWith("pr list "));
expect(prListCalls).toHaveLength(1);
expect(prListCalls[0]).toContain(
"pr list --head octocat:statemachine --state open --limit 1",
);
}),
12_000,
);
it.effect("creates PR when one does not already exist", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1268,65 +1008,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("creates cross-repo PRs with the fork owner selector and default base branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-91/statemachine"]);
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
"[email protected]:octocat/codething-mvp.git",
]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([
{
number: 188,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
baseRefName: "main",
headRefName: "statemachine",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(188);
expect(
ghCalls.some((call) => call.includes("pr create --base main --head octocat:statemachine")),
).toBe(true);
expect(
ghCalls.some((call) =>
call.includes("pr create --base statemachine --head octocat:statemachine"),
),
).toBe(false);
}),
);
it.effect("rejects push/pr actions from detached HEAD", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+59 -225
View File
@@ -42,17 +42,6 @@ interface PullRequestHeadRemoteInfo {
headRepositoryOwnerLogin?: string | null;
}
interface BranchHeadContext {
localBranch: string;
headBranch: string;
headSelectors: ReadonlyArray<string>;
preferredHeadSelector: string;
remoteName: string | null;
headRepositoryNameWithOwner: string | null;
headRepositoryOwnerLogin: string | null;
isCrossRepository: boolean;
}
function parseRepositoryNameFromPullRequestUrl(url: string): string | null {
const trimmed = url.trim();
const match = /^https:\/\/github\.com\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed);
@@ -93,30 +82,6 @@ function resolvePullRequestWorktreeLocalBranchName(
return `t3code/pr-${pullRequest.number}/${suffix}`;
}
function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
const trimmed = url?.trim() ?? "";
if (trimmed.length === 0) {
return null;
}
const match =
/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
trimmed,
);
const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
}
function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null {
const trimmed = nameWithOwner?.trim() ?? "";
if (trimmed.length === 0) {
return null;
}
const [ownerLogin] = trimmed.split("/");
const normalizedOwnerLogin = ownerLogin?.trim() ?? "";
return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;
}
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
if (!Array.isArray(raw)) return [];
@@ -252,14 +217,6 @@ function extractBranchFromRef(ref: string): string {
return normalized.slice(firstSlash + 1).trim();
}
function appendUnique(values: string[], next: string | null | undefined): void {
const trimmed = next?.trim() ?? "";
if (trimmed.length === 0 || values.includes(trimmed)) {
return;
}
values.push(trimmed);
}
function toStatusPr(pr: PullRequestInfo): {
number: number;
title: string;
@@ -437,162 +394,63 @@ export const makeGitManager = Effect.gen(function* () {
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const readConfigValueNullable = (cwd: string, key: string) =>
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
const resolveRemoteRepositoryContext = (cwd: string, remoteName: string | null) =>
Effect.gen(function* () {
if (!remoteName) {
return {
repositoryNameWithOwner: null,
ownerLogin: null,
};
}
const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
return {
repositoryNameWithOwner,
ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
};
});
const resolveBranchHeadContext = (
cwd: string,
details: { branch: string; upstreamRef: string | null },
) =>
Effect.gen(function* () {
const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`);
const headBranchFromUpstream = details.upstreamRef
? extractBranchFromRef(details.upstreamRef)
: "";
const headBranch =
headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch;
const [remoteRepository, originRepository] = yield* Effect.all(
[
resolveRemoteRepositoryContext(cwd, remoteName),
resolveRemoteRepositoryContext(cwd, "origin"),
],
{ concurrency: "unbounded" },
);
const isCrossRepository =
remoteRepository.repositoryNameWithOwner !== null &&
originRepository.repositoryNameWithOwner !== null
? remoteRepository.repositoryNameWithOwner.toLowerCase() !==
originRepository.repositoryNameWithOwner.toLowerCase()
: remoteName !== null &&
remoteName !== "origin" &&
remoteRepository.repositoryNameWithOwner !== null;
const ownerHeadSelector =
remoteRepository.ownerLogin && headBranch.length > 0
? `${remoteRepository.ownerLogin}:${headBranch}`
: null;
const remoteAliasHeadSelector =
remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null;
const shouldProbeRemoteOwnedSelectors =
isCrossRepository || (remoteName !== null && remoteName !== "origin");
const headSelectors: string[] = [];
if (isCrossRepository && shouldProbeRemoteOwnedSelectors) {
appendUnique(headSelectors, ownerHeadSelector);
appendUnique(
headSelectors,
remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
);
}
appendUnique(headSelectors, details.branch);
appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null);
if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) {
appendUnique(headSelectors, ownerHeadSelector);
appendUnique(
headSelectors,
remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
);
}
return {
localBranch: details.branch,
headBranch,
headSelectors,
preferredHeadSelector:
ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
remoteName,
headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
headRepositoryOwnerLogin: remoteRepository.ownerLogin,
isCrossRepository,
} satisfies BranchHeadContext;
});
const findOpenPr = (cwd: string, headSelectors: ReadonlyArray<string>) =>
Effect.gen(function* () {
for (const headSelector of headSelectors) {
const pullRequests = yield* gitHubCli.listOpenPullRequests({
cwd,
headSelector,
limit: 1,
});
const [firstPullRequest] = pullRequests;
if (firstPullRequest) {
const findOpenPr = (cwd: string, branch: string) =>
gitHubCli
.listOpenPullRequests({
cwd,
headBranch: branch,
limit: 1,
})
.pipe(
Effect.map((prs) => {
const [first] = prs;
if (!first) {
return null;
}
return {
number: firstPullRequest.number,
title: firstPullRequest.title,
url: firstPullRequest.url,
baseRefName: firstPullRequest.baseRefName,
headRefName: firstPullRequest.headRefName,
number: first.number,
title: first.title,
url: first.url,
baseRefName: first.baseRefName,
headRefName: first.headRefName,
state: "open",
updatedAt: null,
} satisfies PullRequestInfo;
}
}
}),
);
return null;
});
const findLatestPr = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>
const findLatestPr = (cwd: string, branch: string) =>
Effect.gen(function* () {
const headContext = yield* resolveBranchHeadContext(cwd, details);
const parsedByNumber = new Map<number, PullRequestInfo>();
const stdout = yield* gitHubCli
.execute({
cwd,
args: [
"pr",
"list",
"--head",
branch,
"--state",
"all",
"--limit",
"20",
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
],
})
.pipe(Effect.map((result) => result.stdout));
for (const headSelector of headContext.headSelectors) {
const stdout = yield* gitHubCli
.execute({
cwd,
args: [
"pr",
"list",
"--head",
headSelector,
"--state",
"all",
"--limit",
"20",
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
],
})
.pipe(Effect.map((result) => result.stdout));
const raw = stdout.trim();
if (raw.length === 0) {
continue;
}
const parsedJson = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
});
for (const pr of parsePullRequestList(parsedJson)) {
parsedByNumber.set(pr.number, pr);
}
const raw = stdout.trim();
if (raw.length === 0) {
return null;
}
const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => {
const parsedJson = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
});
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
return right - left;
@@ -605,17 +463,12 @@ export const makeGitManager = Effect.gen(function* () {
return parsed[0] ?? null;
});
const resolveBaseBranch = (
cwd: string,
branch: string,
upstreamRef: string | null,
headContext: Pick<BranchHeadContext, "isCrossRepository">,
) =>
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
Effect.gen(function* () {
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
if (configured) return configured;
if (upstreamRef && !headContext.isCrossRepository) {
if (upstreamRef) {
const upstreamBranch = extractBranchFromRef(upstreamRef);
if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
return upstreamBranch;
@@ -638,10 +491,9 @@ export const makeGitManager = Effect.gen(function* () {
commitMessage?: string;
/** When true, also produce a semantic feature branch name. */
includeBranch?: boolean;
filePaths?: readonly string[];
}) =>
Effect.gen(function* () {
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
const context = yield* gitCore.prepareCommitContext(input.cwd);
if (!context) {
return null;
}
@@ -681,7 +533,6 @@ export const makeGitManager = Effect.gen(function* () {
branch: string | null,
commitMessage?: string,
preResolvedSuggestion?: CommitAndBranchSuggestion,
filePaths?: readonly string[],
) =>
Effect.gen(function* () {
const suggestion =
@@ -690,7 +541,6 @@ export const makeGitManager = Effect.gen(function* () {
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
}));
if (!suggestion) {
return { status: "skipped_no_changes" as const };
@@ -721,12 +571,7 @@ export const makeGitManager = Effect.gen(function* () {
);
}
const headContext = yield* resolveBranchHeadContext(cwd, {
branch,
upstreamRef: details.upstreamRef,
});
const existing = yield* findOpenPr(cwd, headContext.headSelectors);
const existing = yield* findOpenPr(cwd, branch);
if (existing) {
return {
status: "opened_existing" as const,
@@ -738,13 +583,13 @@ export const makeGitManager = Effect.gen(function* () {
};
}
const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext);
const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef);
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
const generated = yield* textGeneration.generatePrContent({
cwd,
baseBranch,
headBranch: headContext.headBranch,
headBranch: branch,
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
@@ -762,18 +607,18 @@ export const makeGitManager = Effect.gen(function* () {
.createPullRequest({
cwd,
baseBranch,
headSelector: headContext.preferredHeadSelector,
headBranch: branch,
title: generated.title,
bodyFile,
})
.pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));
const created = yield* findOpenPr(cwd, headContext.headSelectors);
const created = yield* findOpenPr(cwd, branch);
if (!created) {
return {
status: "created" as const,
baseBranch,
headBranch: headContext.headBranch,
headBranch: branch,
title: generated.title,
};
}
@@ -793,10 +638,7 @@ export const makeGitManager = Effect.gen(function* () {
const pr =
details.branch !== null
? yield* findLatestPr(input.cwd, {
branch: details.branch,
upstreamRef: details.upstreamRef,
}).pipe(
? yield* findLatestPr(input.cwd, details.branch).pipe(
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
Effect.catch(() => Effect.succeed(null)),
)
@@ -967,18 +809,12 @@ export const makeGitManager = Effect.gen(function* () {
},
);
const runFeatureBranchStep = (
cwd: string,
branch: string | null,
commitMessage?: string,
filePaths?: readonly string[],
) =>
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
Effect.gen(function* () {
const suggestion = yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
includeBranch: true,
});
if (!suggestion) {
@@ -1027,7 +863,6 @@ export const makeGitManager = Effect.gen(function* () {
input.cwd,
initialStatus.branch,
input.commitMessage,
input.filePaths,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
@@ -1043,7 +878,6 @@ export const makeGitManager = Effect.gen(function* () {
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
input.filePaths,
);
const push = wantsPush
-1
View File
@@ -101,7 +101,6 @@ export interface GitCoreShape {
*/
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
/**
+2 -2
View File
@@ -47,7 +47,7 @@ export interface GitHubCliShape {
*/
readonly listOpenPullRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly headBranch: string;
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
@@ -73,7 +73,7 @@ export interface GitHubCliShape {
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly headBranch: string;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitHubCliError>;
+41 -98
View File
@@ -22,9 +22,7 @@ import {
Array,
Cache,
Cause,
Deferred,
Effect,
Exit,
FileSystem,
Path,
Layer,
@@ -35,9 +33,7 @@ import {
SchemaGetter,
SchemaIssue,
SchemaTransformation,
Ref,
ServiceMap,
Scope,
Stream,
} from "effect";
import * as Semaphore from "effect/Semaphore";
@@ -426,7 +422,6 @@ export interface KeybindingsConfigState {
}
export interface KeybindingsChangeEvent {
readonly keybindings: ResolvedKeybindingsConfig;
readonly issues: readonly ServerConfigIssue[];
}
@@ -473,22 +468,6 @@ function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): Resolve
* KeybindingsShape - Service API for keybinding configuration operations.
*/
export interface KeybindingsShape {
/**
* Start the keybindings runtime and attach file watching.
*
* Safe to call multiple times. The first successful call establishes the
* runtime; later calls await the same startup.
*/
readonly start: Effect.Effect<void, KeybindingsConfigError>;
/**
* Await keybindings runtime readiness.
*
* Readiness means the config directory exists, the watcher is attached, the
* startup sync has completed, and the current snapshot has been loaded.
*/
readonly ready: Effect.Effect<void, KeybindingsConfigError>;
/**
* Ensure the on-disk keybindings file exists and includes all default
* commands so newly-added defaults are backfilled on startup.
@@ -501,14 +480,9 @@ export interface KeybindingsShape {
readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
/**
* Read the latest keybindings snapshot from cache/disk.
* Stream keybindings config change events.
*/
readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
/**
* Stream of keybindings config change events.
*/
readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
readonly changes: Stream.Stream<KeybindingsChangeEvent>;
/**
* Upsert a keybinding rule and persist the resulting configuration.
@@ -535,12 +509,9 @@ const makeKeybindings = Effect.gen(function* () {
const upsertSemaphore = yield* Semaphore.make(1);
const resolvedConfigCacheKey = "resolved" as const;
const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
const startedRef = yield* Ref.make(false);
const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();
const watcherScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
const emitChange = (configState: KeybindingsConfigState) =>
PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);
const emitChange = (issues: readonly ServerConfigIssue[]) =>
PubSub.publish(changesPubSub, { issues }).pipe(Effect.asVoid);
const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
Effect.mapError(
@@ -705,10 +676,43 @@ const makeKeybindings = Effect.gen(function* () {
Effect.gen(function* () {
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
const configState = yield* loadConfigStateFromCacheOrDisk;
yield* emitChange(configState);
yield* emitChange(configState.issues);
}),
);
const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
const keybindingsConfigFile = path.basename(keybindingsConfigPath);
const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
yield* fs
.makeDirectory(keybindingsConfigDir, { recursive: true })
.pipe(Effect.orElseSucceed(() => undefined));
yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => {
const isTargetConfigEvent =
event.path === keybindingsConfigFile ||
event.path === keybindingsConfigPath ||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved;
if (!isTargetConfigEvent) {
return Effect.void;
}
return revalidateAndEmit.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to revalidate keybindings config after file update", {
path: keybindingsConfigPath,
detail: error.detail,
cause: error.cause,
}),
),
);
}).pipe(
Effect.catch((cause) =>
Effect.logWarning("keybindings config watcher stopped unexpectedly", {
path: keybindingsConfigPath,
cause,
}),
),
Effect.forkScoped,
);
const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
Effect.gen(function* () {
const configExists = yield* readConfigExists;
@@ -799,68 +803,10 @@ const makeKeybindings = Effect.gen(function* () {
}),
);
const startWatcher = Effect.gen(function* () {
const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
const keybindingsConfigFile = path.basename(keybindingsConfigPath);
const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
detail: "failed to prepare keybindings config directory",
cause,
}),
),
);
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => {
const isTargetConfigEvent =
event.path === keybindingsConfigFile ||
event.path === keybindingsConfigPath ||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved;
if (!isTargetConfigEvent) {
return Effect.void;
}
return revalidateAndEmitSafely;
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
});
const start = Effect.gen(function* () {
const alreadyStarted = yield* Ref.get(startedRef);
if (alreadyStarted) {
return yield* Deferred.await(startedDeferred);
}
yield* Ref.set(startedRef, true);
const startup = Effect.gen(function* () {
yield* startWatcher;
yield* syncDefaultKeybindingsOnStartup;
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
yield* loadConfigStateFromCacheOrDisk;
});
const startupExit = yield* Effect.exit(startup);
if (startupExit._tag === "Failure") {
yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
return yield* Effect.failCause(startupExit.cause);
}
yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
});
return {
start,
ready: Deferred.await(startedDeferred),
syncDefaultKeybindingsOnStartup,
loadConfigState: loadConfigStateFromCacheOrDisk,
getSnapshot: loadConfigStateFromCacheOrDisk,
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
changes: Stream.fromPubSub(changesPubSub),
upsertKeybindingRule: (rule) =>
upsertSemaphore.withPermits(1)(
Effect.gen(function* () {
@@ -887,10 +833,7 @@ const makeKeybindings = Effect.gen(function* () {
keybindings: nextResolved,
issues: [],
});
yield* emitChange({
keybindings: nextResolved,
issues: [],
});
yield* emitChange([]);
return nextResolved;
}),
),
+56 -66
View File
@@ -1,7 +1,8 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import { FileSystem, Path, Effect } from "effect";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import {
isCommandAvailable,
@@ -9,19 +10,12 @@ import {
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open";
import { Effect } from "effect";
import { assertSuccess } from "@effect/vitest/utils";
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
describe("resolveEditorLaunch", () => {
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
const antigravityLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "antigravity" },
"darwin",
);
assert.deepEqual(antigravityLaunch, {
command: "agy",
args: ["/tmp/workspace"],
});
const cursorLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "cursor" },
"darwin",
@@ -123,7 +117,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
);
});
it.layer(NodeServices.layer)("launchDetached", (it) => {
describe("launchDetached", () => {
it.effect("resolves when command can be spawned", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
@@ -145,20 +139,26 @@ it.layer(NodeServices.layer)("launchDetached", (it) => {
);
});
it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
it.effect("resolves win32 commands with PATHEXT", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
describe("isCommandAvailable", () => {
function withTempDir(run: (dir: string) => void): void {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-"));
try {
run(dir);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
it("resolves win32 commands with PATHEXT", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "code.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
});
});
it("returns false when a command is not on PATH", () => {
const env = {
@@ -168,65 +168,55 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
});
it.effect("does not treat bare files without executable extension as available on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
it("does not treat bare files without executable extension as available on win32", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "npm"), "echo nope\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
}),
);
});
});
it.effect("appends PATHEXT for commands with non-executable extensions on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
it("appends PATHEXT for commands with non-executable extensions on win32", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "my.tool.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
}),
);
});
});
it.effect("uses platform-specific PATH delimiter for platform overrides", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
const env = {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
it("uses platform-specific PATH delimiter for platform overrides", () => {
withTempDir((firstDir) => {
withTempDir((secondDir) => {
fs.writeFileSync(path.join(secondDir, "code.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
});
});
});
});
it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
it.effect("returns installed editors for command launches", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
describe("resolveAvailableEditors", () => {
it("returns only editors whose launch commands are available", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-"));
try {
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
const editors = resolveAvailableEditors("win32", {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["cursor", "file-manager"]);
}),
);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
@@ -22,7 +22,6 @@ import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
@@ -44,7 +43,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex" | "claudeCode";
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -113,7 +112,7 @@ async function waitForThread(
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}) => boolean,
timeoutMs = 5000,
timeoutMs = 2000,
) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<{
@@ -138,7 +137,7 @@ async function waitForThread(
async function waitForEvent(
engine: OrchestrationEngineShape,
predicate: (event: { type: string }) => boolean,
timeoutMs = 5000,
timeoutMs = 2000,
) {
const deadline = Date.now() + timeoutMs;
const poll = async () => {
@@ -189,7 +188,7 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
return runGit(cwd, ["show", `${ref}:${filePath}`]);
}
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 5000) {
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 2000) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (gitRefExists(cwd, ref)) {
@@ -235,7 +234,6 @@ describe("CheckpointReactor", () => {
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: "codex" | "claudeCode";
}) {
const cwd = createGitRepository();
tempDirs.push(cwd);
@@ -243,7 +241,7 @@ describe("CheckpointReactor", () => {
cwd,
options?.hasSession ?? true,
options?.providerSessionCwd ?? cwd,
options?.providerName ?? "codex",
"codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -254,7 +252,6 @@ describe("CheckpointReactor", () => {
const layer = CheckpointReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
@@ -267,7 +264,7 @@ describe("CheckpointReactor", () => {
const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(reactor.drain);
await Effect.runPromise(Effect.sleep("10 millis"));
const createdAt = new Date().toISOString();
await Effect.runPromise(
@@ -324,7 +321,6 @@ describe("CheckpointReactor", () => {
engine,
provider,
cwd,
drain,
};
}
@@ -453,7 +449,7 @@ describe("CheckpointReactor", () => {
payload: { state: "completed" },
});
await harness.drain();
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
@@ -478,67 +474,6 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
});
it("captures pre-turn and completion checkpoints for claudeCode runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: "claudeCode",
});
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeCode",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
harness.provider.emit({
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
provider: "claudeCode",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
});
await waitForGitRefExists(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
);
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
harness.provider.emit({
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
provider: "claudeCode",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
payload: { state: "completed" },
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
const thread = await waitForThread(
harness.engine,
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
).toBe(true);
});
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
@@ -708,7 +643,7 @@ describe("CheckpointReactor", () => {
status: "completed",
});
await harness.drain();
await Effect.runPromise(Effect.sleep("40 millis"));
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
@@ -854,75 +789,6 @@ describe("CheckpointReactor", () => {
).toBe(false);
});
it("executes provider revert and emits thread.reverted for claudeCode sessions", async () => {
const harness = await createHarness({ providerName: "claudeCode" });
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeCode",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
status: "ready",
files: [],
checkpointTurnCount: 1,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-2"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
status: "ready",
files: [],
checkpointTurnCount: 2,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
);
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
});
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
const harness = await createHarness();
const createdAt = new Date().toISOString();
@@ -2,26 +2,22 @@ import {
CommandId,
EventId,
MessageId,
type ProjectId,
ThreadId,
TurnId,
type OrchestrationEvent,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { Cause, Effect, Layer, Option, Stream } from "effect";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { Cause, Effect, Layer, Option, Queue, Stream } from "effect";
import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
import {
checkpointRefForThreadTurn,
resolveThreadWorkspaceCwd,
} from "../../checkpointing/Utils.ts";
import { clearWorkspaceIndexCache } from "../../workspaceEntries.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import { OrchestrationDispatchError } from "../Errors.ts";
import { isGitRepository } from "../../git/isRepo.ts";
@@ -67,7 +63,6 @@ const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const checkpointStore = yield* CheckpointStore;
const receiptBus = yield* RuntimeReceiptBus;
const appendRevertFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -148,178 +143,6 @@ const make = Effect.gen(function* () {
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
// Resolves the workspace CWD for checkpoint operations, preferring the
// active provider session CWD and falling back to the thread/project config.
// Returns undefined when no CWD can be determined or the workspace is not
// a git repository.
const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
readonly preferSessionRuntime: boolean;
}): Effect.fn.Return<string | undefined> {
const fromSession = yield* resolveSessionRuntimeForThread(input.threadId);
const fromThread = resolveThreadWorkspaceCwd({
thread: input.thread,
projects: input.projects,
});
const cwd = input.preferSessionRuntime
? (Option.match(fromSession, {
onNone: () => undefined,
onSome: (runtime) => runtime.cwd,
}) ?? fromThread)
: (fromThread ??
Option.match(fromSession, {
onNone: () => undefined,
onSome: (runtime) => runtime.cwd,
}));
if (!cwd) {
return undefined;
}
if (!isGitWorkspace(cwd)) {
return undefined;
}
return cwd;
});
// Shared tail for both capture paths: creates the git checkpoint ref, diffs
// it against the previous turn, then dispatches the domain events to update
// the orchestration read model.
const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId;
readonly thread: {
readonly messages: ReadonlyArray<{
readonly id: MessageId;
readonly role: string;
readonly turnId: TurnId | null;
}>;
};
readonly cwd: string;
readonly turnCount: number;
readonly status: "ready" | "missing" | "error";
readonly assistantMessageId: MessageId | undefined;
readonly createdAt: string;
}) {
const fromTurnCount = Math.max(0, input.turnCount - 1);
const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, fromTurnCount);
const targetCheckpointRef = checkpointRefForThreadTurn(input.threadId, input.turnCount);
const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({
cwd: input.cwd,
checkpointRef: fromCheckpointRef,
});
if (!fromCheckpointExists) {
yield* Effect.logWarning("checkpoint capture missing pre-turn baseline", {
threadId: input.threadId,
turnId: input.turnId,
fromTurnCount,
});
}
yield* checkpointStore.captureCheckpoint({
cwd: input.cwd,
checkpointRef: targetCheckpointRef,
});
// Invalidate the workspace entry cache so the @-mention file picker
// reflects files created or deleted during this turn.
clearWorkspaceIndexCache(input.cwd);
const files = yield* checkpointStore
.diffCheckpoints({
cwd: input.cwd,
fromCheckpointRef,
toCheckpointRef: targetCheckpointRef,
fallbackFromToHead: false,
})
.pipe(
Effect.map((diff) =>
parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
path: file.path,
kind: "modified" as const,
additions: file.additions,
deletions: file.deletions,
})),
),
Effect.tapError((error) =>
appendCaptureFailureActivity({
threadId: input.threadId,
turnId: input.turnId,
detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
createdAt: input.createdAt,
}),
),
Effect.catch((error) =>
Effect.logWarning("failed to derive checkpoint file summary", {
threadId: input.threadId,
turnId: input.turnId,
turnCount: input.turnCount,
detail: error.message,
}).pipe(Effect.as([])),
),
);
const assistantMessageId =
input.assistantMessageId ??
input.thread.messages
.toReversed()
.find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??
MessageId.makeUnsafe(`assistant:${input.turnId}`);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: serverCommandId("checkpoint-turn-diff-complete"),
threadId: input.threadId,
turnId: input.turnId,
completedAt: input.createdAt,
checkpointRef: targetCheckpointRef,
status: input.status,
files,
assistantMessageId,
checkpointTurnCount: input.turnCount,
createdAt: input.createdAt,
});
yield* receiptBus.publish({
type: "checkpoint.diff.finalized",
threadId: input.threadId,
turnId: input.turnId,
checkpointTurnCount: input.turnCount,
checkpointRef: targetCheckpointRef,
status: input.status,
createdAt: input.createdAt,
});
yield* receiptBus.publish({
type: "turn.processing.quiesced",
threadId: input.threadId,
turnId: input.turnId,
checkpointTurnCount: input.turnCount,
createdAt: input.createdAt,
});
yield* orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: serverCommandId("checkpoint-captured-activity"),
threadId: input.threadId,
activity: {
id: EventId.makeUnsafe(crypto.randomUUID()),
tone: "info",
kind: "checkpoint.captured",
summary: "Checkpoint captured",
payload: {
turnCount: input.turnCount,
status: input.status,
},
turnId: input.turnId,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
});
});
// Captures a real git checkpoint when a turn completes via a runtime event.
const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
) {
@@ -339,111 +162,134 @@ const make = Effect.gen(function* () {
return;
}
// Only skip if a real (non-placeholder) checkpoint already exists for this turn.
// ProviderRuntimeIngestion may insert placeholder entries with status "missing"
// before this reactor runs; those must not prevent real git capture.
if (
thread.checkpoints.some(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
)
) {
if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: true,
});
const sessionRuntime = yield* resolveSessionRuntimeForThread(thread.id);
const checkpointCwd =
Option.match(sessionRuntime, {
onNone: () => undefined,
onSome: (runtime) => runtime.cwd,
}) ??
resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
});
if (!checkpointCwd) {
yield* Effect.logWarning("checkpoint capture skipped: no active provider session cwd", {
threadId: thread.id,
turnId,
});
return;
}
// If a placeholder checkpoint exists for this turn, reuse its turn count
// instead of incrementing past it.
const existingPlaceholder = thread.checkpoints.find(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
);
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const nextTurnCount = existingPlaceholder
? existingPlaceholder.checkpointTurnCount
: currentTurnCount + 1;
yield* captureAndDispatchCheckpoint({
threadId: thread.id,
turnId,
thread,
cwd: checkpointCwd,
turnCount: nextTurnCount,
status: checkpointStatusFromRuntime(event.payload.state),
assistantMessageId: undefined,
createdAt: event.createdAt,
});
});
// Captures a real git checkpoint when a placeholder checkpoint (status "missing")
// is detected via a domain event. This replaces the placeholder with a real
// git-ref-based checkpoint.
//
// ProviderRuntimeIngestion creates placeholder checkpoints on turn.diff.updated
// events from the Codex runtime. This handler fires when the corresponding
// domain event arrives, allowing the reactor to capture the actual filesystem
// state into a git ref and dispatch a replacement checkpoint.
const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* (
event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
) {
const { threadId, turnId, checkpointTurnCount, status } = event.payload;
// Only replace placeholders; skip events from our own real captures.
if (status !== "missing") {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
if (!thread) {
yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
threadId,
if (!isGitWorkspace(checkpointCwd)) {
yield* Effect.logDebug("checkpoint capture skipped for non-git workspace", {
threadId: thread.id,
turnId,
cwd: checkpointCwd,
});
return;
}
// If a real checkpoint already exists for this turn, skip.
if (
thread.checkpoints.some(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
)
) {
yield* Effect.logDebug(
"checkpoint capture from placeholder skipped: real checkpoint already exists",
{ threadId, turnId },
);
return;
}
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const nextTurnCount = currentTurnCount + 1;
const fromTurnCount = Math.max(0, nextTurnCount - 1);
const fromCheckpointRef = checkpointRefForThreadTurn(thread.id, fromTurnCount);
const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, nextTurnCount);
const checkpointCwd = yield* resolveCheckpointCwd({
threadId,
thread,
projects: readModel.projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
return;
}
yield* captureAndDispatchCheckpoint({
threadId,
turnId,
thread,
const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({
cwd: checkpointCwd,
turnCount: checkpointTurnCount,
status: "ready",
assistantMessageId: event.payload.assistantMessageId ?? undefined,
createdAt: event.payload.completedAt,
checkpointRef: fromCheckpointRef,
});
if (!fromCheckpointExists) {
yield* Effect.logWarning("checkpoint completion missing pre-turn baseline", {
threadId: thread.id,
turnId,
fromTurnCount,
});
}
yield* checkpointStore.captureCheckpoint({
cwd: checkpointCwd,
checkpointRef: targetCheckpointRef,
});
const files = yield* checkpointStore
.diffCheckpoints({
cwd: checkpointCwd,
fromCheckpointRef,
toCheckpointRef: targetCheckpointRef,
fallbackFromToHead: false,
})
.pipe(
Effect.map((diff) =>
parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
path: file.path,
kind: "modified" as const,
additions: file.additions,
deletions: file.deletions,
})),
),
Effect.tapError((error) =>
appendCaptureFailureActivity({
threadId: thread.id,
turnId,
detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
createdAt: event.createdAt,
}),
),
Effect.catch((error) =>
Effect.logWarning("failed to derive checkpoint file summary", {
threadId: thread.id,
turnId,
turnCount: nextTurnCount,
detail: error.message,
}).pipe(Effect.as([])),
),
);
const assistantMessageId =
thread.messages
.toReversed()
.find((entry) => entry.role === "assistant" && entry.turnId === turnId)?.id ??
MessageId.makeUnsafe(`assistant:${turnId}`);
const now = event.createdAt;
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: serverCommandId("checkpoint-turn-diff-complete"),
threadId: thread.id,
turnId,
completedAt: now,
checkpointRef: targetCheckpointRef,
status: checkpointStatusFromRuntime(event.payload.state),
files,
assistantMessageId,
checkpointTurnCount: nextTurnCount,
createdAt: now,
});
yield* orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: serverCommandId("checkpoint-captured-activity"),
threadId: thread.id,
activity: {
id: EventId.makeUnsafe(crypto.randomUUID()),
tone: "info",
kind: "checkpoint.captured",
summary: "Checkpoint captured",
payload: {
turnCount: nextTurnCount,
status: event.payload.state,
},
turnId,
createdAt: now,
},
createdAt: now,
});
});
@@ -461,13 +307,24 @@ const make = Effect.gen(function* () {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
const checkpointCwdFromThreadOrProject = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
preferSessionRuntime: false,
});
const checkpointCwd =
checkpointCwdFromThreadOrProject ??
Option.match(yield* resolveSessionRuntimeForThread(thread.id), {
onNone: () => undefined,
onSome: (runtime) => runtime.cwd,
});
if (!checkpointCwd) {
yield* Effect.logWarning("checkpoint pre-turn capture skipped: no workspace cwd", {
threadId: thread.id,
turnId,
});
return;
}
if (!isGitWorkspace(checkpointCwd)) {
return;
}
@@ -488,13 +345,6 @@ const make = Effect.gen(function* () {
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
yield* receiptBus.publish({
type: "checkpoint.baseline.captured",
threadId: thread.id,
checkpointTurnCount: currentTurnCount,
checkpointRef: baselineCheckpointRef,
createdAt: event.createdAt,
});
});
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
@@ -520,13 +370,23 @@ const make = Effect.gen(function* () {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId,
const checkpointCwdFromThreadOrProject = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
preferSessionRuntime: false,
});
const checkpointCwd =
checkpointCwdFromThreadOrProject ??
Option.match(yield* resolveSessionRuntimeForThread(threadId), {
onNone: () => undefined,
onSome: (runtime) => runtime.cwd,
});
if (!checkpointCwd) {
yield* Effect.logWarning("checkpoint pre-turn capture skipped: no workspace cwd", {
threadId,
});
return;
}
if (!isGitWorkspace(checkpointCwd)) {
return;
}
@@ -547,13 +407,6 @@ const make = Effect.gen(function* () {
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
yield* receiptBus.publish({
type: "checkpoint.baseline.captured",
threadId,
checkpointTurnCount: currentTurnCount,
checkpointRef: baselineCheckpointRef,
createdAt: event.occurredAt,
});
});
const handleRevertRequested = Effect.fnUntraced(function* (
@@ -640,10 +493,6 @@ const make = Effect.gen(function* () {
return;
}
// Invalidate the workspace entry cache so the @-mention file picker
// reflects the reverted filesystem state.
clearWorkspaceIndexCache(sessionRuntime.value.cwd);
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
if (rolledBackTurns > 0) {
yield* providerService.rollbackConversation({
@@ -701,25 +550,6 @@ const make = Effect.gen(function* () {
}),
),
);
return;
}
// When ProviderRuntimeIngestion creates a placeholder checkpoint (status "missing")
// from a turn.diff.updated runtime event, capture the real git checkpoint to
// replace it. The providerService.streamEvents PubSub does not reliably deliver
// turn.completed runtime events to this reactor (shared subscription), so
// reacting to the domain event is the reliable path.
if (event.type === "thread.turn-diff-completed") {
yield* captureCheckpointFromPlaceholder(event).pipe(
Effect.catch((error) =>
appendCaptureFailureActivity({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
detail: error.message,
createdAt: new Date().toISOString(),
}).pipe(Effect.catch(() => Effect.void)),
),
);
}
});
@@ -764,20 +594,24 @@ const make = Effect.gen(function* () {
}),
);
const worker = yield* makeDrainableWorker(processInputSafely);
const start: CheckpointReactorShape["start"] = Effect.gen(function* () {
const queue = yield* Queue.unbounded<ReactorInput>();
yield* Effect.addFinalizer(() => Queue.shutdown(queue).pipe(Effect.asVoid));
yield* Effect.forkScoped(
Effect.forever(Queue.take(queue).pipe(Effect.flatMap(processInputSafely))),
);
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (
event.type !== "thread.turn-start-requested" &&
event.type !== "thread.message-sent" &&
event.type !== "thread.checkpoint-revert-requested" &&
event.type !== "thread.turn-diff-completed"
event.type !== "thread.checkpoint-revert-requested"
) {
return Effect.void;
}
return worker.enqueue({ source: "domain", event });
return Queue.offer(queue, { source: "domain", event }).pipe(Effect.asVoid);
}),
);
@@ -786,14 +620,13 @@ const make = Effect.gen(function* () {
if (event.type !== "turn.started" && event.type !== "turn.completed") {
return Effect.void;
}
return worker.enqueue({ source: "runtime", event });
return Queue.offer(queue, { source: "runtime", event }).pipe(Effect.asVoid);
}),
);
});
return {
start,
drain: worker.drain,
} satisfies CheckpointReactorShape;
});
@@ -49,6 +49,13 @@ function commandToAggregateRef(command: OrchestrationCommand): {
}
}
function formatDispatchError(error: OrchestrationDispatchError): string {
if (error instanceof Error && error.message.length > 0) {
return error.message;
}
return String(error);
}
const makeOrchestrationEngine = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const eventStore = yield* OrchestrationEventStore;
@@ -184,7 +191,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
acceptedAt: new Date().toISOString(),
resultSequence: readModel.snapshotSequence,
status: "rejected",
error: error.message,
error: formatDispatchError(error),
})
.pipe(Effect.catch(() => Effect.void));
}
@@ -222,16 +229,14 @@ const makeOrchestrationEngine = Effect.gen(function* () {
return yield* Deferred.await(result);
});
const streamDomainEvents: OrchestrationEngineShape["streamDomainEvents"] =
Stream.fromPubSub(eventPubSub);
return {
getReadModel,
readEvents,
dispatch,
// Each access creates a fresh PubSub subscription so that multiple
// consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)
// each independently receive all domain events.
get streamDomainEvents(): OrchestrationEngineShape["streamDomainEvents"] {
return Stream.fromPubSub(eventPubSub);
},
streamDomainEvents,
} satisfies OrchestrationEngineShape;
});
@@ -27,7 +27,6 @@ describe("OrchestrationReactor", () => {
start: Effect.sync(() => {
started.push("provider-runtime-ingestion");
}),
drain: Effect.void,
}),
),
Layer.provideMerge(
@@ -35,7 +34,6 @@ describe("OrchestrationReactor", () => {
start: Effect.sync(() => {
started.push("provider-command-reactor");
}),
drain: Effect.void,
}),
),
Layer.provideMerge(
@@ -43,7 +41,6 @@ describe("OrchestrationReactor", () => {
start: Effect.sync(() => {
started.push("checkpoint-reactor");
}),
drain: Effect.void,
}),
),
),
@@ -96,7 +96,7 @@ describe("ProviderCommandReactor", () => {
typeof input === "object" &&
input !== null &&
"provider" in input &&
(input.provider === "codex" || input.provider === "claudeCode")
input.provider === "codex"
? input.provider
: "codex";
const resumeCursor =
@@ -129,7 +129,7 @@ describe("ProviderCommandReactor", () => {
: "full-access",
...(model !== undefined ? { model } : {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
createdAt: now,
updatedAt: now,
};
@@ -219,7 +219,7 @@ describe("ProviderCommandReactor", () => {
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(reactor.drain);
await Effect.runPromise(Effect.sleep("10 millis"));
await Effect.runPromise(
engine.dispatch({
@@ -259,7 +259,6 @@ describe("ProviderCommandReactor", () => {
renameBranch,
generateBranchName,
stateDir,
drain,
};
}
@@ -389,42 +388,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("starts first turn with requested provider when provider is specified", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-first"),
role: "user",
text: "hello claude",
attachments: [],
},
provider: "claudeCode",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeCode",
cwd: "/tmp/provider-project",
runtimeMode: "approval-required",
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerName).toBe("claudeCode");
expect(thread?.session?.threadId).toBe("thread-1");
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -545,7 +508,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
resumeCursor: { opaque: "resume-1" },
resumeCursor: { opaque: "cursor-1" },
runtimeMode: "approval-required",
});
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
@@ -558,66 +521,6 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("switches provider by restarting the session when turn request provider changes", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-2"),
role: "user",
text: "second",
attachments: [],
},
provider: "claudeCode",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
provider: "claudeCode",
runtimeMode: "approval-required",
});
expect(harness.startSession.mock.calls[1]?.[1]).not.toHaveProperty("resumeCursor");
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerName).toBe("claudeCode");
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("does not stop the active session when restart fails before rebind", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -674,7 +577,7 @@ describe("ProviderCommandReactor", () => {
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
await harness.drain();
await Effect.runPromise(Effect.sleep("30 millis"));
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(1);
@@ -12,12 +12,11 @@ import {
type RuntimeMode,
type TurnId,
} from "@t3tools/contracts";
import { Cache, Cause, Duration, Effect, Layer, Option, Schema, Stream } from "effect";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Schema, Stream } from "effect";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -74,8 +73,18 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const WORKTREE_BRANCH_PREFIX = "t3code";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
function toErrorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
try {
return JSON.stringify(error);
} catch {
return String(error);
}
}
function isUnknownPendingApprovalRequestError(error: unknown): boolean {
if (Schema.is(ProviderAdapterRequestError)(error)) {
const detail = error.detail.toLowerCase();
return (
@@ -83,7 +92,7 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
detail.includes("unknown pending permission request")
);
}
const message = Cause.pretty(cause);
const message = toErrorMessage(error).toLowerCase();
return (
message.includes("unknown pending approval request") ||
message.includes("unknown pending permission request")
@@ -206,9 +215,7 @@ const make = Effect.gen(function* () {
const desiredRuntimeMode = thread.runtimeMode;
const currentProvider: ProviderKind | undefined =
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
? thread.session.providerName
: undefined;
thread.session?.providerName === "codex" ? thread.session.providerName : undefined;
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
const desiredModel = options?.model ?? thread.model;
const effectiveCwd = resolveThreadWorkspaceCwd({
@@ -532,17 +539,19 @@ const make = Effect.gen(function* () {
.pipe(
Effect.catchCause((cause) =>
Effect.gen(function* () {
const error = Cause.squash(cause);
const detail = toErrorMessage(error);
yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.approval.respond.failed",
summary: "Provider approval response failed",
detail: Cause.pretty(cause),
detail,
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
if (!isUnknownPendingApprovalRequestError(cause)) return;
if (!isUnknownPendingApprovalRequestError(error)) return;
}),
),
);
@@ -576,14 +585,17 @@ const make = Effect.gen(function* () {
})
.pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
Effect.gen(function* () {
const error = Cause.squash(cause);
yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: toErrorMessage(error),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
}),
),
);
@@ -666,28 +678,34 @@ const make = Effect.gen(function* () {
}),
);
const worker = yield* makeDrainableWorker(processDomainEventSafely);
const start: ProviderCommandReactorShape["start"] = Effect.gen(function* () {
const queue = yield* Queue.unbounded<ProviderIntentEvent>();
yield* Effect.addFinalizer(() => Queue.shutdown(queue).pipe(Effect.asVoid));
const start: ProviderCommandReactorShape["start"] = Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (
event.type !== "thread.runtime-mode-set" &&
event.type !== "thread.turn-start-requested" &&
event.type !== "thread.turn-interrupt-requested" &&
event.type !== "thread.approval-response-requested" &&
event.type !== "thread.user-input-response-requested" &&
event.type !== "thread.session-stop-requested"
) {
return Effect.void;
}
yield* Effect.forkScoped(
Effect.forever(Queue.take(queue).pipe(Effect.flatMap(processDomainEventSafely))),
);
return worker.enqueue(event);
}),
).pipe(Effect.asVoid);
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (
event.type !== "thread.runtime-mode-set" &&
event.type !== "thread.turn-start-requested" &&
event.type !== "thread.turn-interrupt-requested" &&
event.type !== "thread.approval-response-requested" &&
event.type !== "thread.user-input-response-requested" &&
event.type !== "thread.session-stop-requested"
) {
return Effect.void;
}
return Queue.offer(queue, event).pipe(Effect.asVoid);
}),
);
});
return {
start,
drain: worker.drain,
} satisfies ProviderCommandReactorShape;
});
@@ -45,7 +45,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex" | "claudeCode";
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -159,7 +159,7 @@ describe("ProviderRuntimeIngestion", () => {
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(ingestion.start.pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(ingestion.drain);
await Effect.runPromise(Effect.sleep("10 millis"));
const createdAt = new Date().toISOString();
await Effect.runPromise(
@@ -209,7 +209,6 @@ describe("ProviderRuntimeIngestion", () => {
return {
engine,
emit: provider.emit,
drain,
};
}
@@ -378,7 +377,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: asThreadId("thread-1"),
});
await harness.drain();
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
@@ -402,60 +401,6 @@ describe("ProviderRuntimeIngestion", () => {
);
});
it("accepts claude turn lifecycle when seeded thread id is a synthetic placeholder", async () => {
const harness = await createHarness();
const seededAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-seed-claude-placeholder"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeCode",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: seededAt,
lastError: null,
},
createdAt: seededAt,
}),
);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-claude-placeholder"),
provider: "claudeCode",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-claude-placeholder",
);
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-claude-placeholder"),
provider: "claudeCode",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
status: "completed",
});
await waitForThread(
harness.engine,
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
);
});
it("ignores auxiliary turn completions from a different provider thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -485,7 +430,7 @@ describe("ProviderRuntimeIngestion", () => {
status: "completed",
});
await harness.drain();
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
@@ -539,7 +484,7 @@ describe("ProviderRuntimeIngestion", () => {
status: "completed",
});
await harness.drain();
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
@@ -780,7 +725,7 @@ describe("ProviderRuntimeIngestion", () => {
},
});
await harness.drain();
await Effect.runPromise(Effect.sleep("30 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
@@ -839,7 +784,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
}),
);
await harness.drain();
await Effect.runPromise(Effect.sleep("30 millis"));
harness.emit({
type: "turn.started",
@@ -5,14 +5,12 @@ import {
MessageId,
type OrchestrationEvent,
CheckpointRef,
isToolLifecycleItemType,
ThreadId,
TurnId,
type OrchestrationThreadActivity,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { Cache, Cause, Duration, Effect, Layer, Option, Ref, Stream } from "effect";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Ref, Stream } from "effect";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
@@ -174,6 +172,18 @@ function requestKindFromCanonicalRequestType(
}
}
function isToolLifecycleItemType(itemType: string): boolean {
return (
itemType === "command_execution" ||
itemType === "file_change" ||
itemType === "mcp_tool_call" ||
itemType === "dynamic_tool_call" ||
itemType === "collab_agent_tool_call" ||
itemType === "web_search" ||
itemType === "image_view"
);
}
function runtimeEventToActivities(
event: ProviderRuntimeEvent,
): ReadonlyArray<OrchestrationThreadActivity> {
@@ -438,7 +448,7 @@ function runtimeEventToActivities(
createdAt: event.createdAt,
tone: "tool",
kind: "tool.completed",
summary: event.payload.title ?? "Tool",
summary: `${event.payload.title ?? "Tool"} complete`,
payload: {
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
@@ -1053,34 +1063,22 @@ const make = Effect.gen(function* () {
if (event.type === "turn.diff.updated") {
const turnId = toTurnId(event.turnId);
if (turnId && (yield* isGitRepoForThread(thread.id))) {
// Skip if a checkpoint already exists for this turn. A real
// (non-placeholder) capture from CheckpointReactor should not
// be clobbered, and dispatching a duplicate placeholder for the
// same turnId would produce an unstable checkpointTurnCount.
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
// Already tracked; no-op.
} else {
const assistantMessageId = MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
const maxTurnCount = thread.checkpoints.reduce(
(max, c) => Math.max(max, c.checkpointTurnCount),
0,
);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: providerCommandId(event, "thread-turn-diff-complete"),
threadId: thread.id,
turnId,
completedAt: now,
checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`),
status: "missing",
files: [],
assistantMessageId,
checkpointTurnCount: maxTurnCount + 1,
createdAt: now,
});
}
const assistantMessageId = MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: providerCommandId(event, "thread-turn-diff-complete"),
threadId: thread.id,
turnId,
completedAt: now,
checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`),
status: "missing",
files: [],
assistantMessageId,
checkpointTurnCount: thread.checkpoints.length + 1,
createdAt: now,
});
}
}
@@ -1120,12 +1118,16 @@ const make = Effect.gen(function* () {
}),
);
const worker = yield* makeDrainableWorker(processInputSafely);
const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () {
const inputQueue = yield* Queue.unbounded<RuntimeIngestionInput>();
yield* Effect.addFinalizer(() => Queue.shutdown(inputQueue).pipe(Effect.asVoid));
yield* Effect.forkScoped(
Effect.forever(Queue.take(inputQueue).pipe(Effect.flatMap(processInputSafely))),
);
yield* Effect.forkScoped(
Stream.runForEach(providerService.streamEvents, (event) =>
worker.enqueue({ source: "runtime", event }),
Queue.offer(inputQueue, { source: "runtime", event }).pipe(Effect.asVoid),
),
);
yield* Effect.forkScoped(
@@ -1133,14 +1135,13 @@ const make = Effect.gen(function* () {
if (event.type !== "thread.turn-start-requested") {
return Effect.void;
}
return worker.enqueue({ source: "domain", event });
return Queue.offer(inputQueue, { source: "domain", event }).pipe(Effect.asVoid);
}),
);
});
return {
start,
drain: worker.drain,
} satisfies ProviderRuntimeIngestionShape;
});
@@ -1,18 +0,0 @@
import { Effect, Layer, PubSub, Stream } from "effect";
import {
RuntimeReceiptBus,
type RuntimeReceiptBusShape,
type OrchestrationRuntimeReceipt,
} from "../Services/RuntimeReceiptBus.ts";
const makeRuntimeReceiptBus = Effect.gen(function* () {
const pubSub = yield* PubSub.unbounded<OrchestrationRuntimeReceipt>();
return {
publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid),
stream: Stream.fromPubSub(pubSub),
} satisfies RuntimeReceiptBusShape;
});
export const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus);
@@ -23,12 +23,6 @@ export interface CheckpointReactorShape {
* internal queue.
*/
readonly start: Effect.Effect<void, never, Scope.Scope>;
/**
* Resolves when the internal processing queue is empty and idle.
* Intended for test use to replace timing-sensitive sleeps.
*/
readonly drain: Effect.Effect<void>;
}
/**
@@ -23,12 +23,6 @@ export interface ProviderCommandReactorShape {
* processing.
*/
readonly start: Effect.Effect<void, never, Scope.Scope>;
/**
* Resolves when the internal processing queue is empty and idle.
* Intended for test use to replace timing-sensitive sleeps.
*/
readonly drain: Effect.Effect<void>;
}
/**
@@ -23,12 +23,6 @@ export interface ProviderRuntimeIngestionShape {
* logging warnings.
*/
readonly start: Effect.Effect<void, never, Scope.Scope>;
/**
* Resolves when the internal processing queue is empty and idle.
* Intended for test use to replace timing-sensitive sleeps.
*/
readonly drain: Effect.Effect<void>;
}
/**
@@ -1,49 +0,0 @@
import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
export const CheckpointBaselineCapturedReceipt = Schema.Struct({
type: Schema.Literal("checkpoint.baseline.captured"),
threadId: ThreadId,
checkpointTurnCount: NonNegativeInt,
checkpointRef: CheckpointRef,
createdAt: IsoDateTime,
});
export type CheckpointBaselineCapturedReceipt = typeof CheckpointBaselineCapturedReceipt.Type;
export const CheckpointDiffFinalizedReceipt = Schema.Struct({
type: Schema.Literal("checkpoint.diff.finalized"),
threadId: ThreadId,
turnId: TurnId,
checkpointTurnCount: NonNegativeInt,
checkpointRef: CheckpointRef,
status: Schema.Literals(["ready", "missing", "error"]),
createdAt: IsoDateTime,
});
export type CheckpointDiffFinalizedReceipt = typeof CheckpointDiffFinalizedReceipt.Type;
export const TurnProcessingQuiescedReceipt = Schema.Struct({
type: Schema.Literal("turn.processing.quiesced"),
threadId: ThreadId,
turnId: TurnId,
checkpointTurnCount: NonNegativeInt,
createdAt: IsoDateTime,
});
export type TurnProcessingQuiescedReceipt = typeof TurnProcessingQuiescedReceipt.Type;
export const OrchestrationRuntimeReceipt = Schema.Union([
CheckpointBaselineCapturedReceipt,
CheckpointDiffFinalizedReceipt,
TurnProcessingQuiescedReceipt,
]);
export type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Type;
export interface RuntimeReceiptBusShape {
readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect<void>;
readonly stream: Stream.Stream<OrchestrationRuntimeReceipt>;
}
export class RuntimeReceiptBus extends ServiceMap.Service<
RuntimeReceiptBus,
RuntimeReceiptBusShape
>()("t3/orchestration/Services/RuntimeReceiptBus") {}
@@ -500,16 +500,6 @@ export function projectEvent(
"checkpoint",
);
// Do not let a placeholder (status "missing") overwrite a checkpoint
// that has already been captured with a real git ref (status "ready").
// ProviderRuntimeIngestion may fire multiple turn.diff.updated events
// per turn; without this guard later placeholders would clobber the
// real capture dispatched by CheckpointReactor.
const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
return nextBase;
}
const checkpoints = [
...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId),
checkpoint,
@@ -50,35 +50,11 @@ export interface SqliteMemoryClientConfig extends Omit<
"filename" | "readonly"
> {}
/**
* Verify that the current Node.js version includes the `node:sqlite` APIs
* used by `NodeSqliteClient` — specifically `StatementSync.columns()` (added
* in Node 22.16.0 / 23.11.0).
*
* @see https://github.com/nodejs/node/pull/57490
*/
const checkNodeSqliteCompat = () => {
const parts = process.versions.node.split(".").map(Number);
const major = parts[0] ?? 0;
const minor = parts[1] ?? 0;
const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
if (!supported) {
return Effect.die(
`Node.js ${process.versions.node} is missing required node:sqlite APIs ` +
`(StatementSync.columns). Upgrade to Node.js >=22.16, >=23.11, or >=24.`,
);
}
return Effect.void;
};
const makeWithDatabase = (
options: SqliteClientConfig,
openDatabase: () => DatabaseSync,
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
Effect.gen(function* () {
yield* checkNodeSqliteCompat();
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
const transformRows = options.transformResultNames
? Statement.defaultTransforms(options.transformResultNames).array
@@ -1,947 +0,0 @@
import type {
Options as ClaudeQueryOptions,
PermissionMode,
PermissionResult,
SDKMessage,
SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import { Effect, Fiber, Random, Stream } from "effect";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { ClaudeCodeAdapter } from "../Services/ClaudeCodeAdapter.ts";
import {
makeClaudeCodeAdapterLive,
type ClaudeCodeAdapterLiveOptions,
} from "./ClaudeCodeAdapter.ts";
class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
private readonly queue: Array<SDKMessage> = [];
private readonly resolvers: Array<(value: IteratorResult<SDKMessage>) => void> = [];
private done = false;
public readonly interruptCalls: Array<void> = [];
public readonly setModelCalls: Array<string | undefined> = [];
public readonly setPermissionModeCalls: Array<string> = [];
public readonly setMaxThinkingTokensCalls: Array<number | null> = [];
public closeCalls = 0;
emit(message: SDKMessage): void {
if (this.done) {
return;
}
const resolver = this.resolvers.shift();
if (resolver) {
resolver({ done: false, value: message });
return;
}
this.queue.push(message);
}
finish(): void {
if (this.done) {
return;
}
this.done = true;
for (const resolver of this.resolvers.splice(0)) {
resolver({ done: true, value: undefined });
}
}
readonly interrupt = async (): Promise<void> => {
this.interruptCalls.push(undefined);
};
readonly setModel = async (model?: string): Promise<void> => {
this.setModelCalls.push(model);
};
readonly setPermissionMode = async (mode: PermissionMode): Promise<void> => {
this.setPermissionModeCalls.push(mode);
};
readonly setMaxThinkingTokens = async (maxThinkingTokens: number | null): Promise<void> => {
this.setMaxThinkingTokensCalls.push(maxThinkingTokens);
};
readonly close = (): void => {
this.closeCalls += 1;
this.finish();
};
[Symbol.asyncIterator](): AsyncIterator<SDKMessage> {
return {
next: () => {
if (this.queue.length > 0) {
const value = this.queue.shift();
if (value) {
return Promise.resolve({
done: false,
value,
});
}
}
if (this.done) {
return Promise.resolve({
done: true,
value: undefined,
});
}
return new Promise((resolve) => {
this.resolvers.push(resolve);
});
},
};
}
}
interface Harness {
readonly layer: ReturnType<typeof makeClaudeCodeAdapterLive>;
readonly query: FakeClaudeQuery;
readonly getLastCreateQueryInput: () =>
| {
readonly prompt: AsyncIterable<SDKUserMessage>;
readonly options: ClaudeQueryOptions;
}
| undefined;
}
function makeHarness(config?: {
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: ClaudeCodeAdapterLiveOptions["nativeEventLogger"];
}): Harness {
const query = new FakeClaudeQuery();
let createInput:
| {
readonly prompt: AsyncIterable<SDKUserMessage>;
readonly options: ClaudeQueryOptions;
}
| undefined;
const adapterOptions: ClaudeCodeAdapterLiveOptions = {
createQuery: (input) => {
createInput = input;
return query;
},
...(config?.nativeEventLogger
? {
nativeEventLogger: config.nativeEventLogger,
}
: {}),
...(config?.nativeEventLogPath
? {
nativeEventLogPath: config.nativeEventLogPath,
}
: {}),
};
return {
layer: makeClaudeCodeAdapterLive(adapterOptions),
query,
getLastCreateQueryInput: () => createInput,
};
}
function makeDeterministicRandomService(seed = 0x1234_5678): {
nextIntUnsafe: () => number;
nextDoubleUnsafe: () => number;
} {
let state = seed >>> 0;
const nextIntUnsafe = (): number => {
state = (Math.imul(1_664_525, state) + 1_013_904_223) >>> 0;
return state;
};
return {
nextIntUnsafe,
nextDoubleUnsafe: () => nextIntUnsafe() / 0x1_0000_0000,
};
}
const THREAD_ID = ThreadId.makeUnsafe("thread-claude-1");
const RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-claude-resume");
describe("ClaudeCodeAdapterLive", () => {
it.effect("returns validation error for non-claudeCode provider on startSession", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const result = yield* adapter
.startSession({ threadId: THREAD_ID, provider: "codex", runtimeMode: "full-access" })
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
if (result._tag !== "Failure") {
return;
}
assert.deepEqual(
result.failure,
new ProviderAdapterValidationError({
provider: "claudeCode",
operation: "startSession",
issue: "Expected provider 'claudeCode' but received 'codex'.",
}),
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("derives bypass permission mode from full-access runtime policy", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.permissionMode, "bypassPermissions");
assert.equal(createInput?.options.allowDangerouslySkipPermissions, true);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("keeps explicit claude permission mode over runtime-derived defaults", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
providerOptions: {
claudeCode: {
permissionMode: "plan",
},
},
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.permissionMode, "plan");
assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("maps Claude stream/runtime messages to canonical provider runtime events", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 11).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
model: "claude-sonnet-4-5",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-1",
uuid: "stream-1",
parent_tool_use_id: null,
event: {
type: "content_block_delta",
index: 0,
delta: {
type: "text_delta",
text: "Hi",
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-1",
uuid: "stream-2",
parent_tool_use_id: null,
event: {
type: "content_block_start",
index: 1,
content_block: {
type: "tool_use",
id: "tool-1",
name: "Bash",
input: {
command: "ls",
},
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-1",
uuid: "stream-3",
parent_tool_use_id: null,
event: {
type: "content_block_stop",
index: 1,
},
} as unknown as SDKMessage);
harness.query.emit({
type: "assistant",
session_id: "sdk-session-1",
uuid: "assistant-1",
parent_tool_use_id: null,
message: {
id: "assistant-message-1",
content: [{ type: "text", text: "Hi" }],
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-1",
uuid: "result-1",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
"content.delta",
"item.started",
"item.completed",
"item.updated",
"item.completed",
"turn.completed",
],
);
const turnStarted = runtimeEvents[3];
assert.equal(turnStarted?.type, "turn.started");
if (turnStarted?.type === "turn.started") {
assert.equal(String(turnStarted.turnId), String(turn.turnId));
}
const deltaEvent = runtimeEvents.find((event) => event.type === "content.delta");
assert.equal(deltaEvent?.type, "content.delta");
if (deltaEvent?.type === "content.delta") {
assert.equal(deltaEvent.payload.delta, "Hi");
assert.equal(String(deltaEvent.turnId), String(turn.turnId));
}
const toolStarted = runtimeEvents.find((event) => event.type === "item.started");
assert.equal(toolStarted?.type, "item.started");
if (toolStarted?.type === "item.started") {
assert.equal(toolStarted.payload.itemType, "command_execution");
}
const turnCompleted = runtimeEvents[runtimeEvents.length - 1];
assert.equal(turnCompleted?.type, "turn.completed");
if (turnCompleted?.type === "turn.completed") {
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
assert.equal(turnCompleted.payload.state, "completed");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect(
"emits completion only after turn result when assistant frames arrive before deltas",
() => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "assistant",
session_id: "sdk-session-early-assistant",
uuid: "assistant-early",
parent_tool_use_id: null,
message: {
id: "assistant-message-early",
content: [
{ type: "tool_use", id: "tool-early", name: "Read", input: { path: "a.ts" } },
],
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-early-assistant",
uuid: "stream-early",
parent_tool_use_id: null,
event: {
type: "content_block_delta",
index: 0,
delta: {
type: "text_delta",
text: "Late text",
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-early-assistant",
uuid: "result-early",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
"item.updated",
"content.delta",
"item.completed",
"turn.completed",
],
);
const deltaIndex = runtimeEvents.findIndex((event) => event.type === "content.delta");
const completedIndex = runtimeEvents.findIndex((event) => event.type === "item.completed");
assert.equal(deltaIndex >= 0 && completedIndex >= 0 && deltaIndex < completedIndex, true);
const deltaEvent = runtimeEvents[deltaIndex];
assert.equal(deltaEvent?.type, "content.delta");
if (deltaEvent?.type === "content.delta") {
assert.equal(deltaEvent.payload.delta, "Late text");
assert.equal(String(deltaEvent.turnId), String(turn.turnId));
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
},
);
it.effect("falls back to assistant payload text when stream deltas are absent", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "assistant",
session_id: "sdk-session-fallback-text",
uuid: "assistant-fallback",
parent_tool_use_id: null,
message: {
id: "assistant-message-fallback",
content: [{ type: "text", text: "Fallback hello" }],
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-fallback-text",
uuid: "result-fallback",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
"item.updated",
"content.delta",
"item.completed",
"turn.completed",
],
);
const deltaEvent = runtimeEvents.find((event) => event.type === "content.delta");
assert.equal(deltaEvent?.type, "content.delta");
if (deltaEvent?.type === "content.delta") {
assert.equal(deltaEvent.payload.delta, "Fallback hello");
assert.equal(String(deltaEvent.turnId), String(turn.turnId));
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("does not fabricate provider thread ids before first SDK session_id", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 5).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
assert.equal(session.threadId, THREAD_ID);
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
assert.equal(turn.threadId, THREAD_ID);
harness.query.emit({
type: "stream_event",
session_id: "sdk-thread-real",
uuid: "stream-thread-real",
parent_tool_use_id: null,
event: {
type: "message_start",
message: {
id: "msg-thread-real",
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-thread-real",
uuid: "result-thread-real",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
],
);
const sessionStarted = runtimeEvents[0];
assert.equal(sessionStarted?.type, "session.started");
if (sessionStarted?.type === "session.started") {
assert.equal(sessionStarted.threadId, THREAD_ID);
}
const threadStarted = runtimeEvents[4];
assert.equal(threadStarted?.type, "thread.started");
if (threadStarted?.type === "thread.started") {
assert.equal(threadStarted.threadId, THREAD_ID);
assert.deepEqual(threadStarted.payload, {
providerThreadId: "sdk-thread-real",
});
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("bridges approval request/response lifecycle through canUseTool", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "approval-required",
});
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
const createInput = harness.getLastCreateQueryInput();
const canUseTool = createInput?.options.canUseTool;
assert.equal(typeof canUseTool, "function");
if (!canUseTool) {
return;
}
const permissionPromise = canUseTool(
"Bash",
{ command: "pwd" },
{
signal: new AbortController().signal,
suggestions: [
{
type: "setMode",
mode: "default",
destination: "session",
},
],
toolUseID: "tool-use-1",
},
);
const requested = yield* Stream.runHead(adapter.streamEvents);
assert.equal(requested._tag, "Some");
if (requested._tag !== "Some") {
return;
}
assert.equal(requested.value.type, "request.opened");
if (requested.value.type !== "request.opened") {
return;
}
const runtimeRequestId = requested.value.requestId;
assert.equal(typeof runtimeRequestId, "string");
if (runtimeRequestId === undefined) {
return;
}
yield* adapter.respondToRequest(
session.threadId,
ApprovalRequestId.makeUnsafe(runtimeRequestId),
"accept",
);
const resolved = yield* Stream.runHead(adapter.streamEvents);
assert.equal(resolved._tag, "Some");
if (resolved._tag !== "Some") {
return;
}
assert.equal(resolved.value.type, "request.resolved");
if (resolved.value.type !== "request.resolved") {
return;
}
assert.equal(resolved.value.requestId, requested.value.requestId);
assert.equal(resolved.value.payload.decision, "accept");
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.equal((permissionResult as PermissionResult).behavior, "allow");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("passes parsed resume cursor values to Claude query options", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: RESUME_THREAD_ID,
provider: "claudeCode",
resumeCursor: {
threadId: "resume-thread-1",
resume: "550e8400-e29b-41d4-a716-446655440000",
resumeSessionAt: "assistant-99",
turnCount: 3,
},
runtimeMode: "full-access",
});
assert.equal(session.threadId, RESUME_THREAD_ID);
assert.deepEqual(session.resumeCursor, {
threadId: RESUME_THREAD_ID,
resume: "550e8400-e29b-41d4-a716-446655440000",
resumeSessionAt: "assistant-99",
turnCount: 3,
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.resume, "550e8400-e29b-41d4-a716-446655440000");
assert.equal(createInput?.options.resumeSessionAt, "assistant-99");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("does not synthesize resume session id from generated thread ids", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
assert.equal("resume" in (session.resumeCursor as Record<string, unknown>), false);
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.resume, undefined);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect(
"supports rollbackThread by trimming in-memory turns and preserving earlier turns",
() => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
const firstTurn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "first",
attachments: [],
});
const firstCompletedFiber = yield* Stream.filter(
adapter.streamEvents,
(event) => event.type === "turn.completed",
).pipe(Stream.runHead, Effect.forkChild);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-rollback",
uuid: "result-first",
} as unknown as SDKMessage);
const firstCompleted = yield* Fiber.join(firstCompletedFiber);
assert.equal(firstCompleted._tag, "Some");
if (firstCompleted._tag === "Some" && firstCompleted.value.type === "turn.completed") {
assert.equal(String(firstCompleted.value.turnId), String(firstTurn.turnId));
}
const secondTurn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "second",
attachments: [],
});
const secondCompletedFiber = yield* Stream.filter(
adapter.streamEvents,
(event) => event.type === "turn.completed",
).pipe(Stream.runHead, Effect.forkChild);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-rollback",
uuid: "result-second",
} as unknown as SDKMessage);
const secondCompleted = yield* Fiber.join(secondCompletedFiber);
assert.equal(secondCompleted._tag, "Some");
if (secondCompleted._tag === "Some" && secondCompleted.value.type === "turn.completed") {
assert.equal(String(secondCompleted.value.turnId), String(secondTurn.turnId));
}
const threadBeforeRollback = yield* adapter.readThread(session.threadId);
assert.equal(threadBeforeRollback.turns.length, 2);
const rolledBack = yield* adapter.rollbackThread(session.threadId, 1);
assert.equal(rolledBack.turns.length, 1);
assert.equal(rolledBack.turns[0]?.id, firstTurn.turnId);
const threadAfterRollback = yield* adapter.readThread(session.threadId);
assert.equal(threadAfterRollback.turns.length, 1);
assert.equal(threadAfterRollback.turns[0]?.id, firstTurn.turnId);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
},
);
it.effect("updates model on sendTurn when model override is provided", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
model: "claude-opus-4-6",
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("writes provider-native observability records when enabled", () => {
const nativeEvents: Array<{
event?: {
provider?: string;
method?: string;
threadId?: string;
turnId?: string;
};
}> = [];
const harness = makeHarness({
nativeEventLogger: {
filePath: "memory://claude-native-events",
write: (event) => {
nativeEvents.push(event as (typeof nativeEvents)[number]);
return Effect.void;
},
close: () => Effect.void,
},
});
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
const turnCompletedFiber = yield* Stream.filter(
adapter.streamEvents,
(event) => event.type === "turn.completed",
).pipe(Stream.runHead, Effect.forkChild);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-native-log",
uuid: "stream-native-log",
parent_tool_use_id: null,
event: {
type: "content_block_delta",
index: 0,
delta: {
type: "text_delta",
text: "hi",
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-native-log",
uuid: "result-native-log",
} as unknown as SDKMessage);
const turnCompleted = yield* Fiber.join(turnCompletedFiber);
assert.equal(turnCompleted._tag, "Some");
assert.equal(nativeEvents.length > 0, true);
assert.equal(
nativeEvents.some((record) => record.event?.provider === "claudeCode"),
true,
);
assert.equal(
nativeEvents.some(
(record) =>
String(
(record.event as { readonly providerThreadId?: string } | undefined)
?.providerThreadId,
) === "sdk-session-native-log",
),
true,
);
assert.equal(
nativeEvents.some((record) => String(record.event?.turnId) === String(turn.turnId)),
true,
);
assert.equal(
nativeEvents.some(
(record) => record.event?.method === "claude/stream_event/content_block_delta/text_delta",
),
true,
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
});
File diff suppressed because it is too large. Load diff
@@ -22,7 +22,6 @@ import {
type CodexAppServerSendTurnInput,
} from "../../codexAppServerManager.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
@@ -157,29 +156,6 @@ const validationLayer = it.layer(
);
validationLayer("CodexAdapterLive validation", (it) => {
it.effect("returns validation error for non-codex provider on startSession", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const result = yield* adapter
.startSession({
provider: "claudeCode",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
})
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
assert.deepStrictEqual(
result.failure,
new ProviderAdapterValidationError({
provider: "codex",
operation: "startSession",
issue: "Expected provider 'codex' but received 'claudeCode'.",
}),
);
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
}),
);
it.effect("maps codex model options before starting a session", () =>
Effect.gen(function* () {
validationManager.startSessionImpl.mockClear();
@@ -164,7 +164,7 @@ function itemTitle(itemType: CanonicalItemType): string | undefined {
case "plan":
return "Plan";
case "command_execution":
return "Ran command";
return "Command run";
case "file_change":
return "File change";
case "mcp_tool_call":
@@ -1338,17 +1338,11 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
new Error(`Invalid attachment id '${attachment.id}'.`),
);
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: toMessage(cause, "Failed to read attachment file."),
cause,
}),
),
);
const bytes = yield* fileSystem
.readFile(attachmentPath)
.pipe(
Effect.mapError((cause) => toRequestError(input.threadId, "turn/start", cause)),
);
return {
type: "image" as const,
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
@@ -4,7 +4,6 @@ import { assertFailure } from "@effect/vitest/utils";
import { Effect, Layer, Stream } from "effect";
import { ClaudeCodeAdapter, ClaudeCodeAdapterShape } from "../Services/ClaudeCodeAdapter.ts";
import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
@@ -28,32 +27,9 @@ const fakeCodexAdapter: CodexAdapterShape = {
streamEvents: Stream.empty,
};
const fakeClaudeAdapter: ClaudeCodeAdapterShape = {
provider: "claudeCode",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
readThread: vi.fn(),
rollbackThread: vi.fn(),
stopAll: vi.fn(),
streamEvents: Stream.empty,
};
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLive,
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeCodeAdapter, fakeClaudeAdapter),
),
),
Layer.provide(ProviderAdapterRegistryLive, Layer.succeed(CodexAdapter, fakeCodexAdapter)),
NodeServices.layer,
),
);
@@ -63,12 +39,10 @@ layer("ProviderAdapterRegistryLive", (it) => {
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeCode");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex", "claudeCode"]);
assert.deepEqual(providers, ["codex"]);
}),
);
@@ -1,7 +1,7 @@
/**
* ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.
*
* Binds provider kinds (codex/claudeCode/...) to concrete adapter services.
* Binds provider kinds (codex/cursor/...) to concrete adapter services.
* This layer only performs adapter lookup; it does not route session-scoped
* calls or own provider lifecycle workflows.
*
@@ -15,7 +15,6 @@ import {
ProviderAdapterRegistry,
type ProviderAdapterRegistryShape,
} from "../Services/ProviderAdapterRegistry.ts";
import { ClaudeCodeAdapter } from "../Services/ClaudeCodeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
export interface ProviderAdapterRegistryLiveOptions {
@@ -24,10 +23,7 @@ export interface ProviderAdapterRegistryLiveOptions {
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
Effect.gen(function* () {
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeCodeAdapter];
const adapters = options?.adapters !== undefined ? options.adapters : [yield* CodexAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
@@ -1,8 +1,12 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Sink, Stream } from "effect";
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { it } from "@effect/vitest";
import { Effect, Layer, Sink, Stream } from "effect";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { afterEach, beforeEach, describe } from "vitest";
import {
checkCodexProviderStatus,
@@ -59,133 +63,126 @@ function failingSpawnerLayer(description: string) {
}
/**
* Create a temporary CODEX_HOME scoped to the current Effect test.
* Cleanup is registered in the test scope rather than via Vitest hooks.
* Create a temporary CODEX_HOME with an optional config.toml content.
* Returns a cleanup function that restores the original env var.
*/
function withTempCodexHome(configContent?: string) {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" });
yield* Effect.acquireRelease(
Effect.sync(() => {
const originalCodexHome = process.env.CODEX_HOME;
process.env.CODEX_HOME = tmpDir;
return originalCodexHome;
}),
(originalCodexHome) =>
Effect.sync(() => {
if (originalCodexHome !== undefined) {
process.env.CODEX_HOME = originalCodexHome;
} else {
delete process.env.CODEX_HOME;
}
}),
);
if (configContent !== undefined) {
yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent);
}
return { tmpDir } as const;
});
function withTempCodexHome(configContent?: string): { tmpDir: string; cleanup: () => void } {
const originalCodexHome = process.env.CODEX_HOME;
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-test-codex-"));
process.env.CODEX_HOME = tmpDir;
if (configContent !== undefined) {
fs.writeFileSync(path.join(tmpDir, "config.toml"), configContent);
}
return {
tmpDir,
cleanup: () => {
if (originalCodexHome !== undefined) {
process.env.CODEX_HOME = originalCodexHome;
} else {
delete process.env.CODEX_HOME;
}
fs.rmSync(tmpDir, { recursive: true, force: true });
},
};
}
it.layer(NodeServices.layer)("ProviderHealth", (it) => {
// ── checkCodexProviderStatus tests ────────────────────────────────
//
// These tests control CODEX_HOME to ensure the custom-provider detection
// in hasCustomModelProvider() does not interfere with the auth-probe
// path being tested.
// ── checkCodexProviderStatus tests ──────────────────────────────────
//
// These tests control CODEX_HOME to ensure the custom-provider detection
// in hasCustomModelProvider() does not interfere with the auth-probe
// path being tested.
describe("checkCodexProviderStatus", () => {
it.effect("returns ready when codex is installed and authenticated", () =>
Effect.gen(function* () {
// Point CODEX_HOME at an empty tmp dir (no config.toml) so the
// default code path (OpenAI provider, auth probe runs) is exercised.
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
describe("checkCodexProviderStatus", () => {
let cleanup: () => void;
// Point CODEX_HOME at an empty tmp dir (no config.toml) so the
// default code path (OpenAI provider, auth probe runs) is exercised.
beforeEach(() => {
({ cleanup } = withTempCodexHome());
});
afterEach(() => cleanup());
it.effect("returns ready when codex is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
);
),
);
it.effect("returns unavailable when codex is missing", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
it.effect("returns unavailable when codex is missing", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
it.effect("returns unavailable when codex is below the minimum supported version", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
it.effect("returns unavailable when codex is below the minimum supported version", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
);
),
);
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
);
),
);
it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>
it.effect(
"returns unauthenticated when login status output includes 'not logged in'",
() =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
@@ -206,49 +203,52 @@ it.layer(NodeServices.layer)("ProviderHealth", (it) => {
}),
),
),
);
);
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
);
),
);
});
// ── Custom model provider: checkCodexProviderStatus integration ─────
describe("checkCodexProviderStatus with custom model provider", () => {
let cleanup: () => void;
beforeEach(() => {
({ cleanup } = withTempCodexHome(
['model_provider = "portkey"', "", "[model_providers.portkey]", 'base_url = "https://api.portkey.ai/v1"', 'env_key = "PORTKEY_API_KEY"'].join(
"\n",
),
));
});
afterEach(() => cleanup());
// ── Custom model provider: checkCodexProviderStatus integration ───
describe("checkCodexProviderStatus with custom model provider", () => {
it.effect("skips auth probe and returns ready when a custom model provider is configured", () =>
it.effect(
"skips auth probe and returns ready when a custom model provider is configured",
() =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model_provider = "portkey"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'env_key = "PORTKEY_API_KEY"',
].join("\n"),
);
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
@@ -269,199 +269,191 @@ it.layer(NodeServices.layer)("ProviderHealth", (it) => {
}),
),
),
);
);
it.effect("still reports error when codex CLI is missing even with custom provider", () =>
it.effect(
"still reports error when codex CLI is missing even with custom provider",
() =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model_provider = "portkey"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'env_key = "PORTKEY_API_KEY"',
].join("\n"),
);
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
});
);
});
describe("checkCodexProviderStatus with openai model provider", () => {
it.effect("still runs auth probe when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
const status = yield* checkCodexProviderStatus;
// The auth probe runs and sees "not logged in" → error
assert.strictEqual(status.status, "error");
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
describe("checkCodexProviderStatus with openai model provider", () => {
let cleanup: () => void;
beforeEach(() => {
({ cleanup } = withTempCodexHome('model_provider = "openai"\n'));
});
afterEach(() => cleanup());
it.effect("still runs auth probe when model_provider is openai", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
// The auth probe runs and sees "not logged in" → error
assert.strictEqual(status.status, "error");
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
);
),
);
});
// ── parseAuthStatusFromOutput pure tests ────────────────────────────
describe("parseAuthStatusFromOutput", () => {
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
// ── parseAuthStatusFromOutput pure tests ──────────────────────────
describe("parseAuthStatusFromOutput", () => {
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with authenticated=false is unauthenticated", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"authenticated":false}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"ok":true}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
it("JSON with authenticated=false is unauthenticated", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"authenticated":false}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
// ── readCodexConfigModelProvider tests ─────────────────────────────
describe("readCodexConfigModelProvider", () => {
it.effect("returns undefined when config file does not exist", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
}),
);
it.effect("returns undefined when config has no model_provider key", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\n');
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
}),
);
it.effect("returns the provider when model_provider is set at top level", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n');
assert.strictEqual(yield* readCodexConfigModelProvider, "portkey");
}),
);
it.effect("returns openai when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
assert.strictEqual(yield* readCodexConfigModelProvider, "openai");
}),
);
it.effect("ignores model_provider inside section headers", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model = "gpt-5-codex"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'model_provider = "should-be-ignored"',
"",
].join("\n"),
);
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
}),
);
it.effect("handles comments and whitespace", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
"# This is a comment",
"",
' model_provider = "azure" ',
"",
"[profiles.deep-review]",
'model = "gpt-5-pro"',
].join("\n"),
);
assert.strictEqual(yield* readCodexConfigModelProvider, "azure");
}),
);
it.effect("handles single-quoted values in TOML", () =>
Effect.gen(function* () {
yield* withTempCodexHome("model_provider = 'mistral'\n");
assert.strictEqual(yield* readCodexConfigModelProvider, "mistral");
}),
);
});
// ── hasCustomModelProvider tests ───────────────────────────────────
describe("hasCustomModelProvider", () => {
it.effect("returns false when no config file exists", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns false when model_provider is not set", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\n');
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns false when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns true when model_provider is portkey", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "portkey"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is azure", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "azure"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is ollama", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "ollama"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is a custom proxy", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "my-company-proxy"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it("JSON without auth marker is warning", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"ok":true}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
// ── readCodexConfigModelProvider tests ───────────────────────────────
describe("readCodexConfigModelProvider", () => {
let cleanup: () => void;
let tmpDir: string;
beforeEach(() => {
({ tmpDir, cleanup } = withTempCodexHome());
});
afterEach(() => cleanup());
it("returns undefined when config file does not exist", () => {
assert.strictEqual(readCodexConfigModelProvider(), undefined);
});
it("returns undefined when config has no model_provider key", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model = "gpt-5-codex"\n');
assert.strictEqual(readCodexConfigModelProvider(), undefined);
});
it("returns the provider when model_provider is set at top level", () => {
fs.writeFileSync(
path.join(tmpDir, "config.toml"),
'model = "gpt-5-codex"\nmodel_provider = "portkey"\n',
);
assert.strictEqual(readCodexConfigModelProvider(), "portkey");
});
it("returns openai when model_provider is openai", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "openai"\n');
assert.strictEqual(readCodexConfigModelProvider(), "openai");
});
it("ignores model_provider inside section headers", () => {
fs.writeFileSync(
path.join(tmpDir, "config.toml"),
[
'model = "gpt-5-codex"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'model_provider = "should-be-ignored"',
"",
].join("\n"),
);
assert.strictEqual(readCodexConfigModelProvider(), undefined);
});
it("handles comments and whitespace", () => {
fs.writeFileSync(
path.join(tmpDir, "config.toml"),
[
"# This is a comment",
"",
' model_provider = "azure" ',
"",
"[profiles.deep-review]",
'model = "gpt-5-pro"',
].join("\n"),
);
assert.strictEqual(readCodexConfigModelProvider(), "azure");
});
it("handles single-quoted values in TOML", () => {
fs.writeFileSync(
path.join(tmpDir, "config.toml"),
"model_provider = 'mistral'\n",
);
assert.strictEqual(readCodexConfigModelProvider(), "mistral");
});
});
// ── hasCustomModelProvider tests ─────────────────────────────────────
describe("hasCustomModelProvider", () => {
let cleanup: () => void;
let tmpDir: string;
beforeEach(() => {
({ tmpDir, cleanup } = withTempCodexHome());
});
afterEach(() => cleanup());
it("returns false when no config file exists", () => {
assert.strictEqual(hasCustomModelProvider(), false);
});
it("returns false when model_provider is not set", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model = "gpt-5-codex"\n');
assert.strictEqual(hasCustomModelProvider(), false);
});
it("returns false when model_provider is openai", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "openai"\n');
assert.strictEqual(hasCustomModelProvider(), false);
});
it("returns true when model_provider is portkey", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "portkey"\n');
assert.strictEqual(hasCustomModelProvider(), true);
});
it("returns true when model_provider is azure", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "azure"\n');
assert.strictEqual(hasCustomModelProvider(), true);
});
it("returns true when model_provider is ollama", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "ollama"\n');
assert.strictEqual(hasCustomModelProvider(), true);
});
it("returns true when model_provider is a custom proxy", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "my-company-proxy"\n');
assert.strictEqual(hasCustomModelProvider(), true);
});
});
@@ -8,13 +8,15 @@
*
* @module ProviderHealthLive
*/
import * as fs from "node:fs";
import * as OS from "node:os";
import * as NodePath from "node:path";
import type {
ServerProviderAuthStatus,
ServerProviderStatus,
ServerProviderStatusState,
} from "@t3tools/contracts";
import { Array, Effect, Fiber, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
import { Array, Effect, Fiber, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
@@ -189,16 +191,14 @@ const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
* Returns `undefined` when the file does not exist or does not set
* `model_provider`.
*/
export const readCodexConfigModelProvider = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const codexHome = process.env.CODEX_HOME || path.join(OS.homedir(), ".codex");
const configPath = path.join(codexHome, "config.toml");
export function readCodexConfigModelProvider(): string | undefined {
const codexHome = process.env.CODEX_HOME || NodePath.join(OS.homedir(), ".codex");
const configPath = NodePath.join(codexHome, "config.toml");
const content = yield* fileSystem
.readFileString(configPath)
.pipe(Effect.orElseSucceed(() => undefined));
if (content === undefined) {
let content: string;
try {
content = fs.readFileSync(configPath, "utf8");
} catch {
return undefined;
}
@@ -221,7 +221,7 @@ export const readCodexConfigModelProvider = Effect.gen(function* () {
if (match) return match[1];
}
return undefined;
});
}
/**
* Returns `true` when the Codex CLI is configured with a custom
@@ -229,10 +229,10 @@ export const readCodexConfigModelProvider = Effect.gen(function* () {
* required because authentication is handled through provider-specific
* environment variables.
*/
export const hasCustomModelProvider = Effect.map(
readCodexConfigModelProvider,
(provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider),
);
export function hasCustomModelProvider(): boolean {
const provider = readCodexConfigModelProvider();
return provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider);
}
// ── Effect-native command execution ─────────────────────────────────
@@ -269,7 +269,7 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
export const checkCodexProviderStatus: Effect.Effect<
ServerProviderStatus,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
ChildProcessSpawner.ChildProcessSpawner
> = Effect.gen(function* () {
const checkedAt = new Date().toISOString();
@@ -337,7 +337,7 @@ export const checkCodexProviderStatus: Effect.Effect<
// authentication through their own environment variables, so `codex
// login status` will report "not logged in" even when the CLI works
// fine. Skip the auth probe entirely for non-OpenAI providers.
if (yield* hasCustomModelProvider) {
if (hasCustomModelProvider()) {
return {
provider: CODEX_PROVIDER,
status: "ready" as const,
@@ -52,7 +52,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex" | "claudeCode";
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -74,7 +74,7 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
status: "ready",
runtimeMode: input.runtimeMode,
threadId: input.threadId,
resumeCursor: input.resumeCursor ?? { opaque: `resume-${String(input.threadId)}` },
resumeCursor: input.resumeCursor ?? { opaque: `cursor-${String(input.threadId)}` },
cwd: input.cwd ?? process.cwd(),
createdAt: now,
updatedAt: now,
@@ -217,15 +217,12 @@ const sleep = (ms: number) =>
function makeProviderServiceLayer() {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeCode");
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(codex.adapter)
: provider === "claudeCode"
? Effect.succeed(claude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex", "claudeCode"]),
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
@@ -250,7 +247,6 @@ function makeProviderServiceLayer() {
return {
codex,
claude,
layer,
};
}
@@ -537,29 +533,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("routes explicit claudeCode provider session starts to the claude adapter", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-claude"), {
provider: "claudeCode",
threadId: asThreadId("thread-claude"),
cwd: "/tmp/project-claude",
runtimeMode: "full-access",
});
assert.equal(session.provider, "claudeCode");
assert.equal(routing.claude.startSession.mock.calls.length, 1);
const startInput = routing.claude.startSession.mock.calls[0]?.[0];
assert.equal(typeof startInput === "object" && startInput !== null, true);
if (startInput && typeof startInput === "object") {
const startPayload = startInput as { provider?: string; cwd?: string };
assert.equal(startPayload.provider, "claudeCode");
assert.equal(startPayload.cwd, "/tmp/project-claude");
}
}),
);
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -616,7 +589,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
});
yield* routing.codex.stopAll();
yield* routing.claude.stopAll();
const remaining = yield* provider.listSessions();
assert.equal(remaining.length, 0);
@@ -731,7 +703,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
threadId: session.threadId,
turnId: asTurnId("turn-1"),
toolKind: "command",
title: "Ran command",
title: "Command run",
});
fanout.codex.emit({
type: "tool.completed",
@@ -741,7 +713,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
threadId: session.threadId,
turnId: asTurnId("turn-1"),
toolKind: "command",
title: "Ran command",
title: "Command run",
});
fanout.codex.emit({
type: "turn.completed",
@@ -796,7 +768,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
threadId: session.threadId,
turnId: asTurnId("turn-1"),
toolKind: "command",
title: "Ran command",
title: "Command run",
detail: "echo one",
},
{
@@ -292,7 +292,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
yield* upsertSessionBinding(session, threadId, {
providerOptions: input.providerOptions,
...(input.providerOptions !== undefined
? { providerOptions: input.providerOptions }
: {}),
});
yield* analytics.record("provider.session.started", {
provider: session.provider,
@@ -537,12 +539,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
listSessions,
getCapabilities,
rollbackConversation,
// Each access creates a fresh PubSub subscription so that multiple
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
// independently receive all runtime events.
get streamEvents(): ProviderServiceShape["streamEvents"] {
return Stream.fromPubSub(runtimeEventPubSub);
},
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
} satisfies ProviderServiceShape;
});
@@ -141,8 +141,8 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
yield* runtimeRepository.upsert({
threadId,
providerName: "claudeCode",
adapterKey: "claudeCode",
providerName: "cursor",
adapterKey: "cursor",
runtimeMode: "full-access",
status: "running",
lastSeenAt: new Date().toISOString(),
@@ -22,7 +22,7 @@ function decodeProviderKind(
providerName: string,
operation: string,
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
if (providerName === "codex" || providerName === "claudeCode") {
if (providerName === "codex") {
return Effect.succeed(providerName);
}
return Effect.fail(
@@ -1,31 +0,0 @@
/**
* ClaudeCodeAdapter - Claude Code implementation of the generic provider adapter contract.
*
* This service owns Claude runtime/session semantics and emits canonical
* provider runtime events. It does not perform cross-provider routing, shared
* event fan-out, or checkpoint orchestration.
*
* Uses Effect `ServiceMap.Service` for dependency injection and returns the
* shared provider-adapter error channel with `provider: "claudeCode"` context.
*
* @module ClaudeCodeAdapter
*/
import { ServiceMap } from "effect";
import type { ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
/**
* ClaudeCodeAdapterShape - Service API for the Claude Code provider adapter.
*/
export interface ClaudeCodeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
readonly provider: "claudeCode";
}
/**
* ClaudeCodeAdapter - Service tag for Claude Code provider adapter operations.
*/
export class ClaudeCodeAdapter extends ServiceMap.Service<
ClaudeCodeAdapter,
ClaudeCodeAdapterShape
>()("t3/provider/Services/ClaudeCodeAdapter") {}
-7
View File
@@ -17,9 +17,7 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma
import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline";
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus";
import { ProviderUnsupportedError } from "./provider/Errors";
import { makeClaudeCodeAdapterLive } from "./provider/Layers/ClaudeCodeAdapter";
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
@@ -59,12 +57,8 @@ export function makeServerProviderLayer(): Layer.Layer<
const codexAdapterLayer = makeCodexAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const claudeAdapterLayer = makeClaudeCodeAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
Layer.provide(codexAdapterLayer),
Layer.provide(claudeAdapterLayer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
return makeProviderServiceLive(
@@ -93,7 +87,6 @@ export function makeServerRuntimeServicesLayer() {
OrchestrationProjectionSnapshotQueryLive,
CheckpointStoreLive,
checkpointDiffQueryLayer,
RuntimeReceiptBusLive,
);
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
@@ -6,7 +6,6 @@ import {
DEFAULT_TERMINAL_ID,
type TerminalEvent,
type TerminalOpenInput,
type TerminalRestartInput,
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
@@ -135,16 +134,6 @@ function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInpu
};
}
function restartInput(overrides: Partial<TerminalRestartInput> = {}): TerminalRestartInput {
return {
threadId: "thread-1",
cwd: process.cwd(),
cols: 100,
rows: 24,
...overrides,
};
}
function historyLogName(threadId: string): string {
return `terminal_${Encoding.encodeBase64Url(threadId)}.log`;
}
@@ -372,7 +361,7 @@ describe("TerminalManager", () => {
firstProcess.emitData("before restart\n");
await waitFor(() => fs.existsSync(historyLogPath(logsDir)));
const snapshot = await manager.restart(restartInput());
const snapshot = await manager.restart(openInput());
expect(snapshot.history).toBe("");
expect(snapshot.status).toBe("running");
expect(ptyAdapter.spawnInputs).toHaveLength(2);
+2 -4
View File
@@ -8,7 +8,6 @@ import {
TerminalCloseInput,
TerminalOpenInput,
TerminalResizeInput,
TerminalRestartInput,
TerminalWriteInput,
type TerminalEvent,
type TerminalSessionSnapshot,
@@ -38,7 +37,6 @@ const DEFAULT_OPEN_ROWS = 30;
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput);
const decodeTerminalRestartInput = Schema.decodeUnknownSync(TerminalRestartInput);
const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput);
const decodeTerminalResizeInput = Schema.decodeUnknownSync(TerminalResizeInput);
const decodeTerminalClearInput = Schema.decodeUnknownSync(TerminalClearInput);
@@ -480,8 +478,8 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
});
}
async restart(raw: TerminalRestartInput): Promise<TerminalSessionSnapshot> {
const input = decodeTerminalRestartInput(raw);
async restart(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const input = decodeTerminalOpenInput(raw);
return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd);
+1 -2
View File
@@ -12,7 +12,6 @@ import {
TerminalEvent,
TerminalOpenInput,
TerminalResizeInput,
TerminalRestartInput,
TerminalSessionSnapshot,
TerminalSessionStatus,
TerminalWriteInput,
@@ -89,7 +88,7 @@ export interface TerminalManagerShape {
* Always resets history before spawning the new process.
*/
readonly restart: (
input: TerminalRestartInput,
input: TerminalOpenInput,
) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;
/**
-26
View File
@@ -70,32 +70,6 @@ describe("searchWorkspaceEntries", () => {
assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo")));
});
it("supports fuzzy subsequence queries for composer path search", async () => {
const cwd = makeTempDir("t3code-workspace-fuzzy-query-");
writeFile(cwd, "src/components/Composer.tsx");
writeFile(cwd, "src/components/composePrompt.ts");
writeFile(cwd, "docs/composition.md");
const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 });
const paths = result.entries.map((entry) => entry.path);
assert.isAbove(result.entries.length, 0);
assert.include(paths, "src/components");
assert.include(paths, "src/components/Composer.tsx");
});
it("tracks truncation without sorting every fuzzy match", async () => {
const cwd = makeTempDir("t3code-workspace-fuzzy-limit-");
writeFile(cwd, "src/components/Composer.tsx");
writeFile(cwd, "src/components/composePrompt.ts");
writeFile(cwd, "docs/composition.md");
const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 });
assert.lengthOf(result.entries, 1);
assert.isTrue(result.truncated);
});
it("excludes gitignored paths for git repositories", async () => {
const cwd = makeTempDir("t3code-workspace-gitignore-");
runGit(cwd, ["init"]);
+30 -164
View File
@@ -28,20 +28,10 @@ const IGNORED_DIRECTORY_NAMES = new Set([
interface WorkspaceIndex {
scannedAt: number;
entries: SearchableWorkspaceEntry[];
entries: ProjectEntry[];
truncated: boolean;
}
interface SearchableWorkspaceEntry extends ProjectEntry {
normalizedPath: string;
normalizedName: string;
}
interface RankedWorkspaceEntry {
entry: SearchableWorkspaceEntry;
score: number;
}
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
@@ -65,15 +55,6 @@ function basenameOf(input: string): string {
return input.slice(separatorIndex + 1);
}
function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry {
const normalizedPath = entry.path.toLowerCase();
return {
...entry,
normalizedPath,
normalizedName: basenameOf(normalizedPath),
};
}
function normalizeQuery(input: string): string {
return input
.trim()
@@ -81,120 +62,20 @@ function normalizeQuery(input: string): string {
.toLowerCase();
}
function scoreSubsequenceMatch(value: string, query: string): number | null {
if (!query) return 0;
let queryIndex = 0;
let firstMatchIndex = -1;
let previousMatchIndex = -1;
let gapPenalty = 0;
for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
if (value[valueIndex] !== query[queryIndex]) {
continue;
}
if (firstMatchIndex === -1) {
firstMatchIndex = valueIndex;
}
if (previousMatchIndex !== -1) {
gapPenalty += valueIndex - previousMatchIndex - 1;
}
previousMatchIndex = valueIndex;
queryIndex += 1;
if (queryIndex === query.length) {
const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
const lengthPenalty = Math.min(64, value.length - query.length);
return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;
}
}
return null;
}
function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null {
function scoreEntry(entry: ProjectEntry, query: string): number {
if (!query) {
return entry.kind === "directory" ? 0 : 1;
}
const { normalizedPath, normalizedName } = entry;
const normalizedPath = entry.path.toLowerCase();
const normalizedName = basenameOf(normalizedPath);
if (normalizedName === query) return 0;
if (normalizedPath === query) return 1;
if (normalizedName.startsWith(query)) return 2;
if (normalizedPath.startsWith(query)) return 3;
if (normalizedPath.includes(`/${query}`)) return 4;
if (normalizedName.includes(query)) return 5;
if (normalizedPath.includes(query)) return 6;
const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query);
if (nameFuzzyScore !== null) {
return 100 + nameFuzzyScore;
}
const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query);
if (pathFuzzyScore !== null) {
return 200 + pathFuzzyScore;
}
return null;
}
function compareRankedWorkspaceEntries(
left: RankedWorkspaceEntry,
right: RankedWorkspaceEntry,
): number {
const scoreDelta = left.score - right.score;
if (scoreDelta !== 0) return scoreDelta;
return left.entry.path.localeCompare(right.entry.path);
}
function findInsertionIndex(
rankedEntries: RankedWorkspaceEntry[],
candidate: RankedWorkspaceEntry,
): number {
let low = 0;
let high = rankedEntries.length;
while (low < high) {
const middle = low + Math.floor((high - low) / 2);
const current = rankedEntries[middle];
if (!current) {
break;
}
if (compareRankedWorkspaceEntries(candidate, current) < 0) {
high = middle;
} else {
low = middle + 1;
}
}
return low;
}
function insertRankedEntry(
rankedEntries: RankedWorkspaceEntry[],
candidate: RankedWorkspaceEntry,
limit: number,
): void {
if (limit <= 0) {
return;
}
const insertionIndex = findInsertionIndex(rankedEntries, candidate);
if (rankedEntries.length < limit) {
rankedEntries.splice(insertionIndex, 0, candidate);
return;
}
if (insertionIndex >= limit) {
return;
}
rankedEntries.splice(insertionIndex, 0, candidate);
rankedEntries.pop();
return 5;
}
function isPathInIgnoredDirectory(relativePath: string): boolean {
@@ -372,26 +253,20 @@ async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex |
}
}
const directoryEntries = [...directorySet]
const directoryEntries: ProjectEntry[] = [...directorySet]
.toSorted((left, right) => left.localeCompare(right))
.map(
(directoryPath): ProjectEntry => ({
path: directoryPath,
kind: "directory",
parentPath: parentPathOf(directoryPath),
}),
)
.map(toSearchableWorkspaceEntry);
const fileEntries = [...new Set(filePaths)]
.map((directoryPath) => ({
path: directoryPath,
kind: "directory",
parentPath: parentPathOf(directoryPath),
}));
const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
.toSorted((left, right) => left.localeCompare(right))
.map(
(filePath): ProjectEntry => ({
path: filePath,
kind: "file",
parentPath: parentPathOf(filePath),
}),
)
.map(toSearchableWorkspaceEntry);
.map((filePath) => ({
path: filePath,
kind: "file",
parentPath: parentPathOf(filePath),
}));
const entries = [...directoryEntries, ...fileEntries];
return {
@@ -409,7 +284,7 @@ async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
let pendingDirectories: string[] = [""];
const entries: SearchableWorkspaceEntry[] = [];
const entries: ProjectEntry[] = [];
let truncated = false;
while (pendingDirectories.length > 0 && !truncated) {
@@ -476,11 +351,11 @@ async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
continue;
}
const entry = toSearchableWorkspaceEntry({
const entry: ProjectEntry = {
path: candidate.relativePath,
kind: candidate.dirent.isDirectory() ? "directory" : "file",
parentPath: parentPathOf(candidate.relativePath),
});
};
entries.push(entry);
if (candidate.dirent.isDirectory()) {
@@ -534,32 +409,23 @@ async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
return nextPromise;
}
export function clearWorkspaceIndexCache(cwd: string): void {
workspaceIndexCache.delete(cwd);
inFlightWorkspaceIndexBuilds.delete(cwd);
}
export async function searchWorkspaceEntries(
input: ProjectSearchEntriesInput,
): Promise<ProjectSearchEntriesResult> {
const index = await getWorkspaceIndex(input.cwd);
const normalizedQuery = normalizeQuery(input.query);
const limit = Math.max(0, Math.floor(input.limit));
const rankedEntries: RankedWorkspaceEntry[] = [];
let matchedEntryCount = 0;
const candidates = normalizedQuery
? index.entries.filter((entry) => entry.path.toLowerCase().includes(normalizedQuery))
: index.entries;
for (const entry of index.entries) {
const score = scoreEntry(entry, normalizedQuery);
if (score === null) {
continue;
}
matchedEntryCount += 1;
insertRankedEntry(rankedEntries, { entry, score }, limit);
}
const ranked = candidates.toSorted((left, right) => {
const scoreDelta = scoreEntry(left, normalizedQuery) - scoreEntry(right, normalizedQuery);
if (scoreDelta !== 0) return scoreDelta;
return left.path.localeCompare(right.path);
});
return {
entries: rankedEntries.map((candidate) => candidate.entry),
truncated: index.truncated || matchedEntryCount > limit,
entries: ranked.slice(0, input.limit),
truncated: index.truncated || ranked.length > input.limit,
};
}
+160 -204
View File
@@ -27,8 +27,6 @@ import {
type ServerProviderStatus,
type KeybindingsConfig,
type ResolvedKeybindingsConfig,
type WsPushChannel,
type WsPushMessage,
type WsPush,
} from "@t3tools/contracts";
import { compileResolvedKeybindingRule, DEFAULT_KEYBINDINGS } from "./keybindings";
@@ -54,6 +52,13 @@ import { GitCommandError, GitManagerError } from "./git/Errors.ts";
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
interface PendingMessages {
queue: unknown[];
waiters: Array<(message: unknown) => void>;
}
const pendingBySocket = new WeakMap<WebSocket, PendingMessages>();
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
@@ -209,69 +214,44 @@ class MockTerminalManager implements TerminalManagerShape {
readonly dispose: TerminalManagerShape["dispose"] = Effect.void;
}
// ---------------------------------------------------------------------------
// WebSocket test harness
//
// Incoming messages are split into two channels:
// - pushChannel: server push envelopes (type === "push")
// - responseChannel: request/response envelopes (have an "id" field)
//
// This means sendRequest never has to skip push messages and waitForPush
// never has to skip response messages, eliminating a class of ordering bugs.
// ---------------------------------------------------------------------------
function connectWs(port: number, token?: string): Promise<WebSocket> {
return new Promise((resolve, reject) => {
const query = token ? `?token=${encodeURIComponent(token)}` : "";
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
const pending: PendingMessages = { queue: [], waiters: [] };
pendingBySocket.set(ws, pending);
interface MessageChannel<T> {
queue: T[];
waiters: Array<{
resolve: (value: T) => void;
reject: (error: Error) => void;
timeoutId: ReturnType<typeof setTimeout> | null;
}>;
ws.on("message", (raw) => {
const parsed = JSON.parse(String(raw));
const waiter = pending.waiters.shift();
if (waiter) {
waiter(parsed);
return;
}
pending.queue.push(parsed);
});
ws.once("open", () => resolve(ws));
ws.once("error", () => reject(new Error("WebSocket connection failed")));
});
}
interface SocketChannels {
push: MessageChannel<WsPush>;
response: MessageChannel<WebSocketResponse>;
}
const channelsBySocket = new WeakMap<WebSocket, SocketChannels>();
function enqueue<T>(channel: MessageChannel<T>, item: T) {
const waiter = channel.waiters.shift();
if (waiter) {
if (waiter.timeoutId !== null) clearTimeout(waiter.timeoutId);
waiter.resolve(item);
return;
function waitForMessage(ws: WebSocket): Promise<unknown> {
const pending = pendingBySocket.get(ws);
if (!pending) {
return Promise.reject(new Error("WebSocket not initialized"));
}
channel.queue.push(item);
}
function dequeue<T>(channel: MessageChannel<T>, timeoutMs: number): Promise<T> {
const queued = channel.queue.shift();
const queued = pending.queue.shift();
if (queued !== undefined) {
return Promise.resolve(queued);
}
return new Promise((resolve, reject) => {
const waiter = {
resolve,
reject,
timeoutId: setTimeout(() => {
const index = channel.waiters.indexOf(waiter);
if (index >= 0) channel.waiters.splice(index, 1);
reject(new Error(`Timed out waiting for WebSocket message after ${timeoutMs}ms`));
}, timeoutMs) as ReturnType<typeof setTimeout>,
};
channel.waiters.push(waiter);
return new Promise((resolve) => {
pending.waiters.push(resolve);
});
}
function isWsPushEnvelope(message: unknown): message is WsPush {
if (typeof message !== "object" || message === null) return false;
if (!("type" in message) || !("channel" in message)) return false;
return (message as { type?: unknown }).type === "push";
}
function asWebSocketResponse(message: unknown): WebSocketResponse | null {
if (typeof message !== "object" || message === null) return null;
if (!("id" in message)) return null;
@@ -280,68 +260,11 @@ function asWebSocketResponse(message: unknown): WebSocketResponse | null {
return message as WebSocketResponse;
}
function connectWsOnce(port: number, token?: string): Promise<WebSocket> {
return new Promise((resolve, reject) => {
const query = token ? `?token=${encodeURIComponent(token)}` : "";
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
const channels: SocketChannels = {
push: { queue: [], waiters: [] },
response: { queue: [], waiters: [] },
};
channelsBySocket.set(ws, channels);
ws.on("message", (raw) => {
const parsed = JSON.parse(String(raw));
if (isWsPushEnvelope(parsed)) {
enqueue(channels.push, parsed);
} else {
const response = asWebSocketResponse(parsed);
if (response) {
enqueue(channels.response, response);
}
}
});
ws.once("open", () => resolve(ws));
ws.once("error", () => reject(new Error("WebSocket connection failed")));
});
}
async function connectWs(port: number, token?: string, attempts = 5): Promise<WebSocket> {
let lastError: unknown = new Error("WebSocket connection failed");
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
return await connectWsOnce(port, token);
} catch (error) {
lastError = error;
if (attempt < attempts - 1) {
await new Promise((resolve) => setTimeout(resolve, 25));
}
}
}
throw lastError;
}
/** Connect and wait for the server.welcome push. Returns [ws, welcomeData]. */
async function connectAndAwaitWelcome(
port: number,
token?: string,
): Promise<[WebSocket, WsPushMessage<typeof WS_CHANNELS.serverWelcome>]> {
const ws = await connectWs(port, token);
const welcome = await waitForPush(ws, WS_CHANNELS.serverWelcome);
return [ws, welcome];
}
async function sendRequest(
ws: WebSocket,
method: string,
params?: unknown,
): Promise<WebSocketResponse> {
const channels = channelsBySocket.get(ws);
if (!channels) throw new Error("WebSocket not initialized");
const id = crypto.randomUUID();
const body =
method === ORCHESTRATION_WS_METHODS.dispatchCommand
@@ -349,53 +272,44 @@ async function sendRequest(
: params && typeof params === "object" && !Array.isArray(params)
? { _tag: method, ...(params as Record<string, unknown>) }
: { _tag: method };
ws.send(JSON.stringify({ id, body }));
const message = JSON.stringify({ id, body });
ws.send(message);
// Response channel only contains responses — no push filtering needed
// Wait for response with matching id
while (true) {
const response = await dequeue(channels.response, 60_000);
if (response.id === id || response.id === "unknown") {
return response;
const parsed = asWebSocketResponse(await waitForMessage(ws));
if (!parsed) {
continue;
}
if (parsed.id === id) {
return parsed;
}
if (parsed.id === "unknown") {
return parsed;
}
}
}
async function waitForPush<C extends WsPushChannel>(
async function waitForPush(
ws: WebSocket,
channel: C,
predicate?: (push: WsPushMessage<C>) => boolean,
channel: string,
predicate?: (push: WsPush) => boolean,
maxMessages = 120,
idleTimeoutMs = 5_000,
): Promise<WsPushMessage<C>> {
const channels = channelsBySocket.get(ws);
if (!channels) throw new Error("WebSocket not initialized");
for (let remaining = maxMessages; remaining > 0; remaining--) {
const push = await dequeue(channels.push, idleTimeoutMs);
if (push.channel !== channel) continue;
const typed = push as WsPushMessage<C>;
if (!predicate || predicate(typed)) return typed;
}
throw new Error(`Timed out waiting for push on ${channel}`);
}
async function rewriteKeybindingsAndWaitForPush(
ws: WebSocket,
keybindingsPath: string,
contents: string,
predicate: (push: WsPushMessage<typeof WS_CHANNELS.serverConfigUpdated>) => boolean,
attempts = 3,
): Promise<WsPushMessage<typeof WS_CHANNELS.serverConfigUpdated>> {
let lastError: unknown;
for (let attempt = 0; attempt < attempts; attempt++) {
fs.writeFileSync(keybindingsPath, contents, "utf8");
try {
return await waitForPush(ws, WS_CHANNELS.serverConfigUpdated, predicate, 20, 3_000);
} catch (error) {
lastError = error;
): Promise<WsPush> {
const take = async (remaining: number): Promise<WsPush> => {
if (remaining <= 0) {
throw new Error(`Timed out waiting for push on ${channel}`);
}
}
throw lastError;
const message = (await waitForMessage(ws)) as WsPush;
if (message.type !== "push" || message.channel !== channel) {
return take(remaining - 1);
}
if (!predicate || predicate(message)) {
return message;
}
return take(remaining - 1);
};
return take(maxMessages);
}
async function requestPath(
@@ -575,15 +489,18 @@ describe("WebSocket Server", () => {
it("sends welcome message on connect", async () => {
server = await createTestServer({ cwd: "/test/project" });
// Get the actual port after listen
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const [ws, welcome] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
expect(welcome.type).toBe("push");
expect(welcome.data).toEqual({
const message = (await waitForMessage(ws)) as WsPush;
expect(message.type).toBe("push");
expect(message.channel).toBe(WS_CHANNELS.serverWelcome);
expect(message.data).toEqual({
cwd: "/test/project",
projectName: "project",
});
@@ -672,8 +589,10 @@ describe("WebSocket Server", () => {
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const [ws, welcome] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
const welcome = (await waitForMessage(ws)) as WsPush; // welcome
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
expect(welcome.data).toEqual(
expect.objectContaining({
cwd: "/test/bootstrap-workspace",
@@ -747,8 +666,9 @@ describe("WebSocket Server", () => {
let port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const [firstWs, firstWelcome] = await connectAndAwaitWelcome(port);
const firstWs = await connectWs(port);
connections.push(firstWs);
const firstWelcome = (await waitForMessage(firstWs)) as WsPush;
const firstBootstrapProjectId = (firstWelcome.data as { bootstrapProjectId?: string })
.bootstrapProjectId;
const firstBootstrapThreadId = (firstWelcome.data as { bootstrapThreadId?: string })
@@ -770,8 +690,10 @@ describe("WebSocket Server", () => {
port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const [secondWs, secondWelcome] = await connectAndAwaitWelcome(port);
const secondWs = await connectWs(port);
connections.push(secondWs);
const secondWelcome = (await waitForMessage(secondWs)) as WsPush;
expect(secondWelcome.channel).toBe(WS_CHANNELS.serverWelcome);
expect(secondWelcome.data).toEqual(
expect.objectContaining({
cwd,
@@ -795,8 +717,9 @@ describe("WebSocket Server", () => {
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
expect(
logSpy.mock.calls.some(([message]) => {
@@ -819,9 +742,12 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome message
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
@@ -844,8 +770,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
@@ -874,8 +801,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
@@ -913,8 +841,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
@@ -956,28 +885,32 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const malformedPush = await rewriteKeybindingsAndWaitForPush(
fs.writeFileSync(keybindingsPath, "{ not-json", "utf8");
const malformedPush = await waitForPush(
ws,
keybindingsPath,
"{ not-json",
WS_CHANNELS.serverConfigUpdated,
(push) =>
Array.isArray(push.data.issues) &&
Boolean(push.data.issues[0]) &&
push.data.issues[0]!.kind === "keybindings.malformed-config",
Array.isArray((push.data as { issues?: unknown[] }).issues) &&
Boolean((push.data as { issues: Array<{ kind: string }> }).issues[0]) &&
(push.data as { issues: Array<{ kind: string }> }).issues[0]!.kind ===
"keybindings.malformed-config",
);
expect(malformedPush.data).toEqual({
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
providers: defaultProviderStatuses,
});
const successPush = await rewriteKeybindingsAndWaitForPush(
fs.writeFileSync(keybindingsPath, "[]", "utf8");
const successPush = await waitForPush(
ws,
keybindingsPath,
"[]",
(push) => Array.isArray(push.data.issues) && push.data.issues.length === 0,
WS_CHANNELS.serverConfigUpdated,
(push) =>
Array.isArray((push.data as { issues?: unknown[] }).issues) &&
(push.data as { issues: unknown[] }).issues.length === 0,
);
expect(successPush.data).toEqual({ issues: [], providers: defaultProviderStatuses });
});
@@ -996,8 +929,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.shellOpenInEditor, {
cwd: "/my/workspace",
@@ -1023,9 +957,11 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
const persistedConfig = JSON.parse(
@@ -1055,8 +991,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const upsertResponse = await sendRequest(ws, WS_METHODS.serverUpsertKeybinding, {
key: "mod+shift+r",
@@ -1096,9 +1033,12 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome push
await waitForMessage(ws);
const response = await sendRequest(ws, "nonexistent.method");
expect(response.error).toBeDefined();
expect(response.error!.message).toContain("Invalid request format");
@@ -1109,8 +1049,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getTurnDiff, {
threadId: "thread-missing",
@@ -1126,8 +1067,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getTurnDiff, {
threadId: "thread-any",
@@ -1145,8 +1087,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getFullThreadDiff, {
threadId: "thread-missing",
@@ -1161,8 +1104,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const workspaceRoot = makeTempDir("t3code-ws-diff-project-");
const createdAt = new Date().toISOString();
@@ -1239,8 +1183,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const workspaceRoot = makeTempDir("t3code-ws-project-");
const createdAt = new Date().toISOString();
@@ -1331,8 +1276,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const open = await sendRequest(ws, WS_METHODS.terminalOpen, {
threadId: "thread-1",
@@ -1385,13 +1331,8 @@ describe("WebSocket Server", () => {
};
terminalManager.emitEvent(manualEvent);
const push = await waitForPush(
ws,
WS_CHANNELS.terminalEvent,
(candidate) => (candidate.data as TerminalEvent).type === "output",
);
expect(push.type).toBe("push");
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
const push = await waitForPush(ws, WS_CHANNELS.terminalEvent);
expect((push.data as TerminalEvent).type).toBe("output");
});
it("detaches terminal event listener on stop for injected manager", async () => {
@@ -1414,8 +1355,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.terminalOpen, {
threadId: "",
@@ -1431,17 +1373,21 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome
await waitForMessage(ws);
// Send garbage
ws.send("not json at all");
// Error response goes to the response channel
const channels = channelsBySocket.get(ws)!;
let response: WebSocketResponse | null = null;
for (let attempt = 0; attempt < 5; attempt += 1) {
const message = await dequeue(channels.response, 5_000);
const message = asWebSocketResponse(await waitForMessage(ws));
if (!message) {
continue;
}
if (message.id === "unknown") {
response = message;
break;
@@ -1474,8 +1420,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
ws.send(
JSON.stringify({
@@ -1519,8 +1466,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const listResponse = await sendRequest(ws, WS_METHODS.projectsList);
expect(listResponse.result).toBeUndefined();
@@ -1555,8 +1503,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.projectsSearchEntries, {
cwd: workspace,
@@ -1580,8 +1529,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.projectsWriteFile, {
cwd: workspace,
@@ -1605,8 +1555,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.projectsWriteFile, {
cwd: workspace,
@@ -1626,7 +1577,6 @@ describe("WebSocket Server", () => {
Effect.succeed({
branches: [],
isRepo: false,
hasOriginRemote: false,
}),
);
const initRepo = vi.fn(() => Effect.void);
@@ -1652,12 +1602,13 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const listResponse = await sendRequest(ws, WS_METHODS.gitListBranches, { cwd: "/repo/path" });
expect(listResponse.error).toBeUndefined();
expect(listResponse.result).toEqual({ branches: [], isRepo: false, hasOriginRemote: false });
expect(listResponse.result).toEqual({ branches: [], isRepo: false });
expect(listBranches).toHaveBeenCalledWith({ cwd: "/repo/path" });
const initResponse = await sendRequest(ws, WS_METHODS.gitInit, { cwd: "/repo/path" });
@@ -1700,8 +1651,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.gitStatus, {
cwd: "/test",
@@ -1739,8 +1691,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const resolveResponse = await sendRequest(ws, WS_METHODS.gitResolvePullRequest, {
cwd: "/test",
@@ -1787,8 +1740,9 @@ describe("WebSocket Server", () => {
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [ws] = await connectAndAwaitWelcome(port);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.gitRunStackedAction, {
cwd: "/test",
@@ -1809,7 +1763,9 @@ describe("WebSocket Server", () => {
await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed");
const [authorizedWs] = await connectAndAwaitWelcome(port, "secret-token");
const authorizedWs = await connectWs(port, "secret-token");
connections.push(authorizedWs);
const welcome = (await waitForMessage(authorizedWs)) as WsPush;
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
});
});
+110 -70
View File
@@ -20,12 +20,13 @@ import {
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
ProjectId,
ThreadId,
TerminalEvent,
WS_CHANNELS,
WS_METHODS,
WebSocketRequest,
type WsResponse as WsResponseMessage,
WsPush,
WsResponse,
type WsPushEnvelopeBase,
ServerProviderStatus,
} from "@t3tools/contracts";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import {
@@ -36,7 +37,6 @@ import {
Layer,
Path,
Ref,
Result,
Schema,
Scope,
ServiceMap,
@@ -66,7 +66,6 @@ import {
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths";
import {
createAttachmentId,
resolveAttachmentPath,
@@ -75,9 +74,6 @@ import {
import { parseBase64DataUrl } from "./imageMime.ts";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
import { expandHomePath } from "./os-jank.ts";
import { makeServerPushBus } from "./wsServer/pushBus.ts";
import { makeServerReadiness } from "./wsServer/readiness.ts";
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
/**
* ServerShape - Service API for server lifecycle control.
@@ -103,7 +99,8 @@ export interface ServerShape {
*/
export class Server extends ServiceMap.Service<Server, ServerShape>()("t3/wsServer/Server") {}
const isServerNotRunningError = (error: Error): boolean => {
const isServerNotRunningError = (error: unknown): boolean => {
if (!(error instanceof Error)) return false;
const maybeCode = (error as NodeJS.ErrnoException).code;
return (
maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running")
@@ -199,8 +196,11 @@ function stripRequestTag<T extends { _tag: string }>(body: T) {
return Struct.omit(body, ["_tag"]);
}
const encodeWsResponse = Schema.encodeEffect(Schema.fromJsonString(WsResponse));
const decodeWebSocketRequest = decodeJsonResult(WebSocketRequest);
function messageFromCause(cause: Cause.Cause<unknown>): string {
const squashed = Cause.squash(cause);
const message = squashed instanceof Error ? squashed.message.trim() : String(squashed).trim();
return message.length > 0 ? message : Cause.pretty(cause);
}
export type ServerCoreRuntimeServices =
| OrchestrationEngineService
@@ -268,33 +268,38 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
),
);
const providerStatuses = yield* providerHealth.getStatuses;
const clients = yield* Ref.make(new Set<WebSocket>());
const logger = createLogger("ws");
const readiness = yield* makeServerReadiness;
function logOutgoingPush(push: WsPushEnvelopeBase, recipients: number) {
function logOutgoingPush(push: WsPush, recipients: number) {
if (!logWebSocketEvents) return;
logger.event("outgoing push", {
channel: push.channel,
sequence: push.sequence,
recipients,
payload: push.data,
});
}
const pushBus = yield* makeServerPushBus({
clients,
logOutgoingPush,
const encodePush = Schema.encodeEffect(Schema.fromJsonString(WsPush));
const broadcastPush = Effect.fnUntraced(function* (push: WsPush) {
const message = yield* encodePush(push);
let recipients = 0;
for (const client of yield* Ref.get(clients)) {
if (client.readyState === client.OPEN) {
client.send(message);
recipients += 1;
}
}
logOutgoingPush(push, recipients);
});
const onTerminalEvent = Effect.fnUntraced(function* (event: TerminalEvent) {
yield* broadcastPush({
type: "push",
channel: WS_CHANNELS.terminalEvent,
data: event,
});
});
yield* readiness.markPushBusReady;
yield* keybindingsManager.start.pipe(
Effect.mapError(
(cause) => new ServerLifecycleError({ operation: "keybindingsRuntimeStart", cause }),
),
);
yield* readiness.markKeybindingsReady;
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
readonly command: ClientOrchestrationCommand;
@@ -476,7 +481,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
}
}),
).pipe(Effect.exit);
if (Exit.isFailure(streamExit)) {
if (streamExit._tag === "Failure") {
if (!res.destroyed) {
res.destroy();
}
@@ -607,19 +612,43 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const subscriptionsScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
// Push updated provider statuses to connected clients once background health checks finish.
let providers: ReadonlyArray<ServerProviderStatus> = [];
yield* providerHealth.getStatuses.pipe(
Effect.flatMap((statuses) => {
providers = statuses;
return broadcastPush({
type: "push",
channel: WS_CHANNELS.serverConfigUpdated,
data: {
issues: [],
providers: statuses,
},
});
}),
Effect.forkIn(subscriptionsScope),
);
yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) =>
pushBus.publishAll(ORCHESTRATION_WS_CHANNELS.domainEvent, event),
broadcastPush({
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
data: event,
}),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Stream.runForEach(keybindingsManager.streamChanges, (event) =>
pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: event.issues,
providers: providerStatuses,
yield* Stream.runForEach(keybindingsManager.changes, (event) =>
broadcastPush({
type: "push",
channel: WS_CHANNELS.serverConfigUpdated,
data: {
issues: event.issues,
providers,
},
}),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
yield* readiness.markOrchestrationSubscriptionsReady;
let welcomeBootstrapProjectId: ProjectId | undefined;
let welcomeBootstrapThreadId: ThreadId | undefined;
@@ -690,18 +719,23 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const runPromise = Effect.runPromiseWith(runtimeServices);
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
(event) => void Effect.runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
(event) => void Effect.runPromise(onTerminalEvent(event)),
);
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* readiness.markTerminalSubscriptionsReady;
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
);
yield* readiness.markHttpListening;
yield* Effect.addFinalizer(() =>
Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]),
Effect.all([
closeAllClients,
closeWebSocketServer.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to close web socket server", { cause: error }),
),
),
]),
);
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
@@ -873,7 +907,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers: providerStatuses,
providers,
availableEditors,
};
@@ -893,40 +927,44 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
const handleMessage = Effect.fnUntraced(function* (ws: WebSocket, raw: unknown) {
const sendWsResponse = (response: WsResponseMessage) =>
encodeWsResponse(response).pipe(
Effect.tap((encodedResponse) => Effect.sync(() => ws.send(encodedResponse))),
Effect.asVoid,
);
const encodeResponse = Schema.encodeEffect(Schema.fromJsonString(WsResponse));
const messageText = websocketRawToString(raw);
if (messageText === null) {
return yield* sendWsResponse({
const errorResponse = yield* encodeResponse({
id: "unknown",
error: { message: "Invalid request format: Failed to read message" },
});
ws.send(errorResponse);
return;
}
const request = decodeWebSocketRequest(messageText);
if (Result.isFailure(request)) {
return yield* sendWsResponse({
const request = Schema.decodeExit(Schema.fromJsonString(WebSocketRequest))(messageText);
if (request._tag === "Failure") {
const errorResponse = yield* encodeResponse({
id: "unknown",
error: { message: `Invalid request format: ${formatSchemaError(request.failure)}` },
error: { message: `Invalid request format: ${messageFromCause(request.cause)}` },
});
ws.send(errorResponse);
return;
}
const result = yield* Effect.exit(routeRequest(request.success));
if (Exit.isFailure(result)) {
return yield* sendWsResponse({
id: request.success.id,
error: { message: Cause.pretty(result.cause) },
const result = yield* Effect.exit(routeRequest(request.value));
if (result._tag === "Failure") {
const errorResponse = yield* encodeResponse({
id: request.value.id,
error: { message: messageFromCause(result.cause) },
});
ws.send(errorResponse);
return;
}
return yield* sendWsResponse({
id: request.success.id,
const response = yield* encodeResponse({
id: request.value.id,
result: result.value,
});
ws.send(response);
});
httpServer.on("upgrade", (request, socket, head) => {
@@ -954,28 +992,30 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
wss.on("connection", (ws) => {
void runPromise(Ref.update(clients, (clients) => clients.add(ws)));
const segments = cwd.split(/[/\\]/).filter(Boolean);
const projectName = segments[segments.length - 1] ?? "project";
const welcomeData = {
cwd,
projectName,
...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
const welcome: WsPush = {
type: "push",
channel: WS_CHANNELS.serverWelcome,
data: {
cwd,
projectName,
...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
},
};
// Send welcome before adding to broadcast set so publishAll calls
// cannot reach this client before the welcome arrives.
void runPromise(
readiness.awaitServerReady.pipe(
Effect.flatMap(() => pushBus.publishClient(ws, WS_CHANNELS.serverWelcome, welcomeData)),
Effect.flatMap((delivered) =>
delivered ? Ref.update(clients, (clients) => clients.add(ws)) : Effect.void,
),
),
);
logOutgoingPush(welcome, 1);
ws.send(JSON.stringify(welcome));
ws.on("message", (raw) => {
void runPromise(handleMessage(ws, raw).pipe(Effect.ignoreCause({ log: true })));
void runPromise(
handleMessage(ws, raw).pipe(
Effect.catch((error) => Effect.logError("Error handling message", error)),
),
);
});
ws.on("close", () => {
-104
View File
@@ -1,104 +0,0 @@
import type { WebSocket } from "ws";
import { it } from "@effect/vitest";
import { describe, expect } from "vitest";
import { Effect, Ref } from "effect";
import { WS_CHANNELS } from "@t3tools/contracts";
import { makeServerPushBus } from "./pushBus";
class MockWebSocket {
static readonly OPEN = 1;
readonly OPEN = MockWebSocket.OPEN;
readyState = MockWebSocket.OPEN;
readonly sent: string[] = [];
private readonly waiters = new Set<() => void>();
send(message: string) {
this.sent.push(message);
for (const waiter of this.waiters) {
waiter();
}
}
waitForSentCount(count: number): Promise<void> {
if (this.sent.length >= count) {
return Promise.resolve();
}
return new Promise((resolve) => {
const check = () => {
if (this.sent.length < count) {
return;
}
this.waiters.delete(check);
resolve();
};
this.waiters.add(check);
});
}
}
describe("makeServerPushBus", () => {
it.live("waits for the welcome push before a new client joins broadcast delivery", () =>
Effect.scoped(
Effect.gen(function* () {
const client = new MockWebSocket();
const clients = yield* Ref.make(new Set<WebSocket>());
const pushBus = yield* makeServerPushBus({
clients,
logOutgoingPush: () => {},
});
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: [{ kind: "keybindings.malformed-config", message: "queued-before-connect" }],
providers: [],
});
const delivered = yield* pushBus.publishClient(
client as unknown as WebSocket,
WS_CHANNELS.serverWelcome,
{
cwd: "/tmp/project",
projectName: "project",
},
);
expect(delivered).toBe(true);
yield* Ref.update(clients, (current) => current.add(client as unknown as WebSocket));
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: [],
providers: [],
});
yield* Effect.promise(() => client.waitForSentCount(2));
const messages = client.sent.map(
(message) => JSON.parse(message) as { channel: string; data: unknown },
);
expect(messages).toHaveLength(2);
expect(messages[0]).toEqual({
type: "push",
sequence: 2,
channel: WS_CHANNELS.serverWelcome,
data: {
cwd: "/tmp/project",
projectName: "project",
},
});
expect(messages[1]).toEqual({
type: "push",
sequence: 3,
channel: WS_CHANNELS.serverConfigUpdated,
data: {
issues: [],
providers: [],
},
});
}),
),
);
});
-114
View File
@@ -1,114 +0,0 @@
import {
WsPush,
type WsPushChannel,
type WsPushData,
type WsPushEnvelopeBase,
} from "@t3tools/contracts";
import { Deferred, Effect, Queue, Ref, Schema } from "effect";
import type { Scope } from "effect";
import type { WebSocket } from "ws";
type PushTarget =
| { readonly kind: "all" }
| { readonly kind: "client"; readonly client: WebSocket };
interface PushJob<C extends WsPushChannel = WsPushChannel> {
readonly channel: C;
readonly data: WsPushData<C>;
readonly target: PushTarget;
readonly delivered: Deferred.Deferred<boolean> | null;
}
export interface ServerPushBus {
readonly publishAll: <C extends WsPushChannel>(
channel: C,
data: WsPushData<C>,
) => Effect.Effect<void>;
readonly publishClient: <C extends WsPushChannel>(
client: WebSocket,
channel: C,
data: WsPushData<C>,
) => Effect.Effect<boolean>;
}
export const makeServerPushBus = (input: {
readonly clients: Ref.Ref<Set<WebSocket>>;
readonly logOutgoingPush: (push: WsPushEnvelopeBase, recipients: number) => void;
}): Effect.Effect<ServerPushBus, never, Scope.Scope> =>
Effect.gen(function* () {
const nextSequence = yield* Ref.make(0);
const queue = yield* Queue.unbounded<PushJob>();
const encodePush = Schema.encodeUnknownEffect(Schema.fromJsonString(WsPush));
const settleDelivery = (job: PushJob, delivered: boolean) =>
job.delivered === null
? Effect.void
: Deferred.succeed(job.delivered, delivered).pipe(Effect.orDie);
const send = Effect.fnUntraced(function* (job: PushJob) {
const sequence = yield* Ref.updateAndGet(nextSequence, (current) => current + 1);
const push: WsPushEnvelopeBase = {
type: "push",
sequence,
channel: job.channel,
data: job.data,
};
const recipients =
job.target.kind === "all" ? yield* Ref.get(input.clients) : new Set([job.target.client]);
return yield* encodePush(push).pipe(
Effect.map((message) => {
let recipientCount = 0;
for (const client of recipients) {
if (client.readyState !== client.OPEN) {
continue;
}
client.send(message);
recipientCount += 1;
}
input.logOutgoingPush(push, recipientCount);
return recipientCount > 0;
}),
);
});
yield* Effect.forkScoped(
Effect.forever(
Queue.take(queue).pipe(
Effect.flatMap((job) =>
send(job).pipe(
Effect.tap((delivered) => settleDelivery(job, delivered)),
Effect.tapCause(() => settleDelivery(job, false)),
Effect.ignoreCause({ log: true }),
),
),
),
),
);
const publish =
(target: PushTarget) =>
<C extends WsPushChannel>(channel: C, data: WsPushData<C>) =>
Queue.offer(queue, {
channel,
data,
target,
delivered: null,
}).pipe(Effect.asVoid);
return {
publishAll: publish({ kind: "all" }),
publishClient: (client, channel, data) =>
Effect.gen(function* () {
const delivered = yield* Deferred.make<boolean>();
yield* Queue.offer(queue, {
channel,
data,
target: { kind: "client", client },
delivered,
}).pipe(Effect.asVoid);
return yield* Deferred.await(delivered);
}),
} satisfies ServerPushBus;
});
-36
View File
@@ -1,36 +0,0 @@
import { Deferred, Effect } from "effect";
export interface ServerReadiness {
readonly awaitServerReady: Effect.Effect<void>;
readonly markHttpListening: Effect.Effect<void>;
readonly markPushBusReady: Effect.Effect<void>;
readonly markKeybindingsReady: Effect.Effect<void>;
readonly markTerminalSubscriptionsReady: Effect.Effect<void>;
readonly markOrchestrationSubscriptionsReady: Effect.Effect<void>;
}
export const makeServerReadiness = Effect.gen(function* () {
const httpListening = yield* Deferred.make<void>();
const pushBusReady = yield* Deferred.make<void>();
const keybindingsReady = yield* Deferred.make<void>();
const terminalSubscriptionsReady = yield* Deferred.make<void>();
const orchestrationSubscriptionsReady = yield* Deferred.make<void>();
const complete = (deferred: Deferred.Deferred<void>) =>
Deferred.succeed(deferred, undefined).pipe(Effect.orDie);
return {
awaitServerReady: Effect.all([
Deferred.await(httpListening),
Deferred.await(pushBusReady),
Deferred.await(keybindingsReady),
Deferred.await(terminalSubscriptionsReady),
Deferred.await(orchestrationSubscriptionsReady),
]).pipe(Effect.asVoid),
markHttpListening: complete(httpListening),
markPushBusReady: complete(pushBusReady),
markKeybindingsReady: complete(keybindingsReady),
markTerminalSubscriptionsReady: complete(terminalSubscriptionsReady),
markOrchestrationSubscriptionsReady: complete(orchestrationSubscriptionsReady),
} satisfies ServerReadiness;
});
-13
View File
@@ -1,13 +0,0 @@
import { defineConfig, mergeConfig } from "vitest/config";
import baseConfig from "../../vitest.config";
export default mergeConfig(
baseConfig,
defineConfig({
test: {
testTimeout: 15_000,
hookTimeout: 15_000,
},
}),
);
+3 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.10",
"version": "0.0.9",
"private": true,
"type": "module",
"scripts": {
@@ -42,20 +42,18 @@
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@rolldown/plugin-babel": "^0.2.0",
"@tailwindcss/vite": "^4.0.0",
"@tanstack/router-plugin": "^1.161.0",
"@types/babel__core": "^7.20.5",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^6.0.0",
"@vitejs/plugin-react": "^5.1.4",
"@vitest/browser-playwright": "^4.0.18",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"msw": "^2.12.10",
"playwright": "^1.58.2",
"tailwindcss": "^4.0.0",
"typescript": "catalog:",
"vite": "^8.0.0",
"vite": "^8.0.0-beta.12",
"vitest": "catalog:",
"vitest-browser-react": "^2.0.5"
}
+1 -1
View File
@@ -7,7 +7,7 @@
* - Please do NOT modify this file.
*/
const PACKAGE_VERSION = '2.12.9'
const PACKAGE_VERSION = '2.12.10'
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
+14 -29
View File
@@ -1,33 +1,25 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_TIMESTAMP_FORMAT,
getAppModelOptions,
getSlashModelOptions,
normalizeCustomModelSlugs,
resolveAppModelSelection,
} from "./appSettings";
describe("normalizeCustomModelSlugs", () => {
it("removes literal built-ins, trims whitespace, and deduplicates values", () => {
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
expect(
normalizeCustomModelSlugs([
" custom/internal-model ",
"gpt-5.3-codex",
"5.3",
"custom/internal-model",
"",
null,
]),
).toEqual(["custom/internal-model"]);
});
it("preserves aliases and dated versions as custom models", () => {
expect(normalizeCustomModelSlugs(["claude-sonnet-4-6-20251117"], "claudeCode")).toEqual([
"claude-sonnet-4-6-20251117",
]);
expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeCode")).toEqual([
"claude/custom-sonnet",
]);
});
});
describe("getAppModelOptions", () => {
@@ -53,13 +45,6 @@ describe("getAppModelOptions", () => {
isCustom: true,
});
});
it("keeps a saved custom provider model available as an exact slug option", () => {
const options = getAppModelOptions("claudeCode", ["claude/custom-opus"], "claude/custom-opus");
expect(options.some((option) => option.slug === "claude/custom-opus" && option.isCustom)).toBe(
true,
);
});
});
describe("resolveAppModelSelection", () => {
@@ -74,16 +59,16 @@ describe("resolveAppModelSelection", () => {
});
});
describe("timestamp format defaults", () => {
it("defaults timestamp format to locale", () => {
expect(DEFAULT_TIMESTAMP_FORMAT).toBe("locale");
});
});
describe("provider-specific custom models", () => {
it("includes provider-specific custom slugs in non-codex model lists", () => {
const claudeOptions = getAppModelOptions("claudeCode", ["claude/custom-opus"]);
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
describe("getSlashModelOptions", () => {
it("includes saved custom model slugs for /model command suggestions", () => {
const options = getSlashModelOptions("codex", ["custom/internal-model"], "", "gpt-5.3-codex");
expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);
});
it("filters slash-model suggestions across built-in and custom model names", () => {
const options = getSlashModelOptions("codex", ["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
});
});
+114 -36
View File
@@ -1,18 +1,13 @@
import { useCallback } from "react";
import { useCallback, useSyncExternalStore } from "react";
import { Option, Schema } from "effect";
import { type ProviderKind } from "@t3tools/contracts";
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
import { useLocalStorage } from "./hooks/useLocalStorage";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
export const TIMESTAMP_FORMAT_OPTIONS = ["locale", "12-hour", "24-hour"] as const;
export type TimestampFormat = (typeof TIMESTAMP_FORMAT_OPTIONS)[number];
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
claudeCode: new Set(getModelOptions("claudeCode").map((option) => option.slug)),
};
const AppSettingsSchema = Schema.Struct({
@@ -22,22 +17,13 @@ const AppSettingsSchema = Schema.Struct({
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
Schema.withConstructorDefault(() => Option.some("")),
),
defaultThreadEnvMode: Schema.Literals(["local", "worktree"]).pipe(
Schema.withConstructorDefault(() => Option.some("local")),
),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
enableAssistantStreaming: Schema.Boolean.pipe(
Schema.withConstructorDefault(() => Option.some(false)),
),
timestampFormat: Schema.Literals(["locale", "12-hour", "24-hour"]).pipe(
Schema.withConstructorDefault(() => Option.some(DEFAULT_TIMESTAMP_FORMAT)),
),
customCodexModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
customClaudeModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
});
export type AppSettings = typeof AppSettingsSchema.Type;
export interface AppModelOption {
@@ -48,6 +34,10 @@ export interface AppModelOption {
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
let listeners: Array<() => void> = [];
let cachedRawSettings: string | null | undefined;
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
export function normalizeCustomModelSlugs(
models: Iterable<string | null | undefined>,
provider: ProviderKind = "codex",
@@ -57,19 +47,18 @@ export function normalizeCustomModelSlugs(
const builtInModelSlugs = BUILT_IN_MODEL_SLUGS_BY_PROVIDER[provider];
for (const candidate of models) {
if (typeof candidate !== "string") continue;
const trimmed = candidate.trim();
const normalized = normalizeModelSlug(candidate, provider);
if (
!trimmed ||
trimmed.length > MAX_CUSTOM_MODEL_LENGTH ||
builtInModelSlugs.has(trimmed) ||
seen.has(trimmed)
!normalized ||
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
builtInModelSlugs.has(normalized) ||
seen.has(normalized)
) {
continue;
}
seen.add(trimmed);
normalizedModels.push(trimmed);
seen.add(normalized);
normalizedModels.push(normalized);
if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
break;
}
@@ -82,9 +71,9 @@ function normalizeAppSettings(settings: AppSettings): AppSettings {
return {
...settings,
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeCode"),
};
}
export function getAppModelOptions(
provider: ProviderKind,
customModels: readonly string[],
@@ -154,23 +143,112 @@ export function resolveAppModelSelection(
);
}
export function getSlashModelOptions(
provider: ProviderKind,
customModels: readonly string[],
query: string,
selectedModel?: string | null,
): AppModelOption[] {
const normalizedQuery = query.trim().toLowerCase();
const options = getAppModelOptions(provider, customModels, selectedModel);
if (!normalizedQuery) {
return options;
}
return options.filter((option) => {
const searchSlug = option.slug.toLowerCase();
const searchName = option.name.toLowerCase();
return searchSlug.includes(normalizedQuery) || searchName.includes(normalizedQuery);
});
}
function emitChange(): void {
for (const listener of listeners) {
listener();
}
}
function parsePersistedSettings(value: string | null): AppSettings {
if (!value) {
return DEFAULT_APP_SETTINGS;
}
try {
return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
} catch {
return DEFAULT_APP_SETTINGS;
}
}
export function getAppSettingsSnapshot(): AppSettings {
if (typeof window === "undefined") {
return DEFAULT_APP_SETTINGS;
}
const raw = window.localStorage.getItem(APP_SETTINGS_STORAGE_KEY);
if (raw === cachedRawSettings) {
return cachedSnapshot;
}
cachedRawSettings = raw;
cachedSnapshot = parsePersistedSettings(raw);
return cachedSnapshot;
}
function persistSettings(next: AppSettings): void {
if (typeof window === "undefined") return;
const raw = JSON.stringify(next);
try {
if (raw !== cachedRawSettings) {
window.localStorage.setItem(APP_SETTINGS_STORAGE_KEY, raw);
}
} catch {
// Best-effort persistence only.
}
cachedRawSettings = raw;
cachedSnapshot = next;
}
function subscribe(listener: () => void): () => void {
listeners.push(listener);
const onStorage = (event: StorageEvent) => {
if (event.key === APP_SETTINGS_STORAGE_KEY) {
emitChange();
}
};
window.addEventListener("storage", onStorage);
return () => {
listeners = listeners.filter((entry) => entry !== listener);
window.removeEventListener("storage", onStorage);
};
}
export function useAppSettings() {
const [settings, setSettings] = useLocalStorage(
APP_SETTINGS_STORAGE_KEY,
DEFAULT_APP_SETTINGS,
AppSettingsSchema,
const settings = useSyncExternalStore(
subscribe,
getAppSettingsSnapshot,
() => DEFAULT_APP_SETTINGS,
);
const updateSettings = useCallback(
(patch: Partial<AppSettings>) => {
setSettings((prev) => normalizeAppSettings({ ...prev, ...patch }));
},
[setSettings],
);
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
const next = normalizeAppSettings(
Schema.decodeSync(AppSettingsSchema)({
...getAppSettingsSnapshot(),
...patch,
}),
);
persistSettings(next);
emitChange();
}, []);
const resetSettings = useCallback(() => {
setSettings(DEFAULT_APP_SETTINGS);
}, [setSettings]);
persistSettings(DEFAULT_APP_SETTINGS);
emitChange();
}, []);
return {
settings,
-1
View File
@@ -1,4 +1,3 @@
export const APP_BASE_NAME = "T3 Code";
export const APP_STAGE_LABEL = import.meta.env.DEV ? "Dev" : "Alpha";
export const APP_DISPLAY_NAME = `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0";
@@ -149,7 +149,7 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
]);
});
it("keeps non-origin remote refs visible even when a matching local branch exists", () => {
it("dedupes remote refs for remotes whose names contain slashes", () => {
const input: GitBranch[] = [
{
name: "feature/demo",
@@ -169,11 +169,10 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"feature/demo",
"my-org/upstream/feature/demo",
]);
});
it("keeps non-origin remote refs visible when git tracks with first-slash local naming", () => {
it("dedupes remote refs when git tracks with first-slash local naming", () => {
const input: GitBranch[] = [
{
name: "upstream/feature",
@@ -193,7 +192,6 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"upstream/feature",
"my-org/upstream/feature",
]);
});
});
@@ -81,10 +81,6 @@ export function dedupeRemoteBranchesWithLocalMatches(
return true;
}
if (branch.remoteName !== "origin") {
return true;
}
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
branch.name,
branch.remoteName,
+18 -51
View File
@@ -1,5 +1,4 @@
import type { ThreadId } from "@t3tools/contracts";
import { FolderIcon, GitForkIcon } from "lucide-react";
import { useCallback } from "react";
import { newCommandId } from "../lib/utils";
@@ -12,12 +11,7 @@ import {
resolveEffectiveEnvMode,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
const envModeItems = [
{ value: "local", label: "Local" },
{ value: "worktree", label: "New worktree" },
] as const;
import { Button } from "./ui/button";
interface BranchToolbarProps {
threadId: ThreadId;
@@ -110,50 +104,23 @@ export default function BranchToolbar({
return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
{envLocked || activeWorktreePath ? (
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeWorktreePath ? (
<>
<GitForkIcon className="size-3" />
Worktree
</>
) : (
<>
<FolderIcon className="size-3" />
Local
</>
)}
</span>
) : (
<Select
value={effectiveEnvMode}
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
items={envModeItems}
>
<SelectTrigger variant="ghost" size="xs" className="font-medium">
{effectiveEnvMode === "worktree" ? (
<GitForkIcon className="size-3" />
) : (
<FolderIcon className="size-3" />
)}
<SelectValue />
</SelectTrigger>
<SelectPopup>
<SelectItem value="local">
<span className="inline-flex items-center gap-1.5">
<FolderIcon className="size-3" />
Local
</span>
</SelectItem>
<SelectItem value="worktree">
<span className="inline-flex items-center gap-1.5">
<GitForkIcon className="size-3" />
New worktree
</span>
</SelectItem>
</SelectPopup>
</Select>
)}
<div className="flex items-center gap-2">
{envLocked || activeWorktreePath ? (
<span className="border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeWorktreePath ? "Worktree" : "Local"}
</span>
) : (
<Button
type="button"
variant="ghost"
className="text-muted-foreground/70 hover:text-foreground/80"
size="xs"
onClick={() => onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")}
>
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
</Button>
)}
</div>
<BranchToolbarBranchSelector
activeProjectCwd={activeProject.cwd}
+9 -12
View File
@@ -1,4 +1,8 @@
import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
import {
getSharedHighlighter,
type DiffsHighlighter,
type SupportedLanguages,
} from "@pierre/diffs";
import { CheckIcon, CopyIcon } from "lucide-react";
import React, {
Children,
@@ -16,13 +20,13 @@ import React, {
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { openInPreferredEditor } from "../editorPreferences";
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { useTheme } from "../hooks/useTheme";
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
import { readNativeApi } from "../nativeApi";
import { preferredTerminalEditor } from "../terminal-links";
class CodeHighlightErrorBoundary extends React.Component<
{ fallback: ReactNode; children: ReactNode },
@@ -62,9 +66,7 @@ const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
function extractFenceLanguage(className: string | undefined): string {
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
const raw = match?.[1] ?? "text";
// Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
return raw === "gitignore" ? "ini" : raw;
return match?.[1] ?? "text";
}
function nodeToPlainText(node: ReactNode): string {
@@ -209,12 +211,7 @@ function SuspenseShikiCodeBlock({
const highlightedHtml = useMemo(() => {
try {
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
} catch (error) {
// Log highlighting failures for debugging while falling back to plain text
console.warn(
`Code highlighting failed for language "${language}", falling back to plain text.`,
error instanceof Error ? error.message : error,
);
} catch {
// If highlighting fails for this language, render as plain text
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
}
@@ -255,7 +252,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
event.stopPropagation();
const api = readNativeApi();
if (api) {
void openInPreferredEditor(api, targetPath);
void api.shell.openInEditor(targetPath, preferredTerminalEditor());
} else {
console.warn("Native API not found. Unable to open file in editor.");
}
+3 -281
View File
@@ -11,7 +11,6 @@ import {
type WsWelcomePayload,
WS_CHANNELS,
WS_METHODS,
OrchestrationSessionStatus,
} from "@t3tools/contracts";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { HttpResponse, http, ws } from "msw";
@@ -21,13 +20,11 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
import { isMacPlatform } from "../lib/utils";
import { getRouter } from "../router";
import { useStore } from "../store";
import { estimateTimelineMessageHeight } from "./timelineHeight";
const THREAD_ID = "thread-browser-test" as ThreadId;
const UUID_ROUTE_RE = /^\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const PROJECT_ID = "project-1" as ProjectId;
const NOW_ISO = "2026-03-04T12:00:00.000Z";
const BASE_TIME_MS = Date.parse(NOW_ISO);
@@ -88,7 +85,6 @@ interface MountedChatView {
cleanup: () => Promise<void>;
measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
setViewport: (viewport: ViewportSpec) => Promise<void>;
router: ReturnType<typeof getRouter>;
}
function isoAt(offsetSeconds: number): string {
@@ -154,7 +150,6 @@ function createSnapshotForTargetUser(options: {
targetMessageId: MessageId;
targetText: string;
targetAttachmentCount?: number;
sessionStatus?: OrchestrationSessionStatus;
}): OrchestrationReadModel {
const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
@@ -224,7 +219,7 @@ function createSnapshotForTargetUser(options: {
checkpoints: [],
session: {
threadId: THREAD_ID,
status: options.sessionStatus ?? "ready",
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
@@ -250,46 +245,6 @@ function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
};
}
function addThreadToSnapshot(
snapshot: OrchestrationReadModel,
threadId: ThreadId,
): OrchestrationReadModel {
return {
...snapshot,
snapshotSequence: snapshot.snapshotSequence + 1,
threads: [
...snapshot.threads,
{
id: threadId,
projectId: PROJECT_ID,
title: "New thread",
model: "gpt-5",
interactionMode: "default",
runtimeMode: "full-access",
branch: "main",
worktreePath: null,
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
deletedAt: null,
messages: [],
activities: [],
proposedPlans: [],
checkpoints: [],
session: {
threadId,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: NOW_ISO,
},
},
],
};
}
function createDraftOnlySnapshot(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-draft-target" as MessageId,
@@ -356,8 +311,7 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
};
}
function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
const tag = body._tag;
function resolveWsRpc(tag: string): unknown {
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
return fixture.snapshot;
}
@@ -367,7 +321,6 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
if (tag === WS_METHODS.gitListBranches) {
return {
isRepo: true,
hasOriginRemote: true,
branches: [
{
name: "main",
@@ -399,19 +352,6 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
truncated: false,
};
}
if (tag === WS_METHODS.terminalOpen) {
return {
threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID,
terminalId: typeof body.terminalId === "string" ? body.terminalId : "default",
cwd: typeof body.cwd === "string" ? body.cwd : "/repo/project",
status: "running",
pid: 123,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: NOW_ISO,
};
}
return {};
}
@@ -420,7 +360,6 @@ const worker = setupWorker(
client.send(
JSON.stringify({
type: "push",
sequence: 1,
channel: WS_CHANNELS.serverWelcome,
data: fixture.welcome,
}),
@@ -440,7 +379,7 @@ const worker = setupWorker(
client.send(
JSON.stringify({
id: request.id,
result: resolveWsRpc(request.body),
result: resolveWsRpc(method),
}),
);
});
@@ -508,22 +447,6 @@ async function waitForElement<T extends Element>(
return element;
}
async function waitForURL(
router: ReturnType<typeof getRouter>,
predicate: (pathname: string) => boolean,
errorMessage: string,
): Promise<string> {
let pathname = "";
await vi.waitFor(
() => {
pathname = router.state.location.pathname;
expect(predicate(pathname), errorMessage).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
return pathname;
}
async function waitForComposerEditor(): Promise<HTMLElement> {
return waitForElement(
() => document.querySelector<HTMLElement>('[contenteditable="true"]'),
@@ -669,7 +592,6 @@ async function mountChatView(options: {
await setViewport(viewport);
await waitForProductionStyles();
},
router,
};
}
@@ -1011,206 +933,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("shows a pointer cursor for the running stop button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-stop-button-cursor" as MessageId,
targetText: "stop button cursor target",
sessionStatus: "running",
}),
});
try {
const stopButton = await waitForElement(
() => document.querySelector<HTMLButtonElement>('button[aria-label="Stop generation"]'),
"Unable to find stop generation button.",
);
expect(getComputedStyle(stopButton).cursor).toBe("pointer");
} finally {
await mounted.cleanup();
}
});
it("keeps the new thread selected after clicking the new-thread button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-new-thread-test" as MessageId,
targetText: "new thread selection test",
}),
});
try {
// Wait for the sidebar to render with the project.
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await newThreadButton.click();
// The route should change to a new draft thread ID.
const newThreadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
// The composer editor should be present for the new draft thread.
await waitForComposerEditor();
// Simulate the snapshot sync arriving from the server after the draft
// thread has been promoted to a server thread (thread.create + turn.start
// succeeded). The snapshot now includes the new thread, and the sync
// should clear the draft without disrupting the route.
const { syncServerReadModel } = useStore.getState();
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, newThreadId));
// Clear the draft now that the server thread exists (mirrors EventRouter behavior).
useComposerDraftStore.getState().clearDraftThread(newThreadId);
// The route should still be on the new thread — not redirected away.
await waitForURL(
mounted.router,
(path) => path === newThreadPath,
"New thread should remain selected after snapshot sync clears the draft.",
);
// The empty thread view and composer should still be visible.
await expect
.element(page.getByText("Send a message to start the conversation."))
.toBeInTheDocument();
await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument();
} finally {
await mounted.cleanup();
}
});
it("creates a new thread from the global chat.new shortcut", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-chat-shortcut-test" as MessageId,
targetText: "chat shortcut test",
}),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
keybindings: [
{
command: "chat.new",
shortcut: {
key: "o",
metaKey: false,
ctrlKey: false,
shiftKey: true,
altKey: false,
modKey: true,
},
whenAst: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
],
};
},
});
try {
const useMetaForMod = isMacPlatform(navigator.platform);
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "o",
shiftKey: true,
metaKey: useMetaForMod,
ctrlKey: !useMetaForMod,
bubbles: true,
cancelable: true,
}),
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID from the shortcut.",
);
} finally {
await mounted.cleanup();
}
});
it("creates a fresh draft after the previous draft thread is promoted", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-promoted-draft-shortcut-test" as MessageId,
targetText: "promoted draft shortcut test",
}),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
keybindings: [
{
command: "chat.new",
shortcut: {
key: "o",
metaKey: false,
ctrlKey: false,
shiftKey: true,
altKey: false,
modKey: true,
},
whenAst: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
],
};
},
});
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await newThreadButton.click();
const promotedThreadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a promoted draft thread UUID.",
);
const promotedThreadId = promotedThreadPath.slice(1) as ThreadId;
const { syncServerReadModel } = useStore.getState();
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
const useMetaForMod = isMacPlatform(navigator.platform);
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "o",
shiftKey: true,
metaKey: useMetaForMod,
ctrlKey: !useMetaForMod,
bubbles: true,
cancelable: true,
}),
);
const freshThreadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath,
"Shortcut should create a fresh draft instead of reusing the promoted thread.",
);
expect(freshThreadPath).not.toBe(promotedThreadPath);
} finally {
await mounted.cleanup();
}
});
it("keeps long proposed plans lightweight until the user expands them", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
-127
View File
@@ -1,127 +0,0 @@
import { ProjectId, type ProviderKind, type ThreadId } from "@t3tools/contracts";
import { type ChatMessage, type Thread } from "../types";
import { randomUUID } from "~/lib/utils";
import { getAppModelOptions } from "../appSettings";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import { Schema } from "effect";
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
const WORKTREE_BRANCH_PREFIX = "t3code";
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
export function buildLocalDraftThread(
threadId: ThreadId,
draftThread: DraftThreadState,
fallbackModel: string,
error: string | null,
): Thread {
return {
id: threadId,
codexThreadId: null,
projectId: draftThread.projectId,
title: "New thread",
model: fallbackModel,
runtimeMode: draftThread.runtimeMode,
interactionMode: draftThread.interactionMode,
session: null,
messages: [],
error,
createdAt: draftThread.createdAt,
latestTurn: null,
lastVisitedAt: draftThread.createdAt,
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
turnDiffSummaries: [],
activities: [],
proposedPlans: [],
};
}
export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
return;
}
URL.revokeObjectURL(previewUrl);
}
export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
if (message.role !== "user" || !message.attachments) {
return;
}
for (const attachment of message.attachments) {
if (attachment.type !== "image") {
continue;
}
revokeBlobPreviewUrl(attachment.previewUrl);
}
}
export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
if (message.role !== "user" || !message.attachments) {
return [];
}
const previewUrls: string[] = [];
for (const attachment of message.attachments) {
if (attachment.type !== "image") continue;
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
previewUrls.push(attachment.previewUrl);
}
return previewUrls;
}
export type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
export interface PullRequestDialogState {
initialReference: string | null;
key: number;
}
export function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
if (typeof reader.result === "string") {
resolve(reader.result);
return;
}
reject(new Error("Could not read image data."));
});
reader.addEventListener("error", () => {
reject(reader.error ?? new Error("Failed to read image."));
});
reader.readAsDataURL(file);
});
}
export function buildTemporaryWorktreeBranchName(): string {
// Keep the 8-hex suffix shape for backend temporary-branch detection.
const token = randomUUID().slice(0, 8).toLowerCase();
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
}
export function cloneComposerImageForRetry(
image: ComposerImageAttachment,
): ComposerImageAttachment {
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
return image;
}
try {
return {
...image,
previewUrl: URL.createObjectURL(image.file),
};
} catch {
return image;
}
}
export function getCustomModelOptionsByProvider(settings: {
customCodexModels: readonly string[];
customClaudeModels: readonly string[];
}): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
return {
codex: getAppModelOptions("codex", settings.customCodexModels),
claudeCode: getAppModelOptions("claudeCode", settings.customClaudeModels),
};
}
File diff suppressed because it is too large. Load diff
+28 -162
View File
@@ -47,12 +47,7 @@ import {
type Ref,
} from "react";
import {
clampCollapsedComposerCursor,
collapseExpandedComposerCursor,
expandCollapsedComposerCursor,
isCollapsedCursorAdjacentToMention,
} from "~/composer-logic";
import { isCollapsedCursorAdjacentToMention } from "~/composer-logic";
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
import { cn } from "~/lib/utils";
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
@@ -176,7 +171,7 @@ function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
container.append(icon, label);
}
function clampExpandedCursor(value: string, cursor: number): number {
function clampCursor(value: string, cursor: number): number {
if (!Number.isFinite(cursor)) return value.length;
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
}
@@ -197,21 +192,6 @@ function getComposerNodeTextLength(node: LexicalNode): number {
return 0;
}
function getComposerNodeExpandedTextLength(node: LexicalNode): number {
if ($isTextNode(node)) {
return node.getTextContentSize();
}
if ($isLineBreakNode(node)) {
return 1;
}
if ($isElementNode(node)) {
return node
.getChildren()
.reduce((total, child) => total + getComposerNodeExpandedTextLength(child), 0);
}
return 0;
}
function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
let offset = 0;
let current: LexicalNode | null = node;
@@ -256,50 +236,6 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
return offset;
}
function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
let offset = 0;
let current: LexicalNode | null = node;
while (current) {
const nextParent = current.getParent() as LexicalNode | null;
if (!nextParent || !$isElementNode(nextParent)) {
break;
}
const siblings = nextParent.getChildren();
const index = current.getIndexWithinParent();
for (let i = 0; i < index; i += 1) {
const sibling = siblings[i];
if (!sibling) continue;
offset += getComposerNodeExpandedTextLength(sibling);
}
current = nextParent;
}
if ($isTextNode(node)) {
if (node instanceof ComposerMentionNode) {
return offset + (pointOffset > 0 ? node.getTextContentSize() : 0);
}
return offset + Math.min(pointOffset, node.getTextContentSize());
}
if ($isLineBreakNode(node)) {
return offset + Math.min(pointOffset, 1);
}
if ($isElementNode(node)) {
const children = node.getChildren();
const clampedOffset = Math.max(0, Math.min(pointOffset, children.length));
for (let i = 0; i < clampedOffset; i += 1) {
const child = children[i];
if (!child) continue;
offset += getComposerNodeExpandedTextLength(child);
}
return offset;
}
return offset;
}
function findSelectionPointAtOffset(
node: LexicalNode,
remainingRef: { value: number },
@@ -414,17 +350,6 @@ function $readSelectionOffsetFromEditorState(fallback: number): number {
return Math.max(0, Math.min(offset, composerLength));
}
function $readExpandedSelectionOffsetFromEditorState(fallback: number): number {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
return fallback;
}
const anchorNode = selection.anchor.getNode();
const offset = getExpandedAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset);
const expandedLength = $getRoot().getTextContent().length;
return Math.max(0, Math.min(offset, expandedLength));
}
function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
const lines = text.split("\n");
for (let index = 0; index < lines.length; index += 1) {
@@ -458,7 +383,7 @@ export interface ComposerPromptEditorHandle {
focus: () => void;
focusAt: (cursor: number) => void;
focusAtEnd: () => void;
readSnapshot: () => { value: string; cursor: number; expandedCursor: number };
readSnapshot: () => { value: string; cursor: number };
}
interface ComposerPromptEditorProps {
@@ -467,12 +392,7 @@ interface ComposerPromptEditorProps {
disabled: boolean;
placeholder: string;
className?: string;
onChange: (
nextValue: string,
nextCursor: number,
expandedCursor: number,
cursorAdjacentToMention: boolean,
) => void;
onChange: (nextValue: string, nextCursor: number, cursorAdjacentToMention: boolean) => void;
onCommandKeyDown?: (
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
event: KeyboardEvent,
@@ -708,13 +628,7 @@ function ComposerPromptEditorInner({
}: ComposerPromptEditorInnerProps) {
const [editor] = useLexicalComposerContext();
const onChangeRef = useRef(onChange);
const initialCursor = clampCollapsedComposerCursor(value, cursor);
const snapshotRef = useRef({
value,
cursor: initialCursor,
expandedCursor: expandCollapsedComposerCursor(value, initialCursor),
});
const isApplyingControlledUpdateRef = useRef(false);
const snapshotRef = useRef({ value, cursor: clampCursor(value, cursor) });
useEffect(() => {
onChangeRef.current = onChange;
@@ -725,36 +639,27 @@ function ComposerPromptEditorInner({
}, [disabled, editor]);
useLayoutEffect(() => {
const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
const normalizedCursor = clampCursor(value, cursor);
const previousSnapshot = snapshotRef.current;
if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
return;
}
snapshotRef.current = {
value,
cursor: normalizedCursor,
expandedCursor: expandCollapsedComposerCursor(value, normalizedCursor),
};
if (previousSnapshot.value !== value) {
editor.update(() => {
$setComposerEditorPrompt(value);
});
}
snapshotRef.current = { value, cursor: normalizedCursor };
const rootElement = editor.getRootElement();
const isFocused = Boolean(rootElement && document.activeElement === rootElement);
if (previousSnapshot.value === value && !isFocused) {
if (!rootElement || document.activeElement !== rootElement) {
return;
}
isApplyingControlledUpdateRef.current = true;
editor.update(() => {
const valueChanged = previousSnapshot.value !== value;
if (previousSnapshot.value !== value) {
$setComposerEditorPrompt(value);
}
if (valueChanged || isFocused) {
$setSelectionAtComposerOffset(normalizedCursor);
}
});
queueMicrotask(() => {
isApplyingControlledUpdateRef.current = false;
$setSelectionAtComposerOffset(normalizedCursor);
});
}, [cursor, editor, value]);
@@ -762,7 +667,7 @@ function ComposerPromptEditorInner({
(nextCursor: number) => {
const rootElement = editor.getRootElement();
if (!rootElement) return;
const boundedCursor = clampCollapsedComposerCursor(snapshotRef.current.value, nextCursor);
const boundedCursor = clampCursor(snapshotRef.current.value, nextCursor);
rootElement.focus();
editor.update(() => {
$setSelectionAtComposerOffset(boundedCursor);
@@ -770,43 +675,24 @@ function ComposerPromptEditorInner({
snapshotRef.current = {
value: snapshotRef.current.value,
cursor: boundedCursor,
expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
};
onChangeRef.current(
snapshotRef.current.value,
boundedCursor,
snapshotRef.current.expandedCursor,
false,
);
onChangeRef.current(snapshotRef.current.value, boundedCursor, false);
},
[editor],
);
const readSnapshot = useCallback((): {
value: string;
cursor: number;
expandedCursor: number;
} => {
const readSnapshot = useCallback((): { value: string; cursor: number } => {
let snapshot = snapshotRef.current;
editor.getEditorState().read(() => {
const nextValue = $getRoot().getTextContent();
const fallbackCursor = clampCollapsedComposerCursor(nextValue, snapshotRef.current.cursor);
const nextCursor = clampCollapsedComposerCursor(
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
const nextCursor = clampCursor(
nextValue,
$readSelectionOffsetFromEditorState(fallbackCursor),
);
const fallbackExpandedCursor = clampExpandedCursor(
nextValue,
snapshotRef.current.expandedCursor,
);
const nextExpandedCursor = clampExpandedCursor(
nextValue,
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
);
snapshot = {
value: nextValue,
cursor: nextCursor,
expandedCursor: nextExpandedCursor,
};
});
snapshotRef.current = snapshot;
@@ -819,14 +705,11 @@ function ComposerPromptEditorInner({
focus: () => {
focusAt(snapshotRef.current.cursor);
},
focusAt,
focusAt: (nextCursor: number) => {
focusAt(nextCursor);
},
focusAtEnd: () => {
focusAt(
collapseExpandedComposerCursor(
snapshotRef.current.value,
snapshotRef.current.value.length,
),
);
focusAt(snapshotRef.current.value.length);
},
readSnapshot,
}),
@@ -836,39 +719,23 @@ function ComposerPromptEditorInner({
const handleEditorChange = useCallback((editorState: EditorState) => {
editorState.read(() => {
const nextValue = $getRoot().getTextContent();
const fallbackCursor = clampCollapsedComposerCursor(nextValue, snapshotRef.current.cursor);
const nextCursor = clampCollapsedComposerCursor(
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
const nextCursor = clampCursor(
nextValue,
$readSelectionOffsetFromEditorState(fallbackCursor),
);
const fallbackExpandedCursor = clampExpandedCursor(
nextValue,
snapshotRef.current.expandedCursor,
);
const nextExpandedCursor = clampExpandedCursor(
nextValue,
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
);
const previousSnapshot = snapshotRef.current;
if (
previousSnapshot.value === nextValue &&
previousSnapshot.cursor === nextCursor &&
previousSnapshot.expandedCursor === nextExpandedCursor
) {
return;
}
if (isApplyingControlledUpdateRef.current) {
if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {
return;
}
snapshotRef.current = {
value: nextValue,
cursor: nextCursor,
expandedCursor: nextExpandedCursor,
};
const cursorAdjacentToMention =
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, cursorAdjacentToMention);
onChangeRef.current(nextValue, nextCursor, cursorAdjacentToMention);
});
}, []);
@@ -881,7 +748,6 @@ function ComposerPromptEditorInner({
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
className,
)}
data-testid="composer-editor"
aria-placeholder={placeholder}
placeholder={<span />}
onPaste={onPaste}
+41 -20
View File
@@ -12,21 +12,18 @@ import {
useRef,
useState,
} from "react";
import { openInPreferredEditor } from "../editorPreferences";
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
import { resolvePathLinkTarget } from "../terminal-links";
import { preferredTerminalEditor, resolvePathLinkTarget } from "../terminal-links";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { buildPatchCacheKey } from "../lib/diffRendering";
import { resolveDiffThemeName } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useStore } from "../store";
import { useAppSettings } from "../appSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
type DiffRenderMode = "stacked" | "split";
@@ -151,8 +148,15 @@ function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
}
function formatTurnChipTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
}).format(new Date(isoDate));
}
interface DiffPanelProps {
mode?: DiffPanelMode;
mode?: "inline" | "sheet" | "sidebar";
}
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
@@ -160,7 +164,6 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const { settings } = useAppSettings();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const patchViewportRef = useRef<HTMLDivElement>(null);
const turnStripRef = useRef<HTMLDivElement>(null);
@@ -308,7 +311,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const api = readNativeApi();
if (!api) return;
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
void openInPreferredEditor(api, targetPath).catch((error) => {
void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
console.warn("Failed to open diff file in editor.", error);
});
},
@@ -398,6 +401,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
}, [selectedTurn?.turnId, selectedTurnId]);
const shouldUseDragRegion = isElectron && mode !== "sheet";
const headerRow = (
<>
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
@@ -482,7 +486,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
"?"}
</span>
<span className="text-[9px] leading-tight opacity-70">
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
{formatTurnChipTimestamp(summary.completedAt)}
</span>
</div>
</div>
@@ -511,9 +515,28 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
</ToggleGroup>
</>
);
const headerRowClassName = cn(
"flex items-center justify-between gap-2 px-4",
shouldUseDragRegion ? "drag-region h-[52px] border-b border-border" : "h-12",
);
return (
<DiffPanelShell mode={mode} header={headerRow}>
<div
className={cn(
"flex h-full min-w-0 flex-col bg-background",
mode === "inline"
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
: "w-full",
)}
>
{shouldUseDragRegion ? (
<div className={headerRowClassName}>{headerRow}</div>
) : (
<div className="border-b border-border">
<div className={headerRowClassName}>{headerRow}</div>
</div>
)}
{!activeThread ? (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
Select a thread to inspect turn diffs.
@@ -538,17 +561,15 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
</div>
)}
{!renderablePatch ? (
isLoadingCheckpointDiff ? (
<DiffPanelLoadingState label="Loading checkpoint diff..." />
) : (
<div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
<p>
{hasNoNetChanges
<div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
<p>
{isLoadingCheckpointDiff
? "Loading checkpoint diff..."
: hasNoNetChanges
? "No net changes in this selection."
: "No patch available for this selection."}
</p>
</div>
)
</p>
</div>
) : renderablePatch.kind === "files" ? (
<Virtualizer
className="diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2"
@@ -604,6 +625,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
</div>
</>
)}
</DiffPanelShell>
</div>
);
}
@@ -1,92 +0,0 @@
import type { ReactNode } from "react";
import { isElectron } from "~/env";
import { cn } from "~/lib/utils";
import { Skeleton } from "./ui/skeleton";
export type DiffPanelMode = "inline" | "sheet" | "sidebar";
function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) {
const shouldUseDragRegion = isElectron && mode !== "sheet";
return cn(
"flex items-center justify-between gap-2 px-4",
shouldUseDragRegion ? "drag-region h-[52px] border-b border-border" : "h-12",
);
}
export function DiffPanelShell(props: {
mode: DiffPanelMode;
header: ReactNode;
children: ReactNode;
}) {
const shouldUseDragRegion = isElectron && props.mode !== "sheet";
return (
<div
className={cn(
"flex h-full min-w-0 flex-col bg-background",
props.mode === "inline"
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
: "w-full",
)}
>
{shouldUseDragRegion ? (
<div className={getDiffPanelHeaderRowClassName(props.mode)}>{props.header}</div>
) : (
<div className="border-b border-border">
<div className={getDiffPanelHeaderRowClassName(props.mode)}>{props.header}</div>
</div>
)}
{props.children}
</div>
);
}
export function DiffPanelHeaderSkeleton() {
return (
<>
<div className="relative min-w-0 flex-1">
<Skeleton className="absolute left-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50" />
<Skeleton className="absolute right-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50" />
<div className="flex gap-1 overflow-hidden px-8 py-0.5">
<Skeleton className="h-6 w-16 shrink-0 rounded-md" />
<Skeleton className="h-6 w-24 shrink-0 rounded-md" />
<Skeleton className="h-6 w-24 shrink-0 rounded-md max-sm:hidden" />
</div>
</div>
<div className="flex shrink-0 gap-1">
<Skeleton className="size-7 rounded-md" />
<Skeleton className="size-7 rounded-md" />
</div>
</>
);
}
export function DiffPanelLoadingState(props: { label: string }) {
return (
<div className="flex min-h-0 flex-1 flex-col p-2">
<div
className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border/60 bg-card/25"
role="status"
aria-live="polite"
aria-label={props.label}
>
<div className="flex items-center gap-2 border-b border-border/50 px-3 py-2">
<Skeleton className="h-4 w-32 rounded-full" />
<Skeleton className="ml-auto h-4 w-20 rounded-full" />
</div>
<div className="flex min-h-0 flex-1 flex-col gap-4 px-3 py-4">
<div className="space-y-2">
<Skeleton className="h-3 w-full rounded-full" />
<Skeleton className="h-3 w-full rounded-full" />
<Skeleton className="h-3 w-10/12 rounded-full" />
<Skeleton className="h-3 w-11/12 rounded-full" />
<Skeleton className="h-3 w-9/12 rounded-full" />
</div>
<span className="sr-only">{props.label}</span>
</div>
</div>
</div>
);
}
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff. Show more