Compare commits

..
Author SHA1 Message Date
Julius Marminge eca89790d4 Use Debouncer for composer draft persistence writes
- Replace manual timeout/pending-value debounce logic with `@tanstack/react-pacer` `Debouncer`
- Keep `removeItem`/`flush` behavior while simplifying and standardizing persistence timing
2026-03-09 13:00:27 -07:00
Julius Marminge f9dab13472 Use React Pacer throttler for domain event snapshot sync
- Replace manual timeout-based domain event batching with `Throttler`
- Keep provider query invalidation batched with trailing 100ms flushes
- Cancel throttler and reset invalidation flag during EventRouter cleanup
2026-03-09 12:45:34 -07:00
Julius Marminge 4babb1a859 Use Debouncer for store state persistence
- Replace manual timeout debounce logic with `@tanstack/react-pacer`'s `Debouncer`
- Persist updates via `maybeExecute` to reduce localStorage write thrashing
- Flush pending persistence on `beforeunload` to avoid losing recent state
2026-03-09 12:28:26 -07:00
Julius Marminge 75533fbd40 Remove ProviderHealth onReady callback from service interface
- Drop the unused `onReady` hook from `ProviderHealthShape`
- Keep startup health status access focused on `getStatuses`
2026-03-09 12:23:33 -07:00
Tim SmartandClaude Opus 4.6 fd98835834 cleanup
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-09 12:18:33 -07:00
Chukwudi Nwobodo c6dc7c6524 perf: run provider health checks in background, notify clients on ready
The ProviderHealth layer blocked server startup with two sequential CLI
spawns (codex --version + codex login status), each with a 4-second
timeout, delaying startup by up to 8 seconds.

Run health checks in the background via Effect.runPromise so the layer
resolves immediately with a placeholder status. Add an onReady callback
to ProviderHealthShape so wsServer can push the resolved statuses to
connected clients once checks complete, preventing early-connecting
clients from showing "Checking..." indefinitely.
2026-03-08 06:22:26 +00:00
Chukwudi Nwobodo a04e3561ed perf: throttle domain event processing with 100ms batch window
During active sessions, every domain event triggered a full
syncSnapshot (IPC fetch + state rebuild + React re-render cascade) and
sometimes a provider query invalidation. Events fire in rapid bursts
during AI turns.

Replace per-event processing with a throttle-first pattern: schedule a
flush on the first event, absorb subsequent events within a 100ms
window, then sync once. Provider query invalidation is batched via a
flag. Since syncSnapshot fetches the complete snapshot, no events are
lost by skipping intermediate syncs.
2026-03-08 06:22:14 +00:00
Chukwudi Nwobodo dd51d4faec perf: debounce Zustand store persistence and deduplicate legacy cleanup
The useStore subscriber called persistState on every state mutation,
triggering JSON.stringify + localStorage.setItem synchronously. It also
ran 8 localStorage.removeItem calls for legacy keys on every fire.

Wrap the subscriber with a 500ms debounce so rapid state changes batch
into a single write. Move legacy key cleanup behind a one-time flag so
it runs only once per page load. Add a beforeunload handler to flush
the final state.
2026-03-08 06:22:02 +00:00
Chukwudi Nwobodo e21687300e perf: debounce composer draft localStorage writes
Every keystroke triggered full JSON serialization of all composer drafts
(including base64 image attachments) and a synchronous localStorage
write. At normal typing speed this caused 5+ writes/sec, blocking the
main thread and creating noticeable input lag.

Wrap the Zustand persist storage with a 300ms debounce. In-memory state
updates remain immediate; only the serialization and storage write are
deferred. A beforeunload handler flushes pending writes to prevent data
loss. The removeItem method cancels any pending setItem to avoid
resurrecting cleared drafts.

Adds unit tests for the DebouncedStorage utility covering debounce
timing, rapid writes, removeItem cancellation, flush, and edge cases.
2026-03-08 06:21:52 +00:00
99 changed files with 1433 additions and 4680 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
-180
View File
@@ -1,180 +0,0 @@
# Encyclopedia
This is a living glossary for T3 Code. It explains what common terms mean in this codebase.
## Table of contents
- [Project and workspace](#project-and-workspace)
- [Thread timeline](#thread-timeline)
- [Orchestration](#orchestration)
- [Provider runtime](#provider-runtime)
- [Checkpointing](#checkpointing)
## Concepts
### Project and workspace
#### Project
The top-level workspace record in the app. In [the orchestration contracts][1], a project has a `workspaceRoot`, a title, and one or more threads. See [workspace-layout.md][2].
#### Workspace root
The root filesystem path for a project. In [the orchestration model][1], it is the base directory for branches and optional worktrees. See [workspace-layout.md][2].
#### Worktree
A Git worktree used as an isolated workspace for a thread. If a thread has a `worktreePath` in [the contracts][1], it runs there instead of in the main working tree. Git operations live in [GitCore.ts][3].
### Thread timeline
#### Thread
The main durable unit of conversation and workspace history. In [the orchestration contracts][1], a thread holds messages, activities, checkpoints, and session-related state. See [projector.ts][4].
#### Turn
A single user-to-assistant work cycle inside a thread. It starts with user input and ends when follow-up work like checkpointing settles. See [the contracts][1], [ProviderRuntimeIngestion.ts][5], and [CheckpointReactor.ts][6].
#### Activity
A user-visible log item attached to a thread. In [the contracts][1], activities cover important non-message events like approvals, tool actions, and failures. They are projected into thread state in [projector.ts][4].
### Orchestration
Orchestration is the server-side domain layer that turns runtime activity into stable app state. The main entry point is [OrchestrationEngine.ts][7], with core logic in [decider.ts][8] and [projector.ts][4].
#### Aggregate
The domain object a command or event belongs to. In [the contracts][1], that is usually `project` or `thread`. See [decider.ts][8].
#### Command
A typed request to change domain state. In [the contracts][1], commands are validated in [commandInvariants.ts][9] and turned into events by [decider.ts][8].
Examples include `thread.create`, `thread.turn.start`, and `thread.checkpoint.revert`.
#### Domain Event
A persisted fact that something already happened. In [the contracts][1], events are the source of truth, and [projector.ts][4] shows how they are applied.
Examples include `thread.created`, `thread.message-sent`, and `thread.turn-diff-completed`.
#### Decider
The pure orchestration logic that turns commands plus current state into events. The core implementation is in [decider.ts][8], with preconditions in [commandInvariants.ts][9].
#### Projection
A read-optimized view derived from events. See [projector.ts][4], [ProjectionPipeline.ts][11], and [ProjectionSnapshotQuery.ts][10].
#### Projector
The logic that applies domain events to the read model or projection tables. See [projector.ts][4] and [ProjectionPipeline.ts][11].
#### Read model
The current materialized view of orchestration state. In [the contracts][1], it holds projects, threads, messages, activities, checkpoints, and session state. See [ProjectionSnapshotQuery.ts][10] and [OrchestrationEngine.ts][7].
#### Reactor
A side-effecting service that handles follow-up work after events or runtime signals. Examples include [CheckpointReactor.ts][6], [ProviderCommandReactor.ts][12], and [ProviderRuntimeIngestion.ts][5].
#### Receipt
A lightweight typed runtime signal emitted when an async milestone completes. See [RuntimeReceiptBus.ts][13].
Examples include `checkpoint.baseline.captured`, `checkpoint.diff.finalized`, and `turn.processing.quiesced`, which are emitted by flows such as [CheckpointReactor.ts][6].
#### Quiesced
"Quiesced" means a turn has gone quiet and stable. In [the receipt schema][13], it means the follow-up work has settled, including work in [CheckpointReactor.ts][6].
### Provider runtime
The live backend agent implementation and its event stream. The main service is [ProviderService.ts][14], the adapter contract is [ProviderAdapter.ts][15], and the overview is in [provider-architecture.md][16].
#### Provider
The backend agent runtime that actually performs work. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17].
#### Session
The live provider-backed runtime attached to a thread. Session shape is in [the orchestration contracts][1], and lifecycle is managed in [ProviderService.ts][14].
#### Runtime mode
The safety/access mode for a thread or session. In [the contracts][1], the main values are `approval-required` and `full-access`. See [runtime-modes.md][18].
#### Interaction mode
The agent interaction style for a thread. In [the contracts][1], the main values are `default` and `plan`. See [runtime-modes.md][18].
#### Assistant delivery mode
Controls how assistant text reaches the thread timeline. In [the contracts][1], `streaming` updates incrementally and `buffered` delivers a completed result. See [ProviderService.ts][14].
#### Snapshot
A point-in-time view of state. The word is used in multiple layers, including orchestration, provider, and checkpointing. See [ProjectionSnapshotQuery.ts][10], [ProviderAdapter.ts][15], and [CheckpointStore.ts][19].
### Checkpointing
Checkpointing captures workspace state over time so the app can diff turns and restore earlier points. The main pieces are [CheckpointStore.ts][19], [CheckpointDiffQuery.ts][20], and [CheckpointReactor.ts][6].
#### Checkpoint
A saved snapshot of a thread workspace at a particular turn. In practice it is a hidden Git ref in [CheckpointStore.ts][19] plus a projected summary from [ProjectionCheckpoints.ts][21]. Capture and lifecycle work happen in [CheckpointReactor.ts][6].
#### Checkpoint ref
The durable identifier for a filesystem checkpoint, stored as a Git ref. It is typed in [the contracts][1], constructed in [Utils.ts][22], and used by [CheckpointStore.ts][19].
#### Checkpoint baseline
The starting checkpoint for diffing a thread timeline. This flow is surfaced through [RuntimeReceiptBus.ts][13], coordinated in [CheckpointReactor.ts][6], and supported by [Utils.ts][22].
#### Checkpoint diff
The patch difference between two checkpoints. Query logic lives in [CheckpointDiffQuery.ts][20], diff parsing lives in [Diffs.ts][23], and finalization is coordinated by [CheckpointReactor.ts][6].
#### Turn diff
The file patch and changed-file summary for one turn. It is usually computed in [CheckpointDiffQuery.ts][20], represented in [the contracts][1], and recorded into thread state by [projector.ts][4].
## Practical Shortcuts
- If you see `requested`, think "intent recorded".
- If you see `completed`, think "result applied".
- If you see `receipt`, think "async milestone signal".
- If you see `checkpoint`, think "workspace snapshot for diff/restore".
- If you see `quiesced`, think "all relevant follow-up work has gone idle".
## Related Docs
- [architecture.md][24]
- [provider-architecture.md][16]
- [runtime-modes.md][18]
- [workspace-layout.md][2]
[1]: ../packages/contracts/src/orchestration.ts
[2]: ./workspace-layout.md
[3]: ../apps/server/src/git/Layers/GitCore.ts
[4]: ../apps/server/src/orchestration/projector.ts
[5]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[6]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts
[7]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
[8]: ../apps/server/src/orchestration/decider.ts
[9]: ../apps/server/src/orchestration/commandInvariants.ts
[10]: ../apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
[11]: ../apps/server/src/orchestration/Layers/ProjectionPipeline.ts
[12]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[13]: ../apps/server/src/orchestration/Services/RuntimeReceiptBus.ts
[14]: ../apps/server/src/provider/Layers/ProviderService.ts
[15]: ../apps/server/src/provider/Services/ProviderAdapter.ts
[16]: ./provider-architecture.md
[17]: ../apps/server/src/provider/Layers/CodexAdapter.ts
[18]: ./runtime-modes.md
[19]: ../apps/server/src/checkpointing/Services/CheckpointStore.ts
[20]: ../apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts
[21]: ../apps/server/src/persistence/Services/ProjectionCheckpoints.ts
[22]: ../apps/server/src/checkpointing/Utils.ts
[23]: ../apps/server/src/checkpointing/Diffs.ts
[24]: ./architecture.md
+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.
-28
View File
@@ -1,28 +0,0 @@
# Trust list for this repository.
#
# External contributors listed here are treated as trusted by the vouch
# workflow. Collaborators with write access are automatically trusted and
# do not need to be duplicated in this file.
#
# Syntax:
# github:username
# -github:username reason for denouncement
#
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chuks-qua
github:cursoragent
github:gbarros-dev
github:github-actions[bot]
github:hwanseoc
github:jamesx0416
github:jasonLaster
github:JoeEverest
github:nmggithub
github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
-33
View File
@@ -1,33 +0,0 @@
<!--
⚠️ READ BEFORE OPENING ⚠️
We are not actively accepting contributions right now.
You can still open a PR, but please do so knowing there is a high chance
we may close it without merging it, or never review it.
- Small, focused PRs are strongly preferred. Bug fixes are most likely to be merged.
- New features will most likely just annoy us.
- 1,000+ line PRs with a bunch of new features will probably get you banned from the repo.
-->
## What Changed
<!-- Describe the change clearly and keep scope tight. -->
## Why
<!-- Explain the problem being solved and why this approach is the right one. -->
## UI Changes
<!-- If this PR changes UI, include clear before/after screenshots.
If the change involves motion or interaction, include a short video.
Delete this section if not applicable. -->
## Checklist
- [ ] This PR is small and focused
- [ ] I explained what changed and why
- [ ] I included before/after screenshots for any UI changes
- [ ] I included a video for animation/interaction changes
-20
View File
@@ -69,23 +69,3 @@ jobs:
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
release_smoke:
name: Release Smoke
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
-175
View File
@@ -1,175 +0,0 @@
name: PR Vouch
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
issue_comment:
types: [created]
push:
branches:
- main
paths:
- .github/VOUCHED.td
- .github/workflows/pr-vouch.yml
permissions:
contents: read
issues: write
pull-requests: write
jobs:
collect-targets:
name: Collect PR targets
runs-on: ubuntu-24.04
outputs:
targets: ${{ steps.collect.outputs.targets }}
steps:
- id: collect
uses: actions/github-script@v7
with:
script: |
if (context.eventName === "pull_request_target") {
const pr = context.payload.pull_request;
core.setOutput("targets", JSON.stringify([{ number: pr.number, user: pr.user.login }]));
return;
}
if (context.eventName === "issue_comment") {
const issue = context.payload.issue;
const body = context.payload.comment?.body ?? "";
if (!issue?.pull_request || !body.includes("/recheck-vouch")) {
core.setOutput("targets", "[]");
return;
}
core.setOutput(
"targets",
JSON.stringify([{ number: issue.number, user: issue.user.login }]),
);
return;
}
const pulls = await github.paginate(github.rest.pulls.list, {
owner: context.repo.owner,
repo: context.repo.repo,
state: "open",
per_page: 100,
});
const targets = pulls.map((pull) => ({
number: pull.number,
user: pull.user.login,
}));
core.setOutput("targets", JSON.stringify(targets));
label:
name: Label PR ${{ matrix.target.number }}
needs: collect-targets
if: ${{ needs.collect-targets.outputs.targets != '[]' }}
runs-on: ubuntu-24.04
concurrency:
group: pr-vouch-${{ matrix.target.number }}
cancel-in-progress: true
strategy:
fail-fast: false
matrix:
target: ${{ fromJson(needs.collect-targets.outputs.targets) }}
steps:
- id: vouch
name: Check PR author trust
uses: mitchellh/vouch/action/check-user@v1
with:
user: ${{ matrix.target.user }}
allow-fail: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Sync PR labels
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ matrix.target.number }}
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
with:
script: |
const issueNumber = Number(process.env.PR_NUMBER);
const status = process.env.VOUCH_STATUS;
const managedLabels = [
{
name: "vouch:trusted",
color: "1f883d",
description: "PR author is trusted by repo permissions or the VOUCHED list.",
},
{
name: "vouch:unvouched",
color: "fbca04",
description: "PR author is not yet trusted in the VOUCHED list.",
},
{
name: "vouch:denounced",
color: "d1242f",
description: "PR author is explicitly blocked by the VOUCHED list.",
},
];
const managedLabelNames = managedLabels.map((label) => label.name);
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
const nextLabelName =
status === "denounced"
? "vouch:denounced"
: ["bot", "collaborator", "vouched"].includes(status)
? "vouch:trusted"
: "vouch:unvouched";
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
});
const preservedLabels = currentLabels
.map((label) => label.name)
.filter((name) => !managedLabelNames.includes(name));
await github.rest.issues.setLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [...preservedLabels, nextLabelName],
});
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
+28 -19
View File
@@ -255,16 +255,6 @@ jobs:
needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Download all desktop artifacts
uses: actions/download-artifact@v4
with:
@@ -272,13 +262,6 @@ jobs:
merge-multiple: true
path: release-assets
- name: Merge macOS updater manifests
run: |
node scripts/merge-mac-update-manifests.ts \
release-assets/latest-mac.yml \
release-assets/latest-mac-x64.yml
rm -f release-assets/latest-mac-x64.yml
- name: Publish release
uses: softprops/action-gh-release@v2
with:
@@ -322,7 +305,33 @@ jobs:
name: Update version strings
env:
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
run: |
node --input-type=module -e '
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
const files = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
];
let changed = false;
for (const file of files) {
const packageJson = JSON.parse(readFileSync(file, "utf8"));
if (packageJson.version !== process.env.RELEASE_VERSION) {
packageJson.version = process.env.RELEASE_VERSION;
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
changed = true;
}
}
if (!changed) {
console.log("All package.json versions already match release version.");
}
appendFileSync(process.env.GITHUB_OUTPUT, `changed=${changed}\n`);
'
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
@@ -330,7 +339,7 @@ jobs:
- name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true'
run: bun install --lockfile-only --ignore-scripts
run: bun install
- name: Commit and push version bump
if: steps.update_versions.outputs.changed == 'true'
-3
View File
@@ -1,3 +0,0 @@
[tools]
node = "24.13.1"
bun = "1.3.9"
@@ -1,88 +0,0 @@
# Plan: Provider-Neutral Runtime Determinism and Flake Elimination
## Summary
Replace timing-sensitive websocket and orchestration behavior with explicit typed runtime boundaries, ordered push delivery, and server-owned completion receipts. The cutover is broad and single-shot: no compatibility shim, no mixed old/new transport. The design must reduce flakes without baking Codex-specific lifecycle semantics into generic runtime code.
## Key Changes
### 1. Strengthen the generic boundaries, not the Codex boundary
- Keep `ProviderRuntimeEvent` as the canonical provider event contract and `ProviderService` as the only cross-provider facade.
- Do not expose raw Codex payloads or Codex event ordering outside `CodexAdapter.ts` and `codexAppServerManager.ts`.
- Do not expand `ProviderKind` in this change. The runtime stays provider-neutral by contract, while the product remains Codex-only in concrete support.
### 2. Replace loose websocket envelopes with channel-indexed typed pushes
- Refactor `packages/contracts/src/ws.ts` so push messages are derived from a channel-to-schema map instead of `channel: string` plus `data: unknown`.
- Add `sequence: number` to every server push. Ordering becomes explicit and testable.
- Add structured decode diagnostics with stable machine fields: `code`, `reason`, `expected`, `actual`, `path`, optional `jsonOffset`.
- Remove runtime/test dependence on engine-specific pretty strings. Human-readable formatting remains a logging helper only.
### 3. Introduce explicit server readiness and a single push pipeline
- Add a `ServerPushBus` service in `apps/server` backed by one ordered queue/pubsub path. All pushes go through it: `server.welcome`, `server.configUpdated`, terminal events, orchestration domain events.
- Add a `ServerReadiness` service with explicit barriers for:
- HTTP listening
- push bus ready
- keybindings runtime ready
- terminal subscriptions ready
- orchestration subscriptions ready
- Strengthen `server.welcome` semantics: it is emitted only after connection-scoped and server-scoped readiness is complete.
- `wsServer` should never publish directly from ad hoc background streams once the bus exists.
### 4. Turn background watchers into explicit runtimes
- Extract keybindings watching into a `KeybindingsRuntime` service with `start`, `ready`, `snapshot`, and `changes`.
- Initial config load, startup sync, cache warmup, and watcher attachment complete before `ready` resolves.
- Keep the real `fs.watch` adapter thin. Most behavior tests use a fake watch source and deterministic change stream.
### 5. Replace polling-based orchestration waiting with receipts
- Add server-owned completion receipts for operations that tests currently infer by polling:
- checkpoint capture complete
- checkpoint diff finalized
- turn processing quiesced
- A receipt means append, projection, and required side effects are complete. It must not mean the provider emitted a certain event sequence.
- Update the orchestration harness and checkpoint tests to await receipts/barriers instead of polling snapshots and git refs.
### 6. Centralize client transport state and decoding
- Refactor `apps/web/src/wsTransport.ts` into an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Decode and validate typed push payloads at the transport boundary, not downstream in `apps/web/src/wsNativeApi.ts`.
- Keep cached latest welcome/config behavior only if it is modeled as explicit state, not as a late-subscriber race workaround.
### 7. Replace ad hoc test helpers with semantic test clients
- Add a shared `WsTestClient` for server/websocket tests:
- connect
- await semantic welcome
- await typed push by channel and optional predicate
- track `sequence`
- match RPC responses by id
- Add one orchestration test harness that waits on receipts/barriers instead of custom `waitForThread`, `waitForGitRef`, and arbitrary retry loops.
- Keep only a narrow set of integration tests for real filesystem/watch/socket behavior. Move behavioral assertions to deterministic unit-style harnesses.
## Provider-Coupling Guardrails
- No generic runtime API may depend on Codex-native event names, thread IDs, or request payload shapes.
- No readiness barrier may be defined as “Codex has emitted X.” Readiness is owned by the server runtime, not by provider event order.
- No websocket channel payload may contain raw provider-native payloads unless the channel is explicitly debug/internal.
- Any provider-specific divergence must be exposed through provider capabilities from `ProviderService.getCapabilities()`, not `if provider === "codex"` branches in shared runtime code.
- Generic tests must use canonical `ProviderRuntimeEvent` fixtures. Codex-specific ordering and translation tests stay in adapter/app-server suites only.
- Keep UI/provider-specific knobs such as Codex-only options scoped to provider UX code. Do not pull them into generic transport or orchestration state.
## Test Plan
- Contracts:
- schema tests for typed push envelopes and structured decode diagnostics
- ordering tests for `sequence`
- Server:
- readiness tests proving `server.welcome` cannot precede runtime readiness
- push bus tests proving terminal/config/orchestration pushes are serialized and typed
- keybindings runtime tests with fake watch source plus one real watcher integration test
- Orchestration:
- receipt tests proving checkpoint refs and projections are complete before completion signals resolve
- replacement of polling-based checkpoint/integration waits with receipt-based waits
- Web:
- transport tests for invalid JSON, invalid envelope, invalid payload, reconnect queue flushing, cached semantic state
- Validation gate:
- `bun run lint`
- `bun run typecheck`
- `mise exec -- bun run test`
- repeated full-suite run after cutover to confirm flake removal
## Assumptions and Defaults
- This remains a single-provider product during the cutover, but the runtime contracts must stay provider-neutral.
- No backward-compatibility layer is required for old websocket push envelopes.
- The goal is deterministic runtime behavior first; reducing retries and sleeps in tests is a consequence, not the primary mechanism.
- If a completion signal cannot be expressed provider-neutrally, it does not belong in the shared runtime layer and must stay adapter-local.
-65
View File
@@ -1,65 +0,0 @@
# Contributing
## Read This First
We are not actively accepting contributions right now.
You can still open an issue or PR, but please do so knowing there is a high chance we close it, defer it forever, or never look at it.
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
PRs are automatically labeled with a `vouch:*` trust status.
If you are an external contributor, expect `vouch:unvouched` until we explicitly add you to [.github/VOUCHED.td](.github/VOUCHED.td).
## What We Are Most Likely To Accept
Small, focused bug fixes.
Small reliability fixes.
Small performance improvements.
Tightly scoped maintenance work that clearly improves the project without changing its direction.
## What We Are Least Likely To Accept
Large PRs.
Drive-by feature work.
Opinionated rewrites.
Anything that expands product scope without us asking for it first.
If you open a 1,000+ line PR full of new features, we will probably close it quickly and remember that you ignored the clearly written instructions.
## If You Still Want To Open A PR
Keep it small.
Explain exactly what changed.
Explain exactly why the change should exist.
Do not mix unrelated fixes together.
If the PR makes anything resembling a UI change, include clear before/after images.
If the change depends on motion, timing, transitions, or interaction details, include a short video.
If we have to guess what changed, we are much less likely to review it.
## Issues First
If you are thinking about a non-trivial change, open an issue first.
That still does not mean we will want the PR, but it gives you a chance to avoid wasting your time.
## Be Realistic
Opening a PR does not create an obligation on our side.
We may close it. We may ignore it. We may ask you to shrink it. We may reimplement the idea ourselves later.
If you are fine with that, proceed.
-4
View File
@@ -21,8 +21,4 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
## If you REALLY want to contribute still.... read this first
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.9",
"version": "0.0.4-alpha.1",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+16 -110
View File
@@ -31,7 +31,6 @@ import {
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
fixPath();
@@ -51,8 +50,6 @@ const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
const COMMIT_HASH_DISPLAY_LENGTH = 12;
const LOG_DIR = Path.join(STATE_DIR, "logs");
@@ -81,13 +78,7 @@ let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
platform: process.platform,
processArch: process.arch,
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
const initialUpdateState = (): DesktopUpdateState => createInitialDesktopUpdateState(app.getVersion());
function logTimestamp(): string {
return new Date().toISOString();
@@ -121,25 +112,6 @@ function formatErrorMessage(error: unknown): string {
return String(error);
}
function getSafeExternalUrl(rawUrl: unknown): string | null {
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
return null;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return null;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
return null;
}
return parsedUrl.toString();
}
function writeDesktopStreamChunk(
streamName: "stdout" | "stderr",
chunk: unknown,
@@ -602,34 +574,6 @@ function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
return resolveResourcePath(`icon.${ext}`);
}
/**
* Resolve the Electron userData directory path.
*
* Electron derives the default userData path from `productName` in
* package.json, which currently produces directories with spaces and
* parentheses (e.g. `~/.config/T3 Code (Alpha)` on Linux). This is
* unfriendly for shell usage and violates Linux naming conventions.
*
* We override it to a clean lowercase name (`t3code`). If the legacy
* directory already exists we keep using it so existing users don't
* lose their Chromium profile data (localStorage, cookies, sessions).
*/
function resolveUserDataPath(): string {
const appDataBase =
process.platform === "win32"
? process.env.APPDATA || Path.join(OS.homedir(), "AppData", "Roaming")
: process.platform === "darwin"
? Path.join(OS.homedir(), "Library", "Application Support")
: process.env.XDG_CONFIG_HOME || Path.join(OS.homedir(), ".config");
const legacyPath = Path.join(appDataBase, LEGACY_USER_DATA_DIR_NAME);
if (FS.existsSync(legacyPath)) {
return legacyPath;
}
return Path.join(appDataBase, USER_DATA_DIR_NAME);
}
function configureAppIdentity(): void {
app.setName(APP_DISPLAY_NAME);
const commitHash = resolveAboutCommitHash();
@@ -715,7 +659,6 @@ async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed
}
updateDownloadInFlight = true;
setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState));
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
console.info("[desktop-updater] Downloading update...");
try {
@@ -754,7 +697,7 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
function configureAutoUpdater(): void {
const enabled = shouldEnableAutoUpdates();
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
...createInitialDesktopUpdateState(app.getVersion()),
enabled,
status: enabled ? "idle" : "disabled",
});
@@ -788,15 +731,8 @@ function configureAutoUpdater(): void {
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
autoUpdater.allowDowngrade = false;
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
let lastLoggedDownloadMilestone = -1;
if (isArm64HostRunningIntelBuild(desktopRuntimeInfo)) {
console.info(
"[desktop-updater] Apple Silicon host detected while running Intel build; updates will switch to arm64 packages.",
);
}
autoUpdater.on("checking-for-update", () => {
console.info("[desktop-updater] Looking for updates...");
});
@@ -1097,13 +1033,23 @@ function registerIpcHandlers(): void {
ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
const externalUrl = getSafeExternalUrl(rawUrl);
if (!externalUrl) {
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
return false;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return false;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
return false;
}
try {
await shell.openExternal(externalUrl);
await shell.openExternal(parsedUrl.toString());
return true;
} catch {
return false;
@@ -1168,42 +1114,7 @@ function createWindow(): BrowserWindow {
},
});
window.webContents.on("context-menu", (event, params) => {
event.preventDefault();
const menuTemplate: MenuItemConstructorOptions[] = [];
if (params.misspelledWord) {
for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
menuTemplate.push({
label: suggestion,
click: () => window.webContents.replaceMisspelling(suggestion),
});
}
if (params.dictionarySuggestions.length === 0) {
menuTemplate.push({ label: "No suggestions", enabled: false });
}
menuTemplate.push({ type: "separator" });
}
menuTemplate.push(
{ role: "cut", enabled: params.editFlags.canCut },
{ role: "copy", enabled: params.editFlags.canCopy },
{ role: "paste", enabled: params.editFlags.canPaste },
{ role: "selectAll", enabled: params.editFlags.canSelectAll },
);
Menu.buildFromTemplate(menuTemplate).popup({ window });
});
window.webContents.setWindowOpenHandler(({ url }) => {
const externalUrl = getSafeExternalUrl(url);
if (externalUrl) {
void shell.openExternal(externalUrl);
}
return { action: "deny" };
});
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
window.on("page-title-updated", (event) => {
event.preventDefault();
window.setTitle(APP_DISPLAY_NAME);
@@ -1232,11 +1143,6 @@ function createWindow(): BrowserWindow {
return window;
}
// Override Electron's userData path before the `ready` event so that
// Chromium session data uses a filesystem-friendly directory name.
// Must be called synchronously at the top level — before `app.whenReady()`.
app.setPath("userData", resolveUserDataPath());
configureAppIdentity();
async function bootstrap(): Promise<void> {
-49
View File
@@ -1,49 +0,0 @@
import { describe, expect, it } from "vitest";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
describe("resolveDesktopRuntimeInfo", () => {
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "darwin",
processArch: "x64",
runningUnderArm64Translation: true,
});
expect(runtimeInfo).toEqual({
hostArch: "arm64",
appArch: "x64",
runningUnderArm64Translation: true,
});
expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(true);
});
it("detects native Apple Silicon builds", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "darwin",
processArch: "arm64",
runningUnderArm64Translation: false,
});
expect(runtimeInfo).toEqual({
hostArch: "arm64",
appArch: "arm64",
runningUnderArm64Translation: false,
});
expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(false);
});
it("passes through non-mac builds without translation", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "linux",
processArch: "x64",
runningUnderArm64Translation: true,
});
expect(runtimeInfo).toEqual({
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
});
});
});
-40
View File
@@ -1,40 +0,0 @@
import type { DesktopRuntimeArch, DesktopRuntimeInfo } from "@t3tools/contracts";
interface ResolveDesktopRuntimeInfoInput {
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly runningUnderArm64Translation: boolean;
}
function normalizeDesktopArch(arch: string): DesktopRuntimeArch {
if (arch === "arm64") return "arm64";
if (arch === "x64") return "x64";
return "other";
}
export function resolveDesktopRuntimeInfo(
input: ResolveDesktopRuntimeInfoInput,
): DesktopRuntimeInfo {
const appArch = normalizeDesktopArch(input.processArch);
if (input.platform !== "darwin") {
return {
hostArch: appArch,
appArch,
runningUnderArm64Translation: false,
};
}
const hostArch =
appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
return {
hostArch,
appArch,
runningUnderArm64Translation: input.runningUnderArm64Translation,
};
}
export function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
}
+6 -12
View File
@@ -13,17 +13,11 @@ import {
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
const runtimeInfo = {
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
} as const;
describe("updateMachine", () => {
it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "error",
message: "network",
@@ -42,7 +36,7 @@ describe("updateMachine", () => {
it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "checking",
},
@@ -58,7 +52,7 @@ describe("updateMachine", () => {
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -76,7 +70,7 @@ describe("updateMachine", () => {
it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -95,7 +89,7 @@ describe("updateMachine", () => {
it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "error",
availableVersion: "1.1.0",
@@ -117,7 +111,7 @@ describe("updateMachine", () => {
it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "checking",
},
+3 -8
View File
@@ -1,18 +1,12 @@
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
import type { DesktopUpdateState } from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
export function createInitialDesktopUpdateState(
currentVersion: string,
runtimeInfo: DesktopRuntimeInfo,
): DesktopUpdateState {
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
currentVersion,
hostArch: runtimeInfo.hostArch,
appArch: runtimeInfo.appArch,
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
@@ -158,3 +152,4 @@ export function reduceDesktopUpdateStateOnInstallFailure(
canRetry: true,
};
}
-3
View File
@@ -12,9 +12,6 @@ const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
+4 -109
View File
@@ -39,14 +39,12 @@
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<a
id="download-btn"
href="https://github.com/pingdotgg/t3code/releases"
target="_blank"
rel="noopener noreferrer"
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>
Download now
</a>
<div class="screenshot-wrap">
@@ -66,88 +64,6 @@
</body>
</html>
<script>
const REPO = "pingdotgg/t3code";
const RELEASES_URL = `https://github.com/${REPO}/releases`;
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
type Platform = { os: "mac" | "win" | "linux"; label: string; arch?: string };
function detectPlatform(): Platform | null {
const ua = navigator.userAgent;
if (/Win/i.test(ua)) return { os: "win", label: "Download for Windows" };
if (/Mac/i.test(ua)) {
return {
os: "mac",
label: `Download for macOS`,
arch: "arm64",
};
}
if (/Linux/i.test(ua)) return { os: "linux", label: "Download for Linux" };
return null;
}
function pickAsset(
assets: Array<{ name: string; browser_download_url: string }>,
platform: Platform,
): string | null {
if (platform.os === "win") {
return (
assets.find((a) => a.name.endsWith("-x64.exe"))
?.browser_download_url ?? null
);
}
if (platform.os === "mac") {
const preferred = assets.find((a) =>
a.name.endsWith(`-${platform.arch}.dmg`),
);
const fallback = assets.find((a) => a.name.endsWith(".dmg"));
return (preferred ?? fallback)?.browser_download_url ?? null;
}
if (platform.os === "linux") {
return (
assets.find((a) => a.name.endsWith(".AppImage"))
?.browser_download_url ?? null
);
}
return null;
}
async function init() {
const btn = document.getElementById("download-btn") as HTMLAnchorElement | null;
const label = document.getElementById("download-label");
if (!btn || !label) return;
const platform = detectPlatform();
if (!platform) return;
document.documentElement.dataset.platform = platform.os;
label.textContent = platform.label;
try {
const cached = sessionStorage.getItem("t3code-latest-release");
const data = cached
? JSON.parse(cached)
: await fetch(API_URL).then((r) => r.json());
if (!cached && data?.assets) {
sessionStorage.setItem("t3code-latest-release", JSON.stringify(data));
}
const url = pickAsset(data.assets ?? [], platform);
if (url) {
btn.href = url;
btn.removeAttribute("target");
btn.removeAttribute("rel");
}
} catch {
btn.href = RELEASES_URL;
}
}
init();
</script>
<style>
:root {
--bg: #09090b;
@@ -282,9 +198,7 @@
/* ── Hero button ── */
.hero-button {
display: inline-flex;
align-items: center;
gap: 0.55rem;
display: inline-block;
background: #fafafa;
color: #09090b;
padding: 0.75rem 2rem;
@@ -306,25 +220,6 @@
transform: scale(0.98);
}
.hero-button-icon {
display: none;
width: 1em;
height: 1em;
flex-shrink: 0;
}
:global([data-platform="mac"]) .hero-button-icon--apple {
display: block;
}
:global([data-platform="win"]) .hero-button-icon--windows {
display: block;
}
:global([data-platform="linux"]) .hero-button-icon--linux {
display: block;
}
/* ── Screenshot ── */
.screenshot-wrap {
@@ -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,16 +185,6 @@ 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>;
}
@@ -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,32 +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) {
@@ -493,7 +443,6 @@ export const makeOrchestrationIntegrationHarness = (
waitForThread,
waitForDomainEvent,
waitForPendingApproval,
waitForReceipt,
dispose,
} satisfies OrchestrationIntegrationHarness;
});
@@ -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);
@@ -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,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.9",
"version": "0.0.4-alpha.1",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
-4
View File
@@ -132,8 +132,6 @@ const buildCmd = Command.make(
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun tsdown`,
);
@@ -227,8 +225,6 @@ const publishCmd = Command.make(
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
}),
);
}),
+2 -2
View File
@@ -524,7 +524,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(
[
@@ -1162,7 +1162,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)),
);
});
+42 -125
View File
@@ -22,9 +22,7 @@ import {
Array,
Cache,
Cause,
Deferred,
Effect,
Exit,
FileSystem,
Path,
Layer,
@@ -35,14 +33,11 @@ import {
SchemaGetter,
SchemaIssue,
SchemaTransformation,
Ref,
ServiceMap,
Scope,
Stream,
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { watchFileWithStatPolling } from "./watchFileWithStatPolling";
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
"KeybindingsConfigParseError",
@@ -427,7 +422,6 @@ export interface KeybindingsConfigState {
}
export interface KeybindingsChangeEvent {
readonly keybindings: ResolvedKeybindingsConfig;
readonly issues: readonly ServerConfigIssue[];
}
@@ -474,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.
@@ -502,22 +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>;
/**
* Subscribe to keybindings config change events.
*
* Returns a scoped subscription. Callers should subscribe in the
* current fiber (not inside a fork) to avoid missing events due to
* lazy subscription setup in `Stream.fromPubSub`.
*/
readonly subscribeChanges: Effect.Effect<
PubSub.Subscription<KeybindingsChangeEvent>,
never,
Scope.Scope
>;
readonly changes: Stream.Stream<KeybindingsChangeEvent>;
/**
* Upsert a keybinding rule and persist the resulting configuration.
@@ -544,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(
@@ -569,7 +531,7 @@ const makeKeybindings = Effect.gen(function* () {
configPath: keybindingsConfigPath,
detail: "failed to read keybindings config",
cause,
}),
}),
),
);
@@ -714,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;
@@ -808,85 +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 }),
);
// fs.watch (inotify/kqueue) gives instant detection on most platforms
// but can silently miss events on Linux containers.
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,
);
// fs.watchFile (stat-based polling on libuv timers) as a reliable
// backup. Unlike an Effect.sleep loop in a forked fiber, libuv
// timers fire regardless of Effect fiber scheduling pressure.
yield* Stream.runForEach(
watchFileWithStatPolling({
filePath: keybindingsConfigPath,
pollIntervalMs: 100,
}),
() => revalidateAndEmitSafely,
).pipe(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,
subscribeChanges: PubSub.subscribe(changesPubSub),
changes: Stream.fromPubSub(changesPubSub),
upsertKeybindingRule: (rule) =>
upsertSemaphore.withPermits(1)(
Effect.gen(function* () {
@@ -913,10 +833,7 @@ const makeKeybindings = Effect.gen(function* () {
keybindings: nextResolved,
issues: [],
});
yield* emitChange({
keybindings: nextResolved,
issues: [],
});
yield* emitChange([]);
return nextResolved;
}),
),
@@ -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";
@@ -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)) {
@@ -253,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())),
@@ -266,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(
@@ -323,7 +321,6 @@ describe("CheckpointReactor", () => {
engine,
provider,
cwd,
drain,
};
}
@@ -452,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"),
@@ -646,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(
@@ -7,8 +7,7 @@ import {
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 {
@@ -19,7 +18,6 @@ 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";
@@ -65,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;
@@ -118,7 +115,9 @@ const make = Effect.gen(function* () {
const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
threadId: ThreadId,
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
): Effect.fn.Return<
Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>
> {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
@@ -134,7 +133,9 @@ const make = Effect.gen(function* () {
};
if (thread) {
const projectedSession = sessions.find((session) => session.threadId === thread.id);
const projectedSession = sessions.find(
(session) => session.threadId === thread.id,
);
const fromProjected = findSessionWithCwd(projectedSession);
if (Option.isSome(fromProjected)) {
return fromProjected;
@@ -275,22 +276,6 @@ const make = Effect.gen(function* () {
checkpointTurnCount: nextTurnCount,
createdAt: now,
});
yield* receiptBus.publish({
type: "checkpoint.diff.finalized",
threadId: thread.id,
turnId,
checkpointTurnCount: nextTurnCount,
checkpointRef: targetCheckpointRef,
status: checkpointStatusFromRuntime(event.payload.state),
createdAt: now,
});
yield* receiptBus.publish({
type: "turn.processing.quiesced",
threadId: thread.id,
turnId,
checkpointTurnCount: nextTurnCount,
createdAt: now,
});
yield* orchestrationEngine.dispatch({
type: "thread.activity.append",
@@ -321,7 +306,9 @@ const make = Effect.gen(function* () {
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
const thread = readModel.threads.find(
(entry) => entry.id === event.threadId,
);
if (!thread) {
return;
}
@@ -364,13 +351,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* (
@@ -433,13 +413,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* (
@@ -627,9 +600,14 @@ 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 (
@@ -639,7 +617,7 @@ const make = Effect.gen(function* () {
) {
return Effect.void;
}
return worker.enqueue({ source: "domain", event });
return Queue.offer(queue, { source: "domain", event }).pipe(Effect.asVoid);
}),
);
@@ -648,14 +626,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;
});
@@ -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,
}),
),
),
@@ -213,7 +213,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({
@@ -253,7 +253,6 @@ describe("ProviderCommandReactor", () => {
renameBranch,
generateBranchName,
stateDir,
drain,
};
}
@@ -568,7 +567,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);
@@ -5,15 +5,14 @@ import {
type OrchestrationEvent,
type ProviderModelOptions,
type ProviderKind,
type ProviderStartOptions,
type ProviderServiceTier,
type OrchestrationSession,
ThreadId,
type ProviderSession,
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";
@@ -145,8 +144,6 @@ const make = Effect.gen(function* () {
),
);
const threadProviderOptions = new Map<string, ProviderStartOptions>();
const appendProviderFailureActivity = (input: {
readonly threadId: ThreadId;
readonly kind:
@@ -205,7 +202,7 @@ const make = Effect.gen(function* () {
readonly provider?: ProviderKind;
readonly model?: string;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
readonly serviceTier?: ProviderServiceTier | null;
},
) {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -225,9 +222,9 @@ const make = Effect.gen(function* () {
});
const resolveActiveSession = (threadId: ThreadId) =>
providerService
.listSessions()
.pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));
providerService.listSessions().pipe(
Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)),
);
const startProviderSession = (input?: {
readonly resumeCursor?: unknown;
@@ -235,13 +232,13 @@ const make = Effect.gen(function* () {
}) =>
providerService.startSession(threadId, {
threadId,
...((input?.provider ?? preferredProvider)
...(input?.provider ?? preferredProvider
? { provider: input?.provider ?? preferredProvider }
: {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(desiredModel ? { model: desiredModel } : {}),
...(options?.serviceTier !== undefined ? { serviceTier: options.serviceTier } : {}),
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
...(options?.providerOptions !== undefined ? { providerOptions: options.providerOptions } : {}),
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
});
@@ -266,15 +263,16 @@ const make = Effect.gen(function* () {
thread.session && thread.session.status !== "stopped" ? thread.id : null;
if (existingSessionThreadId) {
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
const providerChanged =
options?.provider !== undefined && options.provider !== currentProvider;
const providerChanged = options?.provider !== undefined && options.provider !== currentProvider;
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const modelChanged =
options?.model !== undefined && options.model !== activeSession?.model;
const shouldRestartForModelChange =
modelChanged && sessionModelSwitch === "restart-session";
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
return existingSessionThreadId;
@@ -325,8 +323,8 @@ const make = Effect.gen(function* () {
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly provider?: ProviderKind;
readonly model?: string;
readonly serviceTier?: ProviderServiceTier | null;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
readonly interactionMode?: "default" | "plan";
readonly createdAt: string;
}) {
@@ -334,33 +332,30 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService
.listSessions()
.pipe(
Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),
);
const activeSession = yield* providerService.listSessions().pipe(
Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),
);
const sessionModelSwitch =
activeSession === undefined
? "in-session"
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
const modelForTurn =
sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
yield* providerService.sendTurn({
threadId: input.threadId,
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
@@ -475,12 +470,8 @@ const make = Effect.gen(function* () {
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.modelOptions !== undefined
? { modelOptions: event.payload.modelOptions }
: {}),
...(event.payload.providerOptions !== undefined
? { providerOptions: event.payload.providerOptions }
: {}),
...(event.payload.serviceTier !== undefined ? { serviceTier: event.payload.serviceTier } : {}),
...(event.payload.modelOptions !== undefined ? { modelOptions: event.payload.modelOptions } : {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
});
@@ -636,10 +627,7 @@ const make = Effect.gen(function* () {
if (!thread?.session || thread.session.status === "stopped") {
return;
}
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
...(cachedProviderOptions !== undefined ? { providerOptions: cachedProviderOptions } : {}),
});
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt);
return;
}
case "thread.turn-start-requested":
@@ -673,28 +661,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;
});
@@ -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"));
expect(midThread?.session?.status).toBe("running");
@@ -429,7 +428,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"),
@@ -483,7 +482,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"),
@@ -721,7 +720,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"),
@@ -780,7 +779,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
}),
);
await harness.drain();
await Effect.runPromise(Effect.sleep("30 millis"));
harness.emit({
type: "turn.started",
@@ -835,7 +834,6 @@ describe("ProviderRuntimeIngestion", () => {
payload: {
itemType: "assistant_message",
status: "completed",
detail: "hello live",
},
});
@@ -10,8 +10,7 @@ import {
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";
@@ -211,9 +210,9 @@ function runtimeEventToActivities(
? "Command approval requested"
: requestKind === "file-read"
? "File-read approval requested"
: requestKind === "file-change"
? "File-change approval requested"
: "Approval requested",
: requestKind === "file-change"
? "File-change approval requested"
: "Approval requested",
payload: {
requestId: toApprovalRequestId(event.requestId),
...(requestKind ? { requestKind } : {}),
@@ -299,9 +298,7 @@ function runtimeEventToActivities(
summary: "Plan updated",
payload: {
plan: event.payload.plan,
...(event.payload.explanation !== undefined
? { explanation: event.payload.explanation }
: {}),
...(event.payload.explanation !== undefined ? { explanation: event.payload.explanation } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -361,9 +358,7 @@ function runtimeEventToActivities(
payload: {
taskId: event.payload.taskId,
...(event.payload.taskType ? { taskType: event.payload.taskType } : {}),
...(event.payload.description
? { detail: truncateDetail(event.payload.description) }
: {}),
...(event.payload.description ? { detail: truncateDetail(event.payload.description) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -530,7 +525,11 @@ const make = Effect.gen(function* () {
return isGitRepository(workspaceCwd);
});
const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
const rememberAssistantMessageId = (
threadId: ThreadId,
turnId: TurnId,
messageId: MessageId,
) =>
Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
Effect.flatMap((existingIds) =>
Cache.set(
@@ -548,7 +547,11 @@ const make = Effect.gen(function* () {
),
);
const forgetAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
const forgetAssistantMessageId = (
threadId: ThreadId,
turnId: TurnId,
messageId: MessageId,
) =>
Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
Effect.flatMap((existingIds) =>
Option.match(existingIds, {
@@ -613,8 +616,7 @@ const make = Effect.gen(function* () {
const existing = Option.getOrUndefined(existingEntry);
return Cache.set(bufferedProposedPlanById, planId, {
text: `${existing?.text ?? ""}${delta}`,
createdAt:
existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt,
createdAt: existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt,
});
}),
);
@@ -631,8 +633,7 @@ const make = Effect.gen(function* () {
const clearBufferedProposedPlan = (planId: string) =>
Cache.invalidate(bufferedProposedPlanById, planId);
const clearAssistantMessageState = (messageId: MessageId) =>
clearBufferedAssistantText(messageId);
const clearAssistantMessageState = (messageId: MessageId) => clearBufferedAssistantText(messageId);
const finalizeAssistantMessage = (input: {
event: ProviderRuntimeEvent;
@@ -861,8 +862,8 @@ const make = Effect.gen(function* () {
: event.type === "turn.completed" && runtimeTurnState(event) === "failed"
? (runtimeTurnErrorMessage(event) ?? thread.session?.lastError ?? "Turn failed")
: status === "ready"
? null
: (thread.session?.lastError ?? null);
? null
: (thread.session?.lastError ?? null);
if (shouldApplyThreadLifecycle) {
yield* orchestrationEngine.dispatch({
@@ -934,9 +935,7 @@ const make = Effect.gen(function* () {
const assistantCompletion =
event.type === "item.completed" && event.payload.itemType === "assistant_message"
? {
messageId: MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
),
messageId: MessageId.makeUnsafe(`assistant:${event.itemId ?? event.turnId ?? event.eventId}`),
fallbackText: event.payload.detail,
}
: undefined;
@@ -952,10 +951,6 @@ const make = Effect.gen(function* () {
if (assistantCompletion) {
const assistantMessageId = assistantCompletion.messageId;
const turnId = toTurnId(event.turnId);
const existingAssistantMessage = thread.messages.find((entry) => entry.id === assistantMessageId);
const shouldApplyFallbackCompletionText =
!existingAssistantMessage ||
existingAssistantMessage.text.length === 0;
if (turnId) {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
@@ -968,7 +963,7 @@ const make = Effect.gen(function* () {
createdAt: now,
commandTag: "assistant-complete",
finalDeltaCommandTag: "assistant-delta-finalize",
...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText
...(assistantCompletion.fallbackText !== undefined
? { fallbackText: assistantCompletion.fallbackText }
: {}),
});
@@ -1030,7 +1025,9 @@ const make = Effect.gen(function* () {
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
? true
: activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId);
: activeTurnId === null ||
eventTurnId === undefined ||
sameId(activeTurnId, eventTurnId);
if (shouldApplyRuntimeError) {
yield* orchestrationEngine.dispatch({
@@ -1118,12 +1115,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(
@@ -1131,14 +1132,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") {}
+1 -1
View File
@@ -301,8 +301,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
messageId: command.message.messageId,
...(command.provider !== undefined ? { provider: command.provider } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.serviceTier !== undefined ? { serviceTier: command.serviceTier } : {}),
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
...(command.providerOptions !== undefined ? { providerOptions: command.providerOptions } : {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
runtimeMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
@@ -1354,6 +1354,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
threadId: input.threadId,
...(input.input !== undefined ? { input: input.input } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions?.codex?.reasoningEffort !== undefined
? { effort: input.modelOptions.codex.reasoningEffort }
: {}),
@@ -13,7 +13,7 @@ import type {
ServerProviderStatus,
ServerProviderStatusState,
} from "@t3tools/contracts";
import { Effect, Layer, Option, Result, Stream } from "effect";
import { Array, Effect, Fiber, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
@@ -312,9 +312,13 @@ export const checkCodexProviderStatus: Effect.Effect<
export const ProviderHealthLive = Layer.effect(
ProviderHealth,
Effect.gen(function* () {
const codexStatus = yield* checkCodexProviderStatus;
const codexStatusFiber = yield* checkCodexProviderStatus.pipe(
Effect.map(Array.of),
Effect.forkScoped,
);
return {
getStatuses: Effect.succeed([codexStatus]),
getStatuses: Fiber.join(codexStatusFiber),
} satisfies ProviderHealthShape;
}),
);
@@ -86,30 +86,15 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
}
}
function toRuntimePayloadFromSession(
session: ProviderSession,
extra?: { readonly providerOptions?: unknown },
): Record<string, unknown> {
function toRuntimePayloadFromSession(session: ProviderSession): Record<string, unknown> {
return {
cwd: session.cwd ?? null,
model: session.model ?? null,
activeTurnId: session.activeTurnId ?? null,
lastError: session.lastError ?? null,
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
};
}
function readPersistedProviderOptions(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): Record<string, unknown> | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const raw = "providerOptions" in runtimePayload ? runtimePayload.providerOptions : undefined;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
return raw as Record<string, unknown>;
}
function readPersistedCwd(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): string | undefined {
@@ -152,7 +137,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
extra?: { readonly providerOptions?: unknown },
) =>
directory.upsert({
threadId,
@@ -160,7 +144,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
runtimeMode: session.runtimeMode,
status: toRuntimeStatus(session),
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
runtimePayload: toRuntimePayloadFromSession(session, extra),
runtimePayload: toRuntimePayloadFromSession(session),
});
const providers = yield* registry.listProviders();
@@ -213,13 +197,11 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
});
@@ -291,9 +273,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
);
}
yield* upsertSessionBinding(session, threadId, {
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
yield* upsertSessionBinding(session, threadId);
yield* analytics.record("provider.session.started", {
provider: session.provider,
runtimeMode: input.runtimeMode,
-2
View File
@@ -17,7 +17,6 @@ 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 { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
@@ -88,7 +87,6 @@ export function makeServerRuntimeServicesLayer() {
OrchestrationProjectionSnapshotQueryLive,
CheckpointStoreLive,
checkpointDiffQueryLayer,
RuntimeReceiptBusLive,
);
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
@@ -1,34 +0,0 @@
import nodeFs from "node:fs";
import { Effect, Queue, Stream } from "effect";
export interface WatchFileWithStatPollingOptions {
readonly filePath: string;
readonly pollIntervalMs?: number;
}
/**
* Expose Node's stat-based file poller as a scoped Effect stream.
*
* `fs.watchFile` uses libuv timers, so it remains a reliable fallback when
* the Effect scheduler is under load and prompt fiber wake-ups are not
* guaranteed.
*/
export const watchFileWithStatPolling = ({
filePath,
pollIntervalMs = 100,
}: WatchFileWithStatPollingOptions) =>
Stream.callback<void>((queue) =>
Effect.acquireRelease(
Effect.sync(() => {
const onChange = () => {
Queue.offerUnsafe(queue, undefined);
};
nodeFs.watchFile(filePath, { interval: pollIntervalMs }, onChange);
return onChange;
}),
(onChange) =>
Effect.sync(() => {
nodeFs.unwatchFile(filePath, onChange);
}),
),
);
+157 -201
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,55 +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(
@@ -577,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",
});
@@ -674,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",
@@ -749,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 })
@@ -772,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,
@@ -797,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]) => {
@@ -821,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({
@@ -846,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();
@@ -876,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();
@@ -915,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();
@@ -958,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 });
});
@@ -998,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",
@@ -1025,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(
@@ -1057,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",
@@ -1098,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");
@@ -1111,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",
@@ -1128,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",
@@ -1147,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",
@@ -1163,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();
@@ -1241,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();
@@ -1335,8 +1278,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",
@@ -1389,13 +1333,10 @@ describe("WebSocket Server", () => {
};
terminalManager.emitEvent(manualEvent);
const push = await waitForPush(
ws,
WS_CHANNELS.terminalEvent,
(candidate) => (candidate.data as TerminalEvent).type === "output",
);
const push = (await waitForMessage(ws)) as WsPush;
expect(push.type).toBe("push");
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
expect((push.data as TerminalEvent).type).toBe("output");
});
it("detaches terminal event listener on stop for injected manager", async () => {
@@ -1418,8 +1359,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: "",
@@ -1435,17 +1377,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;
@@ -1478,8 +1424,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({
@@ -1523,8 +1470,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();
@@ -1559,8 +1507,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,
@@ -1584,8 +1533,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,
@@ -1609,8 +1559,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,
@@ -1653,8 +1604,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.gitListBranches, { cwd: "/repo/path" });
expect(listResponse.error).toBeUndefined();
@@ -1694,8 +1646,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",
@@ -1723,8 +1676,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",
@@ -1745,7 +1699,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);
});
});
+98 -66
View File
@@ -20,11 +20,13 @@ import {
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
ProjectId,
ThreadId,
TerminalEvent,
WS_CHANNELS,
WS_METHODS,
WebSocketRequest,
WsPush,
WsResponse,
ServerProviderStatus,
} from "@t3tools/contracts";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import {
@@ -34,7 +36,6 @@ import {
FileSystem,
Layer,
Path,
PubSub,
Ref,
Schema,
Scope,
@@ -73,8 +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";
/**
* ServerShape - Service API for server lifecycle control.
@@ -199,7 +198,8 @@ function stripRequestTag<T extends { _tag: string }>(body: T) {
function messageFromCause(cause: Cause.Cause<unknown>): string {
const squashed = Cause.squash(cause);
const message = squashed instanceof Error ? squashed.message.trim() : String(squashed).trim();
const message =
squashed instanceof Error ? squashed.message.trim() : String(squashed).trim();
return message.length > 0 ? message : Cause.pretty(cause);
}
@@ -259,33 +259,48 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const providerStatuses = yield* providerHealth.getStatuses;
yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to sync keybindings defaults on startup", {
path: error.configPath,
detail: error.detail,
cause: error.cause,
}),
),
);
const clients = yield* Ref.make(new Set<WebSocket>());
const logger = createLogger("ws");
const readiness = yield* makeServerReadiness;
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;
@@ -315,7 +330,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
} satisfies OrchestrationCommand;
}
if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) {
if (
input.command.type === "project.meta.update" &&
input.command.workspaceRoot !== undefined
) {
return {
...input.command,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
@@ -598,29 +616,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));
// Subscribe synchronously so the subscription exists before the
// readiness barrier — avoids a race where the polling watcher
// publishes before a lazily-created Stream.fromPubSub subscription.
const keybindingsChangesSub = yield* keybindingsManager.subscribeChanges.pipe(
Scope.provide(subscriptionsScope),
);
yield* Effect.forever(
PubSub.take(keybindingsChangesSub).pipe(
Effect.flatMap((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;
@@ -691,20 +723,22 @@ 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 })),
closeWebSocketServer.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to close web socket server", { cause: error }),
),
),
]),
);
@@ -759,16 +793,14 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
relativePath: body.relativePath,
path,
});
yield* fileSystem
.makeDirectory(path.dirname(target.absolutePath), { recursive: true })
.pipe(
Effect.mapError(
(cause) =>
new RouteRequestError({
message: `Failed to prepare workspace path: ${String(cause)}`,
}),
),
);
yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new RouteRequestError({
message: `Failed to prepare workspace path: ${String(cause)}`,
}),
),
);
yield* fileSystem.writeFileString(target.absolutePath, body.contents).pipe(
Effect.mapError(
(cause) =>
@@ -867,7 +899,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers: providerStatuses,
providers,
availableEditors,
};
@@ -952,29 +984,29 @@ 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 })),
handleMessage(ws, raw).pipe(
Effect.catch((error) => Effect.logError("Error handling message", error)),
),
);
});
-120
View File
@@ -1,120 +0,0 @@
import type { WebSocket } from "ws";
import { afterEach, describe, expect, it } from "vitest";
import { Effect, Exit, Ref, Scope } 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", () => {
let scope: Scope.Closeable | null = null;
afterEach(async () => {
if (scope) {
await Effect.runPromise(Scope.close(scope, Exit.void));
}
scope = null;
});
it("waits for the welcome push before a new client joins broadcast delivery", async () => {
scope = await Effect.runPromise(Scope.make("sequential"));
const client = new MockWebSocket();
const { clients, pushBus } = await Effect.runPromise(
Effect.gen(function* () {
const clients = yield* Ref.make(new Set<WebSocket>());
const pushBus = yield* makeServerPushBus({
clients,
logOutgoingPush: () => {},
});
return { clients, pushBus };
}).pipe(Scope.provide(scope)),
);
await Effect.runPromise(
Effect.gen(function* () {
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: [],
});
}),
);
await 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: [],
},
});
});
});
-106
View File
@@ -1,106 +0,0 @@
import { type WsPushChannel, type WsPushData, type WsPush } from "@t3tools/contracts";
import { Deferred, Effect, Queue, Ref } 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: WsPush, 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 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 = {
type: "push",
sequence,
channel: job.channel,
data: job.data,
} as WsPush;
const message = JSON.stringify(push);
const recipients =
job.target.kind === "all" ? yield* Ref.get(input.clients) : new Set([job.target.client]);
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,
},
}),
);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.9",
"version": "0.0.4-alpha.1",
"private": true,
"type": "module",
"scripts": {
+21
View File
@@ -4,6 +4,8 @@ import {
getAppModelOptions,
getSlashModelOptions,
normalizeCustomModelSlugs,
resolveAppServiceTier,
shouldShowFastTierIcon,
resolveAppModelSelection,
} from "./appSettings";
@@ -82,3 +84,22 @@ describe("getSlashModelOptions", () => {
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
});
});
describe("resolveAppServiceTier", () => {
it("maps automatic to no override", () => {
expect(resolveAppServiceTier("auto")).toBeNull();
});
it("preserves explicit service tier overrides", () => {
expect(resolveAppServiceTier("fast")).toBe("fast");
expect(resolveAppServiceTier("flex")).toBe("flex");
});
});
describe("shouldShowFastTierIcon", () => {
it("shows the fast-tier icon only for gpt-5.4 on fast tier", () => {
expect(shouldShowFastTierIcon("gpt-5.4", "fast")).toBe(true);
expect(shouldShowFastTierIcon("gpt-5.4", "auto")).toBe(false);
expect(shouldShowFastTierIcon("gpt-5.3-codex", "fast")).toBe(false);
});
});
+38 -1
View File
@@ -1,11 +1,31 @@
import { useCallback, useSyncExternalStore } from "react";
import { Option, Schema } from "effect";
import { type ProviderKind } from "@t3tools/contracts";
import { type ProviderKind, type ProviderServiceTier } from "@t3tools/contracts";
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
export const APP_SERVICE_TIER_OPTIONS = [
{
value: "auto",
label: "Automatic",
description: "Use Codex defaults without forcing a service tier.",
},
{
value: "fast",
label: "Fast",
description: "Request the fast service tier when the model supports it.",
},
{
value: "flex",
label: "Flex",
description: "Request the flex service tier when the model supports it.",
},
] as const;
export type AppServiceTier = (typeof APP_SERVICE_TIER_OPTIONS)[number]["value"];
const AppServiceTierSchema = Schema.Literals(["auto", "fast", "flex"]);
const MODELS_WITH_FAST_SUPPORT = new Set(["gpt-5.4"]);
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
};
@@ -21,6 +41,7 @@ const AppSettingsSchema = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(
Schema.withConstructorDefault(() => Option.some(false)),
),
codexServiceTier: AppServiceTierSchema.pipe(Schema.withConstructorDefault(() => Option.some("auto"))),
customCodexModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
@@ -32,6 +53,22 @@ export interface AppModelOption {
isCustom: boolean;
}
export function resolveAppServiceTier(serviceTier: AppServiceTier): ProviderServiceTier | null {
return serviceTier === "auto" ? null : serviceTier;
}
export function shouldShowFastTierIcon(
model: string | null | undefined,
serviceTier: AppServiceTier,
): boolean {
const normalizedModel = normalizeModelSlug(model);
return (
resolveAppServiceTier(serviceTier) === "fast" &&
normalizedModel !== null &&
MODELS_WITH_FAST_SUPPORT.has(normalizedModel)
);
}
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
let listeners: Array<() => void> = [];
@@ -305,7 +305,6 @@ const worker = setupWorker(
client.send(
JSON.stringify({
type: "push",
sequence: 1,
channel: WS_CHANNELS.serverWelcome,
data: fixture.welcome,
}),
+118 -297
View File
@@ -92,8 +92,6 @@ import {
buildPlanImplementationThreadTitle,
buildPlanImplementationPrompt,
buildProposedPlanMarkdownFilename,
downloadPlanAsTextFile,
normalizePlanMarkdownForExport,
proposedPlanTitle,
resolvePlanFollowUpSubmission,
} from "../proposedPlan";
@@ -124,9 +122,8 @@ import {
shortcutLabelForCommand,
} from "../keybindings";
import ChatMarkdown from "./ChatMarkdown";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
import {
BotIcon,
ChevronDownIcon,
@@ -138,13 +135,13 @@ import {
DiffIcon,
EllipsisIcon,
FolderClosedIcon,
ListTodoIcon,
LockIcon,
LockOpenIcon,
Undo2Icon,
XIcon,
CopyIcon,
CheckIcon,
ZapIcon,
} from "lucide-react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
@@ -204,6 +201,9 @@ import { readNativeApi } from "~/nativeApi";
import {
getAppModelOptions,
resolveAppModelSelection,
resolveAppServiceTier,
shouldShowFastTierIcon,
type AppServiceTier,
useAppSettings,
} from "../appSettings";
import {
@@ -291,7 +291,21 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
return "text-muted-foreground/40";
}
function normalizePlanMarkdownForExport(planMarkdown: string): string {
return `${planMarkdown.trimEnd()}\n`;
}
function downloadTextFile(filename: string, contents: string): void {
const blob = new Blob([contents], { type: "text/markdown;charset=utf-8" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.click();
window.setTimeout(() => {
URL.revokeObjectURL(url);
}, 0);
}
interface ExpandedImageItem {
src: string;
@@ -406,6 +420,7 @@ type ComposerCommandItem =
model: ModelSlug;
label: string;
description: string;
showFastBadge: boolean;
};
type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
@@ -516,6 +531,9 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
</Badge>
) : null}
<span className="flex min-w-0 items-center gap-1.5 truncate">
{props.item.type === "model" && props.item.showFastBadge ? (
<ZapIcon className="size-3.5 shrink-0 text-amber-500" />
) : null}
<span className="truncate">{props.item.label}</span>
</span>
<span className="truncate text-muted-foreground/70 text-xs">{props.item.description}</span>
@@ -638,12 +656,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
useState<Record<string, number>>({});
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
const [planSidebarOpen, setPlanSidebarOpen] = useState(false);
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
// When set, the thread-change reset effect will open the sidebar instead of closing it.
// Used by "Implement in new thread" to carry the sidebar-open intent across navigation.
const planSidebarOpenOnNextThreadRef = useRef(false);
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
@@ -745,7 +757,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
composerDraft.interactionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE;
const isServerThread = serverThread !== undefined;
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
const diffOpen = rawSearch.diff === "1";
const diffSearch = useMemo(
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
[rawSearch],
);
const diffOpen = diffSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const activeLatestTurn = activeThread?.latestTurn ?? null;
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
@@ -777,6 +793,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeThread.messages.length > 0 ||
activeThread.session !== null),
);
const selectedServiceTierSetting = settings.codexServiceTier;
const selectedServiceTier = resolveAppServiceTier(selectedServiceTierSetting);
const lockedProvider: ProviderKind | null = hasThreadStarted
? (sessionProvider ?? selectedProviderByThreadId ?? null)
: null;
@@ -812,17 +830,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
return Object.keys(codexOptions).length > 0 ? { codex: codexOptions } : undefined;
}, [selectedCodexFastModeEnabled, selectedEffort, selectedProvider, supportsReasoningEffort]);
const providerOptionsForDispatch = useMemo(() => {
if (!settings.codexBinaryPath && !settings.codexHomePath) {
return undefined;
}
return {
codex: {
...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
},
};
}, [settings.codexBinaryPath, settings.codexHomePath]);
const selectedModelForPicker = selectedModel;
const modelOptionsByProvider = useMemo(
() => getCustomModelOptionsByProvider(settings),
@@ -1244,8 +1251,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
model: slug,
label: name,
description: `${providerLabel} · ${slug}`,
showFastBadge:
provider === "codex" && shouldShowFastTierIcon(slug, selectedServiceTierSetting),
}));
}, [composerTrigger, searchableModelOptions, workspaceEntries]);
}, [composerTrigger, searchableModelOptions, selectedServiceTierSetting, workspaceEntries]);
const composerMenuOpen = Boolean(composerTrigger);
const activeComposerMenuItem = useMemo(
() =>
@@ -1601,36 +1610,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
},
[activeProject, persistProjectScripts],
);
const deleteProjectScript = useCallback(
async (scriptId: string) => {
if (!activeProject) return;
const nextScripts = activeProject.scripts.filter((script) => script.id !== scriptId);
const deletedName = activeProject.scripts.find((s) => s.id === scriptId)?.name;
try {
await persistProjectScripts({
projectId: activeProject.id,
projectCwd: activeProject.cwd,
previousScripts: activeProject.scripts,
nextScripts,
keybinding: null,
keybindingCommand: commandForProjectScript(scriptId),
});
toastManager.add({
type: "success",
title: `Deleted action "${deletedName ?? "Unknown"}"`,
});
} catch (error) {
toastManager.add({
type: "error",
title: "Could not delete action",
description: error instanceof Error ? error.message : "An unexpected error occurred.",
});
}
},
[activeProject, persistProjectScripts],
);
const handleRuntimeModeChange = useCallback(
(mode: RuntimeMode) => {
@@ -1773,7 +1752,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
"button, summary, [role='button'], [data-scroll-anchor-target]",
);
if (!trigger || !scrollContainer.contains(trigger)) return;
if (trigger.closest("[data-scroll-anchor-ignore]")) return;
pendingInteractionAnchorRef.current = {
element: trigger,
@@ -1922,17 +1900,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => {
setExpandedWorkGroups({});
if (planSidebarOpenOnNextThreadRef.current) {
planSidebarOpenOnNextThreadRef.current = false;
setPlanSidebarOpen(true);
} else {
setPlanSidebarOpen(false);
}
planSidebarDismissedForTurnRef.current = null;
}, [activeThread?.id]);
useEffect(() => {
if (!composerMenuOpen) {
setComposerHighlightedItemId(null);
@@ -2653,12 +2622,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
attachments: turnAttachments,
},
model: selectedModel || undefined,
serviceTier: selectedServiceTier,
...(selectedModelOptionsForDispatch
? { modelOptions: selectedModelOptionsForDispatch }
: {}),
...(providerOptionsForDispatch
? { providerOptions: providerOptionsForDispatch }
: {}),
provider: selectedProvider,
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
runtimeMode,
@@ -2936,21 +2903,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
...(selectedModelOptionsForDispatch
? { modelOptions: selectedModelOptionsForDispatch }
: {}),
...(providerOptionsForDispatch
? { providerOptions: providerOptionsForDispatch }
: {}),
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
runtimeMode,
interactionMode: nextInteractionMode,
createdAt: messageCreatedAt,
});
// Optimistically open the plan sidebar when implementing (not refining).
// "default" mode here means the agent is executing the plan, which produces
// step-tracking activities that the sidebar will display.
if (nextInteractionMode === "default") {
planSidebarDismissedForTurnRef.current = null;
setPlanSidebarOpen(true);
}
sendInFlightRef.current = false;
} catch (err) {
setOptimisticUserMessages((existing) =>
@@ -2976,7 +2933,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
runtimeMode,
selectedModel,
selectedModelOptionsForDispatch,
providerOptionsForDispatch,
selectedProvider,
setComposerDraftInteractionMode,
setThreadError,
@@ -3031,8 +2987,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath: activeThread.worktreePath,
createdAt,
})
.then(() => {
return api.orchestration.dispatchCommand({
.then(() =>
api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
threadId: nextThreadId,
@@ -3047,20 +3003,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
...(selectedModelOptionsForDispatch
? { modelOptions: selectedModelOptionsForDispatch }
: {}),
...(providerOptionsForDispatch
? { providerOptions: providerOptionsForDispatch }
: {}),
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
runtimeMode,
interactionMode: "default",
createdAt,
});
})
}),
)
.then(() => api.orchestration.getSnapshot())
.then((snapshot) => {
syncServerReadModel(snapshot);
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
return navigate({
to: "/$threadId",
params: { threadId: nextThreadId },
@@ -3101,7 +3052,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
runtimeMode,
selectedModel,
selectedModelOptionsForDispatch,
providerOptionsForDispatch,
selectedProvider,
settings.enableAssistantStreaming,
syncServerReadModel,
@@ -3456,21 +3406,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
}}
onAddProjectScript={saveProjectScript}
onUpdateProjectScript={updateProjectScript}
onDeleteProjectScript={deleteProjectScript}
onToggleDiff={onToggleDiff}
/>
</header>
{/* Error banner */}
<ProviderHealthBanner status={activeProviderStatus} />
<ThreadErrorBanner
error={activeThread.error}
onDismiss={() => setThreadError(activeThread.id, null)}
/>
{/* Main content area with optional plan sidebar */}
<div className="flex min-h-0 flex-1">
{/* Chat column */}
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
<ThreadErrorBanner error={activeThread.error} />
<PlanModePanel activePlan={activePlan} />
{/* Messages */}
<div
@@ -3544,7 +3487,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
answers={activePendingDraftAnswers}
questionIndex={activePendingQuestionIndex}
onSelectOption={onSelectActivePendingUserInputOption}
onAdvance={onAdvanceActivePendingUserInput}
/>
</div>
) : showPlanFollowUpPrompt && activeProposedPlan ? (
@@ -3687,6 +3629,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
model={selectedModelForPickerWithCustomFallback}
lockedProvider={lockedProvider}
modelOptionsByProvider={modelOptionsByProvider}
serviceTierSetting={selectedServiceTierSetting}
onProviderModelChange={onProviderModelSelect}
/>
@@ -3750,43 +3693,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
{runtimeMode === "full-access" ? "Full access" : "Supervised"}
</span>
</Button>
{/* Plan sidebar toggle */}
{(activePlan || activeProposedPlan || planSidebarOpen) ? (
<>
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
<Button
variant="ghost"
className={cn(
"shrink-0 whitespace-nowrap px-2 sm:px-3",
planSidebarOpen
? "text-blue-400 hover:text-blue-300"
: "text-muted-foreground/70 hover:text-foreground/80",
)}
size="sm"
type="button"
onClick={() => {
setPlanSidebarOpen((open) => {
if (open) {
// Closing: track dismissal for current turn
const turnKey = activePlan?.turnId ?? activeProposedPlan?.turnId ?? null;
if (turnKey) {
planSidebarDismissedForTurnRef.current = turnKey;
}
} else {
// Re-opening: clear dismissal tracking
planSidebarDismissedForTurnRef.current = null;
}
return !open;
});
}}
title={planSidebarOpen ? "Hide plan sidebar" : "Show plan sidebar"}
>
<ListTodoIcon />
<span className="sr-only sm:not-sr-only">Plan</span>
</Button>
</>
) : null}
</div>
{/* Right side: send / stop button */}
@@ -3953,27 +3859,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
</form>
</div>
</div>{/* end chat column */}
{/* Plan sidebar */}
{planSidebarOpen ? (
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={activeProposedPlan}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeProject?.cwd ?? undefined}
onClose={() => {
setPlanSidebarOpen(false);
// Track that the user explicitly dismissed for this turn so auto-open won't fight them.
const turnKey = activePlan?.turnId ?? activeProposedPlan?.turnId ?? null;
if (turnKey) {
planSidebarDismissedForTurnRef.current = turnKey;
}
}}
/>
) : null}
</div>{/* end horizontal flex container */}
{isGitRepo && (
<BranchToolbar
threadId={activeThread.id}
@@ -4098,7 +3983,6 @@ interface ChatHeaderProps {
onRunProjectScript: (script: ProjectScript) => void;
onAddProjectScript: (input: NewProjectScriptInput) => Promise<void>;
onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void>;
onDeleteProjectScript: (scriptId: string) => Promise<void>;
onToggleDiff: () => void;
}
@@ -4118,7 +4002,6 @@ const ChatHeader = memo(function ChatHeader({
onRunProjectScript,
onAddProjectScript,
onUpdateProjectScript,
onDeleteProjectScript,
onToggleDiff,
}: ChatHeaderProps) {
return (
@@ -4151,7 +4034,6 @@ const ChatHeader = memo(function ChatHeader({
onRunScript={onRunProjectScript}
onAddScript={onAddProjectScript}
onUpdateScript={onUpdateProjectScript}
onDeleteScript={onDeleteProjectScript}
/>
)}
{activeProjectName && (
@@ -4191,13 +4073,7 @@ const ChatHeader = memo(function ChatHeader({
);
});
const ThreadErrorBanner = memo(function ThreadErrorBanner({
error,
onDismiss,
}: {
error: string | null;
onDismiss?: () => void;
}) {
const ThreadErrorBanner = memo(function ThreadErrorBanner({ error }: { error: string | null }) {
if (!error) return null;
return (
<div className="pt-3 mx-auto max-w-3xl">
@@ -4206,18 +4082,6 @@ const ThreadErrorBanner = memo(function ThreadErrorBanner({
<AlertDescription className="line-clamp-3" title={error}>
{error}
</AlertDescription>
{onDismiss && (
<AlertAction>
<button
type="button"
aria-label="Dismiss error"
className="inline-flex size-6 items-center justify-center rounded-md text-destructive/60 transition-colors hover:text-destructive"
onClick={onDismiss}
>
<XIcon className="size-3.5" />
</button>
</AlertAction>
)}
</Alert>
</div>
);
@@ -4333,13 +4197,61 @@ const ComposerPendingApprovalActions = memo(function ComposerPendingApprovalActi
);
});
interface PlanModePanelProps {
activePlan: ReturnType<typeof deriveActivePlanState>;
}
const PlanModePanel = memo(function PlanModePanel({ activePlan }: PlanModePanelProps) {
if (!activePlan) return null;
return (
<div className="pt-3 mx-auto max-w-3xl">
<div className="rounded-xl border border-border/70 bg-muted/30 p-4">
<div className="flex items-center gap-2">
<Badge variant="secondary">Plan</Badge>
<span className="text-xs text-muted-foreground">
Updated {formatTimestamp(activePlan.createdAt)}
</span>
</div>
{activePlan.explanation ? (
<p className="mt-2 text-sm text-muted-foreground">{activePlan.explanation}</p>
) : null}
<div className="mt-3 space-y-2">
{activePlan.steps.map((step) => (
<div
key={`${step.status}:${step.step}`}
className="flex items-start gap-3 rounded-lg border border-border/60 bg-background/80 px-3 py-2"
>
<Badge
variant={
step.status === "completed"
? "default"
: step.status === "inProgress"
? "secondary"
: "outline"
}
>
{step.status === "inProgress"
? "In progress"
: step.status === "completed"
? "Done"
: "Pending"}
</Badge>
<div className="min-w-0 flex-1 text-sm">{step.step}</div>
</div>
))}
</div>
</div>
</div>
);
});
interface PendingUserInputPanelProps {
pendingUserInputs: PendingUserInput[];
respondingRequestIds: ApprovalRequestId[];
answers: Record<string, PendingUserInputDraftAnswer>;
questionIndex: number;
onSelectOption: (questionId: string, optionLabel: string) => void;
onAdvance: () => void;
}
const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
@@ -4348,7 +4260,6 @@ const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPane
answers,
questionIndex,
onSelectOption,
onAdvance,
}: PendingUserInputPanelProps) {
if (pendingUserInputs.length === 0) return null;
const activePrompt = pendingUserInputs[0];
@@ -4362,7 +4273,6 @@ const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPane
answers={answers}
questionIndex={questionIndex}
onSelectOption={onSelectOption}
onAdvance={onAdvance}
/>
);
});
@@ -4373,135 +4283,42 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
answers,
questionIndex,
onSelectOption,
onAdvance,
}: {
prompt: PendingUserInput;
isResponding: boolean;
answers: Record<string, PendingUserInputDraftAnswer>;
questionIndex: number;
onSelectOption: (questionId: string, optionLabel: string) => void;
onAdvance: () => void;
}) {
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
const activeQuestion = progress.activeQuestion;
const autoAdvanceTimerRef = useRef<number | null>(null);
// Clear auto-advance timer on unmount
useEffect(() => {
return () => {
if (autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
}
};
}, []);
const selectOptionAndAutoAdvance = useCallback(
(questionId: string, optionLabel: string) => {
onSelectOption(questionId, optionLabel);
if (autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
}
autoAdvanceTimerRef.current = window.setTimeout(() => {
autoAdvanceTimerRef.current = null;
onAdvance();
}, 200);
},
[onSelectOption, onAdvance],
);
// Keyboard shortcut: number keys 1-9 select corresponding option and auto-advance.
// Works even when the Lexical composer (contenteditable) has focus — the composer
// doubles as a custom-answer field during user input, and when it's empty the digit
// keys should pick options instead of typing into the editor.
useEffect(() => {
if (!activeQuestion || isResponding) return;
const handler = (event: globalThis.KeyboardEvent) => {
if (event.metaKey || event.ctrlKey || event.altKey) return;
const target = event.target;
if (
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement
) {
return;
}
// If the user has started typing a custom answer in the contenteditable
// composer, let digit keys pass through so they can type numbers.
if (target instanceof HTMLElement && target.isContentEditable) {
const hasCustomText = progress.customAnswer.length > 0;
if (hasCustomText) return;
}
const digit = Number.parseInt(event.key, 10);
if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
const optionIndex = digit - 1;
if (optionIndex >= activeQuestion.options.length) return;
const option = activeQuestion.options[optionIndex];
if (!option) return;
event.preventDefault();
selectOptionAndAutoAdvance(activeQuestion.id, option.label);
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
}, [activeQuestion, isResponding, selectOptionAndAutoAdvance, progress.customAnswer.length]);
if (!activeQuestion) {
return null;
}
return (
<div className="px-4 py-3 sm:px-5">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
{prompt.questions.length > 1 ? (
<span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-[10px] font-medium tabular-nums text-muted-foreground/60">
{questionIndex + 1}/{prompt.questions.length}
</span>
) : null}
<span className="text-[11px] font-semibold tracking-widest text-muted-foreground/50 uppercase">
{activeQuestion.header}
</span>
</div>
<div className="px-4 py-4 sm:px-5">
<div className="flex gap-2">
<span className="uppercase text-sm tracking-[0.2em]">
{questionIndex + 1}/{prompt.questions.length} {activeQuestion.header}
</span>
<div className="text-sm font-medium">{activeQuestion.question}</div>
</div>
<p className="mt-1.5 text-sm text-foreground/90">{activeQuestion.question}</p>
<div className="mt-3 space-y-1">
{activeQuestion.options.map((option, index) => {
<div className="mt-3 flex flex-wrap gap-2">
{activeQuestion.options.map((option) => {
const isSelected = progress.selectedOptionLabel === option.label;
const shortcutKey = index < 9 ? index + 1 : null;
return (
<button
<Button
key={`${activeQuestion.id}:${option.label}`}
type="button"
size="sm"
variant={isSelected ? "default" : "outline"}
disabled={isResponding}
onClick={() => selectOptionAndAutoAdvance(activeQuestion.id, option.label)}
className={cn(
"group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left transition-all duration-150",
isSelected
? "border-blue-500/40 bg-blue-500/8 text-foreground"
: "border-transparent bg-muted/20 text-foreground/80 hover:bg-muted/40 hover:border-border/40",
isResponding && "opacity-50 cursor-not-allowed",
)}
onClick={() => onSelectOption(activeQuestion.id, option.label)}
title={option.description}
>
{shortcutKey !== null ? (
<kbd
className={cn(
"flex size-5 shrink-0 items-center justify-center rounded text-[11px] font-medium tabular-nums transition-colors duration-150",
isSelected
? "bg-blue-500/20 text-blue-400"
: "bg-muted/40 text-muted-foreground/50 group-hover:bg-muted/60 group-hover:text-muted-foreground/70",
)}
>
{shortcutKey}
</kbd>
) : null}
<div className="min-w-0 flex-1">
<span className="text-sm font-medium">{option.label}</span>
{option.description && option.description !== option.label ? (
<span className="ml-2 text-xs text-muted-foreground/50">{option.description}</span>
) : null}
</div>
{isSelected ? (
<CheckIcon className="size-3.5 shrink-0 text-blue-400" />
) : null}
</button>
{option.label}
</Button>
);
})}
</div>
@@ -4715,7 +4532,7 @@ const ProposedPlanCard = memo(function ProposedPlanCard({
const saveContents = normalizePlanMarkdownForExport(planMarkdown);
const handleDownload = () => {
downloadPlanAsTextFile(downloadFilename, saveContents);
downloadTextFile(downloadFilename, saveContents);
};
const openSaveDialog = () => {
@@ -4807,12 +4624,7 @@ const ProposedPlanCard = memo(function ProposedPlanCard({
</div>
{canCollapse ? (
<div className="mt-4 flex justify-center">
<Button
size="sm"
variant="outline"
data-scroll-anchor-ignore
onClick={() => setExpanded((value) => !value)}
>
<Button size="sm" variant="outline" onClick={() => setExpanded((value) => !value)}>
{expanded ? "Collapse plan" : "Expand plan"}
</Button>
</div>
@@ -5405,7 +5217,8 @@ const MessagesTimeline = memo(function MessagesTimeline({
)}
{row.kind === "working" && (
<div className="py-0.5 pl-1.5">
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
@@ -5534,6 +5347,7 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {
model: ModelSlug;
lockedProvider: ProviderKind | null;
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>;
serviceTierSetting: AppServiceTier;
disabled?: boolean;
onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void;
}) {
@@ -5566,6 +5380,9 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {
>
<span className="flex min-w-0 items-center gap-2">
<ProviderIcon aria-hidden="true" className="size-4 shrink-0 text-muted-foreground/70" />
{props.provider === "codex" && shouldShowFastTierIcon(props.model, props.serviceTierSetting) ? (
<ZapIcon className="size-3.5 shrink-0 text-amber-500" />
) : null}
<span className="truncate">{selectedModelLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
</span>
@@ -5608,6 +5425,10 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {
value={modelOption.slug}
onClick={() => setIsMenuOpen(false)}
>
{option.value === "codex" &&
shouldShowFastTierIcon(modelOption.slug, props.serviceTierSetting) ? (
<ZapIcon className="size-3.5 shrink-0 text-amber-500" />
) : null}
{modelOption.name}
</MenuRadioItem>
))}
@@ -42,7 +42,7 @@ describe("when: branch is clean and has an open PR", () => {
}),
false,
);
assert.deepInclude(quick, { kind: "open_pr", label: "View PR", disabled: false });
assert.deepInclude(quick, { kind: "open_pr", label: "Open PR", disabled: false });
});
it("buildMenuItems disables commit/push and enables open PR", () => {
@@ -78,7 +78,7 @@ describe("when: branch is clean and has an open PR", () => {
},
{
id: "pr",
label: "View PR",
label: "Open PR",
disabled: false,
icon: "pr",
kind: "open_pr",
@@ -199,7 +199,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
},
{
id: "pr",
label: "View PR",
label: "Open PR",
disabled: false,
icon: "pr",
kind: "open_pr",
@@ -547,7 +547,7 @@ describe("when: branch has no upstream configured", () => {
);
assert.deepInclude(quick, {
kind: "open_pr",
label: "View PR",
label: "Open PR",
disabled: false,
});
});
@@ -151,7 +151,7 @@ export function buildMenuItems(
hasOpenPr
? {
id: "pr",
label: "View PR",
label: "Open PR",
disabled: !canOpenPr,
icon: "pr",
kind: "open_pr",
@@ -216,7 +216,7 @@ export function resolveQuickAction(
if (!gitStatus.hasUpstream) {
if (!isAhead) {
if (hasOpenPr) {
return { label: "View PR", disabled: false, kind: "open_pr" };
return { label: "Open PR", disabled: false, kind: "open_pr" };
}
return {
label: "Push",
@@ -266,7 +266,7 @@ export function resolveQuickAction(
}
if (hasOpenPr && gitStatus.hasUpstream) {
return { label: "View PR", disabled: false, kind: "open_pr" };
return { label: "Open PR", disabled: false, kind: "open_pr" };
}
return {
@@ -98,7 +98,7 @@ function getMenuActionDisabledReason(
}
if (hasOpenPr) {
return "View PR is currently unavailable.";
return "Open PR is currently unavailable.";
}
if (!hasBranch) {
return "Detached HEAD: checkout a branch before creating a PR.";
@@ -374,12 +374,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
},
}
: shouldOfferOpenPrCta
? {
actionProps: {
children: "View PR",
onClick: () => {
const api = readNativeApi();
if (!api) return;
? {
actionProps: {
children: "Open PR",
onClick: () => {
const api = readNativeApi();
if (!api) return;
closeResultToast();
void api.shell.openExternal(prUrl);
},
-267
View File
@@ -1,267 +0,0 @@
import { memo, useState, useCallback } from "react";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { ScrollArea } from "./ui/scroll-area";
import ChatMarkdown from "./ChatMarkdown";
import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
EllipsisIcon,
LoaderIcon,
PanelRightCloseIcon,
} from "lucide-react";
import { cn } from "~/lib/utils";
import { formatTimestamp } from "../session-logic";
import type { ActivePlanState } from "../session-logic";
import type { LatestProposedPlanState } from "../session-logic";
import {
proposedPlanTitle,
buildProposedPlanMarkdownFilename,
normalizePlanMarkdownForExport,
downloadPlanAsTextFile,
} from "../proposedPlan";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
import { readNativeApi } from "~/nativeApi";
import { toastManager } from "./ui/toast";
function stepStatusIcon(status: string): React.ReactNode {
if (status === "completed") {
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-emerald-500/15 text-emerald-500">
<CheckIcon className="size-3" />
</span>
);
}
if (status === "inProgress") {
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-blue-500/15 text-blue-400">
<LoaderIcon className="size-3 animate-spin" />
</span>
);
}
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full border border-border/60 bg-muted/30">
<span className="size-1.5 rounded-full bg-muted-foreground/30" />
</span>
);
}
interface PlanSidebarProps {
activePlan: ActivePlanState | null;
activeProposedPlan: LatestProposedPlanState | null;
markdownCwd: string | undefined;
workspaceRoot: string | undefined;
onClose: () => void;
}
const PlanSidebar = memo(function PlanSidebar({
activePlan,
activeProposedPlan,
markdownCwd,
workspaceRoot,
onClose,
}: PlanSidebarProps) {
const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false);
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
const [copied, setCopied] = useState(false);
const planMarkdown = activeProposedPlan?.planMarkdown ?? null;
const planTitle = planMarkdown ? proposedPlanTitle(planMarkdown) : null;
const handleCopyPlan = useCallback(() => {
if (!planMarkdown) return;
void navigator.clipboard.writeText(planMarkdown);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}, [planMarkdown]);
const handleDownload = useCallback(() => {
if (!planMarkdown) return;
const filename = buildProposedPlanMarkdownFilename(planMarkdown);
downloadPlanAsTextFile(filename, normalizePlanMarkdownForExport(planMarkdown));
}, [planMarkdown]);
const handleSaveToWorkspace = useCallback(() => {
const api = readNativeApi();
if (!api || !workspaceRoot || !planMarkdown) return;
const filename = buildProposedPlanMarkdownFilename(planMarkdown);
setIsSavingToWorkspace(true);
void api.projects
.writeFile({
cwd: workspaceRoot,
relativePath: filename,
contents: normalizePlanMarkdownForExport(planMarkdown),
})
.then((result) => {
toastManager.add({
type: "success",
title: "Plan saved",
description: result.relativePath,
});
})
.catch((error) => {
toastManager.add({
type: "error",
title: "Could not save plan",
description:
error instanceof Error ? error.message : "An error occurred.",
});
})
.then(
() => setIsSavingToWorkspace(false),
() => setIsSavingToWorkspace(false),
);
}, [planMarkdown, workspaceRoot]);
return (
<div className="flex h-full w-[340px] shrink-0 flex-col border-l border-border/70 bg-card/50">
{/* Header */}
<div className="flex h-12 shrink-0 items-center justify-between border-b border-border/60 px-3">
<div className="flex items-center gap-2">
<Badge
variant="secondary"
className="rounded-md bg-blue-500/10 px-1.5 py-0 text-[10px] font-semibold tracking-wide text-blue-400 uppercase"
>
Plan
</Badge>
{activePlan ? (
<span className="text-[11px] text-muted-foreground/60">
{formatTimestamp(activePlan.createdAt)}
</span>
) : null}
</div>
<div className="flex items-center gap-1">
{planMarkdown ? (
<Menu>
<MenuTrigger
render={
<Button
size="icon-xs"
variant="ghost"
className="text-muted-foreground/50 hover:text-foreground/70"
aria-label="Plan actions"
/>
}
>
<EllipsisIcon className="size-3.5" />
</MenuTrigger>
<MenuPopup align="end">
<MenuItem onClick={handleCopyPlan}>
{copied ? "Copied!" : "Copy to clipboard"}
</MenuItem>
<MenuItem onClick={handleDownload}>Download as markdown</MenuItem>
<MenuItem
onClick={handleSaveToWorkspace}
disabled={!workspaceRoot || isSavingToWorkspace}
>
Save to workspace
</MenuItem>
</MenuPopup>
</Menu>
) : null}
<Button
size="icon-xs"
variant="ghost"
onClick={onClose}
aria-label="Close plan sidebar"
className="text-muted-foreground/50 hover:text-foreground/70"
>
<PanelRightCloseIcon className="size-3.5" />
</Button>
</div>
</div>
{/* Content */}
<ScrollArea className="min-h-0 flex-1">
<div className="p-3 space-y-4">
{/* Explanation */}
{activePlan?.explanation ? (
<p className="text-[13px] leading-relaxed text-muted-foreground/80">
{activePlan.explanation}
</p>
) : null}
{/* Plan Steps */}
{activePlan && activePlan.steps.length > 0 ? (
<div className="space-y-1">
<p className="mb-2 text-[10px] font-semibold tracking-widest text-muted-foreground/40 uppercase">
Steps
</p>
{activePlan.steps.map((step) => (
<div
key={`${step.status}:${step.step}`}
className={cn(
"flex items-start gap-2.5 rounded-lg px-2.5 py-2 transition-colors duration-200",
step.status === "inProgress" && "bg-blue-500/5",
step.status === "completed" && "bg-emerald-500/5",
)}
>
<div className="mt-0.5">
{stepStatusIcon(step.status)}
</div>
<p
className={cn(
"text-[13px] leading-snug",
step.status === "completed"
? "text-muted-foreground/50 line-through decoration-muted-foreground/20"
: step.status === "inProgress"
? "text-foreground/90"
: "text-muted-foreground/70",
)}
>
{step.step}
</p>
</div>
))}
</div>
) : null}
{/* Proposed Plan Markdown */}
{planMarkdown ? (
<div className="space-y-2">
<button
type="button"
className="group flex w-full items-center gap-1.5 text-left"
onClick={() => setProposedPlanExpanded((v) => !v)}
>
{proposedPlanExpanded ? (
<ChevronDownIcon className="size-3 shrink-0 text-muted-foreground/40 transition-transform" />
) : (
<ChevronRightIcon className="size-3 shrink-0 text-muted-foreground/40 transition-transform" />
)}
<span className="text-[10px] font-semibold tracking-widest text-muted-foreground/40 uppercase group-hover:text-muted-foreground/60">
{planTitle ?? "Full Plan"}
</span>
</button>
{proposedPlanExpanded ? (
<div className="rounded-lg border border-border/50 bg-background/50 p-3">
<ChatMarkdown
text={planMarkdown}
cwd={markdownCwd}
isStreaming={false}
/>
</div>
) : null}
</div>
) : null}
{/* Empty state */}
{!activePlan && !planMarkdown ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-[13px] text-muted-foreground/40">
No active plan yet.
</p>
<p className="mt-1 text-[11px] text-muted-foreground/30">
Plans will appear here when generated.
</p>
</div>
) : null}
</div>
</ScrollArea>
</div>
);
});
export default PlanSidebar;
export type { PlanSidebarProps };
@@ -14,7 +14,7 @@ import {
SettingsIcon,
WrenchIcon,
} from "lucide-react";
import React, { type FormEvent, type KeyboardEvent, useCallback, useMemo, useState } from "react";
import React, { type FormEvent, type KeyboardEvent, useMemo, useState } from "react";
import {
keybindingValueForCommand,
@@ -27,15 +27,6 @@ import {
} from "~/projectScripts";
import { shortcutLabelForCommand } from "~/keybindings";
import { isMacPlatform } from "~/lib/utils";
import {
AlertDialog,
AlertDialogClose,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogPopup,
AlertDialogTitle,
} from "./ui/alert-dialog";
import { Button } from "./ui/button";
import {
Dialog,
@@ -93,7 +84,6 @@ interface ProjectScriptsControlProps {
onRunScript: (script: ProjectScript) => void;
onAddScript: (input: NewProjectScriptInput) => Promise<void> | void;
onUpdateScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void> | void;
onDeleteScript: (scriptId: string) => Promise<void> | void;
}
function normalizeShortcutKeyToken(key: string): string | null {
@@ -154,7 +144,6 @@ export default function ProjectScriptsControl({
onRunScript,
onAddScript,
onUpdateScript,
onDeleteScript,
}: ProjectScriptsControlProps) {
const addScriptFormId = React.useId();
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
@@ -166,7 +155,6 @@ export default function ProjectScriptsControl({
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
const [keybinding, setKeybinding] = useState("");
const [validationError, setValidationError] = useState<string | null>(null);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const primaryScript = useMemo(() => {
if (preferredScriptId) {
@@ -259,13 +247,6 @@ export default function ProjectScriptsControl({
setDialogOpen(true);
};
const confirmDeleteScript = useCallback(() => {
if (!editingScriptId) return;
setDeleteConfirmOpen(false);
setDialogOpen(false);
void onDeleteScript(editingScriptId);
}, [editingScriptId, onDeleteScript]);
return (
<>
{primaryScript ? (
@@ -459,16 +440,6 @@ export default function ProjectScriptsControl({
</form>
</DialogPanel>
<DialogFooter>
{isEditing && (
<Button
type="button"
variant="destructive-outline"
className="mr-auto"
onClick={() => setDeleteConfirmOpen(true)}
>
Delete
</Button>
)}
<Button
type="button"
variant="outline"
@@ -484,21 +455,6 @@ export default function ProjectScriptsControl({
</DialogFooter>
</DialogPopup>
</Dialog>
<AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Delete action "{name}"?</AlertDialogTitle>
<AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button variant="destructive" onClick={confirmDeleteScript}>
Delete action
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
</>
);
}
@@ -1,124 +0,0 @@
import { describe, expect, it } from "vitest";
import { hasUnseenCompletion, resolveThreadStatusPill } from "./Sidebar.logic";
function makeLatestTurn(overrides?: {
completedAt?: string | null;
startedAt?: string | null;
}): Parameters<typeof hasUnseenCompletion>[0]["latestTurn"] {
return {
turnId: "turn-1" as never,
state: "completed",
assistantMessageId: null,
requestedAt: "2026-03-09T10:00:00.000Z",
startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z",
completedAt: overrides?.completedAt ?? "2026-03-09T10:05:00.000Z",
};
}
describe("hasUnseenCompletion", () => {
it("returns true when a thread completed after its last visit", () => {
expect(
hasUnseenCompletion({
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
proposedPlans: [],
session: null,
}),
).toBe(true);
});
});
describe("resolveThreadStatusPill", () => {
const baseThread = {
interactionMode: "plan" as const,
latestTurn: null,
lastVisitedAt: undefined,
proposedPlans: [],
session: {
provider: "codex" as const,
status: "running" as const,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
orchestrationStatus: "running" as const,
},
};
it("shows pending approval before all other statuses", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: true,
hasPendingUserInput: true,
}),
).toMatchObject({ label: "Pending Approval", pulse: false });
});
it("shows awaiting input when plan mode is blocked on user answers", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: true,
}),
).toMatchObject({ label: "Awaiting Input", pulse: false });
});
it("falls back to working when the thread is actively running without blockers", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Working", pulse: true });
});
it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
latestTurn: makeLatestTurn(),
proposedPlans: [
{
id: "plan-1" as never,
turnId: "turn-1" as never,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
},
],
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Plan Ready", pulse: false });
});
it("shows completed when there is an unseen completion and no active blocker", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Completed", pulse: false });
});
});
-100
View File
@@ -1,100 +0,0 @@
import type { Thread } from "../types";
import { findLatestProposedPlan, isLatestTurnSettled } from "../session-logic";
export interface ThreadStatusPill {
label:
| "Working"
| "Connecting"
| "Completed"
| "Pending Approval"
| "Awaiting Input"
| "Plan Ready";
colorClass: string;
dotClass: string;
pulse: boolean;
}
type ThreadStatusInput = Pick<
Thread,
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
>;
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
if (!thread.latestTurn?.completedAt) return false;
const completedAt = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(completedAt)) return false;
if (!thread.lastVisitedAt) return true;
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAt)) return true;
return completedAt > lastVisitedAt;
}
export function resolveThreadStatusPill(input: {
thread: ThreadStatusInput;
hasPendingApprovals: boolean;
hasPendingUserInput: boolean;
}): ThreadStatusPill | null {
const { hasPendingApprovals, hasPendingUserInput, thread } = input;
if (hasPendingApprovals) {
return {
label: "Pending Approval",
colorClass: "text-amber-600 dark:text-amber-300/90",
dotClass: "bg-amber-500 dark:bg-amber-300/90",
pulse: false,
};
}
if (hasPendingUserInput) {
return {
label: "Awaiting Input",
colorClass: "text-indigo-600 dark:text-indigo-300/90",
dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
pulse: false,
};
}
if (thread.session?.status === "running") {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (thread.session?.status === "connecting") {
return {
label: "Connecting",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
const hasPlanReadyPrompt =
!hasPendingUserInput &&
thread.interactionMode === "plan" &&
isLatestTurnSettled(thread.latestTurn, thread.session) &&
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null) !== null;
if (hasPlanReadyPrompt) {
return {
label: "Plan Ready",
colorClass: "text-violet-600 dark:text-violet-300/90",
dotClass: "bg-violet-500 dark:bg-violet-300/90",
pulse: false,
};
}
if (hasUnseenCompletion(thread)) {
return {
label: "Completed",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
pulse: false,
};
}
return null;
}
+130 -205
View File
@@ -1,14 +1,10 @@
import {
ArrowLeftIcon,
ChevronRightIcon,
FolderIcon,
GitPullRequestIcon,
PlusIcon,
RocketIcon,
SettingsIcon,
SquarePenIcon,
TerminalIcon,
TriangleAlertIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
@@ -21,14 +17,15 @@ import {
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
import { type Thread } from "../types";
import { derivePendingApprovals } from "../session-logic";
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
@@ -36,18 +33,14 @@ import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraft
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { toastManager } from "./ui/toast";
import {
getArm64IntelBuildWarningDescription,
getDesktopUpdateActionError,
getDesktopUpdateButtonTooltip,
isDesktopUpdateButtonDisabled,
resolveDesktopUpdateButtonAction,
shouldShowArm64IntelBuildWarning,
shouldHighlightDesktopUpdateError,
shouldShowDesktopUpdateButton,
shouldToastDesktopUpdateActionResult,
} from "./desktopUpdate.logic";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
import { Button } from "./ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import {
@@ -67,7 +60,6 @@ import {
} from "./ui/sidebar";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { isNonEmpty as isNonEmptyString } from "effect/String";
import { resolveThreadStatusPill } from "./Sidebar.logic";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
@@ -89,6 +81,13 @@ function formatRelativeTime(iso: string): string {
return `${Math.floor(hours / 24)}d ago`;
}
interface ThreadStatusPill {
label: "Working" | "Connecting" | "Completed" | "Pending Approval";
colorClass: string;
dotClass: string;
pulse: boolean;
}
interface TerminalStatusIndicator {
label: "Terminal process running";
colorClass: string;
@@ -104,6 +103,57 @@ interface PrStatusIndicator {
type ThreadPr = GitStatusResult["pr"];
function hasUnseenCompletion(thread: Thread): boolean {
if (!thread.latestTurn?.completedAt) return false;
const completedAt = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(completedAt)) return false;
if (!thread.lastVisitedAt) return true;
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAt)) return true;
return completedAt > lastVisitedAt;
}
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
if (hasPendingApprovals) {
return {
label: "Pending Approval",
colorClass: "text-amber-600 dark:text-amber-300/90",
dotClass: "bg-amber-500 dark:bg-amber-300/90",
pulse: false,
};
}
if (thread.session?.status === "running") {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (thread.session?.status === "connecting") {
return {
label: "Connecting",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (hasUnseenCompletion(thread)) {
return {
label: "Completed",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
pulse: false,
};
}
return null;
}
function terminalStatusFromRunningIds(
runningTerminalIds: string[],
): TerminalStatusIndicator | null {
@@ -175,7 +225,7 @@ function getServerHttpOrigin(): string {
? bridgeUrl
: envUrl && envUrl.length > 0
? envUrl
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`;
: `ws://${window.location.hostname}:${window.location.port}`;
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
try {
@@ -228,7 +278,6 @@ export default function Sidebar() {
(store) => store.clearProjectDraftThreadById,
);
const navigate = useNavigate();
const isOnSettings = useLocation({ select: (loc) => loc.pathname === "/settings" });
const { settings: appSettings } = useAppSettings();
const routeThreadId = useParams({
strict: false,
@@ -244,8 +293,6 @@ export default function Sidebar() {
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const [addProjectError, setAddProjectError] = useState<string | null>(null);
const addProjectInputRef = useRef<HTMLInputElement | null>(null);
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
@@ -254,8 +301,6 @@ export default function Sidebar() {
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const [desktopUpdateState, setDesktopUpdateState] = useState<DesktopUpdateState | null>(null);
const shouldBrowseForProjectImmediately = isElectron;
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<ThreadId, boolean>();
for (const thread of threads) {
@@ -263,13 +308,6 @@ export default function Sidebar() {
}
return map;
}, [threads]);
const pendingUserInputByThreadId = useMemo(() => {
const map = new Map<ThreadId, boolean>();
for (const thread of threads) {
map.set(thread.id, derivePendingUserInputs(thread.activities).length > 0);
}
return map;
}, [threads]);
const projectCwdById = useMemo(
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
[projects],
@@ -448,7 +486,6 @@ export default function Sidebar() {
const finishAddingProject = () => {
setIsAddingProject(false);
setNewCwd("");
setAddProjectError(null);
setAddingProject(false);
};
@@ -474,29 +511,18 @@ export default function Sidebar() {
});
await handleNewThread(projectId).catch(() => undefined);
} catch (error) {
const description =
error instanceof Error ? error.message : "An error occurred while adding the project.";
setIsAddingProject(false);
if (shouldBrowseForProjectImmediately) {
toastManager.add({
type: "error",
title: "Failed to add project",
description,
});
} else {
setAddProjectError(description);
}
toastManager.add({
type: "error",
title: "Unable to add project",
description:
error instanceof Error ? error.message : "An error occurred while adding the project.",
});
return;
}
finishAddingProject();
},
[
focusMostRecentThreadForProject,
handleNewThread,
isAddingProject,
projects,
shouldBrowseForProjectImmediately,
],
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
);
const handleAddProject = () => {
@@ -515,21 +541,10 @@ export default function Sidebar() {
}
if (pickedPath) {
await addProjectFromPath(pickedPath);
} else if (!shouldBrowseForProjectImmediately) {
addProjectInputRef.current?.focus();
}
setIsPickingFolder(false);
};
const handleStartAddProject = () => {
setAddProjectError(null);
if (shouldBrowseForProjectImmediately) {
void handlePickFolder();
return;
}
setAddingProject((prev) => !prev);
};
const cancelRename = useCallback(() => {
setRenamingThreadId(null);
renamingInputRef.current = null;
@@ -866,12 +881,6 @@ export default function Sidebar() {
const desktopUpdateButtonAction = desktopUpdateState
? resolveDesktopUpdateButtonAction(desktopUpdateState)
: "none";
const showArm64IntelBuildWarning =
isElectron && shouldShowArm64IntelBuildWarning(desktopUpdateState);
const arm64IntelBuildWarningDescription =
desktopUpdateState && showArm64IntelBuildWarning
? getArm64IntelBuildWarningDescription(desktopUpdateState)
: null;
const desktopUpdateButtonInteractivityClasses = desktopUpdateButtonDisabled
? "cursor-not-allowed opacity-60"
: "hover:bg-accent hover:text-foreground";
@@ -969,7 +978,7 @@ export default function Sidebar() {
const wordmark = (
<div className="flex items-center gap-2">
<SidebarTrigger className="shrink-0 md:hidden" />
<div className="flex min-w-0 flex-1 items-center gap-1 mt-1.5 ml-1">
<div className="flex min-w-0 flex-1 items-center gap-1 mt-2 ml-1">
<T3Wordmark />
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
Code
@@ -985,7 +994,7 @@ export default function Sidebar() {
<>
{isElectron ? (
<>
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[90px]">
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
{wordmark}
{showDesktopUpdateButton && (
<Tooltip>
@@ -996,7 +1005,7 @@ export default function Sidebar() {
aria-label={desktopUpdateTooltip}
aria-disabled={desktopUpdateButtonDisabled || undefined}
disabled={desktopUpdateButtonDisabled}
className={`inline-flex size-7 ml-auto mt-1.5 items-center justify-center rounded-md text-muted-foreground transition-colors ${desktopUpdateButtonInteractivityClasses} ${desktopUpdateButtonClasses}`}
className={`inline-flex size-7 ml-auto mt-2 items-center justify-center rounded-md text-muted-foreground transition-colors ${desktopUpdateButtonInteractivityClasses} ${desktopUpdateButtonClasses}`}
onClick={handleDesktopUpdateButtonClick}
>
<RocketIcon className="size-3.5" />
@@ -1015,121 +1024,7 @@ export default function Sidebar() {
)}
<SidebarContent className="gap-0">
{showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? (
<SidebarGroup className="px-2 pt-2 pb-0">
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
<TriangleAlertIcon />
<AlertTitle>Intel build on Apple Silicon</AlertTitle>
<AlertDescription>{arm64IntelBuildWarningDescription}</AlertDescription>
{desktopUpdateButtonAction !== "none" ? (
<AlertAction>
<Button
size="xs"
variant="outline"
disabled={desktopUpdateButtonDisabled}
onClick={handleDesktopUpdateButtonClick}
>
{desktopUpdateButtonAction === "download"
? "Download ARM build"
: "Install ARM build"}
</Button>
</AlertAction>
) : null}
</Alert>
</SidebarGroup>
) : null}
<SidebarGroup className="px-2 py-2">
<div className="mb-1 flex items-center justify-between px-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
Projects
</span>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="Add project"
aria-pressed={shouldShowProjectPathEntry}
className="inline-flex size-5 items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
onClick={handleStartAddProject}
/>
}
>
<PlusIcon
className={`size-3.5 transition-transform duration-150 ${
shouldShowProjectPathEntry ? "rotate-45" : "rotate-0"
}`}
/>
</TooltipTrigger>
<TooltipPopup side="right">Add project</TooltipPopup>
</Tooltip>
</div>
{shouldShowProjectPathEntry && (
<div className="mb-2 px-1">
{isElectron && (
<button
type="button"
className="mb-1.5 flex w-full items-center justify-center gap-2 rounded-md border border-border bg-secondary py-1.5 text-xs text-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => void handlePickFolder()}
disabled={isPickingFolder || isAddingProject}
>
<FolderIcon className="size-3.5" />
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
)}
<div className="flex gap-1.5">
<input
ref={addProjectInputRef}
className={`min-w-0 flex-1 rounded-md border bg-secondary px-2 py-1 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:outline-none ${
addProjectError
? "border-red-500/70 focus:border-red-500"
: "border-border focus:border-ring"
}`}
placeholder="/path/to/project"
value={newCwd}
onChange={(event) => {
setNewCwd(event.target.value);
setAddProjectError(null);
}}
onKeyDown={(event) => {
if (event.key === "Enter") handleAddProject();
if (event.key === "Escape") {
setAddingProject(false);
setAddProjectError(null);
}
}}
autoFocus
/>
<button
type="button"
className="shrink-0 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90 disabled:opacity-60"
onClick={handleAddProject}
disabled={isAddingProject}
>
{isAddingProject ? "Adding..." : "Add"}
</button>
</div>
{addProjectError && (
<p className="mt-1 px-0.5 text-[11px] leading-tight text-red-400">
{addProjectError}
</p>
)}
<div className="mt-1.5 px-0.5">
<button
type="button"
className="text-[11px] text-muted-foreground/50 transition-colors hover:text-muted-foreground"
onClick={() => {
setAddingProject(false);
setAddProjectError(null);
}}
>
Cancel
</button>
</div>
</div>
)}
<SidebarMenu>
{projects.map((project) => {
const projectThreads = threads
@@ -1217,11 +1112,10 @@ export default function Sidebar() {
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
{visibleThreads.map((thread) => {
const isActive = routeThreadId === thread.id;
const threadStatus = resolveThreadStatusPill({
const threadStatus = threadStatusPill(
thread,
hasPendingApprovals: pendingApprovalByThreadId.get(thread.id) === true,
hasPendingUserInput: pendingUserInputByThreadId.get(thread.id) === true,
});
pendingApprovalByThreadId.get(thread.id) === true,
);
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id)
@@ -1392,39 +1286,70 @@ export default function Sidebar() {
})}
</SidebarMenu>
{projects.length === 0 && !shouldShowProjectPathEntry && (
{projects.length === 0 && !addingProject && (
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
No projects yet
No projects yet.
<br />
Add one to get started.
</div>
)}
</SidebarGroup>
</SidebarContent>
<SidebarSeparator />
<SidebarFooter className="p-2">
<SidebarMenu>
<SidebarMenuItem>
{isOnSettings ? (
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
onClick={() => window.history.back()}
<SidebarFooter className="gap-0 p-3">
{addingProject ? (
<>
<p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
Add project
</p>
<input
className="mb-2 w-full rounded-md border border-border bg-secondary px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:border-ring focus:outline-none"
placeholder="/path/to/project"
value={newCwd}
onChange={(event) => setNewCwd(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") handleAddProject();
if (event.key === "Escape") setAddingProject(false);
}}
/>
{isElectron && (
<button
type="button"
className="mb-2 flex w-full items-center justify-center rounded-md border border-border px-2 py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => void handlePickFolder()}
disabled={isPickingFolder || isAddingProject}
>
<ArrowLeftIcon className="size-3.5" />
<span className="text-xs">Back</span>
</SidebarMenuButton>
) : (
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
onClick={() => void navigate({ to: "/settings" })}
>
<SettingsIcon className="size-3.5" />
<span className="text-xs">Settings</span>
</SidebarMenuButton>
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
)}
</SidebarMenuItem>
</SidebarMenu>
<div className="flex gap-2">
<button
type="button"
className="flex-1 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90"
onClick={handleAddProject}
disabled={isAddingProject}
>
{isAddingProject ? "Adding..." : "Add"}
</button>
<button
type="button"
className="flex-1 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground/80 transition-colors duration-150 hover:bg-secondary"
onClick={() => setAddingProject(false)}
>
Cancel
</button>
</div>
</>
) : (
<button
type="button"
className="flex w-full items-center justify-center gap-1 rounded-md border border-dashed border-border py-2 text-xs text-muted-foreground/70 transition-colors duration-150 hover:border-ring hover:text-muted-foreground"
onClick={() => setAddingProject(true)}
>
+ Add project
</button>
)}
</SidebarFooter>
</>
);
@@ -2,13 +2,11 @@ import { describe, expect, it } from "vitest";
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
import {
getArm64IntelBuildWarningDescription,
getDesktopUpdateActionError,
getDesktopUpdateButtonTooltip,
isDesktopUpdateButtonDisabled,
resolveDesktopUpdateButtonAction,
shouldHighlightDesktopUpdateError,
shouldShowArm64IntelBuildWarning,
shouldShowDesktopUpdateButton,
shouldToastDesktopUpdateActionResult,
} from "./desktopUpdate.logic";
@@ -17,9 +15,6 @@ const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
@@ -176,30 +171,4 @@ describe("desktop update UI helpers", () => {
}),
).toBe(false);
});
it("shows an Apple Silicon warning for Intel builds under Rosetta", () => {
const state: DesktopUpdateState = {
...baseState,
hostArch: "arm64",
appArch: "x64",
runningUnderArm64Translation: true,
};
expect(shouldShowArm64IntelBuildWarning(state)).toBe(true);
expect(getArm64IntelBuildWarningDescription(state)).toContain("Apple Silicon");
expect(getArm64IntelBuildWarningDescription(state)).toContain("Intel build");
});
it("changes the warning copy when a native build update is ready to download", () => {
const state: DesktopUpdateState = {
...baseState,
hostArch: "arm64",
appArch: "x64",
runningUnderArm64Translation: true,
status: "available",
availableVersion: "1.1.0",
};
expect(getArm64IntelBuildWarningDescription(state)).toContain("Download the available update");
});
});
@@ -32,29 +32,10 @@ export function shouldShowDesktopUpdateButton(state: DesktopUpdateState | null):
return resolveDesktopUpdateButtonAction(state) !== "none";
}
export function shouldShowArm64IntelBuildWarning(state: DesktopUpdateState | null): boolean {
return state?.hostArch === "arm64" && state.appArch === "x64";
}
export function isDesktopUpdateButtonDisabled(state: DesktopUpdateState | null): boolean {
return state?.status === "downloading";
}
export function getArm64IntelBuildWarningDescription(state: DesktopUpdateState): string {
if (!shouldShowArm64IntelBuildWarning(state)) {
return "This install is using the correct architecture.";
}
const action = resolveDesktopUpdateButtonAction(state);
if (action === "download") {
return "This Mac has Apple Silicon, but T3 Code is still running the Intel build under Rosetta. Download the available update to switch to the native Apple Silicon build.";
}
if (action === "install") {
return "This Mac has Apple Silicon, but T3 Code is still running the Intel build under Rosetta. Restart to install the downloaded Apple Silicon build.";
}
return "This Mac has Apple Silicon, but T3 Code is still running the Intel build under Rosetta. The next app update will replace it with the native Apple Silicon build.";
}
export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string {
if (state.status === "available") {
return `Update ${state.availableVersion ?? "available"} ready to download`;
+1 -2
View File
@@ -566,8 +566,7 @@ function SidebarRail({
<button
aria-label={railLabel}
className={cn(
/* disable pointer events only when offcanvas sidebar is collapsed, that's when the rail sits over the native scrollbar on windows and linux. icon mode stays fully clickable. */
"-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex [[data-collapsible=offcanvas][data-state=collapsed]_&]:pointer-events-none",
"-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
+1 -40
View File
@@ -1,5 +1,5 @@
import { assert, describe, it } from "vitest";
import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
import { shouldHideCollapsedToastContent } from "./toast.logic";
describe("shouldHideCollapsedToastContent", () => {
it("keeps a single visible toast readable", () => {
@@ -14,42 +14,3 @@ describe("shouldHideCollapsedToastContent", () => {
assert.equal(shouldHideCollapsedToastContent(1, 3), true);
});
});
describe("buildVisibleToastLayout", () => {
it("computes indices and offsets from the visible subset", () => {
const visibleToasts = [{ id: "a", height: 48 }, { id: "b", height: 72 }, { id: "c", height: 24 }];
const layout = buildVisibleToastLayout(visibleToasts);
assert.equal(layout.frontmostHeight, 48);
assert.deepEqual(
layout.items.map(({ toast, visibleIndex, offsetY }) => ({
id: toast.id,
visibleIndex,
offsetY,
})),
[
{ id: "a", visibleIndex: 0, offsetY: 0 },
{ id: "b", visibleIndex: 1, offsetY: 48 },
{ id: "c", visibleIndex: 2, offsetY: 120 },
],
);
});
it("treats missing heights as zero", () => {
const layout = buildVisibleToastLayout([{ id: "a" }, { id: "b", height: undefined }, { id: "c", height: 30 }]);
assert.equal(layout.frontmostHeight, 0);
assert.deepEqual(
layout.items.map(({ toast, offsetY }) => ({
id: toast.id,
offsetY,
})),
[
{ id: "a", offsetY: 0 },
{ id: "b", offsetY: 0 },
{ id: "c", offsetY: 0 },
],
);
});
});
-37
View File
@@ -7,40 +7,3 @@ export function shouldHideCollapsedToastContent(
if (visibleToastCount <= 1) return false;
return visibleToastIndex > 0;
}
type ToastWithHeight = {
height?: number | null | undefined;
};
type VisibleToastLayoutItem<TToast extends object> = {
toast: TToast;
visibleIndex: number;
offsetY: number;
};
export function buildVisibleToastLayout<TToast extends object>(
visibleToasts: readonly (TToast & ToastWithHeight)[],
): {
frontmostHeight: number;
items: VisibleToastLayoutItem<TToast & ToastWithHeight>[];
} {
let offsetY = 0;
return {
frontmostHeight: normalizeToastHeight(visibleToasts[0]?.height),
items: visibleToasts.map((toast, visibleIndex) => {
const item = {
toast,
visibleIndex,
offsetY,
};
offsetY += normalizeToastHeight(toast.height);
return item;
}),
};
}
function normalizeToastHeight(height: number | null | undefined): number {
return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : 0;
}
+4 -16
View File
@@ -1,7 +1,7 @@
"use client";
import { Toast } from "@base-ui/react/toast";
import { useEffect, type CSSProperties } from "react";
import { useEffect } from "react";
import { useParams } from "@tanstack/react-router";
import { ThreadId } from "@t3tools/contracts";
import {
@@ -14,7 +14,7 @@ import {
import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button";
import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
import { shouldHideCollapsedToastContent } from "./toast.logic";
type ThreadToastData = {
threadId?: ThreadId | null;
@@ -158,7 +158,6 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const visibleToasts = toasts.filter((toast) =>
shouldRenderForActiveThread(toast.data, activeThreadId),
);
const visibleToastLayout = buildVisibleToastLayout(visibleToasts);
useEffect(() => {
const activeToastIds = new Set(toasts.map((toast) => toast.id));
@@ -184,17 +183,12 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
)}
data-position={position}
data-slot="toast-viewport"
style={
{
"--toast-frontmost-height": `${visibleToastLayout.frontmostHeight}px`,
} as CSSProperties
}
>
{visibleToastLayout.items.map(({ toast, visibleIndex, offsetY }) => {
{visibleToasts.map((toast, visibleIndex) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
const hideCollapsedContent = shouldHideCollapsedToastContent(
visibleIndex,
visibleToastLayout.items.length,
visibleToasts.length,
);
return (
@@ -247,12 +241,6 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
)}
data-position={position}
key={toast.id}
style={
{
"--toast-index": visibleIndex,
"--toast-offset-y": `${offsetY}px`,
} as CSSProperties
}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
+127 -1
View File
@@ -1,7 +1,11 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { type ComposerImageAttachment, useComposerDraftStore } from "./composerDraftStore";
import {
type ComposerImageAttachment,
createDebouncedStorage,
useComposerDraftStore,
} from "./composerDraftStore";
function makeImage(input: {
id: string;
@@ -451,3 +455,125 @@ describe("composerDraftStore runtime and interaction settings", () => {
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
});
// ---------------------------------------------------------------------------
// createDebouncedStorage
// ---------------------------------------------------------------------------
function createMockStorage() {
const store = new Map<string, string>();
return {
getItem: vi.fn((name: string) => store.get(name) ?? null),
setItem: vi.fn((name: string, value: string) => {
store.set(name, value);
}),
removeItem: vi.fn((name: string) => {
store.delete(name);
}),
};
}
describe("createDebouncedStorage", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("delegates getItem immediately", () => {
const base = createMockStorage();
base.getItem.mockReturnValueOnce("value");
const storage = createDebouncedStorage(base);
expect(storage.getItem("key")).toBe("value");
expect(base.getItem).toHaveBeenCalledWith("key");
});
it("does not write to base storage until the debounce fires", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
expect(base.setItem).not.toHaveBeenCalled();
vi.advanceTimersByTime(299);
expect(base.setItem).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(base.setItem).toHaveBeenCalledWith("key", "v1");
});
it("only writes the last value when setItem is called rapidly", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
storage.setItem("key", "v2");
storage.setItem("key", "v3");
vi.advanceTimersByTime(300);
expect(base.setItem).toHaveBeenCalledTimes(1);
expect(base.setItem).toHaveBeenCalledWith("key", "v3");
});
it("removeItem cancels a pending setItem write", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
storage.removeItem("key");
vi.advanceTimersByTime(300);
expect(base.setItem).not.toHaveBeenCalled();
expect(base.removeItem).toHaveBeenCalledWith("key");
});
it("flush writes the pending value immediately", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
expect(base.setItem).not.toHaveBeenCalled();
storage.flush();
expect(base.setItem).toHaveBeenCalledWith("key", "v1");
// Timer should be cancelled; no duplicate write.
vi.advanceTimersByTime(300);
expect(base.setItem).toHaveBeenCalledTimes(1);
});
it("flush is a no-op when nothing is pending", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.flush();
expect(base.setItem).not.toHaveBeenCalled();
});
it("flush after removeItem is a no-op", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
storage.removeItem("key");
storage.flush();
expect(base.setItem).not.toHaveBeenCalled();
});
it("setItem works normally after removeItem cancels a pending write", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
storage.removeItem("key");
storage.setItem("key", "v2");
vi.advanceTimersByTime(300);
expect(base.setItem).toHaveBeenCalledTimes(1);
expect(base.setItem).toHaveBeenCalledWith("key", "v2");
});
});
+44 -2
View File
@@ -14,12 +14,54 @@ import {
DEFAULT_RUNTIME_MODE,
type ChatImageAttachment,
} from "./types";
import { Debouncer } from "@tanstack/react-pacer";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { createJSONStorage, persist, type StateStorage } from "zustand/middleware";
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
export type DraftThreadEnvMode = "local" | "worktree";
const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
interface DebouncedStorage extends StateStorage {
flush: () => void;
}
export function createDebouncedStorage(baseStorage: StateStorage): DebouncedStorage {
const debouncedSetItem = new Debouncer(
(name: string, value: string) => {
baseStorage.setItem(name, value);
},
{ wait: COMPOSER_PERSIST_DEBOUNCE_MS },
);
return {
getItem: (name) => baseStorage.getItem(name),
setItem: (name, value) => {
debouncedSetItem.maybeExecute(name, value);
},
removeItem: (name) => {
debouncedSetItem.cancel();
baseStorage.removeItem(name);
},
flush: () => {
debouncedSetItem.flush();
},
};
}
const composerDebouncedStorage: DebouncedStorage =
typeof localStorage !== "undefined"
? createDebouncedStorage(localStorage)
: { getItem: () => null, setItem: () => {}, removeItem: () => {}, flush: () => {} };
// Flush pending composer draft writes before page unload to prevent data loss.
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
composerDebouncedStorage.flush();
});
}
export interface PersistedComposerImageAttachment {
id: string;
name: string;
@@ -1169,7 +1211,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
{
name: COMPOSER_DRAFT_STORAGE_KEY,
version: 1,
storage: createJSONStorage(() => localStorage),
storage: createJSONStorage(() => composerDebouncedStorage),
partialize: (state) => {
const persistedDraftsByThreadId: PersistedComposerDraftStoreState["draftsByThreadId"] = {};
for (const [threadId, draft] of Object.entries(state.draftsByThreadId)) {
-16
View File
@@ -49,19 +49,3 @@ export function buildProposedPlanMarkdownFilename(planMarkdown: string): string
const title = proposedPlanTitle(planMarkdown);
return `${sanitizePlanFileSegment(title ?? "plan")}.md`;
}
export function normalizePlanMarkdownForExport(planMarkdown: string): string {
return `${planMarkdown.trimEnd()}\n`;
}
export function downloadPlanAsTextFile(filename: string, contents: string): void {
const blob = new Blob([contents], { type: "text/markdown;charset=utf-8" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.click();
window.setTimeout(() => {
URL.revokeObjectURL(url);
}, 0);
}
+20 -3
View File
@@ -8,6 +8,7 @@ import {
} from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import { QueryClient, useQueryClient } from "@tanstack/react-query";
import { Throttler } from "@tanstack/react-pacer";
import { APP_DISPLAY_NAME } from "../branding";
import { Button } from "../components/ui/button";
@@ -150,6 +151,7 @@ function EventRouter() {
let latestSequence = 0;
let syncing = false;
let pending = false;
let needsProviderInvalidation = false;
const flushSnapshotSync = async (): Promise<void> => {
const snapshot = await api.orchestration.getSnapshot();
@@ -185,7 +187,20 @@ function EventRouter() {
syncing = false;
};
void syncSnapshot().catch(() => undefined);
const domainEventFlushThrottler = new Throttler(
() => {
if (needsProviderInvalidation) {
needsProviderInvalidation = false;
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
}
void syncSnapshot();
},
{
wait: 100,
leading: false,
trailing: true,
},
);
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
if (event.sequence <= latestSequence) {
@@ -193,9 +208,9 @@ function EventRouter() {
}
latestSequence = event.sequence;
if (event.type === "thread.turn-diff-completed" || event.type === "thread.reverted") {
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
needsProviderInvalidation = true;
}
void syncSnapshot();
domainEventFlushThrottler.maybeExecute();
});
const unsubTerminalEvent = api.terminal.onEvent((event) => {
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
@@ -280,6 +295,8 @@ function EventRouter() {
});
return () => {
disposed = true;
needsProviderInvalidation = false;
domainEventFlushThrottler.cancel();
unsubDomainEvent();
unsubTerminalEvent();
unsubWelcome();
+54 -4
View File
@@ -3,8 +3,14 @@ import { useQuery } from "@tanstack/react-query";
import { useCallback, useState } from "react";
import { type ProviderKind } from "@t3tools/contracts";
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
import { ZapIcon } from "lucide-react";
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
import {
APP_SERVICE_TIER_OPTIONS,
MAX_CUSTOM_MODEL_LENGTH,
shouldShowFastTierIcon,
useAppSettings,
} from "../appSettings";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
@@ -12,6 +18,7 @@ import { ensureNativeApi } from "../nativeApi";
import { preferredTerminalEditor } from "../terminal-links";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../components/ui/select";
import { Switch } from "../components/ui/switch";
import { SidebarInset } from "~/components/ui/sidebar";
@@ -96,6 +103,7 @@ function SettingsRouteView() {
const codexBinaryPath = settings.codexBinaryPath;
const codexHomePath = settings.codexHomePath;
const codexServiceTier = settings.codexServiceTier;
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
const openKeybindingsFile = useCallback(() => {
@@ -302,6 +310,43 @@ function SettingsRouteView() {
</div>
<div className="space-y-5">
<label className="block space-y-1">
<span className="text-xs font-medium text-foreground">Default service tier</span>
<Select
items={APP_SERVICE_TIER_OPTIONS.map((option) => ({
label: option.label,
value: option.value,
}))}
value={codexServiceTier}
onValueChange={(value) => {
if (!value) return;
updateSettings({ codexServiceTier: value });
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectPopup alignItemWithTrigger={false}>
{APP_SERVICE_TIER_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
<div className="flex min-w-0 items-center gap-2">
{option.value === "fast" ? (
<ZapIcon className="size-3.5 text-amber-500" />
) : (
<span className="size-3.5 shrink-0" aria-hidden="true" />
)}
<span className="truncate">{option.label}</span>
</div>
</SelectItem>
))}
</SelectPopup>
</Select>
<span className="text-xs text-muted-foreground">
{APP_SERVICE_TIER_OPTIONS.find((option) => option.value === codexServiceTier)
?.description ?? "Use Codex defaults without forcing a service tier."}
</span>
</label>
{MODEL_PROVIDER_SETTINGS.map((providerSettings) => {
const provider = providerSettings.provider;
const customModels = getCustomModelsForProvider(settings, provider);
@@ -400,9 +445,14 @@ function SettingsRouteView() {
key={`${provider}:${slug}`}
className="flex items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2"
>
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
{slug}
</code>
<div className="flex min-w-0 flex-1 items-center gap-2">
{provider === "codex" && shouldShowFastTierIcon(slug, codexServiceTier) ? (
<ZapIcon className="size-3.5 shrink-0 text-amber-500" />
) : null}
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
{slug}
</code>
</div>
<Button
size="xs"
variant="ghost"
+18 -5
View File
@@ -14,6 +14,7 @@ import {
} from "@t3tools/shared/model";
import { create } from "zustand";
import { type ChatMessage, type Project, type Thread } from "./types";
import { Debouncer } from "@tanstack/react-pacer";
// ── State ────────────────────────────────────────────────────────────
@@ -25,7 +26,6 @@ export interface AppState {
const PERSISTED_STATE_KEY = "t3code:renderer-state:v8";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v7",
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
@@ -63,6 +63,8 @@ function readPersistedState(): AppState {
}
}
let legacyKeysCleanedUp = false;
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
@@ -74,13 +76,17 @@ function persistState(state: AppState): void {
.map((project) => project.cwd),
}),
);
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
if (!legacyKeysCleanedUp) {
legacyKeysCleanedUp = true;
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
}
const debouncedPersistState = new Debouncer(persistState, { wait: 500 });
// ── Pure helpers ──────────────────────────────────────────────────────
@@ -395,8 +401,15 @@ export const useStore = create<AppStore>((set) => ({
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
}));
// Persist on every state change
useStore.subscribe((state) => persistState(state));
// Persist state changes with debouncing to avoid localStorage thrashing
useStore.subscribe((state) => debouncedPersistState.maybeExecute(state));
// Flush pending writes synchronously before page unload to prevent data loss.
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
debouncedPersistState.flush();
});
}
export function StoreProvider({ children }: { children: ReactNode }) {
useEffect(() => {
+85 -53
View File
@@ -1,18 +1,12 @@
import {
CommandId,
type ContextMenuItem,
EventId,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
type OrchestrationEvent,
ProjectId,
ThreadId,
type WsPushChannel,
type WsPushData,
type WsPushMessage,
WS_CHANNELS,
WS_METHODS,
type WsPush,
type ServerProviderStatus,
} from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -24,19 +18,12 @@ const showContextMenuFallbackMock = vi.fn<
position?: { x: number; y: number },
) => Promise<T | null>
>();
const channelListeners = new Map<string, Set<(message: WsPush) => void>>();
const latestPushByChannel = new Map<string, WsPush>();
const subscribeMock = vi.fn<
(channel: string, listener: (message: WsPush) => void, options?: { replayLatest?: boolean }) => () => void
>(
(channel, listener, options) => {
const listeners = channelListeners.get(channel) ?? new Set<(message: WsPush) => void>();
const channelListeners = new Map<string, Set<(data: unknown) => void>>();
const subscribeMock = vi.fn<(channel: string, listener: (data: unknown) => void) => () => void>(
(channel, listener) => {
const listeners = channelListeners.get(channel) ?? new Set<(data: unknown) => void>();
listeners.add(listener);
channelListeners.set(channel, listeners);
const latest = latestPushByChannel.get(channel);
if (latest && options?.replayLatest) {
listener(latest);
}
return () => {
listeners.delete(listener);
if (listeners.size === 0) {
@@ -51,9 +38,6 @@ vi.mock("./wsTransport", () => {
WsTransport: class MockWsTransport {
request = requestMock;
subscribe = subscribeMock;
getLatestPush(channel: string) {
return latestPushByChannel.get(channel) ?? null;
}
},
};
});
@@ -62,20 +46,11 @@ vi.mock("./contextMenuFallback", () => ({
showContextMenuFallback: showContextMenuFallbackMock,
}));
let nextPushSequence = 1;
function emitPush<C extends WsPushChannel>(channel: C, data: WsPushData<C>): void {
function emitPush(channel: string, data: unknown): void {
const listeners = channelListeners.get(channel);
const message = {
type: "push" as const,
sequence: nextPushSequence++,
channel,
data,
} as WsPushMessage<C>;
latestPushByChannel.set(channel, message);
if (!listeners) return;
for (const listener of listeners) {
listener(message);
listener(data);
}
}
@@ -105,8 +80,6 @@ beforeEach(() => {
showContextMenuFallbackMock.mockReset();
subscribeMock.mockClear();
channelListeners.clear();
latestPushByChannel.clear();
nextPushSequence = 1;
Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
});
@@ -116,6 +89,7 @@ afterEach(() => {
describe("wsNativeApi", () => {
it("delivers and caches valid server.welcome payloads", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
createWsNativeApi();
@@ -133,6 +107,7 @@ describe("wsNativeApi", () => {
expect(lateListener).toHaveBeenCalledTimes(1);
expect(lateListener).toHaveBeenCalledWith(expect.objectContaining(payload));
expect(warnSpy).not.toHaveBeenCalled();
});
it("preserves bootstrap ids from server.welcome payloads", async () => {
@@ -145,8 +120,8 @@ describe("wsNativeApi", () => {
emitPush(WS_CHANNELS.serverWelcome, {
cwd: "/tmp/workspace",
projectName: "t3-code",
bootstrapProjectId: ProjectId.makeUnsafe("project-1"),
bootstrapThreadId: ThreadId.makeUnsafe("thread-1"),
bootstrapProjectId: "project-1",
bootstrapThreadId: "thread-1",
});
expect(listener).toHaveBeenCalledTimes(1);
@@ -160,26 +135,31 @@ describe("wsNativeApi", () => {
);
});
it("delivers successive server.welcome payloads to active listeners", async () => {
it("ignores invalid server.welcome payloads and keeps subscription active", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
createWsNativeApi();
const listener = vi.fn();
onServerWelcome(listener);
emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/one", projectName: "one" });
emitPush(WS_CHANNELS.serverWelcome, { cwd: 42, projectName: "t3-code" });
emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" });
expect(listener).toHaveBeenCalledTimes(2);
expect(listener).toHaveBeenLastCalledWith(
expect.objectContaining({
cwd: "/tmp/workspace",
projectName: "t3-code",
}),
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({ cwd: "/tmp/workspace", projectName: "t3-code" }),
);
expect(warnSpy).toHaveBeenCalledTimes(1);
expect(warnSpy).toHaveBeenCalledWith("Dropped inbound WebSocket push payload", {
reason: "decode-failed",
raw: { cwd: 42, projectName: "t3-code" },
issue: expect.stringContaining("SchemaError"),
});
});
it("delivers and caches valid server.configUpdated payloads", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi");
createWsNativeApi();
@@ -205,9 +185,11 @@ describe("wsNativeApi", () => {
onServerConfigUpdated(lateListener);
expect(lateListener).toHaveBeenCalledTimes(1);
expect(lateListener).toHaveBeenCalledWith(payload);
expect(warnSpy).not.toHaveBeenCalled();
});
it("delivers successive server.configUpdated payloads to active listeners", async () => {
it("drops malformed server.configUpdated payloads", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi");
createWsNativeApi();
@@ -215,22 +197,24 @@ describe("wsNativeApi", () => {
onServerConfigUpdated(listener);
emitPush(WS_CHANNELS.serverConfigUpdated, {
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
issues: [{ kind: "keybindings.invalid-entry", message: "missing index" }],
providers: defaultProviders,
});
emitPush(WS_CHANNELS.serverConfigUpdated, {
issues: [],
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
providers: defaultProviders,
});
expect(listener).toHaveBeenCalledTimes(2);
expect(listener).toHaveBeenLastCalledWith({
issues: [],
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith({
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
providers: defaultProviders,
});
expect(warnSpy).toHaveBeenCalledTimes(1);
});
it("forwards valid terminal and orchestration events", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const { createWsNativeApi } = await import("./wsNativeApi");
const api = createWsNativeApi();
@@ -251,9 +235,9 @@ describe("wsNativeApi", () => {
const orchestrationEvent = {
sequence: 1,
eventId: EventId.makeUnsafe("event-1"),
eventId: "event-1",
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-1"),
aggregateId: "project-1",
occurredAt: "2026-02-24T00:00:00.000Z",
commandId: null,
causationEventId: null,
@@ -261,7 +245,7 @@ describe("wsNativeApi", () => {
metadata: {},
type: "project.created",
payload: {
projectId: ProjectId.makeUnsafe("project-1"),
projectId: "project-1",
title: "Project",
workspaceRoot: "/tmp/workspace",
defaultModel: null,
@@ -269,13 +253,61 @@ describe("wsNativeApi", () => {
createdAt: "2026-02-24T00:00:00.000Z",
updatedAt: "2026-02-24T00:00:00.000Z",
},
} satisfies Extract<OrchestrationEvent, { type: "project.created" }>;
} as const;
emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, orchestrationEvent);
expect(onTerminalEvent).toHaveBeenCalledTimes(1);
expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
expect(onDomainEvent).toHaveBeenCalledTimes(1);
expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
expect(warnSpy).not.toHaveBeenCalled();
});
it("drops malformed terminal and orchestration push payloads", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const { createWsNativeApi } = await import("./wsNativeApi");
const api = createWsNativeApi();
const onTerminalEvent = vi.fn();
const onDomainEvent = vi.fn();
api.terminal.onEvent(onTerminalEvent);
api.orchestration.onDomainEvent(onDomainEvent);
emitPush(WS_CHANNELS.terminalEvent, {
threadId: "thread-1",
terminalId: "",
createdAt: "2026-02-24T00:00:00.000Z",
type: "output",
data: "hello",
});
emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, {
sequence: -1,
type: "project.created",
});
expect(onTerminalEvent).not.toHaveBeenCalled();
expect(onDomainEvent).not.toHaveBeenCalled();
expect(warnSpy).toHaveBeenCalledTimes(2);
expect(warnSpy).toHaveBeenNthCalledWith(1, "Dropped inbound WebSocket push payload", {
reason: "decode-failed",
raw: {
threadId: "thread-1",
terminalId: "",
createdAt: "2026-02-24T00:00:00.000Z",
type: "output",
data: "hello",
},
issue: expect.stringContaining("SchemaError"),
});
expect(warnSpy).toHaveBeenNthCalledWith(2, "Dropped inbound WebSocket push payload", {
reason: "decode-failed",
raw: {
sequence: -1,
type: "project.created",
},
issue: expect.stringContaining("SchemaError"),
});
});
it("wraps orchestration dispatch commands in the command envelope", async () => {
+45 -15
View File
@@ -1,13 +1,16 @@
import {
OrchestrationEvent,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
type ContextMenuItem,
type NativeApi,
ServerConfigUpdatedPayload,
TerminalEvent,
WS_CHANNELS,
WS_METHODS,
type WsWelcomePayload,
WsWelcomePayload,
} from "@t3tools/contracts";
import { Cause, Schema } from "effect";
import { showContextMenuFallback } from "./contextMenuFallback";
import { WsTransport } from "./wsTransport";
@@ -15,6 +18,24 @@ import { WsTransport } from "./wsTransport";
let instance: { api: NativeApi; transport: WsTransport } | null = null;
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
const serverConfigUpdatedListeners = new Set<(payload: ServerConfigUpdatedPayload) => void>();
let lastWelcome: WsWelcomePayload | null = null;
let lastServerConfigUpdated: ServerConfigUpdatedPayload | null = null;
const decodeAndWarnOnFailure = <T>(
schema: Schema.Schema<T> & { readonly DecodingServices: never },
raw: unknown,
): T | null => {
const decoded = Schema.decodeUnknownExit(schema)(raw);
if (decoded._tag === "Failure") {
console.warn("Dropped inbound WebSocket push payload", {
reason: "decode-failed",
raw,
issue: Cause.pretty(decoded.cause),
});
return null;
}
return decoded.value;
};
/**
* Subscribe to the server welcome message. If a welcome was already received
@@ -24,10 +45,10 @@ const serverConfigUpdatedListeners = new Set<(payload: ServerConfigUpdatedPayloa
export function onServerWelcome(listener: (payload: WsWelcomePayload) => void): () => void {
welcomeListeners.add(listener);
const latestWelcome = instance?.transport.getLatestPush(WS_CHANNELS.serverWelcome)?.data ?? null;
if (latestWelcome) {
// Replay cached welcome for late subscribers
if (lastWelcome) {
try {
listener(latestWelcome);
listener(lastWelcome);
} catch {
// Swallow listener errors
}
@@ -47,10 +68,9 @@ export function onServerConfigUpdated(
): () => void {
serverConfigUpdatedListeners.add(listener);
const latestConfig = instance?.transport.getLatestPush(WS_CHANNELS.serverConfigUpdated)?.data ?? null;
if (latestConfig) {
if (lastServerConfigUpdated) {
try {
listener(latestConfig);
listener(lastServerConfigUpdated);
} catch {
// Swallow listener errors
}
@@ -66,8 +86,12 @@ export function createWsNativeApi(): NativeApi {
const transport = new WsTransport();
transport.subscribe(WS_CHANNELS.serverWelcome, (message) => {
const payload = message.data;
// Listen for server welcome and forward to registered listeners.
// Also cache it so late subscribers (React effects) get it immediately.
transport.subscribe(WS_CHANNELS.serverWelcome, (data) => {
const payload = decodeAndWarnOnFailure(WsWelcomePayload, data);
if (!payload) return;
lastWelcome = payload;
for (const listener of welcomeListeners) {
try {
listener(payload);
@@ -76,8 +100,10 @@ export function createWsNativeApi(): NativeApi {
}
}
});
transport.subscribe(WS_CHANNELS.serverConfigUpdated, (message) => {
const payload = message.data;
transport.subscribe(WS_CHANNELS.serverConfigUpdated, (data) => {
const payload = decodeAndWarnOnFailure(ServerConfigUpdatedPayload, data);
if (!payload) return;
lastServerConfigUpdated = payload;
for (const listener of serverConfigUpdatedListeners) {
try {
listener(payload);
@@ -108,7 +134,10 @@ export function createWsNativeApi(): NativeApi {
restart: (input) => transport.request(WS_METHODS.terminalRestart, input),
close: (input) => transport.request(WS_METHODS.terminalClose, input),
onEvent: (callback) =>
transport.subscribe(WS_CHANNELS.terminalEvent, (message) => callback(message.data)),
transport.subscribe(WS_CHANNELS.terminalEvent, (data) => {
const payload = decodeAndWarnOnFailure(TerminalEvent, data);
if (payload) callback(payload);
}),
},
projects: {
searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
@@ -167,9 +196,10 @@ export function createWsNativeApi(): NativeApi {
replayEvents: (fromSequenceExclusive) =>
transport.request(ORCHESTRATION_WS_METHODS.replayEvents, { fromSequenceExclusive }),
onDomainEvent: (callback) =>
transport.subscribe(ORCHESTRATION_WS_CHANNELS.domainEvent, (message) =>
callback(message.data),
),
transport.subscribe(ORCHESTRATION_WS_CHANNELS.domainEvent, (data) => {
const payload = decodeAndWarnOnFailure(OrchestrationEvent, data);
if (payload) callback(payload);
}),
},
};
+17 -57
View File
@@ -1,4 +1,3 @@
import { WS_CHANNELS } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { WsTransport } from "./wsTransport";
@@ -91,24 +90,18 @@ describe("WsTransport", () => {
socket.open();
const listener = vi.fn();
transport.subscribe(WS_CHANNELS.serverConfigUpdated, listener);
transport.subscribe("providers.event", listener);
socket.serverMessage(
JSON.stringify({
type: "push",
sequence: 1,
channel: WS_CHANNELS.serverConfigUpdated,
data: { issues: [], providers: [] },
channel: "providers.event",
data: { status: "ok" },
}),
);
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith({
type: "push",
sequence: 1,
channel: WS_CHANNELS.serverConfigUpdated,
data: { issues: [], providers: [] },
});
expect(listener).toHaveBeenCalledWith({ status: "ok" });
transport.dispose();
});
@@ -144,13 +137,12 @@ describe("WsTransport", () => {
socket.open();
const listener = vi.fn();
transport.subscribe(WS_CHANNELS.serverConfigUpdated, listener);
transport.subscribe("providers.event", listener);
socket.serverMessage("{ invalid-json");
socket.serverMessage(
JSON.stringify({
type: "push",
sequence: 2,
channel: 42,
data: { bad: true },
}),
@@ -158,58 +150,26 @@ describe("WsTransport", () => {
socket.serverMessage(
JSON.stringify({
type: "push",
sequence: 3,
channel: WS_CHANNELS.serverConfigUpdated,
data: { issues: [], providers: [] },
channel: "providers.event",
data: { ok: true },
}),
);
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith({
type: "push",
sequence: 3,
channel: WS_CHANNELS.serverConfigUpdated,
data: { issues: [], providers: [] },
});
expect(listener).toHaveBeenCalledWith({ ok: true });
expect(warnSpy).toHaveBeenCalledTimes(2);
expect(warnSpy).toHaveBeenNthCalledWith(
1,
"Dropped inbound WebSocket envelope",
expect.objectContaining({
code: "invalid-json",
reason: expect.stringContaining("Expected property name or '}'"),
rawKind: "string",
}),
);
expect(warnSpy).toHaveBeenNthCalledWith(1, "Dropped inbound WebSocket envelope", {
reason: "decode-failed",
issue:
"SchemaError: SyntaxError: Expected property name or '}' in JSON at position 2 (line 1 column 3)",
raw: "{ invalid-json",
});
expect(warnSpy).toHaveBeenNthCalledWith(2, "Dropped inbound WebSocket envelope", {
code: "invalid-envelope",
reason: expect.stringContaining("Expected"),
rawKind: "object",
expected: "WsResponse",
actual: "object",
reason: "decode-failed",
issue: expect.stringContaining("SchemaError: Expected string, got 42"),
raw: '{"type":"push","channel":42,"data":{"bad":true}}',
});
transport.dispose();
});
it("queues requests until the websocket opens", async () => {
const transport = new WsTransport("ws://localhost:3020");
const socket = getSocket();
const requestPromise = transport.request("projects.list");
expect(socket.sent).toHaveLength(0);
socket.open();
expect(socket.sent).toHaveLength(1);
const requestEnvelope = JSON.parse(socket.sent[0] ?? "{}") as { id: string };
socket.serverMessage(
JSON.stringify({
id: requestEnvelope.id,
result: { projects: [] },
}),
);
await expect(requestPromise).resolves.toEqual({ projects: [] });
transport.dispose();
});
});
+55 -204
View File
@@ -1,15 +1,7 @@
import {
type WsDecodeDiagnostic,
type WsPush,
type WsPushChannel,
type WsPushMessage,
WebSocketResponse,
type WsResponse as WsResponseMessage,
WsResponse as WsResponseSchema,
} from "@t3tools/contracts";
import { Schema, SchemaIssue } from "effect";
import { WebSocketResponse, WsPush, WsResponse } from "@t3tools/contracts";
import { Cause, Schema } from "effect";
type PushListener<C extends WsPushChannel> = (message: WsPushMessage<C>) => void;
type PushListener = (data: unknown) => void;
interface PendingRequest {
resolve: (result: unknown) => void;
@@ -17,20 +9,12 @@ interface PendingRequest {
timeout: ReturnType<typeof setTimeout>;
}
interface SubscribeOptions {
readonly replayLatest?: boolean;
}
type TransportState = "connecting" | "open" | "reconnecting" | "closed" | "disposed";
const REQUEST_TIMEOUT_MS = 60_000;
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
const decodeWsResponse = Schema.decodeUnknownSync(WsResponseSchema);
const decodeWsResponseFromJson = Schema.decodeUnknownExit(Schema.fromJsonString(WsResponse));
const isWsPushEnvelope = Schema.is(WsPush);
const isWebSocketResponseEnvelope = Schema.is(WebSocketResponse);
const isWsPushMessage = (value: WsResponseMessage): value is WsPush =>
"type" in value && value.type === "push";
interface WsRequestEnvelope {
id: string;
body: {
@@ -39,106 +23,20 @@ interface WsRequestEnvelope {
};
}
function describeValue(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
return typeof value;
}
function parseJsonOffset(error: unknown): number | undefined {
if (!(error instanceof Error)) {
return undefined;
}
const match = /position\s+(\d+)/i.exec(error.message);
if (!match) {
return undefined;
}
const parsed = Number(match[1]);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
}
function makeEnvelopeDiagnostic(raw: unknown, reason: string): WsDecodeDiagnostic {
return {
code: "invalid-envelope",
reason,
rawKind: describeValue(raw),
expected: "WsResponse",
actual: describeValue(raw),
};
}
function decodeInboundMessage(
raw: unknown,
): { readonly ok: true; readonly message: WsResponseMessage } | { readonly ok: false; readonly diagnostic: WsDecodeDiagnostic } {
if (typeof raw !== "string") {
return {
ok: false,
diagnostic: {
code: "invalid-envelope",
reason: "Expected a text WebSocket frame.",
rawKind: describeValue(raw),
expected: "string",
actual: describeValue(raw),
},
};
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (error) {
return {
ok: false,
diagnostic: {
code: "invalid-json",
reason: error instanceof Error ? error.message : "Failed to parse JSON.",
rawKind: "string",
expected: "valid JSON string",
actual: raw,
...(parseJsonOffset(error) !== undefined ? { jsonOffset: parseJsonOffset(error) } : {}),
},
};
}
try {
return { ok: true, message: decodeWsResponse(parsed) };
} catch (error) {
return {
ok: false,
diagnostic: makeEnvelopeDiagnostic(
parsed,
typeof error === "object" && error !== null && "issue" in error
? SchemaIssue.makeFormatterDefault()((error as Schema.SchemaError).issue)
: error instanceof Error
? error.message
: "Failed to decode WebSocket envelope.",
),
};
}
}
function asError(value: unknown, fallback: string): Error {
if (value instanceof Error) {
return value;
}
return new Error(fallback);
}
export class WsTransport {
private ws: WebSocket | null = null;
private nextId = 1;
private readonly pending = new Map<string, PendingRequest>();
private readonly listeners = new Map<string, Set<(message: WsPush) => void>>();
private readonly latestPushByChannel = new Map<string, WsPush>();
private readonly outboundQueue: string[] = [];
private readonly listeners = new Map<string, Set<PushListener>>();
private reconnectAttempt = 0;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private disposed = false;
private state: TransportState = "connecting";
private readonly url: string;
constructor(url?: string) {
const bridgeUrl = window.desktopBridge?.getWsUrl();
// In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.
// In production, the page is served by the WS server on the same host:port.
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
this.url =
url ??
@@ -146,7 +44,7 @@ export class WsTransport {
? bridgeUrl
: envUrl && envUrl.length > 0
? envUrl
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`);
: `ws://${window.location.hostname}:${window.location.port}`);
this.connect();
}
@@ -154,11 +52,9 @@ export class WsTransport {
if (typeof method !== "string" || method.length === 0) {
throw new Error("Request method is required");
}
const id = String(this.nextId++);
const body = params != null ? { ...params, _tag: method } : { _tag: method };
const message: WsRequestEnvelope = { id, body };
const encoded = JSON.stringify(message);
return new Promise<T>((resolve, reject) => {
const timeout = setTimeout(() => {
@@ -172,53 +68,28 @@ export class WsTransport {
timeout,
});
this.send(encoded);
this.send(message);
});
}
subscribe<C extends WsPushChannel>(
channel: C,
listener: PushListener<C>,
options?: SubscribeOptions,
): () => void {
subscribe(channel: string, listener: PushListener): () => void {
let channelListeners = this.listeners.get(channel);
if (!channelListeners) {
channelListeners = new Set<(message: WsPush) => void>();
channelListeners = new Set();
this.listeners.set(channel, channelListeners);
}
const wrappedListener = (message: WsPush) => {
listener(message as WsPushMessage<C>);
};
channelListeners.add(wrappedListener);
if (options?.replayLatest) {
const latest = this.latestPushByChannel.get(channel);
if (latest) {
wrappedListener(latest);
}
}
channelListeners.add(listener);
return () => {
channelListeners?.delete(wrappedListener);
if (channelListeners?.size === 0) {
channelListeners!.delete(listener);
if (channelListeners!.size === 0) {
this.listeners.delete(channel);
}
};
}
getLatestPush<C extends WsPushChannel>(channel: C): WsPushMessage<C> | null {
const latest = this.latestPushByChannel.get(channel);
return latest ? (latest as WsPushMessage<C>) : null;
}
getState(): TransportState {
return this.state;
}
dispose() {
this.disposed = true;
this.state = "disposed";
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
@@ -228,24 +99,18 @@ export class WsTransport {
pending.reject(new Error("Transport disposed"));
}
this.pending.clear();
this.outboundQueue.length = 0;
this.ws?.close();
this.ws = null;
}
private connect() {
if (this.disposed) {
return;
}
if (this.disposed) return;
this.state = this.reconnectAttempt > 0 ? "reconnecting" : "connecting";
const ws = new WebSocket(this.url);
ws.addEventListener("open", () => {
this.ws = ws;
this.state = "open";
this.reconnectAttempt = 0;
this.flushQueue();
});
ws.addEventListener("message", (event) => {
@@ -253,37 +118,34 @@ export class WsTransport {
});
ws.addEventListener("close", () => {
if (this.ws === ws) {
this.ws = null;
}
if (this.disposed) {
this.state = "disposed";
return;
}
this.state = "closed";
this.ws = null;
this.scheduleReconnect();
});
ws.addEventListener("error", () => {
// close will follow
// close event will fire after error
});
}
private handleMessage(raw: unknown) {
const decoded = decodeInboundMessage(raw);
if (!decoded.ok) {
console.warn("Dropped inbound WebSocket envelope", decoded.diagnostic);
const exit = decodeWsResponseFromJson(raw);
if (exit._tag === "Failure") {
console.warn("Dropped inbound WebSocket envelope", {
reason: "decode-failed",
raw,
issue: Cause.pretty(exit.cause),
});
return;
}
const message = exit.value;
const message = decoded.message;
if (isWsPushMessage(message)) {
this.latestPushByChannel.set(message.channel, message);
// Push event
if (isWsPushEnvelope(message)) {
const channelListeners = this.listeners.get(message.channel);
if (channelListeners) {
for (const listener of channelListeners) {
try {
listener(message);
listener(message.data);
} catch {
// Swallow listener errors
}
@@ -292,68 +154,57 @@ export class WsTransport {
return;
}
// Response to a request
if (!isWebSocketResponseEnvelope(message)) {
return;
}
const pending = this.pending.get(message.id);
if (!pending) {
return;
}
if (!pending) return;
clearTimeout(pending.timeout);
this.pending.delete(message.id);
if (message.error) {
pending.reject(new Error(message.error.message));
return;
}
pending.resolve(message.result);
}
private send(encodedMessage: string) {
if (this.disposed) {
return;
}
this.outboundQueue.push(encodedMessage);
try {
this.flushQueue();
} catch {
// Swallow: flushQueue has queued the message for retry on reconnect
} else {
pending.resolve(message.result);
}
}
private flushQueue() {
if (this.ws?.readyState !== WebSocket.OPEN) {
private send(message: WsRequestEnvelope) {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(message));
return;
}
while (this.outboundQueue.length > 0) {
const message = this.outboundQueue.shift();
if (!message) {
continue;
}
try {
this.ws.send(message);
} catch (error) {
this.outboundQueue.unshift(message);
throw asError(error, "Failed to send WebSocket request.");
}
}
// If not connected, wait for connection
const waitForOpen = () => {
const check = setInterval(() => {
if (this.disposed) {
clearInterval(check);
return;
}
if (this.ws?.readyState === WebSocket.OPEN) {
clearInterval(check);
this.ws.send(JSON.stringify(message));
}
}, 50);
// Give up after timeout (the pending request will time out on its own)
setTimeout(() => clearInterval(check), REQUEST_TIMEOUT_MS);
};
waitForOpen();
}
private scheduleReconnect() {
if (this.disposed || this.reconnectTimer !== null) {
return;
}
if (this.disposed) return;
const delay =
RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)] ??
RECONNECT_DELAYS_MS[0]!;
this.reconnectAttempt += 1;
this.reconnectAttempt++;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.connect();
-9
View File
@@ -4,14 +4,6 @@ import { tanstackRouter } from "@tanstack/router-plugin/vite";
import { defineConfig } from "vite";
const port = Number(process.env.PORT ?? 5733);
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
const buildSourcemap =
sourcemapEnv === "0" || sourcemapEnv === "false"
? false
: sourcemapEnv === "hidden"
? "hidden"
: true;
export default defineConfig({
plugins: [
@@ -50,6 +42,5 @@ export default defineConfig({
build: {
outDir: "dist",
emptyOutDir: true,
sourcemap: buildSourcemap,
},
});
+4 -4
View File
@@ -14,7 +14,7 @@
},
"apps/desktop": {
"name": "@t3tools/desktop",
"version": "0.0.9",
"version": "0.0.4-alpha.1",
"dependencies": {
"effect": "catalog:",
"electron": "40.6.0",
@@ -43,7 +43,7 @@
},
"apps/server": {
"name": "t3",
"version": "0.0.9",
"version": "0.0.4-alpha.1",
"bin": {
"t3": "./dist/index.mjs",
},
@@ -72,7 +72,7 @@
},
"apps/web": {
"name": "@t3tools/web",
"version": "0.0.9",
"version": "0.0.4-alpha.1",
"dependencies": {
"@base-ui/react": "^1.2.0",
"@lexical/react": "^0.41.0",
@@ -116,7 +116,7 @@
},
"packages/contracts": {
"name": "@t3tools/contracts",
"version": "0.0.9",
"version": "0.0.4-alpha.1",
"dependencies": {
"effect": "catalog:",
},
-3
View File
@@ -36,9 +36,6 @@ This document covers how to run desktop releases from one tag, first without sig
- platform installers (`.exe`, `.dmg`, `.AppImage`, plus macOS `.zip` for Squirrel.Mac update payloads)
- `latest*.yml` metadata
- `*.blockmap` files (used for differential downloads)
- macOS metadata note:
- `electron-updater` reads `latest-mac.yml` for both Intel and Apple Silicon.
- The workflow merges the per-arch mac manifests into one `latest-mac.yml` before publishing the GitHub Release.
## 0) npm OIDC trusted publishing setup (CLI)
-1
View File
@@ -45,7 +45,6 @@
"dist:desktop:dmg:x64": "node scripts/build-desktop-artifact.ts --platform mac --target dmg --arch x64",
"dist:desktop:linux": "node scripts/build-desktop-artifact.ts --platform linux --target AppImage --arch x64",
"dist:desktop:win": "node scripts/build-desktop-artifact.ts --platform win --target nsis --arch x64",
"release:smoke": "node scripts/release-smoke.ts",
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo",
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.9",
"version": "0.0.4-alpha.1",
"private": true,
"files": [
"dist"
-11
View File
@@ -58,21 +58,10 @@ export type DesktopUpdateStatus =
| "downloaded"
| "error";
export type DesktopRuntimeArch = "arm64" | "x64" | "other";
export interface DesktopRuntimeInfo {
hostArch: DesktopRuntimeArch;
appArch: DesktopRuntimeArch;
runningUnderArm64Translation: boolean;
}
export interface DesktopUpdateState {
enabled: boolean;
status: DesktopUpdateStatus;
currentVersion: string;
hostArch: DesktopRuntimeArch;
appArch: DesktopRuntimeArch;
runningUnderArm64Translation: boolean;
availableVersion: string | null;
downloadedVersion: string | null;
downloadPercent: number | null;
+123 -10
View File
@@ -42,14 +42,9 @@ export const ProviderSandboxMode = Schema.Literals([
"danger-full-access",
]);
export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
export const ProviderServiceTier = Schema.Literals(["fast", "flex"]);
export type ProviderServiceTier = typeof ProviderServiceTier.Type;
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
const CodexProviderStartOptions = Schema.Struct({
binaryPath: Schema.optional(TrimmedNonEmptyString),
homePath: Schema.optional(TrimmedNonEmptyString),
});
const ProviderStartOptions = Schema.Struct({
codex: Schema.optional(CodexProviderStartOptions),
});
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
export type RuntimeMode = typeof RuntimeMode.Type;
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
@@ -369,8 +364,8 @@ export const ThreadTurnStartCommand = Schema.Struct({
}),
provider: Schema.optional(ProviderKind),
model: Schema.optional(TrimmedNonEmptyString),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
providerOptions: Schema.optional(ProviderStartOptions),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
interactionMode: ProviderInteractionMode.pipe(
@@ -391,8 +386,8 @@ const ClientThreadTurnStartCommand = Schema.Struct({
}),
provider: Schema.optional(ProviderKind),
model: Schema.optional(TrimmedNonEmptyString),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
providerOptions: Schema.optional(ProviderStartOptions),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
@@ -671,8 +666,8 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
messageId: MessageId,
provider: Schema.optional(ProviderKind),
model: Schema.optional(TrimmedNonEmptyString),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
providerOptions: Schema.optional(ProviderStartOptions),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
interactionMode: ProviderInteractionMode.pipe(
@@ -764,6 +759,20 @@ const EventBaseFields = {
metadata: OrchestrationEventMetadata,
} as const;
const PersistedEventBaseFields = {
sequence: NonNegativeInt,
eventId: EventId,
aggregateKind: OrchestrationAggregateKind,
streamId: Schema.Union([ProjectId, ThreadId]),
streamVersion: NonNegativeInt,
occurredAt: IsoDateTime,
commandId: Schema.NullOr(CommandId),
causationEventId: Schema.NullOr(EventId),
correlationId: Schema.NullOr(CommandId),
actorKind: OrchestrationActorKind,
metadata: OrchestrationEventMetadata,
} as const;
export const OrchestrationEvent = Schema.Union([
Schema.Struct({
...EventBaseFields,
@@ -868,6 +877,110 @@ export const OrchestrationEvent = Schema.Union([
]);
export type OrchestrationEvent = typeof OrchestrationEvent.Type;
export const OrchestrationPersistedEvent = Schema.Union([
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("project.created"),
payload: ProjectCreatedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("project.meta-updated"),
payload: ProjectMetaUpdatedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("project.deleted"),
payload: ProjectDeletedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.created"),
payload: ThreadCreatedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.deleted"),
payload: ThreadDeletedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.meta-updated"),
payload: ThreadMetaUpdatedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.runtime-mode-set"),
payload: ThreadRuntimeModeSetPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.interaction-mode-set"),
payload: ThreadInteractionModeSetPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.message-sent"),
payload: ThreadMessageSentPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.turn-start-requested"),
payload: ThreadTurnStartRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.turn-interrupt-requested"),
payload: ThreadTurnInterruptRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.approval-response-requested"),
payload: ThreadApprovalResponseRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.user-input-response-requested"),
payload: ThreadUserInputResponseRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.checkpoint-revert-requested"),
payload: ThreadCheckpointRevertRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.reverted"),
payload: ThreadRevertedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.session-stop-requested"),
payload: ThreadSessionStopRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.session-set"),
payload: ThreadSessionSetPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.proposed-plan-upserted"),
payload: ThreadProposedPlanUpsertedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.turn-diff-completed"),
payload: ThreadTurnDiffCompletedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.activity-appended"),
payload: ThreadActivityAppendedPayload,
}),
]);
export type OrchestrationPersistedEvent = typeof OrchestrationPersistedEvent.Type;
export const OrchestrationCommandReceiptStatus = Schema.Literals(["accepted", "rejected"]);
export type OrchestrationCommandReceiptStatus = typeof OrchestrationCommandReceiptStatus.Type;
+4 -2
View File
@@ -19,6 +19,7 @@ import {
ProviderKind,
ProviderRequestKind,
ProviderSandboxMode,
ProviderServiceTier,
ProviderUserInputAnswers,
RuntimeMode,
} from "./orchestration";
@@ -52,10 +53,9 @@ const CodexProviderStartOptions = Schema.Struct({
homePath: Schema.optional(TrimmedNonEmptyStringSchema),
});
export const ProviderStartOptions = Schema.Struct({
const ProviderStartOptions = Schema.Struct({
codex: Schema.optional(CodexProviderStartOptions),
});
export type ProviderStartOptions = typeof ProviderStartOptions.Type;
export const ProviderSessionStartInput = Schema.Struct({
threadId: ThreadId,
@@ -64,6 +64,7 @@ export const ProviderSessionStartInput = Schema.Struct({
model: Schema.optional(TrimmedNonEmptyStringSchema),
modelOptions: Schema.optional(ProviderModelOptions),
resumeCursor: Schema.optional(Schema.Unknown),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
approvalPolicy: Schema.optional(ProviderApprovalPolicy),
sandboxMode: Schema.optional(ProviderSandboxMode),
providerOptions: Schema.optional(ProviderStartOptions),
@@ -80,6 +81,7 @@ export const ProviderSendTurnInput = Schema.Struct({
Schema.Array(ChatAttachment).check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS)),
),
model: Schema.optional(TrimmedNonEmptyStringSchema),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
interactionMode: Schema.optional(ProviderInteractionMode),
});
+2 -43
View File
@@ -1,11 +1,10 @@
import { assert, it } from "@effect/vitest";
import { Effect, Schema } from "effect";
import { ORCHESTRATION_WS_CHANNELS, ORCHESTRATION_WS_METHODS } from "./orchestration";
import { WebSocketRequest, WsResponse, WS_CHANNELS } from "./ws";
import { ORCHESTRATION_WS_METHODS } from "./orchestration";
import { WebSocketRequest } from "./ws";
const decodeWebSocketRequest = Schema.decodeUnknownEffect(WebSocketRequest);
const decodeWsResponse = Schema.decodeUnknownEffect(WsResponse);
it.effect("accepts getTurnDiff requests when fromTurnCount <= toTurnCount", () =>
Effect.gen(function* () {
@@ -57,43 +56,3 @@ it.effect("trims websocket request id and nested orchestration ids", () =>
}
}),
);
it.effect("accepts typed websocket push envelopes with sequence", () =>
Effect.gen(function* () {
const parsed = yield* decodeWsResponse({
type: "push",
sequence: 1,
channel: WS_CHANNELS.serverWelcome,
data: {
cwd: "/tmp/workspace",
projectName: "workspace",
},
});
if (!("type" in parsed) || parsed.type !== "push") {
assert.fail("expected websocket response to decode as a push envelope");
}
assert.strictEqual(parsed.type, "push");
assert.strictEqual(parsed.sequence, 1);
assert.strictEqual(parsed.channel, WS_CHANNELS.serverWelcome);
}),
);
it.effect("rejects push envelopes when channel payload does not match the channel schema", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
decodeWsResponse({
type: "push",
sequence: 2,
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
data: {
cwd: "/tmp/workspace",
projectName: "workspace",
},
}),
);
assert.strictEqual(result._tag, "Failure");
}),
);
+14 -89
View File
@@ -1,10 +1,8 @@
import { Schema, Struct } from "effect";
import { NonNegativeInt, ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas";
import { ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas";
import {
ClientOrchestrationCommand,
OrchestrationEvent,
ORCHESTRATION_WS_CHANNELS,
OrchestrationGetFullThreadDiffInput,
ORCHESTRATION_WS_METHODS,
OrchestrationGetSnapshotInput,
@@ -25,7 +23,6 @@ import {
import {
TerminalClearInput,
TerminalCloseInput,
TerminalEvent,
TerminalOpenInput,
TerminalResizeInput,
TerminalRestartInput,
@@ -34,7 +31,6 @@ import {
import { KeybindingRule } from "./keybindings";
import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project";
import { OpenInEditorInput } from "./editor";
import { ServerConfigUpdatedPayload } from "./server";
// ── WebSocket RPC Method Names ───────────────────────────────────────
@@ -152,8 +148,19 @@ export const WebSocketResponse = Schema.Struct({
});
export type WebSocketResponse = typeof WebSocketResponse.Type;
export const WsPushSequence = NonNegativeInt;
export type WsPushSequence = typeof WsPushSequence.Type;
export const WsPush = Schema.Struct({
type: Schema.Literal("push"),
channel: TrimmedNonEmptyString,
data: Schema.Unknown,
});
export type WsPush = typeof WsPush.Type;
// ── Union of all server → client messages ─────────────────────────────
export const WsResponse = Schema.Union([WebSocketResponse, WsPush]);
export type WsResponse = typeof WsResponse.Type;
// ── Server welcome payload ───────────────────────────────────────────
export const WsWelcomePayload = Schema.Struct({
cwd: TrimmedNonEmptyString,
@@ -162,85 +169,3 @@ export const WsWelcomePayload = Schema.Struct({
bootstrapThreadId: Schema.optional(ThreadId),
});
export type WsWelcomePayload = typeof WsWelcomePayload.Type;
export const WsDecodeDiagnosticCode = Schema.Literals([
"invalid-json",
"invalid-envelope",
"invalid-request",
"invalid-response",
]);
export type WsDecodeDiagnosticCode = typeof WsDecodeDiagnosticCode.Type;
export const WsDecodeDiagnostic = Schema.Struct({
code: WsDecodeDiagnosticCode,
reason: TrimmedNonEmptyString,
rawKind: Schema.optional(TrimmedNonEmptyString),
expected: Schema.optional(TrimmedNonEmptyString),
actual: Schema.optional(TrimmedNonEmptyString),
path: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
jsonOffset: Schema.optional(NonNegativeInt),
});
export type WsDecodeDiagnostic = typeof WsDecodeDiagnostic.Type;
export interface WsPushPayloadByChannel {
readonly [WS_CHANNELS.serverWelcome]: WsWelcomePayload;
readonly [WS_CHANNELS.serverConfigUpdated]: typeof ServerConfigUpdatedPayload.Type;
readonly [WS_CHANNELS.terminalEvent]: typeof TerminalEvent.Type;
readonly [ORCHESTRATION_WS_CHANNELS.domainEvent]: OrchestrationEvent;
}
export type WsPushChannel = keyof WsPushPayloadByChannel;
export type WsPushData<C extends WsPushChannel> = WsPushPayloadByChannel[C];
const makeWsPushSchema = <const Channel extends string, Payload extends Schema.Schema<any>>(
channel: Channel,
payload: Payload,
) =>
Schema.Struct({
type: Schema.Literal("push"),
sequence: WsPushSequence,
channel: Schema.Literal(channel),
data: payload,
});
export const WsPushServerWelcome = makeWsPushSchema(WS_CHANNELS.serverWelcome, WsWelcomePayload);
export const WsPushServerConfigUpdated = makeWsPushSchema(
WS_CHANNELS.serverConfigUpdated,
ServerConfigUpdatedPayload,
);
export const WsPushTerminalEvent = makeWsPushSchema(WS_CHANNELS.terminalEvent, TerminalEvent);
export const WsPushOrchestrationDomainEvent = makeWsPushSchema(
ORCHESTRATION_WS_CHANNELS.domainEvent,
OrchestrationEvent,
);
export const WsPushChannelSchema = Schema.Literals([
WS_CHANNELS.serverWelcome,
WS_CHANNELS.serverConfigUpdated,
WS_CHANNELS.terminalEvent,
ORCHESTRATION_WS_CHANNELS.domainEvent,
]);
export type WsPushChannelSchema = typeof WsPushChannelSchema.Type;
export const WsPush = Schema.Union([
WsPushServerWelcome,
WsPushServerConfigUpdated,
WsPushTerminalEvent,
WsPushOrchestrationDomainEvent,
]);
export type WsPush = typeof WsPush.Type;
export type WsPushMessage<C extends WsPushChannel> = Extract<WsPush, { channel: C }>;
export const WsPushEnvelopeBase = Schema.Struct({
type: Schema.Literal("push"),
sequence: WsPushSequence,
channel: WsPushChannelSchema,
data: Schema.Unknown,
});
export type WsPushEnvelopeBase = typeof WsPushEnvelopeBase.Type;
// ── Union of all server → client messages ─────────────────────────────
export const WsResponse = Schema.Union([WebSocketResponse, WsPush]);
export type WsResponse = typeof WsResponse.Type;
-4
View File
@@ -23,10 +23,6 @@
"./Net": {
"types": "./src/Net.ts",
"import": "./src/Net.ts"
},
"./DrainableWorker": {
"types": "./src/DrainableWorker.ts",
"import": "./src/DrainableWorker.ts"
}
},
"scripts": {
@@ -1,76 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { Deferred, Effect, Exit, Scope } from "effect";
import { makeDrainableWorker } from "./DrainableWorker";
describe("makeDrainableWorker", () => {
let scope: Scope.Closeable | null = null;
afterEach(async () => {
if (scope) {
await Effect.runPromise(Scope.close(scope, Exit.void));
}
scope = null;
});
it("waits for work enqueued during active processing before draining", async () => {
scope = await Effect.runPromise(Scope.make("sequential"));
const processed: string[] = [];
const { worker, firstStarted, releaseFirst, secondStarted, releaseSecond } =
await Effect.runPromise(
Effect.gen(function* () {
const firstStarted = yield* Deferred.make<void>();
const releaseFirst = yield* Deferred.make<void>();
const secondStarted = yield* Deferred.make<void>();
const releaseSecond = yield* Deferred.make<void>();
const worker = yield* makeDrainableWorker((item: string) =>
Effect.gen(function* () {
if (item === "first") {
yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
yield* Deferred.await(releaseFirst);
}
if (item === "second") {
yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie);
yield* Deferred.await(releaseSecond);
}
processed.push(item);
}),
);
return {
worker,
firstStarted,
releaseFirst,
secondStarted,
releaseSecond,
};
}).pipe(Scope.provide(scope)),
);
await Effect.runPromise(worker.enqueue("first"));
await Effect.runPromise(Deferred.await(firstStarted));
const drainPromise = Effect.runPromise(worker.drain);
await Effect.runPromise(worker.enqueue("second"));
await Effect.runPromise(Deferred.succeed(releaseFirst, undefined));
await Effect.runPromise(Deferred.await(secondStarted));
const earlyResult = await Promise.race([
drainPromise.then(() => "resolved" as const),
new Promise<"pending">((resolve) => {
setTimeout(() => resolve("pending"), 20);
}),
]);
expect(earlyResult).toBe("pending");
await Effect.runPromise(Deferred.succeed(releaseSecond, undefined));
await drainPromise;
expect(processed).toEqual(["first", "second"]);
});
});
-82
View File
@@ -1,82 +0,0 @@
/**
* DrainableWorker - A queue-based worker that exposes a `drain()` effect.
*
* Wraps the common `Queue.unbounded` + `Effect.forever` pattern and adds
* a signal that resolves when the queue is empty **and** the current item
* has finished processing. This lets tests replace timing-sensitive
* `Effect.sleep` calls with deterministic `drain()`.
*
* @module DrainableWorker
*/
import { Effect, Queue, Ref, Schedule } from "effect";
import type { Scope } from "effect";
export interface DrainableWorker<A> {
/**
* Enqueue a work item and track it for `drain()`.
*
* This wraps `Queue.offer` so drain state is updated atomically with the
* enqueue path instead of inferring it from queue internals.
*/
readonly enqueue: (item: A) => Effect.Effect<void>;
/**
* Resolves when the queue is empty and the worker is idle (not processing).
*
* Uses a tight `Schedule.spaced("1 millis")` poll which resolves in
* microseconds in practice — intended for test use only.
*/
readonly drain: Effect.Effect<void>;
}
/**
* Create a drainable worker that processes items from an unbounded queue.
*
* The worker is forked into the current scope and will be interrupted when
* the scope closes. A finalizer shuts down the queue.
*
* @param process - The effect to run for each queued item.
* @returns A `DrainableWorker` with `queue` and `drain`.
*/
export const makeDrainableWorker = <A, E, R>(
process: (item: A) => Effect.Effect<void, E, R>,
): Effect.Effect<DrainableWorker<A>, never, Scope.Scope | R> =>
Effect.gen(function* () {
const queue = yield* Queue.unbounded<A>();
const outstanding = yield* Ref.make(0);
yield* Effect.addFinalizer(() => Queue.shutdown(queue).pipe(Effect.asVoid));
yield* Effect.forkScoped(
Effect.forever(
Queue.take(queue).pipe(
Effect.flatMap((item) =>
process(item).pipe(
Effect.ensuring(Ref.update(outstanding, (count) => Math.max(0, count - 1))),
),
),
),
),
);
const enqueue: DrainableWorker<A>["enqueue"] = (item) =>
Ref.update(outstanding, (count) => count + 1).pipe(
Effect.flatMap(() => Queue.offer(queue, item)),
Effect.flatMap((accepted) =>
accepted === false
? Ref.update(outstanding, (count) => Math.max(0, count - 1))
: Effect.void,
),
Effect.asVoid,
);
const drain: DrainableWorker<A>["drain"] = Ref.get(outstanding).pipe(
Effect.repeat({
while: (count) => count > 0,
schedule: Schedule.spaced("1 millis"),
}),
Effect.asVoid,
);
return { enqueue, drain } satisfies DrainableWorker<A>;
});
-6
View File
@@ -580,8 +580,6 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
ChildProcess.make({
cwd: repoRoot,
...commandOutputOptions(options.verbose),
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun run build:desktop`,
);
}
@@ -644,8 +642,6 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
ChildProcess.make({
cwd: stageAppDir,
...commandOutputOptions(options.verbose),
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun install --production`,
);
@@ -684,8 +680,6 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
cwd: stageAppDir,
env: buildEnv,
...commandOutputOptions(options.verbose),
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
})`bunx electron-builder ${platformConfig.cliFlag} --${options.arch} --publish never`,
);
-2
View File
@@ -455,8 +455,6 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
stderr: "inherit",
env,
extendEnv: false,
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
// Keep turbo in the same process group so terminal signals (Ctrl+C)
// reach it directly. Effect defaults to detached: true on non-Windows,
// which would put turbo in a new group and require manual forwarding.
-108
View File
@@ -1,108 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import {
mergeMacUpdateManifests,
parseMacUpdateManifest,
serializeMacUpdateManifest,
} from "./merge-mac-update-manifests.ts";
describe("merge-mac-update-manifests", () => {
it("merges arm64 and x64 macOS update manifests into one multi-arch manifest", () => {
const arm64 = parseMacUpdateManifest(
`version: 0.0.4
files:
- url: T3-Code-0.0.4-arm64.zip
sha512: arm64zip
size: 125621344
- url: T3-Code-0.0.4-arm64.dmg
sha512: arm64dmg
size: 131754935
path: T3-Code-0.0.4-arm64.zip
sha512: arm64zip
releaseDate: '2026-03-07T10:32:14.587Z'
`,
"latest-mac.yml",
);
const x64 = parseMacUpdateManifest(
`version: 0.0.4
files:
- url: T3-Code-0.0.4-x64.zip
sha512: x64zip
size: 132000112
- url: T3-Code-0.0.4-x64.dmg
sha512: x64dmg
size: 138148807
path: T3-Code-0.0.4-x64.zip
sha512: x64zip
releaseDate: '2026-03-07T10:36:07.540Z'
`,
"latest-mac-x64.yml",
);
const merged = mergeMacUpdateManifests(arm64, x64);
assert.equal(merged.version, "0.0.4");
assert.equal(merged.releaseDate, "2026-03-07T10:36:07.540Z");
assert.deepStrictEqual(
merged.files.map((file) => file.url),
[
"T3-Code-0.0.4-arm64.zip",
"T3-Code-0.0.4-arm64.dmg",
"T3-Code-0.0.4-x64.zip",
"T3-Code-0.0.4-x64.dmg",
],
);
const serialized = serializeMacUpdateManifest(merged);
assert.ok(!serialized.includes("path:"));
assert.equal((serialized.match(/- url:/g) ?? []).length, 4);
});
it("rejects mismatched manifest versions", () => {
const arm64 = parseMacUpdateManifest(
`version: 0.0.4
files:
- url: T3-Code-0.0.4-arm64.zip
sha512: arm64zip
size: 1
releaseDate: '2026-03-07T10:32:14.587Z'
`,
"latest-mac.yml",
);
const x64 = parseMacUpdateManifest(
`version: 0.0.5
files:
- url: T3-Code-0.0.5-x64.zip
sha512: x64zip
size: 1
releaseDate: '2026-03-07T10:36:07.540Z'
`,
"latest-mac-x64.yml",
);
assert.throws(() => mergeMacUpdateManifests(arm64, x64), /different versions/);
});
it("preserves quoted scalars as strings", () => {
const manifest = parseMacUpdateManifest(
`version: '1.0'
files:
- url: T3-Code-1.0-x64.zip
sha512: zipsha
size: 1
releaseName: 'true'
minimumSystemVersion: '13.0'
stagingPercentage: 50
releaseDate: '2026-03-07T10:36:07.540Z'
`,
"latest-mac.yml",
);
assert.equal(manifest.version, "1.0");
assert.equal(manifest.extras.releaseName, "true");
assert.equal(manifest.extras.minimumSystemVersion, "13.0");
assert.equal(manifest.extras.stagingPercentage, 50);
});
});
-287
View File
@@ -1,287 +0,0 @@
import { readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
interface MacUpdateFile {
readonly url: string;
readonly sha512: string;
readonly size: number;
}
type MacUpdateScalar = string | number | boolean;
interface MacUpdateManifest {
readonly version: string;
readonly releaseDate: string;
readonly files: ReadonlyArray<MacUpdateFile>;
readonly extras: Readonly<Record<string, MacUpdateScalar>>;
}
interface MutableMacUpdateFile {
url?: string;
sha512?: string;
size?: number;
}
function stripSingleQuotes(value: string): string {
if (value.startsWith("'") && value.endsWith("'")) {
return value.slice(1, -1).replace(/''/g, "'");
}
return value;
}
function parseFileRecord(
currentFile: MutableMacUpdateFile | null,
sourcePath: string,
lineNumber: number,
): MacUpdateFile | null {
if (currentFile === null) {
return null;
}
if (
typeof currentFile.url !== "string" ||
typeof currentFile.sha512 !== "string" ||
typeof currentFile.size !== "number"
) {
throw new Error(
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: incomplete file entry.`,
);
}
return {
url: currentFile.url,
sha512: currentFile.sha512,
size: currentFile.size,
};
}
function parseScalarValue(rawValue: string): MacUpdateScalar {
const trimmed = rawValue.trim();
const isQuoted = trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2;
const value = isQuoted ? trimmed.slice(1, -1).replace(/''/g, "'") : trimmed;
if (isQuoted) return value;
if (value === "true") return true;
if (value === "false") return false;
if (/^-?\d+(?:\.\d+)?$/.test(value)) {
return Number(value);
}
return value;
}
export function parseMacUpdateManifest(raw: string, sourcePath: string): MacUpdateManifest {
const lines = raw.split(/\r?\n/);
const files: MacUpdateFile[] = [];
const extras: Record<string, MacUpdateScalar> = {};
let version: string | null = null;
let releaseDate: string | null = null;
let inFiles = false;
let currentFile: MutableMacUpdateFile | null = null;
for (const [index, rawLine] of lines.entries()) {
const lineNumber = index + 1;
const line = rawLine.trimEnd();
if (line.length === 0) continue;
const fileUrlMatch = line.match(/^ - url:\s*(.+)$/);
if (fileUrlMatch?.[1]) {
const finalized = parseFileRecord(currentFile, sourcePath, lineNumber);
if (finalized) files.push(finalized);
currentFile = { url: stripSingleQuotes(fileUrlMatch[1].trim()) };
inFiles = true;
continue;
}
const fileShaMatch = line.match(/^ sha512:\s*(.+)$/);
if (fileShaMatch?.[1]) {
if (currentFile === null) {
throw new Error(
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: sha512 without a file entry.`,
);
}
currentFile.sha512 = stripSingleQuotes(fileShaMatch[1].trim());
continue;
}
const fileSizeMatch = line.match(/^ size:\s*(\d+)$/);
if (fileSizeMatch?.[1]) {
if (currentFile === null) {
throw new Error(
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: size without a file entry.`,
);
}
currentFile.size = Number(fileSizeMatch[1]);
continue;
}
if (line === "files:") {
inFiles = true;
continue;
}
if (inFiles && currentFile !== null) {
const finalized = parseFileRecord(currentFile, sourcePath, lineNumber);
if (finalized) files.push(finalized);
currentFile = null;
}
inFiles = false;
const topLevelMatch = line.match(/^([A-Za-z][A-Za-z0-9]*):\s*(.+)$/);
if (!topLevelMatch?.[1] || topLevelMatch[2] === undefined) {
throw new Error(
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: unsupported line '${line}'.`,
);
}
const [, key, rawValue] = topLevelMatch;
const value = parseScalarValue(rawValue);
if (key === "version") {
if (typeof value !== "string") {
throw new Error(
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: version must be a string.`,
);
}
version = value;
continue;
}
if (key === "releaseDate") {
if (typeof value !== "string") {
throw new Error(
`Invalid macOS update manifest at ${sourcePath}:${lineNumber}: releaseDate must be a string.`,
);
}
releaseDate = value;
continue;
}
if (key === "path" || key === "sha512") {
continue;
}
extras[key] = value;
}
const finalized = parseFileRecord(currentFile, sourcePath, lines.length);
if (finalized) files.push(finalized);
if (!version) {
throw new Error(`Invalid macOS update manifest at ${sourcePath}: missing version.`);
}
if (!releaseDate) {
throw new Error(`Invalid macOS update manifest at ${sourcePath}: missing releaseDate.`);
}
if (files.length === 0) {
throw new Error(`Invalid macOS update manifest at ${sourcePath}: missing files.`);
}
return {
version,
releaseDate,
files,
extras,
};
}
function mergeExtras(
primary: Readonly<Record<string, MacUpdateScalar>>,
secondary: Readonly<Record<string, MacUpdateScalar>>,
): Record<string, MacUpdateScalar> {
const merged: Record<string, MacUpdateScalar> = { ...primary };
for (const [key, value] of Object.entries(secondary)) {
const existing = merged[key];
if (existing !== undefined && existing !== value) {
throw new Error(
`Cannot merge macOS update manifests: conflicting '${key}' values ('${existing}' vs '${value}').`,
);
}
merged[key] = value;
}
return merged;
}
export function mergeMacUpdateManifests(
primary: MacUpdateManifest,
secondary: MacUpdateManifest,
): MacUpdateManifest {
if (primary.version !== secondary.version) {
throw new Error(
`Cannot merge macOS update manifests with different versions (${primary.version} vs ${secondary.version}).`,
);
}
const filesByUrl = new Map<string, MacUpdateFile>();
for (const file of [...primary.files, ...secondary.files]) {
const existing = filesByUrl.get(file.url);
if (existing && (existing.sha512 !== file.sha512 || existing.size !== file.size)) {
throw new Error(
`Cannot merge macOS update manifests: conflicting file entry for ${file.url}.`,
);
}
filesByUrl.set(file.url, file);
}
return {
version: primary.version,
releaseDate:
primary.releaseDate >= secondary.releaseDate ? primary.releaseDate : secondary.releaseDate,
files: [...filesByUrl.values()],
extras: mergeExtras(primary.extras, secondary.extras),
};
}
function quoteYamlString(value: string): string {
return `'${value.replace(/'/g, "''")}'`;
}
function serializeScalarValue(value: MacUpdateScalar): string {
if (typeof value === "string") {
return quoteYamlString(value);
}
return String(value);
}
export function serializeMacUpdateManifest(manifest: MacUpdateManifest): string {
const lines = [`version: ${manifest.version}`, "files:"];
for (const file of manifest.files) {
lines.push(` - url: ${file.url}`);
lines.push(` sha512: ${file.sha512}`);
lines.push(` size: ${file.size}`);
}
for (const key of Object.keys(manifest.extras).toSorted()) {
const value = manifest.extras[key];
if (value === undefined) {
throw new Error(`Cannot serialize macOS update manifest: missing value for '${key}'.`);
}
lines.push(`${key}: ${serializeScalarValue(value)}`);
}
lines.push(`releaseDate: ${quoteYamlString(manifest.releaseDate)}`);
lines.push("");
return lines.join("\n");
}
function main(args: ReadonlyArray<string>): void {
const [arm64PathArg, x64PathArg, outputPathArg] = args;
if (!arm64PathArg || !x64PathArg) {
throw new Error(
"Usage: node scripts/merge-mac-update-manifests.ts <latest-mac.yml> <latest-mac-x64.yml> [output-path]",
);
}
const arm64Path = resolve(arm64PathArg);
const x64Path = resolve(x64PathArg);
const outputPath = resolve(outputPathArg ?? arm64PathArg);
const arm64Manifest = parseMacUpdateManifest(readFileSync(arm64Path, "utf8"), arm64Path);
const x64Manifest = parseMacUpdateManifest(readFileSync(x64Path, "utf8"), x64Path);
const merged = mergeMacUpdateManifests(arm64Manifest, x64Manifest);
writeFileSync(outputPath, serializeMacUpdateManifest(merged));
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main(process.argv.slice(2));
}
-113
View File
@@ -1,113 +0,0 @@
import { execFileSync } from "node:child_process";
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const workspaceFiles = [
"package.json",
"bun.lock",
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"apps/marketing/package.json",
"packages/contracts/package.json",
"packages/shared/package.json",
"scripts/package.json",
] as const;
function copyWorkspaceManifestFixture(targetRoot: string): void {
for (const relativePath of workspaceFiles) {
const sourcePath = resolve(repoRoot, relativePath);
const destinationPath = resolve(targetRoot, relativePath);
mkdirSync(dirname(destinationPath), { recursive: true });
cpSync(sourcePath, destinationPath);
}
}
function writeMacManifestFixtures(targetRoot: string): { arm64Path: string; x64Path: string } {
const assetDirectory = resolve(targetRoot, "release-assets");
mkdirSync(assetDirectory, { recursive: true });
const arm64Path = resolve(assetDirectory, "latest-mac.yml");
const x64Path = resolve(assetDirectory, "latest-mac-x64.yml");
writeFileSync(
arm64Path,
`version: 9.9.9-smoke.0
files:
- url: T3-Code-9.9.9-smoke.0-arm64.zip
sha512: arm64zip
size: 125621344
- url: T3-Code-9.9.9-smoke.0-arm64.dmg
sha512: arm64dmg
size: 131754935
path: T3-Code-9.9.9-smoke.0-arm64.zip
sha512: arm64zip
releaseDate: '2026-03-08T10:32:14.587Z'
`,
);
writeFileSync(
x64Path,
`version: 9.9.9-smoke.0
files:
- url: T3-Code-9.9.9-smoke.0-x64.zip
sha512: x64zip
size: 132000112
- url: T3-Code-9.9.9-smoke.0-x64.dmg
sha512: x64dmg
size: 138148807
path: T3-Code-9.9.9-smoke.0-x64.zip
sha512: x64zip
releaseDate: '2026-03-08T10:36:07.540Z'
`,
);
return { arm64Path, x64Path };
}
function assertContains(haystack: string, needle: string, message: string): void {
if (!haystack.includes(needle)) {
throw new Error(message);
}
}
const tempRoot = mkdtempSync(join(tmpdir(), "t3-release-smoke-"));
try {
copyWorkspaceManifestFixture(tempRoot);
execFileSync(
process.execPath,
[resolve(repoRoot, "scripts/update-release-package-versions.ts"), "9.9.9-smoke.0", "--root", tempRoot],
{
cwd: repoRoot,
stdio: "inherit",
},
);
execFileSync("bun", ["install", "--lockfile-only", "--ignore-scripts"], {
cwd: tempRoot,
stdio: "inherit",
});
const lockfile = readFileSync(resolve(tempRoot, "bun.lock"), "utf8");
assertContains(lockfile, `"version": "9.9.9-smoke.0"`, "Expected bun.lock to contain the smoke version.");
const { arm64Path, x64Path } = writeMacManifestFixtures(tempRoot);
execFileSync(process.execPath, [resolve(repoRoot, "scripts/merge-mac-update-manifests.ts"), arm64Path, x64Path], {
cwd: repoRoot,
stdio: "inherit",
});
const mergedManifest = readFileSync(arm64Path, "utf8");
assertContains(mergedManifest, "T3-Code-9.9.9-smoke.0-arm64.zip", "Merged manifest is missing the arm64 asset.");
assertContains(mergedManifest, "T3-Code-9.9.9-smoke.0-x64.zip", "Merged manifest is missing the x64 asset.");
console.log("Release smoke checks passed.");
} finally {
rmSync(tempRoot, { recursive: true, force: true });
}
-111
View File
@@ -1,111 +0,0 @@
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
export const releasePackageFiles = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
] as const;
interface UpdateReleasePackageVersionsOptions {
readonly rootDir?: string;
}
interface MutablePackageJson {
version?: string;
[key: string]: unknown;
}
export function updateReleasePackageVersions(
version: string,
options: UpdateReleasePackageVersionsOptions = {},
): { changed: boolean } {
const rootDir = resolve(options.rootDir ?? process.cwd());
let changed = false;
for (const relativePath of releasePackageFiles) {
const filePath = resolve(rootDir, relativePath);
const packageJson = JSON.parse(readFileSync(filePath, "utf8")) as MutablePackageJson;
if (packageJson.version === version) {
continue;
}
packageJson.version = version;
writeFileSync(filePath, `${JSON.stringify(packageJson, null, 2)}\n`);
changed = true;
}
return { changed };
}
function parseArgs(argv: ReadonlyArray<string>): {
version: string;
rootDir: string | undefined;
writeGithubOutput: boolean;
} {
let version: string | undefined;
let rootDir: string | undefined;
let writeGithubOutput = false;
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
if (argument === undefined) {
continue;
}
if (argument === "--github-output") {
writeGithubOutput = true;
continue;
}
if (argument === "--root") {
rootDir = argv[index + 1];
if (!rootDir) {
throw new Error("Missing value for --root.");
}
index += 1;
continue;
}
if (argument.startsWith("--")) {
throw new Error(`Unknown argument: ${argument}`);
}
if (version !== undefined) {
throw new Error("Only one release version can be provided.");
}
version = argument;
}
if (!version) {
throw new Error(
"Usage: node scripts/update-release-package-versions.ts <version> [--root <path>] [--github-output]",
);
}
return { version, rootDir, writeGithubOutput };
}
const isMain = process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isMain) {
const { version, rootDir, writeGithubOutput } = parseArgs(process.argv.slice(2));
const { changed } = updateReleasePackageVersions(
version,
rootDir === undefined ? {} : { rootDir },
);
if (!changed) {
console.log("All package.json versions already match release version.");
}
if (writeGithubOutput) {
const githubOutputPath = process.env.GITHUB_OUTPUT;
if (!githubOutputPath) {
throw new Error("GITHUB_OUTPUT is required when --github-output is set.");
}
appendFileSync(githubOutputPath, `changed=${changed}\n`);
}
}