Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex 9678d3b144 Fix visited timestamp under clock skew
Co-authored-by: codex <[email protected]>
2026-04-29 16:33:06 -07:00
Julius Marminge 0f6f2035e4 Log SSH tunnel lifecycle and surface bootstrap failures
- Add structured logging around SSH command, tunnel, and pairing flows
- Let desktop SSH bootstrap failures propagate instead of timing out locally
- Update reconnect test to expect the underlying SSH timeout error
2026-04-29 14:58:23 -07:00
Julius Marminge 873158254c Add hosted SSH pairing state handling
- Support remote T3 runner selection for hosted pairing
- Surface SSH/environment disconnect states in the UI
- Improve websocket snapshot and password prompt error handling
2026-04-29 13:14:52 -07:00
Julius Marminge fce33cadab Refine hosted pairing and SSH connection flows
- Simplify add-environment dialog around remote and SSH pairing
- Auto-detect pairing URLs and improve SSH prompt handling
- Add coverage for tunnel and connection parsing behavior
2026-04-28 21:13:31 -07:00
Julius Marminge ae9545e184 Refactor SSH desktop pairing onto shared runtime
- Move SSH auth, config, and tunnel logic into `packages/ssh`
- Wire `apps/desktop` to the shared Effect runtime
- Add tests for config, auth, and tunnel behavior
2026-04-28 17:44:04 -07:00
Julius Marminge 0d692d0cc2 Disable Tailscale Serve on server shutdown
- Factor Tailscale command execution into a reusable helper
- Add tests for `tailscale serve off`
- Ensure hosted pairing UI cleans up Tailscale Serve after startup
2026-04-28 14:07:09 -07:00
Julius Marminge 290b9db72e Gate pair route fallback to hosted static app
- Avoid showing the hosted pairing flow outside the static app
- Keep the existing error boundary behavior for local builds
2026-04-28 13:59:42 -07:00
Julius Marminge e4b6dd4efa Split SSH helpers into dedicated modules
- Add auth, command, config, and tunnel exports
- Update desktop SSH environment imports
- Add tests for auth and command helpers
2026-04-28 11:54:58 -07:00
Julius Marminge 20edab789d Extract SSH helpers into shared package
- Move SSH parsing and discovery logic into `@t3tools/ssh`
- Reuse the shared helpers from the desktop app and release smoke checks
- Add coverage for host discovery, parsing, and package spec resolution
2026-04-28 11:34:52 -07:00
Julius Marminge ed93c76d15 Update release smoke to include tailscale package
- Relax settings UI text assertions to match reachable URLs
- Add `packages/tailscale/package.json` to release smoke coverage
2026-04-28 10:02:51 -07:00
Julius Marminge bae05b2e88 Handle malformed custom endpoints in pairing flow
- Ignore invalid custom HTTPS endpoint URLs when building desktop exposure
- Reset pairing submission state after backend errors and clarify retry guidance
- Add coverage for malformed endpoint inputs
2026-04-28 09:30:19 -07:00
Julius Marminge bff64a3f19 Harden pairing and SSH prompt flows
- Preserve Tailscale Serve port when toggling exposure
- Prevent reused hosted pairing tokens and double SSH responses
- Refine endpoint compatibility for HTTP custom URLs
2026-04-27 23:54:23 -07:00
Julius Marminge fc49669529 Add Tailscale Serve pairing support
- add desktop and server settings for hosted HTTPS pairing
- resolve and probe MagicDNS endpoints via shared Tailscale helpers
- update remote pairing docs and UI to surface the new setup flow
2026-04-27 22:24:40 -07:00
Julius Marminge db6a2a6dc1 Delay SSH tunnel disposal until pending setup settles
- Fix auth-failure matching for permission denied variants
- Allow remote port picker to run without a state file path
- Dispose only after pending tunnel creation resolves
2026-04-27 18:37:13 -07:00
Julius Marmingeandcodex 02e194c000 docs(remote): document desktop ssh launch
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex cebe697733 Fix PR CI failures
- use type-only imports required by verbatim module syntax
- fix SSH desktop build/typecheck regressions and auth test isolation
- tighten browser test selectors for the add-environment dialog

Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marminge 0f2ed34b4f Simplify ssh askpass to require cached secret
- Remove native password prompts from posix and Windows scripts
- Fail loudly when T3_SSH_AUTH_SECRET is missing
2026-04-27 18:14:50 -07:00
Julius Marminge 6ea09363b2 Extract SSH launch scripts
- Externalize askpass, remote launch, and runner helpers into script assets
- Copy SSH scripts into `dist-electron` for packaging
- Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marminge bf81ea87ea Extract desktop SSH bridge into dedicated class
- Move SSH IPC handlers and password prompt state out of main.ts
- Keep SSH environment launch and auth flow owned by sshEnvironment.ts
2026-04-27 18:14:50 -07:00
Julius Marminge eaf246a400 Format settings and IPC imports
- No functional change
- Keep staged code style consistent
2026-04-27 18:14:50 -07:00
Julius Marminge 3652081556 Tighten SSH setup dialog scrolling
- Add a capped scroll area for discovered SSH hosts
- Keep the manual SSH form always visible and simplify the dialog layout
- Ensure the scroll area viewport respects inherited max height
2026-04-27 18:14:50 -07:00
Julius Marminge efef363e59 Improve SSH launch diagnostics
- surface stdout when remote launch or pairing fails
- report parse errors and invalid remote port or credential values
2026-04-27 18:14:50 -07:00
Julius Marminge fcf9ce0b10 Use nightly remote T3 CLI in development
- Resolve dev remote package specs to `t3@nightly`
- Cover the dev fallback in sshEnvironment tests
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 3af684f852 Address SSH launch review feedback
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 7fd550ec31 Pin nightly SSH bootstrap to desktop version
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 1f5187f0fa Respect desktop release channel for SSH bootstrap
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marminge 2ab77a2255 Harden remote SSH environment recovery
- Validate SSH targets and known-host parsing more strictly
- Retry desktop SSH session refresh on auth failures
- Preserve saved registry state when bearer persistence fails
2026-04-27 18:14:50 -07:00
Julius Marminge 399264836a Add remote SSH environment launch support
- Discover SSH hosts and persist SSH targets
- Bootstrap tunneled SSH sessions with desktop password prompts
- Extend IPC and storage tests for SSH metadata
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 596a25fefa fix(desktop): include port in tailscale https endpoint
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 53523d1719 docs(remote): document tailscale endpoint add-on
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 17d557cc84 fix(web): dedupe advertised pairing helpers
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex df66553b3f feat(desktop): add tailscale endpoint addon
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 4fff6c8894 feat(remote): add advertised endpoint registry
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 722b41412e feat(web): make advertised endpoint defaults explicit
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex b500b84e34 fix(web): hide endpoint rows when network access is disabled
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex f822b301fd docs(remote): describe advertised endpoint selection
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex e06c5780b3 feat(remote): add advertised endpoint registry
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex b0cf85f69a fix(web): treat hosted app as static
Co-authored-by: codex <[email protected]>
2026-04-26 23:34:48 -07:00
Julius Marmingeandcodex 008fc1c628 docs(remote): document hosted pairing constraints
Co-authored-by: codex <[email protected]>
2026-04-26 19:55:24 -07:00
Julius Marmingeandcodex a28ba8b083 fix(web): keep hosted pairing to secure endpoints
Co-authored-by: codex <[email protected]>
2026-04-26 19:43:08 -07:00
Julius Marmingeandcodex 814c206bde feat(web): support hosted pairing links
Co-authored-by: codex <[email protected]>
2026-04-26 19:31:35 -07:00
Julius Marmingeandcodex 5cf83ffe8f fix(release): use configured node for smoke manifest merge (#2364)
Co-authored-by: codex <[email protected]>
2026-04-27 02:30:18 +00:00
t3-code[bot] ada410bccf chore(release): prepare v0.0.21 2026-04-23 18:05:15 +00:00
legs 00b5c3e1b3 Add task sidebar auto-open setting (#2314) 2026-04-23 13:59:08 -04:00
188df6da07 Fix Claude session cwd resume drift (#2292)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-23 13:29:54 -04:00
Pedro Silva 0d55a42840 fix(web): ignore stale runtime projection snapshots (#2301) 2026-04-23 15:52:02 +00:00
Thimo Sietsma 0ee302e24d fix(request-permission): add dynamic_tool_call to command request (#2311) 2026-04-23 15:42:35 +00:00
Julius Marminge d5b7690f95 Exclude subscribe RPCs from latency tracking (#2313) 2026-04-23 15:24:06 +00:00
8d1d699f88 Refactor provider model selections to option arrays (#2246)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
Co-authored-by: codex <[email protected]>
2026-04-23 09:35:40 -04:00
Raul Pereira da Silvaandmacroscopeapp[bot] b0b7b38da1 fix(server): detect localized Windows command errors (#2152)
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
2026-04-23 04:42:19 +00:00
Bas Milius fd3b96b487 Add IntelliJ project icon to the list of possible favicon paths (#1651) 2026-04-23 04:40:27 +00:00
Hauke Schnau aa2d385a62 fix(server): restore CODEX_HOME tilde expansion for Codex launches (#2255) 2026-04-23 00:37:58 -04:00
e25db3a572 Fix provider cache atomic write temp path collisions (#2291)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-23 00:33:16 -04:00
Heinz-GandHeinz Gericke b8305afa29 fix: increase Claude auth probe timeout to 10s (#2272)
Co-authored-by: Heinz Gericke <[email protected]>
2026-04-22 01:04:50 +00:00
Julius MarmingeandCursor Agent b7c89cf496 Refresh Codex protocol bindings to be75785504ff152fa6333e380a2d50642f42fba0 (#2276)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-21 15:30:54 -07:00
NoxireandJulius Marminge 3a1daa87ac Add close buttons to toasts (#2023)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-21 08:32:08 -07:00
Mike Olson 055897f0ea fix: enforce opencode >= 1.14.19 and reveal window on Wayland (#2262) 2026-04-21 08:15:41 -07:00
Adin Schmidt 40b3a80034 fix(server): trim OpenCode provider model names (#2252) 2026-04-21 02:45:56 +00:00
Adam Mansfield f6978db605 chore(turbo): pass through PATHEXT (#2184) 2026-04-19 23:35:37 -07:00
Mike Olson de05b0c94e fix(web): restore manual sort drag and keep per-group expand state (#2221) 2026-04-19 23:29:56 -07:00
CraigandJulius Marminge 6d1505c9fb fix: Change right panel sheet to be below title bar / action bar (#2224)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-19 23:25:39 -07:00
Julius MarmingeandClaude Opus 4.7 306ec4bb84 Refactor OpenCode lifecycle and structured output handling (#2218)
Co-authored-by: Claude Opus 4.7 <[email protected]>
2026-04-19 22:56:44 -07:00
Julius Marmingeandcodex 3b98fe3548 effect-codex-app-server (#1942)
Co-authored-by: codex <[email protected]>
2026-04-19 21:46:40 -07:00
Ellie GummereandJulius Marminge 66c326b8c4 Redesign model picker with favorites and search (#2153)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-19 17:43:40 -07:00
8dbcf92a0d fix(server): prevent probeClaudeCapabilities from wasting API requests (#2192)
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-20 00:13:20 +00:00
Abdul Azeez 37965da01d fix(server): handle OpenCode text response format in commit message g… (#2202) 2026-04-20 00:12:35 +00:00
Kyle Gottfried 57b59b5bf2 Devcontainer / IDE updates (#2208) 2026-04-19 17:07:12 -07:00
20f346d8ef Expand leading ~ in Codex home paths before exporting CODEX_HOME (#2210)
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: = <=>
2026-04-20 00:06:19 +00:00
Efe Baran Durmaz c83bc5d48a fix(release): use v<semver> tag format for nightly releases (#2186) 2026-04-19 10:58:04 -07:00
Julius Marminge 9df3c64021 Use GitHub App token for release uploads (#2149) 2026-04-17 16:52:56 -07:00
Julius Marminge 8ac57f7944 Guard release workflow jobs on upstream success (#2147) 2026-04-17 16:40:43 -07:00
Julius Marminge 29cb917ac4 Guard release workflow jobs from upstream failures (#2146) 2026-04-17 16:34:19 -07:00
9c64f12ea0 Add ACP support with Cursor provider (#1355)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-17 16:21:31 -07:00
Matt Van HornandMatt Van Horn 0f184c28b0 fix(web): use capture-phase keydown listener so CTRL+J toggles terminal from terminal focus on Windows (#2113) (#2142)
Co-authored-by: Matt Van Horn <[email protected]>
2026-04-17 23:07:04 +00:00
Julius Marminge a3b1df5224 Add Claude Opus 4.5 to built-in Claude models (#2143) 2026-04-17 16:02:41 -07:00
4e0c003e78 fix(web): allow deleting non-empty projects from the warning toast (#1264)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-17 15:05:56 -07:00
Utkarsh Patil 60387f67e9 fix: show restore defaults only on General settings (#1710) 2026-04-17 13:49:18 -07:00
ce94feeea1 feat: add opencode provider support (#1758)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-04-17 13:31:41 -07:00
Ariaj 39ca3ee858 fix(web): bypass xterm for global terminal shortcuts (#1580) 2026-04-17 13:11:04 -07:00
Julius Marminge 52a6067802 Throttle nightly release workflow to every 3 hours (#2134) 2026-04-17 11:39:20 -07:00
721b6b4c6f Preserve provider bindings when stopping sessions (#2125)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-17 11:27:12 -07:00
Julius Marminge 40009735ee Extract backend startup readiness coordination (#2133) 2026-04-17 11:09:26 -07:00
df9d34004f Modernize release workflow runners (#2129)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-17 16:23:02 +00:00
340 changed files with 91675 additions and 10807 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
plans/
+11 -4
View File
@@ -2,15 +2,22 @@
"name": "T3 Code Dev",
"image": "debian:bookworm",
"features": {
"ghcr.io/devcontainers-extra/features/bun:1": {},
"ghcr.io/devcontainers/features/git:1": {},
"ghcr.io/devcontainers-extra/features/bun:1": {
"version": "1.3.11"
},
"ghcr.io/devcontainers/features/node:1": {
"version": "24",
"nodeGypDependencies": true
"version": "24.13.1"
},
"ghcr.io/devcontainers/features/python:1": {
"version": "3.12"
"version": "3.10",
"installTools": false
}
},
"overrideFeatureInstallOrder": [
"ghcr.io/devcontainers/features/git",
"ghcr.io/devcontainers-extra/features/bun"
],
"postCreateCommand": {
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
},
+80
View File
@@ -93,6 +93,8 @@ Examples:
A known environment may or may not know the target `environmentId` before first successful connect.
In the hosted web app, known environments are browser-local. A hosted pairing URL can create the saved entry, but it does not give the hosted app a server-side control plane or a copy of the session state.
### AccessEndpoint
An `AccessEndpoint` is one concrete way to reach a known environment.
@@ -108,6 +110,67 @@ A single environment may have many endpoints:
The environment stays the same. Only the access path changes.
### AdvertisedEndpoint
An `AdvertisedEndpoint` is a server or desktop-authored candidate endpoint for an environment. It is how the backend tells the client which URLs may be useful for pairing and reconnecting.
`AdvertisedEndpoint` is deliberately narrower than the full access model:
- it describes a concrete HTTP and WebSocket base URL pair
- it can mark the endpoint as default, available, or unavailable
- it includes reachability hints such as loopback, LAN, private, public, or tunnel
- it includes compatibility hints such as whether the endpoint can be used from the hosted HTTPS app
Clients should treat advertised endpoints as hints, not as proof that a route works from the current device. The final connection attempt still decides whether the endpoint is reachable.
The UI presents one default advertised endpoint in the network-access summary and keeps the rest behind an expandable advanced list. The default controls pairing QR codes and primary copy actions. Users can override it, but that override is a UI preference, not backend configuration.
Persist the override by stable endpoint kind rather than raw URL whenever possible. For example, a LAN endpoint should be stored as the desktop LAN endpoint preference, not as `192.168.x.y`, because the address can change when the user switches networks. Provider endpoints should use provider-specific stable keys such as Tailscale IP or Tailscale MagicDNS HTTPS. Custom endpoints may fall back to their concrete identity.
When no user default is saved, endpoint selection should prefer:
1. endpoints compatible with the hosted HTTPS app
2. explicitly default endpoints
3. non-loopback endpoints
4. loopback endpoints only for same-machine clients
This keeps endpoint discovery centralized without making any one provider, such as Tailscale or a future tunnel service, part of the core environment model.
### Endpoint providers
Endpoint providers are add-ons that contribute advertised endpoints for the current environment.
The provider boundary is intentionally outside the core environment model:
- core owns `ExecutionEnvironment`, saved environments, pairing, and connection lifecycle
- providers discover or synthesize endpoints
- providers return normalized `AdvertisedEndpoint` records
- the UI and pairing logic select from those records without knowing provider-specific commands
The first provider is Tailscale. It can discover Tailnet IP and MagicDNS addresses from the local machine and publish them as additional endpoint candidates. Future providers, such as a hosted tunnel service, should plug into the same shape rather than adding a separate remote environment path.
Provider-specific confidence should remain a hint. A Tailscale endpoint still needs a successful browser or desktop connection before the client treats it as connected.
### Hosted pairing request
A hosted pairing request is a bootstrap URL for the static web app, not a transport.
Example:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
The hosted app reads the `host` parameter and pairing token, exchanges the token directly with that backend, then saves the resulting environment record in browser local storage.
Important constraints:
- the hosted app does not proxy HTTP or WebSocket traffic
- the backend must still be reachable directly from the browser
- HTTPS pages can only connect to HTTPS/WSS backends
- HTTP LAN endpoints should keep using direct desktop or CLI pairing URLs
- the token belongs in the URL hash so it is not sent to the hosted app origin
### RepositoryIdentity
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
@@ -151,6 +214,8 @@ Benefits:
- no client-specific process management required
- best fit for hosted or self-managed remote T3 deployments
Browser security rules are part of this access method. A hosted HTTPS web client can connect to `wss://` backends, but it cannot connect to plain `ws://` or `http://` LAN backends because that would be mixed content.
### 2. Tunneled WebSocket access
Examples:
@@ -170,6 +235,8 @@ This is especially useful when:
- mobile must reach a desktop-hosted environment
- a machine should be reachable without exposing raw LAN or public ports
Tailscale-backed access sits here architecturally even though the current implementation is endpoint discovery rather than a T3-managed tunnel. It contributes private-network endpoints and lets the existing HTTP/WebSocket client path do the actual connection.
### 3. Desktop-managed SSH access
SSH is an access and launch helper, not a separate environment type.
@@ -185,6 +252,8 @@ After that, the renderer should still connect using an ordinary WebSocket URL ag
This keeps the renderer transport model consistent with every other access method.
The desktop main process owns the SSH bridge because it can spawn local SSH processes, manage askpass prompts, write temporary launch scripts, and clean up forwards. The renderer receives a saved environment record and connects through the forwarded URL; it should not need SSH-specific RPC paths for normal environment traffic.
## Launch methods
Launch methods answer a different question:
@@ -227,6 +296,15 @@ The recommended T3 flow is:
4. Desktop establishes local port forwarding.
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
The saved environment should remember that it was created by desktop SSH launch only for reconnect and lifecycle UX. That metadata should not change the server protocol or the environment identity model.
Failure handling should be explicit:
- SSH authentication failure should surface before any environment is saved
- remote launch failure should include remote logs or the launcher command output when available
- forwarded-port failure should leave the saved environment disconnected rather than falling back to an unrelated endpoint
- reconnect should attempt to restore the SSH bridge before reconnecting the normal WebSocket client
### 3. Client-managed local publish
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
@@ -267,6 +345,8 @@ T3 already supports a WebSocket auth token on the server. That should become a f
For publicly reachable environments, authenticated access should be treated as required.
Hosted pairing should be treated as a client-side convenience only. The hosted app must not receive pairing tokens through query parameters, must not store pairing state server-side, and must not imply that an HTTP backend is safe or reachable from an HTTPS browser context.
## Relationship to Zed
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
+80 -4
View File
@@ -4,8 +4,9 @@ on:
push:
tags:
- "v*.*.*"
- "!v*-nightly.*"
schedule:
- cron: "0 9 * * *"
- cron: "0 */3 * * *"
workflow_dispatch:
inputs:
channel:
@@ -26,8 +27,45 @@ permissions:
id-token: write
jobs:
check_changes:
name: Check for changes since last nightly
if: github.event_name == 'schedule'
runs-on: ubuntu-24.04
outputs:
has_changes: ${{ steps.check.outputs.has_changes }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- id: check
name: Compare HEAD to last nightly tag
run: |
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
if [[ -z "$last_nightly_tag" ]]; then
echo "No previous nightly tag found. Proceeding with release."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
exit 0
fi
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
head_sha=$(git rev-parse HEAD)
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
echo "has_changes=false" >> "$GITHUB_OUTPUT"
else
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
fi
preflight:
name: Preflight
needs: [check_changes]
if: |
!failure() && !cancelled() &&
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
outputs:
@@ -134,6 +172,7 @@ jobs:
build:
name: Build ${{ matrix.label }}
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
strategy:
@@ -156,7 +195,7 @@ jobs:
target: AppImage
arch: x64
- label: Windows x64
runner: windows-2022 # blacksmith-32vcpu-windows-2025
runner: blacksmith-32vcpu-windows-2025
platform: win
target: nsis
arch: x64
@@ -188,6 +227,23 @@ jobs:
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Install Spectre-mitigated MSVC libs
if: matrix.platform == 'win'
shell: pwsh
run: |
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$installPath = & $vswhere -products * -latest -property installationPath
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
$proc = Start-Process -FilePath $setupExe `
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
-Wait -PassThru -NoNewWindow
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
Write-Error "Visual Studio Installer failed with exit code $code"
exit $code
}
- name: Build desktop artifact
shell: bash
env:
@@ -299,6 +355,7 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
@@ -333,19 +390,36 @@ jobs:
release:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
runs-on: blacksmith-8vcpu-ubuntu-2404
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
with:
@@ -412,6 +486,7 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
@@ -431,10 +506,11 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
finalize:
name: Finalize release
if: needs.preflight.outputs.release_channel == 'stable'
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
needs: [preflight, release]
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
+1
View File
@@ -22,3 +22,4 @@ apps/web/src/components/__screenshots__
__screenshots__/
.tanstack
squashfs-root/
.vercel
+9 -1
View File
@@ -13,5 +13,13 @@
"apps/web/src/lib/vendor/qrcodegen.ts",
"*.icon/**"
],
"sortPackageJson": {}
"sortPackageJson": {},
"overrides": [
{
"files": [".devcontainer/devcontainer.json"],
"options": {
"trailingComma": "none"
}
}
]
}
+350
View File
@@ -0,0 +1,350 @@
# Remote Endpoints and Hosted Static App Plan
## Purpose
Make remote access feel first-class while keeping the free DIY path open.
The immediate product goal is:
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
- users can generate a hosted pairing link for `app.t3.codes`
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
## Current State
Already present or in progress:
- Server auth distinguishes bootstrap credentials from session credentials.
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
- Remote environment WebSocket connections use a short-lived WebSocket token.
- Pairing URLs can carry tokens in the URL fragment.
- Hosted `/pair?host=...#token=...` can add a saved environment.
- Hosted static startup can avoid assuming the page origin is the backend.
Main gaps:
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
- Tailscale/MagicDNS endpoints are not detected or surfaced.
- Hosted-static empty/offline states are still thin.
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
## Core Decision: Add `AdvertisedEndpoint`
Add a new first-class contract instead of extending the environment descriptor.
### Why not extend `ExecutionEnvironmentDescriptor`
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
Examples:
- environment id
- label
- platform
- server version
- capabilities
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
Examples:
- loopback URL
- LAN URL
- Tailscale IP URL
- MagicDNS/Serve URL
- manual URL
- future T3 Tunnel URL
- browser compatibility and exposure level
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
### Target Contract
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
```ts
type AdvertisedEndpointProvider =
| "loopback"
| "lan"
| "tailscale-ip"
| "tailscale-magicdns"
| "manual"
| "t3-tunnel";
type AdvertisedEndpointVisibility = "local" | "private-network" | "tailnet" | "public";
type AdvertisedEndpointCompatibility = {
hostedHttpsApp: "compatible" | "mixed-content-blocked" | "untrusted-certificate" | "unknown";
desktopApp: "compatible" | "unknown";
};
type AdvertisedEndpoint = {
id: string;
provider: AdvertisedEndpointProvider;
label: string;
httpBaseUrl: string;
wsBaseUrl: string;
visibility: AdvertisedEndpointVisibility;
compatibility: AdvertisedEndpointCompatibility;
source: "server" | "desktop" | "user";
status: "available" | "unavailable" | "unknown";
isDefault?: boolean;
};
```
Keep the contract schema-only. All classification logic belongs in `packages/shared`, `apps/server`, `apps/desktop`, or `apps/web`.
## HTTP/WS and HTTPS/WSS Readiness
The codebase is partially ready, but the UX and compatibility model are not explicit enough.
What is ready:
- Remote target parsing already derives `ws://` from `http://` and `wss://` from `https://`.
- Saved environments store both HTTP and WebSocket base URLs.
- Remote auth uses bearer tokens instead of cookies, so cross-origin hosted clients are viable.
- WebSocket connections can use a dynamically issued `wsToken`.
- Server CORS support exists for browser remote auth endpoints.
What is not solved by code alone:
- `https://app.t3.codes` cannot reliably call `http://...` or `ws://...` endpoints because browsers block mixed content.
- `wss://100.x.y.z:3773` needs a certificate the browser trusts. A raw Tailscale IP does not solve certificate trust.
- LAN `http://192.168.x.y:3773` is usable from another desktop/native context but not from the hosted HTTPS app.
- The UI needs to explain why an endpoint is copyable for desktop pairing but not hosted-app compatible.
Policy:
- Support both HTTP/WS and HTTPS/WSS at the runtime layer.
- Mark endpoint compatibility at the product layer.
- Generate `app.t3.codes` links only from endpoints that are likely hosted-browser compatible, or show a warning with an explicit fallback.
## Architecture
### Endpoint Sources
Endpoint records can come from several providers:
1. **Server runtime**
- headless bind host and port
- server-known explicit advertised host config
2. **Desktop shell**
- loopback backend URL
- LAN exposure state
- network interface discovery
- Tailscale CLI/status discovery
3. **User configuration**
- manually added hostnames
- preferred endpoint labels
- hidden/disabled endpoints
4. **Future cloud provider**
- T3 Tunnel endpoint
- billing/account status
- tunnel lifecycle state
### Endpoint Registry
Create a central runtime registry:
- `packages/contracts/src/remoteAccess.ts`
- `packages/shared/src/remoteAccess.ts` for URL normalization and compatibility classification
- `apps/server/src/remoteAccess/*` for server/headless endpoints
- `apps/desktop/src/remoteAccess/*` for desktop-discovered endpoints
- `apps/web/src/environments/endpoints/*` for client-side display and pairing selection
The web app should consume endpoint records and not care whether they came from LAN, Tailscale, or a future tunnel.
### Pairing Link Generation
Move hosted pairing link generation to endpoint-driven input:
```ts
buildHostedPairingUrl({
endpoint: AdvertisedEndpoint,
token,
});
```
Generated URL:
```text
https://app.t3.codes/pair?host=<encoded endpoint httpBaseUrl>#token=<one-time token>
```
Use fragment tokens by default. Continue accepting `?token=` for compatibility.
## Phase 1: Endpoint Abstraction
### Goals
- Centralize URL normalization, protocol derivation, and compatibility checks.
- Replace ad hoc desktop `endpointUrl` pairing logic with endpoint selection.
- Preserve all current remote behavior.
### Tasks
1. Add `AdvertisedEndpoint` schemas to `packages/contracts`.
2. Add shared helpers:
- normalize HTTP base URL
- derive WebSocket base URL
- classify loopback/private/LAN/Tailscale/public host
- classify hosted HTTPS compatibility
3. Add server endpoint discovery:
- loopback endpoint
- configured non-loopback endpoint
- explicit advertised host override
4. Add desktop endpoint discovery:
- local loopback
- LAN exposure endpoint
- endpoint status labels
5. Add WebSocket/API method or existing config field for endpoint snapshots.
6. Refactor settings connections UI:
- render endpoint rows
- endpoint picker for pairing link copy
- show compatibility warnings
7. Refactor hosted link builder to accept endpoint records.
8. Add tests for URL normalization and compatibility classification.
### Acceptance Criteria
- Existing LAN/network access UI still works.
- Pairing links are generated from endpoint records.
- Loopback endpoints never produce hosted pairing links silently.
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
- No remote environment runtime changes are required for existing saved environments.
## Phase 2: BYO Tailscale/MagicDNS
### Goals
- Detect free DIY Tailscale reachability.
- Surface Tailscale endpoints as normal advertised endpoints.
- Keep users in control of their own tailnet.
### Tasks
1. Detect Tailscale IPs from network interfaces:
- IPv4 `100.64.0.0/10`
- mark as `provider: "tailscale-ip"`
2. Add optional desktop-side `tailscale status --json` discovery:
- MagicDNS hostname
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
- graceful failure if CLI is missing
3. Add manual Tailscale endpoint override:
- hostname
- label
- preferred/default flag
4. Show Tailscale endpoint rows in settings:
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
5. Generate pairing links using selected Tailscale endpoint.
6. Document DIY setup:
- local desktop-to-desktop over Tailscale
- hosted app requirements
- why HTTPS matters
### Acceptance Criteria
- A machine on Tailscale shows a Tailscale endpoint without paid features.
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
- Tailscale is optional and never required for regular LAN/loopback use.
## Phase 3: Hosted Static App Completion
### Goals
- `app.t3.codes` works as a real client shell.
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
### Tasks
1. Finish hosted-static root behavior:
- no primary backend required
- saved environment hydration before initial routing decisions
- first saved environment selected as active
2. Add hosted empty state:
- no saved environments
- paste pairing URL
- add host + token
3. Add offline saved environment UI:
- last connected
- reconnect
- remove
- copy/add alternate endpoint
4. Audit primary-backend assumptions:
- command palette
- settings pages
- server config atom defaults
- keybindings
- provider/model lists
- update/desktop-only affordances
5. Add route tests for:
- hosted `/pair?host=...#token=...`
- hosted root with no saved environments
- hosted root with saved environment
- primary backend unavailable but saved environment present
6. Add deployment hardening:
- SPA fallback
- strict CSP
- no third-party scripts
- no query token logging
- disable or hide source maps in production if needed
7. Add browser error messages:
- mixed content
- unreachable backend
- CORS failure
- certificate failure
### Acceptance Criteria
- `app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
- A saved environment can be used without any backend at `app.t3.codes`.
- Offline machines show a useful state instead of a generic boot error.
- HTTP endpoints are still supported in desktop/native/local contexts.
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
## Phase 4: Future T3 Tunnel Provider
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
Future tunnel provider responsibilities:
- create endpoint with `provider: "t3-tunnel"`
- surface tunnel status
- provide stable HTTPS URL
- use existing backend pairing/session auth
- never bypass server auth
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
## Security Checklist
- Pairing tokens are short-lived and one-time.
- Generated hosted pairing links put tokens in the fragment.
- The backend remains the authorization boundary.
- Endpoint discovery never disables backend auth.
- Hosted app does not silently downgrade to HTTP.
- Tunnel/public endpoints require explicit user action.
- Client sessions remain revocable.
- Endpoint URLs and request logs must avoid recording pairing tokens.
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
## Verification
Each implementation PR should run:
- `bun fmt`
- `bun lint`
- `bun typecheck`
- focused tests for changed backend/web behavior
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
+1 -1
View File
@@ -5,5 +5,5 @@
"source.fixAll.oxc": "always"
},
"oxc.unusedDisableDirectives": "warn",
"typescript.tsdk": "node_modules/typescript/lib"
"js/ts.tsdk.path": "node_modules/typescript/lib"
}
+76 -1
View File
@@ -22,9 +22,41 @@ If you are already running the desktop app and want to make it reachable from ot
1. Open **Settings** → **Connections**.
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
3. The settings panel will show the default reachable endpoint, with a `+N` control when more endpoints are available. Expand it to inspect alternatives such as loopback, LAN, private-network, or HTTPS endpoints.
4. Use **Create Link** to generate a pairing link you can share with another device.
The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks.
When no user default is saved, the app uses the built-in LAN endpoint for pairing links when
available. You can set another endpoint as the default from the expanded endpoint list.
- HTTPS/WSS-compatible endpoints work from `https://app.t3.codes`, but are not made the default
automatically.
- Non-loopback HTTP endpoints are useful for direct LAN pairing.
- Loopback-only endpoints are not useful for another device unless that device is the same machine.
If the copied link points directly at `http://192.168.x.y:3773`, open it from a client that can reach that LAN address. If it points at `https://app.t3.codes/pair?...`, the hosted web app will save the environment and connect directly to the backend URL in the link.
### Tailscale Endpoints
When the desktop app can detect Tailscale, it adds Tailnet endpoints to the reachable endpoint list.
Depending on your Tailscale setup, this may include:
- the machine's `100.x.y.z` Tailnet IP
- a MagicDNS name
- an HTTPS MagicDNS endpoint when Tailscale Serve is configured for this backend
The Tailscale HTTPS endpoint uses the clean MagicDNS URL, such as
`https://machine.tailnet.ts.net/`, and is disabled until the app verifies that the URL reaches this
backend. Use **Setup** on the Tailscale HTTPS row to opt in. The desktop app restarts the backend
with the same server-side behavior as `t3 serve --tailscale-serve`, then the server asks Tailscale
Serve to proxy HTTPS traffic to the local backend.
The Tailscale support is an endpoint provider add-on. The core remote model still works without Tailscale: LAN HTTP endpoints, custom HTTPS endpoints, future tunnels, and SSH-launched environments all use the same saved environment and pairing flow.
For `https://app.t3.codes`, prefer an HTTPS Tailnet or other HTTPS endpoint. A plain `http://100.x.y.z:3773` endpoint can still work from a desktop client or another browser page served over HTTP, but it will not work from the hosted HTTPS app because of browser mixed-content rules.
### Option 2: Headless Server (CLI)
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
@@ -47,14 +79,42 @@ From there, connect from another device in either of these ways:
- scan the QR code on your phone
- in the desktop app, enter the full pairing URL
- in the desktop app, enter the host and token separately
- in the hosted web app, open a hosted pairing URL when the backend is reachable over HTTPS
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
For hosted web pairing over Tailscale HTTPS, opt in to Tailscale Serve:
```bash
npx t3 serve --tailscale-serve
```
By default this configures Tailscale Serve on HTTPS port 443 and advertises
`https://machine.tailnet.ts.net/`. Advanced users can choose a different HTTPS port:
```bash
npx t3 serve --tailscale-serve --tailscale-serve-port 8443
```
> Note
> The GUIs do not currently support adding projects on remote environments.
> For now, use `t3 project ...` on the server machine instead.
> Full GUI support for remote project management is coming soon.
### Option 3: Desktop-Managed SSH Launch
Use this when you want the desktop app to start or reuse T3 Code on another machine over SSH.
1. Open **Settings** → **Connections**.
2. Under **Remote Environments**, choose **Add environment**.
3. Select the SSH launch flow.
4. Enter the SSH target, such as `[email protected]`.
5. Confirm the launch. The desktop app probes the host, starts or reuses a remote T3 server, opens a local port forward, and saves the environment.
After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint. The remote host still owns the actual T3 server, projects, files, git state, terminals, and provider sessions.
SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.
## How Pairing Works
The remote device does not need a long-lived secret up front.
@@ -67,6 +127,20 @@ Instead:
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
## Hosted Web App Pairing
The hosted web app at `https://app.t3.codes` can save a remote backend in browser local storage from a URL like:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
Use hosted pairing when the backend is reachable from the browser over HTTPS/WSS. This includes a backend behind a trusted HTTPS tunnel or another HTTPS endpoint you operate.
Do not use hosted pairing for plain HTTP LAN URLs such as `http://192.168.x.y:3773`. Browsers block an HTTPS page from connecting to an insecure HTTP or WS backend. For those endpoints, use the direct pairing URL shown by the desktop app or CLI from a client that can open that HTTP URL directly.
Hosted pairing does not proxy traffic through T3 Code. The browser still connects directly to the backend URL in the pairing link.
## Managing Access Later
Use `t3 auth` to manage access after the initial pairing flow.
@@ -84,4 +158,5 @@ Use `t3 auth --help` and the nested subcommand help pages for the full reference
- Treat pairing URLs and pairing tokens like passwords.
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
- Hosted pairing links keep the credential in the URL hash so it is not sent to the hosted app server, but it can still be exposed through browser history, screenshots, logs, or copy/paste.
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
+6 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.20",
"version": "0.0.21",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -15,14 +15,19 @@
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"effect": "catalog:",
"electron": "40.6.0",
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
@@ -0,0 +1,58 @@
import { describe, expect, it, vi } from "vitest";
import { BackendReadinessAbortedError } from "./backendReadiness.ts";
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
describe("waitForBackendStartupReady", () => {
it("falls back to the HTTP probe when no listening signal exists", async () => {
const waitForHttpReady = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
const cancelHttpWait = vi.fn();
await expect(
waitForBackendStartupReady({
waitForHttpReady,
cancelHttpWait,
}),
).resolves.toBe("http");
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
expect(cancelHttpWait).not.toHaveBeenCalled();
});
it("uses the listening signal and cancels the HTTP probe", async () => {
let rejectHttpWait: ((error: unknown) => void) | null = null;
const waitForHttpReady = vi.fn(
() =>
new Promise<void>((_resolve, reject) => {
rejectHttpWait = reject;
}),
);
const cancelHttpWait = vi.fn(() => {
rejectHttpWait?.(new BackendReadinessAbortedError());
});
await expect(
waitForBackendStartupReady({
listeningPromise: Promise.resolve(),
waitForHttpReady,
cancelHttpWait,
}),
).resolves.toBe("listening");
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
expect(cancelHttpWait).toHaveBeenCalledTimes(1);
});
it("rejects when the listening signal fails before HTTP readiness", async () => {
const error = new Error("backend exited");
const waitForHttpReady = vi.fn(() => new Promise<void>(() => {}));
await expect(
waitForBackendStartupReady({
listeningPromise: Promise.reject(error),
waitForHttpReady,
cancelHttpWait: vi.fn(),
}),
).rejects.toBe(error);
});
});
@@ -0,0 +1,56 @@
import { isBackendReadinessAborted } from "./backendReadiness.ts";
export interface WaitForBackendStartupReadyOptions {
readonly listeningPromise?: Promise<void> | null;
readonly waitForHttpReady: () => Promise<void>;
readonly cancelHttpWait: () => void;
}
export async function waitForBackendStartupReady(
options: WaitForBackendStartupReadyOptions,
): Promise<"listening" | "http"> {
const httpReadyPromise = options.waitForHttpReady();
const listeningPromise = options.listeningPromise;
if (!listeningPromise) {
await httpReadyPromise;
return "http";
}
return await new Promise<"listening" | "http">((resolve, reject) => {
let settled = false;
const settleResolve = (source: "listening" | "http") => {
if (settled) {
return;
}
settled = true;
if (source === "listening") {
options.cancelHttpWait();
}
resolve(source);
};
const settleReject = (error: unknown) => {
if (settled) {
return;
}
settled = true;
reject(error);
};
listeningPromise.then(
() => settleResolve("listening"),
(error) => settleReject(error),
);
httpReadyPromise.then(
() => settleResolve("http"),
(error) => {
if (settled && isBackendReadinessAborted(error)) {
return;
}
settleReject(error);
},
);
});
}
@@ -49,9 +49,11 @@ function makeSecretStorage(available: boolean): DesktopSecretStorage {
}
const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
favorites: [],
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
@@ -68,6 +70,12 @@ const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: "2026-04-09T01:00:00.000Z",
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
};
describe("clientPersistence", () => {
+12 -3
View File
@@ -57,6 +57,12 @@ function isPersistedSavedEnvironmentStorageRecord(
typeof value.wsBaseUrl === "string" &&
typeof value.createdAt === "string" &&
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
(value.desktopSsh === undefined ||
(Predicate.isObject(value.desktopSsh) &&
typeof value.desktopSsh.alias === "string" &&
typeof value.desktopSsh.hostname === "string" &&
(value.desktopSsh.username === null || typeof value.desktopSsh.username === "string") &&
(value.desktopSsh.port === null || typeof value.desktopSsh.port === "number"))) &&
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
);
}
@@ -77,7 +83,7 @@ function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmen
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
): PersistedSavedEnvironmentRecord {
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -85,6 +91,7 @@ function toPersistedSavedEnvironmentRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
@@ -134,6 +141,7 @@ export function writeSavedEnvironmentRegistry(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
encryptedBearerToken,
}
: record;
@@ -189,7 +197,7 @@ export function writeSavedEnvironmentSecret(input: {
const encryptedBearerToken = input.secretStorage
.encryptString(input.secret)
.toString("base64");
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -197,7 +205,8 @@ export function writeSavedEnvironmentSecret(input: {
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
} satisfies PersistedSavedEnvironmentStorageRecord;
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}),
} satisfies SavedEnvironmentRegistryDocument);
return found;
+83
View File
@@ -9,6 +9,7 @@ import {
readDesktopSettings,
resolveDefaultDesktopSettings,
setDesktopServerExposurePreference,
setDesktopTailscaleServePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
@@ -35,6 +36,8 @@ describe("desktopSettings", () => {
it("defaults packaged nightly builds to the nightly update channel", () => {
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -45,12 +48,16 @@ describe("desktopSettings", () => {
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
@@ -61,6 +68,8 @@ describe("desktopSettings", () => {
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
@@ -68,6 +77,50 @@ describe("desktopSettings", () => {
),
).toEqual({
serverExposureMode: "network-accessible",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("persists the requested Tailscale Serve preference", () => {
expect(
setDesktopTailscaleServePreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
{ enabled: true, port: 8443 },
),
).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("preserves the configured Tailscale Serve port when no new port is requested", () => {
expect(
setDesktopTailscaleServePreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
{ enabled: true },
),
).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
@@ -78,6 +131,8 @@ describe("desktopSettings", () => {
setDesktopUpdateChannelPreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
@@ -85,6 +140,8 @@ describe("desktopSettings", () => {
),
).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
});
@@ -103,6 +160,8 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -121,6 +180,8 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -140,8 +201,30 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
it("falls back to the default Tailscale Serve port when the persisted port is invalid", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
tailscaleServeEnabled: true,
tailscaleServePort: 0,
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
});
+33
View File
@@ -6,12 +6,18 @@ import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
}
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
};
@@ -35,6 +41,29 @@ export function setDesktopServerExposurePreference(
};
}
export function setDesktopTailscaleServePreference(
settings: DesktopSettings,
input: { readonly enabled: boolean; readonly port?: number },
): DesktopSettings {
const port =
input.port === undefined
? settings.tailscaleServePort
: normalizeTailscaleServePort(input.port);
return settings.tailscaleServeEnabled === input.enabled && settings.tailscaleServePort === port
? settings
: {
...settings,
tailscaleServeEnabled: input.enabled,
tailscaleServePort: port,
};
}
export function normalizeTailscaleServePort(value: unknown): number {
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65_535
? value
: DEFAULT_TAILSCALE_SERVE_PORT;
}
export function setDesktopUpdateChannelPreference(
settings: DesktopSettings,
requestedChannel: DesktopUpdateChannel,
@@ -57,6 +86,8 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D
const raw = FS.readFileSync(settingsPath, "utf8");
const parsed = JSON.parse(raw) as {
readonly serverExposureMode?: unknown;
readonly tailscaleServeEnabled?: unknown;
readonly tailscaleServePort?: unknown;
readonly updateChannel?: unknown;
readonly updateChannelConfiguredByUser?: unknown;
};
@@ -72,6 +103,8 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
tailscaleServePort: normalizeTailscaleServePort(parsed.tailscaleServePort),
updateChannel:
updateChannelConfiguredByUser && parsedUpdateChannel !== null
? parsedUpdateChannel
+152 -63
View File
@@ -36,11 +36,14 @@ import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
import {
type DesktopSettings,
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
setDesktopTailscaleServePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
@@ -55,8 +58,13 @@ import {
} from "./clientPersistence.ts";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
import { resolveDesktopServerExposure } from "./serverExposure.ts";
import {
resolveDesktopCoreAdvertisedEndpoints,
resolveDesktopServerExposure,
} from "./serverExposure.ts";
import { DesktopSshEnvironmentBridge, resolveRemoteT3CliPackageSpec } from "./sshEnvironment.ts";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels.ts";
import { ServerListeningDetector } from "./serverListeningDetector.ts";
@@ -74,6 +82,8 @@ import {
} from "./updateMachine.ts";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
import { resolveDesktopAppBranding } from "./appBranding.ts";
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
syncShellEnvironment();
@@ -100,6 +110,8 @@ const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secr
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
@@ -108,6 +120,12 @@ const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
// Dev-only SSH launcher override. Set this to an absolute path on the SSH host
// for a built server entry, for example:
// "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs"
const DEV_REMOTE_T3_SERVER_ENTRY_PATH =
process.env.T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH?.trim() ??
"/Users/julius/Developer/t3code/apps/server/dist/bin.mjs";
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
isDevelopment,
appVersion: app.getVersion(),
@@ -295,6 +313,9 @@ function backendChildEnv(): NodeJS.ProcessEnv {
delete env.T3CODE_DESKTOP_WS_URL;
delete env.T3CODE_DESKTOP_LAN_ACCESS;
delete env.T3CODE_DESKTOP_LAN_HOST;
delete env.T3CODE_DESKTOP_HTTPS_ENDPOINTS;
delete env.T3CODE_TAILSCALE_SERVE;
delete env.T3CODE_TAILSCALE_SERVE_PORT;
return env;
}
@@ -303,9 +324,32 @@ function getDesktopServerExposureState(): DesktopServerExposureState {
mode: desktopServerExposureMode,
endpointUrl: backendEndpointUrl,
advertisedHost: backendAdvertisedHost,
tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,
tailscaleServePort: desktopSettings.tailscaleServePort,
};
}
async function getDesktopAdvertisedEndpoints() {
const exposure = resolveDesktopServerExposure({
mode: desktopServerExposureMode,
port: backendPort,
networkInterfaces: OS.networkInterfaces(),
...(backendAdvertisedHost ? { advertisedHostOverride: backendAdvertisedHost } : {}),
});
const coreEndpoints = resolveDesktopCoreAdvertisedEndpoints({
port: backendPort,
exposure,
customHttpsEndpointUrls: resolveCustomHttpsEndpointUrls(),
});
const tailscaleEndpoints = await resolveTailscaleAdvertisedEndpoints({
port: backendPort,
serveEnabled: desktopSettings.tailscaleServeEnabled,
servePort: desktopSettings.tailscaleServePort,
networkInterfaces: OS.networkInterfaces(),
});
return [...coreEndpoints, ...tailscaleEndpoints];
}
function getDesktopSecretStorage() {
return {
isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
@@ -319,9 +363,19 @@ function resolveAdvertisedHostOverride(): string | undefined {
return override && override.length > 0 ? override : undefined;
}
function resolveCustomHttpsEndpointUrls(): readonly string[] {
return (process.env.T3CODE_DESKTOP_HTTPS_ENDPOINTS ?? "")
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
}
async function applyDesktopServerExposureMode(
mode: DesktopServerExposureMode,
options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean },
options?: {
readonly persist?: boolean;
readonly rejectIfUnavailable?: boolean;
},
): Promise<DesktopServerExposureState> {
const advertisedHostOverride = resolveAdvertisedHostOverride();
const requestedMode = mode;
@@ -359,6 +413,17 @@ async function applyDesktopServerExposureMode(
return getDesktopServerExposureState();
}
async function applyDesktopTailscaleServeEnabled(
nextSettings: DesktopSettings,
): Promise<DesktopServerExposureState> {
desktopSettings = nextSettings;
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
relaunchDesktopApp(
desktopSettings.tailscaleServeEnabled ? "tailscale-serve-enabled" : "tailscale-serve-disabled",
);
return getDesktopServerExposureState();
}
function relaunchDesktopApp(reason: string): void {
writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`);
setImmediate(() => {
@@ -371,6 +436,7 @@ function relaunchDesktopApp(reason: string): void {
`desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
);
})
.then(() => desktopSshEnvironmentBridge.dispose().catch(() => undefined))
.finally(() => {
restoreStdIoCapture?.();
if (isDevelopment) {
@@ -459,51 +525,13 @@ function cancelBackendReadinessWait(): void {
}
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
timeoutMs: 60_000,
});
const listeningPromise = backendListeningDetector?.promise;
if (!listeningPromise) {
await httpReadyPromise;
return "http";
}
return await new Promise<"listening" | "http">((resolve, reject) => {
let settled = false;
const settleResolve = (source: "listening" | "http") => {
if (settled) {
return;
}
settled = true;
if (source === "listening") {
cancelBackendReadinessWait();
}
resolve(source);
};
const settleReject = (error: unknown) => {
if (settled) {
return;
}
settled = true;
reject(error);
};
listeningPromise.then(
() => settleResolve("listening"),
(error) => settleReject(error),
);
httpReadyPromise.then(
() => settleResolve("http"),
(error) => {
if (settled && isBackendReadinessAborted(error)) {
return;
}
settleReject(error);
},
);
return await waitForBackendStartupReady({
listeningPromise: backendListeningDetector?.promise ?? null,
waitForHttpReady: () =>
waitForBackendHttpReady(baseUrl, {
timeoutMs: 60_000,
}),
cancelHttpWait: cancelBackendReadinessWait,
});
}
@@ -665,6 +693,22 @@ let updateInstallInFlight = false;
let updaterConfigured = false;
let updateState: DesktopUpdateState = initialUpdateState();
const desktopSshEnvironmentBridge = new DesktopSshEnvironmentBridge({
getMainWindow: () => mainWindow,
resolveCliRunner: (): RemoteT3RunnerOptions => {
if (isDevelopment && DEV_REMOTE_T3_SERVER_ENTRY_PATH.length > 0) {
return { nodeScriptPath: DEV_REMOTE_T3_SERVER_ENTRY_PATH };
}
return {
packageSpec: resolveRemoteT3CliPackageSpec({
appVersion: app.getVersion(),
updateChannel: desktopSettings.updateChannel,
isDevelopment,
}),
};
},
});
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
if (updateInstallInFlight) return "install";
if (updateDownloadInFlight) return "download";
@@ -1216,7 +1260,10 @@ async function checkForUpdates(reason: string): Promise<boolean> {
}
}
async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
async function downloadAvailableUpdate(): Promise<{
accepted: boolean;
completed: boolean;
}> {
if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
return { accepted: false, completed: false };
}
@@ -1238,7 +1285,10 @@ async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed
}
}
async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
async function installDownloadedUpdate(): Promise<{
accepted: boolean;
completed: boolean;
}> {
if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
return { accepted: false, completed: false };
}
@@ -1438,6 +1488,8 @@ function startBackend(): void {
t3Home: BASE_DIR,
host: backendBindHost,
desktopBootstrapToken: backendBootstrapToken,
tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,
tailscaleServePort: desktopSettings.tailscaleServePort,
...(backendObservabilitySettings.otlpTracesUrl
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
: {}),
@@ -1683,6 +1735,8 @@ function registerIpcHandlers(): void {
},
);
desktopSshEnvironmentBridge.registerIpcHandlers(ipcMain);
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
@@ -1705,6 +1759,31 @@ function registerIpcHandlers(): void {
return nextState;
});
ipcMain.removeHandler(SET_TAILSCALE_SERVE_ENABLED_CHANNEL);
ipcMain.handle(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, async (_event, rawInput: unknown) => {
if (typeof rawInput !== "object" || rawInput === null) {
throw new Error("Invalid Tailscale Serve input.");
}
const input = rawInput as {
readonly enabled?: unknown;
readonly port?: unknown;
};
if (typeof input.enabled !== "boolean") {
throw new Error("Invalid Tailscale Serve input.");
}
const nextSettings = setDesktopTailscaleServePreference(desktopSettings, {
enabled: input.enabled,
...(typeof input.port === "number" ? { port: input.port } : {}),
});
if (nextSettings === desktopSettings) {
return getDesktopServerExposureState();
}
return applyDesktopTailscaleServeEnabled(nextSettings);
});
ipcMain.removeHandler(GET_ADVERTISED_ENDPOINTS_CHANNEL);
ipcMain.handle(GET_ADVERTISED_ENDPOINTS_CHANNEL, async () => getDesktopAdvertisedEndpoints());
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
@@ -1995,7 +2074,10 @@ function createWindow(): BrowserWindow {
const externalUrl = getSafeExternalUrl(params.linkURL);
if (externalUrl) {
menuTemplate.push(
{ label: "Copy Link", click: () => clipboard.writeText(params.linkURL) },
{
label: "Copy Link",
click: () => clipboard.writeText(params.linkURL),
},
{ type: "separator" },
);
}
@@ -2035,16 +2117,17 @@ function createWindow(): BrowserWindow {
emitUpdateState();
});
let initialRevealScheduled = false;
const revealInitialWindow = () => {
if (initialRevealScheduled) {
return;
}
initialRevealScheduled = true;
revealWindow(window);
};
window.once("ready-to-show", revealInitialWindow);
// On Linux/Wayland with `show: false`, Electron's `ready-to-show` only
// fires after `show()` is called, deadlocking the standard "wait for
// ready, then show" pattern. Add `did-finish-load` as a Linux-only
// fallback so the window still surfaces once the renderer has loaded
// the page. Other platforms keep the no-flash `ready-to-show` path,
// since `did-finish-load` typically fires before the first paint there.
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
if (process.platform === "linux") {
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
}
bindFirstRevealTrigger(revealSubscribers, () => revealWindow(window));
if (isDevelopment) {
void window.loadURL(resolveDesktopDevServerUrl());
@@ -2054,6 +2137,9 @@ function createWindow(): BrowserWindow {
}
window.on("closed", () => {
desktopSshEnvironmentBridge.cancelPendingPasswordPrompts(
"SSH authentication was cancelled because the app window closed.",
);
if (mainWindow === window) {
mainWindow = null;
}
@@ -2119,9 +2205,9 @@ async function bootstrap(): Promise<void> {
if (isDevelopment) {
mainWindow = createWindow();
writeDesktopLogHeader("bootstrap main window created");
void waitForBackendHttpReady(backendHttpUrl)
.then(() => {
writeDesktopLogHeader("bootstrap backend ready");
void waitForBackendWindowReady(backendHttpUrl)
.then((source) => {
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
})
.catch((error) => {
if (isBackendReadinessAborted(error)) {
@@ -2145,6 +2231,7 @@ app.on("before-quit", () => {
clearUpdatePollTimer();
cancelBackendReadinessWait();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
});
@@ -2194,6 +2281,7 @@ if (process.platform !== "win32") {
clearUpdatePollTimer();
cancelBackendReadinessWait();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
app.quit();
});
@@ -2204,6 +2292,7 @@ if (process.platform !== "win32") {
writeDesktopLogHeader("SIGTERM received");
clearUpdatePollTimer();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
app.quit();
});
+40
View File
@@ -22,8 +22,19 @@ const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-re
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
@@ -51,8 +62,37 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
discoverSshHosts: () => ipcRenderer.invoke(DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: (target, options) =>
ipcRenderer.invoke(ENSURE_SSH_ENVIRONMENT_CHANNEL, target, options),
disconnectSshEnvironment: (target) =>
ipcRenderer.invoke(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, target),
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
ipcRenderer.invoke(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, httpBaseUrl),
bootstrapSshBearerSession: (httpBaseUrl, credential) =>
ipcRenderer.invoke(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL, httpBaseUrl, credential),
fetchSshSessionState: (httpBaseUrl, bearerToken) =>
ipcRenderer.invoke(FETCH_SSH_SESSION_STATE_CHANNEL, httpBaseUrl, bearerToken),
issueSshWebSocketToken: (httpBaseUrl, bearerToken) =>
ipcRenderer.invoke(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL, httpBaseUrl, bearerToken),
onSshPasswordPrompt: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {
if (typeof request !== "object" || request === null) return;
listener(request as Parameters<typeof listener>[0]);
};
ipcRenderer.on(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
};
},
resolveSshPasswordPrompt: (requestId, password) =>
ipcRenderer.invoke(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL, requestId, password),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
setTailscaleServeEnabled: (input) =>
ipcRenderer.invoke(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL),
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
+120 -1
View File
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
import {
resolveDesktopCoreAdvertisedEndpoints,
resolveDesktopServerExposure,
resolveLanAdvertisedHost,
} from "./serverExposure.ts";
describe("resolveLanAdvertisedHost", () => {
it("prefers an explicit host override", () => {
@@ -74,6 +78,121 @@ describe("resolveLanAdvertisedHost", () => {
});
});
describe("resolveDesktopCoreAdvertisedEndpoints", () => {
it("advertises loopback and LAN endpoints without provider-specific assumptions", () => {
const exposure = resolveDesktopServerExposure({
mode: "network-accessible",
port: 3773,
networkInterfaces: {
en0: [
{
address: "192.168.1.44",
family: "IPv4",
internal: false,
netmask: "255.255.255.0",
cidr: "192.168.1.44/24",
mac: "00:00:00:00:00:00",
},
],
},
});
expect(
resolveDesktopCoreAdvertisedEndpoints({
port: 3773,
exposure,
customHttpsEndpointUrls: [
"https://desktop.example.ts.net",
"http://desktop.example.test:3773",
"not-a-url",
],
}),
).toEqual([
{
id: "desktop-loopback:3773",
label: "This machine",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
},
httpBaseUrl: "http://127.0.0.1:3773/",
wsBaseUrl: "ws://127.0.0.1:3773/",
reachability: "loopback",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
description: "Loopback endpoint for this desktop app.",
},
{
id: "desktop-lan:http://192.168.1.44:3773",
label: "Local network",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
},
httpBaseUrl: "http://192.168.1.44:3773/",
wsBaseUrl: "ws://192.168.1.44:3773/",
reachability: "lan",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
isDefault: true,
description: "Reachable from devices on the same network.",
},
{
id: "manual:https://desktop.example.ts.net",
label: "Custom HTTPS",
provider: {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "https://desktop.example.ts.net/",
wsBaseUrl: "wss://desktop.example.ts.net/",
reachability: "public",
compatibility: {
hostedHttpsApp: "compatible",
desktopApp: "compatible",
},
source: "user",
status: "unknown",
description: "User-configured HTTPS endpoint for this desktop backend.",
},
{
id: "manual:http://desktop.example.test:3773",
label: "Custom HTTPS",
provider: {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "http://desktop.example.test:3773/",
wsBaseUrl: "ws://desktop.example.test:3773/",
reachability: "public",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "user",
status: "unknown",
description: "User-configured HTTPS endpoint for this desktop backend.",
},
]);
});
});
describe("resolveDesktopServerExposure", () => {
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
expect(
+108 -1
View File
@@ -1,5 +1,13 @@
import type { NetworkInterfaceInfo } from "node:os";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/client-runtime";
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
DesktopServerExposureMode,
} from "@t3tools/contracts";
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
@@ -13,6 +21,26 @@ export interface DesktopServerExposure {
readonly advertisedHost: string | null;
}
export interface DesktopAdvertisedEndpointInput {
readonly port: number;
readonly exposure: DesktopServerExposure;
readonly customHttpsEndpointUrls?: readonly string[];
}
const DESKTOP_CORE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
};
const DESKTOP_MANUAL_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
};
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? normalized : undefined;
@@ -21,6 +49,14 @@ const normalizeOptionalHost = (value: string | undefined): string | undefined =>
const isUsableLanIpv4Address = (address: string): boolean =>
!address.startsWith("127.") && !address.startsWith("169.254.");
function isHttpsEndpointUrl(value: string): boolean {
try {
return new URL(value).protocol === "https:";
} catch {
return false;
}
}
export function resolveLanAdvertisedHost(
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
explicitHost: string | undefined,
@@ -78,3 +114,74 @@ export function resolveDesktopServerExposure(input: {
advertisedHost,
};
}
function createDesktopEndpoint(
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
): AdvertisedEndpoint {
return createAdvertisedEndpoint({
...input,
provider: DESKTOP_CORE_ENDPOINT_PROVIDER,
source: "desktop-core",
});
}
function createManualEndpoint(
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
): AdvertisedEndpoint {
return createAdvertisedEndpoint({
...input,
provider: DESKTOP_MANUAL_ENDPOINT_PROVIDER,
source: "user",
});
}
export function resolveDesktopCoreAdvertisedEndpoints(
input: DesktopAdvertisedEndpointInput,
): readonly AdvertisedEndpoint[] {
const endpoints: AdvertisedEndpoint[] = [
createDesktopEndpoint({
id: `desktop-loopback:${input.port}`,
label: "This machine",
httpBaseUrl: input.exposure.localHttpUrl,
reachability: "loopback",
status: "available",
description: "Loopback endpoint for this desktop app.",
}),
];
if (input.exposure.endpointUrl) {
endpoints.push(
createDesktopEndpoint({
id: `desktop-lan:${input.exposure.endpointUrl}`,
label: "Local network",
httpBaseUrl: input.exposure.endpointUrl,
reachability: "lan",
status: "available",
isDefault: true,
description: "Reachable from devices on the same network.",
}),
);
}
for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) {
try {
endpoints.push(
createManualEndpoint({
id: `manual:${customEndpointUrl}`,
label: "Custom HTTPS",
httpBaseUrl: customEndpointUrl,
reachability: "public",
...(isHttpsEndpointUrl(customEndpointUrl)
? ({ hostedHttpsCompatibility: "compatible" } as const)
: {}),
status: "unknown",
description: "User-configured HTTPS endpoint for this desktop backend.",
}),
);
} catch {
// Ignore malformed user-configured endpoints without dropping valid endpoints.
}
}
return endpoints;
}
+86
View File
@@ -0,0 +1,86 @@
import * as FS from "node:fs";
import * as OS from "node:os";
import * as Path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { discoverDesktopSshHosts } from "./sshEnvironment.ts";
const tempDirectories: string[] = [];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
FS.rmSync(directory, { recursive: true, force: true });
}
});
function makeTempHomeDir(): string {
const directory = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-ssh-env-test-"));
tempDirectories.push(directory);
return directory;
}
describe("sshEnvironment", () => {
it("wires desktop host discovery through the ssh package runtime", async () => {
const homeDir = makeTempHomeDir();
const sshDir = Path.join(homeDir, ".ssh");
FS.mkdirSync(Path.join(sshDir, "config.d"), { recursive: true });
FS.writeFileSync(
Path.join(sshDir, "config"),
["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"),
"utf8",
);
FS.writeFileSync(
Path.join(sshDir, "config.d", "team.conf"),
[
"Host staging",
" HostName staging.example.com",
"Host *",
" ServerAliveInterval 30",
"",
].join("\n"),
"utf8",
);
FS.writeFileSync(
Path.join(sshDir, "known_hosts"),
[
"known.example.com ssh-ed25519 AAAA",
"|1|hashed|entry ssh-ed25519 AAAA",
"[bastion.example.com]:2222 ssh-ed25519 AAAA",
"",
].join("\n"),
"utf8",
);
await expect(discoverDesktopSshHosts({ homeDir })).resolves.toEqual([
{
alias: "bastion.example.com",
hostname: "bastion.example.com",
username: null,
port: null,
source: "known-hosts",
},
{
alias: "devbox",
hostname: "devbox",
username: null,
port: null,
source: "ssh-config",
},
{
alias: "known.example.com",
hostname: "known.example.com",
username: null,
port: null,
source: "known-hosts",
},
{
alias: "staging",
hostname: "staging",
username: null,
port: null,
source: "ssh-config",
},
]);
});
});
+379
View File
@@ -0,0 +1,379 @@
import * as Crypto from "node:crypto";
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NetService } from "@t3tools/shared/Net";
import type {
AuthBearerBootstrapResult,
AuthSessionState,
AuthWebSocketTokenResult,
DesktopDiscoveredSshHost,
DesktopSshEnvironmentTarget,
DesktopSshPasswordPromptRequest,
ExecutionEnvironmentDescriptor,
} from "@t3tools/contracts";
import {
SshPasswordPrompt,
type SshPasswordPromptShape,
type SshPasswordRequest,
} from "@t3tools/ssh/auth";
import { discoverSshHosts } from "@t3tools/ssh/config";
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
import {
fetchLoopbackSshJson,
SshEnvironmentManager,
type RemoteT3RunnerOptions,
} from "@t3tools/ssh/tunnel";
import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
export { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
interface DesktopSshEnvironmentManagerOptions {
readonly passwordProvider?: (request: SshPasswordRequest) => Promise<string | null>;
readonly resolveCliPackageSpec?: () => string;
readonly resolveCliRunner?: () => RemoteT3RunnerOptions;
}
const sshRuntime = ManagedRuntime.make(
Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, NetService.layer),
);
function createDesktopSshRuntime(
passwordPrompt: SshPasswordPromptShape,
scope: Scope.Scope,
options: DesktopSshEnvironmentManagerOptions,
) {
return ManagedRuntime.make(
Layer.mergeAll(
NodeServices.layer,
NodeHttpClient.layerUndici,
NetService.layer,
Layer.succeed(Scope.Scope, scope),
Layer.succeed(SshPasswordPrompt, SshPasswordPrompt.of(passwordPrompt)),
SshEnvironmentManager.layer({
...(options.resolveCliPackageSpec === undefined
? {}
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
...(options.resolveCliRunner === undefined
? {}
: { resolveCliRunner: options.resolveCliRunner }),
}),
),
);
}
export async function discoverDesktopSshHosts(input?: {
readonly homeDir?: string;
}): Promise<readonly DesktopDiscoveredSshHost[]> {
return await sshRuntime.runPromise(discoverSshHosts(input ?? {}));
}
export class DesktopSshEnvironmentManager {
private readonly runtime: ReturnType<typeof createDesktopSshRuntime>;
private readonly scope: Scope.Scope;
constructor(options: DesktopSshEnvironmentManagerOptions = {}) {
const passwordPrompt: SshPasswordPromptShape = {
isAvailable: options.passwordProvider !== undefined,
request: (request) => {
const passwordProvider = options.passwordProvider;
if (!passwordProvider) {
return Effect.succeed(null);
}
return Effect.tryPromise({
try: () => passwordProvider(request),
catch: (cause) =>
new SshPasswordPromptError({
message: cause instanceof Error ? cause.message : "SSH password prompt failed.",
cause,
}),
});
},
};
this.scope = Effect.runSync(Scope.make());
this.runtime = createDesktopSshRuntime(passwordPrompt, this.scope, options);
}
async discoverHosts(): Promise<readonly DesktopDiscoveredSshHost[]> {
return await discoverDesktopSshHosts();
}
async ensureEnvironment(
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
) {
return await this.runtime.runPromise(
Effect.service(SshEnvironmentManager).pipe(
Effect.flatMap((manager) => manager.ensureEnvironment(target, options)),
),
);
}
async disconnectEnvironment(target: DesktopSshEnvironmentTarget): Promise<void> {
await this.runtime.runPromise(
Effect.service(SshEnvironmentManager).pipe(
Effect.flatMap((manager) => manager.disconnectEnvironment(target)),
),
);
}
async dispose(): Promise<void> {
await this.runtime.runPromise(Scope.close(this.scope, Exit.void));
await this.runtime.dispose();
}
}
function getSafeDesktopSshTarget(rawTarget: unknown): DesktopSshEnvironmentTarget | null {
if (typeof rawTarget !== "object" || rawTarget === null) {
return null;
}
const target = rawTarget as Partial<DesktopSshEnvironmentTarget>;
if (typeof target.alias !== "string" || typeof target.hostname !== "string") {
return null;
}
if (
target.username !== null &&
target.username !== undefined &&
typeof target.username !== "string"
) {
return null;
}
if (target.port !== null && target.port !== undefined && !Number.isInteger(target.port)) {
return null;
}
const alias = target.alias.trim();
const hostname = target.hostname.trim();
if (alias.length === 0 || hostname.length === 0) {
return null;
}
return {
alias,
hostname,
username: target.username?.trim() || null,
port: target.port ?? null,
};
}
/** Minimal subset of Electron's BrowserWindow used by the SSH bridge. */
export interface DesktopSshBridgeWindow {
isDestroyed(): boolean;
isMinimized(): boolean;
restore(): void;
focus(): void;
readonly webContents: {
send(channel: string, ...args: readonly unknown[]): void;
};
}
/** Minimal subset of Electron's ipcMain used by the SSH bridge. */
export interface DesktopSshBridgeIpcMain {
removeHandler(channel: string): void;
handle(
channel: string,
listener: (event: unknown, ...args: readonly unknown[]) => unknown | Promise<unknown>,
): void;
}
export interface DesktopSshEnvironmentBridgeOptions {
readonly getMainWindow: () => DesktopSshBridgeWindow | null;
readonly resolveCliPackageSpec?: () => string;
readonly resolveCliRunner?: () => RemoteT3RunnerOptions;
readonly passwordPromptTimeoutMs?: number;
}
interface PendingSshPasswordPrompt {
readonly resolve: (password: string | null) => void;
readonly reject: (error: Error) => void;
readonly timeout: ReturnType<typeof setTimeout>;
}
/**
* Wires the SSH environment manager to Electron IPC, owning the renderer-facing
* password prompt state so `main.ts` only needs to register, cancel, and dispose.
*/
export class DesktopSshEnvironmentBridge {
private readonly options: DesktopSshEnvironmentBridgeOptions;
private readonly manager: DesktopSshEnvironmentManager;
private readonly pendingPrompts = new Map<string, PendingSshPasswordPrompt>();
private readonly passwordPromptTimeoutMs: number;
constructor(options: DesktopSshEnvironmentBridgeOptions) {
this.options = options;
this.passwordPromptTimeoutMs =
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
this.manager = new DesktopSshEnvironmentManager({
passwordProvider: (request) => this.requestPasswordFromRenderer(request),
...(options.resolveCliPackageSpec === undefined
? {}
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
...(options.resolveCliRunner === undefined
? {}
: { resolveCliRunner: options.resolveCliRunner }),
});
}
registerIpcHandlers(ipcMain: DesktopSshBridgeIpcMain): void {
ipcMain.removeHandler(DISCOVER_SSH_HOSTS_CHANNEL);
ipcMain.handle(DISCOVER_SSH_HOSTS_CHANNEL, async () => this.manager.discoverHosts());
ipcMain.removeHandler(ENSURE_SSH_ENVIRONMENT_CHANNEL);
ipcMain.handle(ENSURE_SSH_ENVIRONMENT_CHANNEL, async (_event, rawTarget, rawOptions) => {
const target = getSafeDesktopSshTarget(rawTarget);
if (!target) {
throw new Error("Invalid desktop SSH target.");
}
const issuePairingToken =
typeof rawOptions === "object" &&
rawOptions !== null &&
"issuePairingToken" in rawOptions &&
(rawOptions as { issuePairingToken?: unknown }).issuePairingToken === true;
return await this.manager.ensureEnvironment(target, {
issuePairingToken,
});
});
ipcMain.removeHandler(DISCONNECT_SSH_ENVIRONMENT_CHANNEL);
ipcMain.handle(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, async (_event, rawTarget) => {
const target = getSafeDesktopSshTarget(rawTarget);
if (!target) {
throw new Error("Invalid desktop SSH target.");
}
await this.manager.disconnectEnvironment(target);
});
ipcMain.removeHandler(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL);
ipcMain.handle(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, async (_event, rawHttpBaseUrl) =>
sshRuntime.runPromise(
fetchLoopbackSshJson<ExecutionEnvironmentDescriptor>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/.well-known/t3/environment",
}),
),
);
ipcMain.removeHandler(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL);
ipcMain.handle(
BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
async (_event, rawHttpBaseUrl, rawCredential) =>
sshRuntime.runPromise(
fetchLoopbackSshJson<AuthBearerBootstrapResult>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/api/auth/bootstrap/bearer",
method: "POST",
body: { credential: rawCredential },
}),
),
);
ipcMain.removeHandler(FETCH_SSH_SESSION_STATE_CHANNEL);
ipcMain.handle(
FETCH_SSH_SESSION_STATE_CHANNEL,
async (_event, rawHttpBaseUrl, rawBearerToken) =>
sshRuntime.runPromise(
fetchLoopbackSshJson<AuthSessionState>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/api/auth/session",
bearerToken: rawBearerToken,
}),
),
);
ipcMain.removeHandler(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL);
ipcMain.handle(
ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
async (_event, rawHttpBaseUrl, rawBearerToken) =>
sshRuntime.runPromise(
fetchLoopbackSshJson<AuthWebSocketTokenResult>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/api/auth/ws-token",
method: "POST",
bearerToken: rawBearerToken,
}),
),
);
ipcMain.removeHandler(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL);
ipcMain.handle(
RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
async (_event, rawRequestId, rawPassword) => {
if (typeof rawRequestId !== "string" || rawRequestId.trim().length === 0) {
throw new Error("Invalid SSH password prompt id.");
}
if (rawPassword !== null && typeof rawPassword !== "string") {
throw new Error("Invalid SSH password prompt response.");
}
const pending = this.pendingPrompts.get(rawRequestId);
if (!pending) {
throw new Error("SSH password prompt expired. Try connecting again.");
}
clearTimeout(pending.timeout);
this.pendingPrompts.delete(rawRequestId);
pending.resolve(rawPassword);
},
);
}
cancelPendingPasswordPrompts(reason: string): void {
for (const [requestId, pending] of this.pendingPrompts) {
clearTimeout(pending.timeout);
this.pendingPrompts.delete(requestId);
pending.reject(new Error(reason));
}
}
async dispose(): Promise<void> {
this.cancelPendingPasswordPrompts("SSH environment bridge disposed.");
await this.manager.dispose();
}
private async requestPasswordFromRenderer(input: SshPasswordRequest): Promise<string | null> {
const window = this.options.getMainWindow();
if (!window || window.isDestroyed()) {
throw new Error("T3 Code window is not available for SSH authentication.");
}
const request: DesktopSshPasswordPromptRequest = {
requestId: Crypto.randomUUID(),
destination: input.destination,
username: input.username,
prompt: input.prompt,
expiresAt: new Date(Date.now() + this.passwordPromptTimeoutMs).toISOString(),
};
return await new Promise<string | null>((resolve, reject) => {
const timeout = setTimeout(() => {
this.pendingPrompts.delete(request.requestId);
reject(new Error(`SSH authentication timed out for ${input.destination}.`));
}, this.passwordPromptTimeoutMs);
timeout.unref();
this.pendingPrompts.set(request.requestId, { resolve, reject, timeout });
window.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, request);
if (window.isMinimized()) {
window.restore();
}
window.focus();
});
}
}
@@ -0,0 +1,10 @@
#!/bin/sh
# Invoked by ssh via SSH_ASKPASS when T3 Code re-runs ssh with a cached password
# from the renderer's in-app prompt. We never expose a native dialog here — if
# T3_SSH_AUTH_SECRET is missing, that's a caller bug and we fail loudly.
if [ "${T3_SSH_AUTH_SECRET+x}" = "x" ]; then
printf "%s\n" "$T3_SSH_AUTH_SECRET"
exit 0
fi
printf 'T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.\n' >&2
exit 1
@@ -0,0 +1,2 @@
@echo off
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0ssh-askpass.ps1" %*
@@ -0,0 +1,10 @@
# Invoked by ssh via SSH_ASKPASS (through ssh-askpass.cmd) when T3 Code re-runs
# ssh with a cached password from the renderer's in-app prompt. We never expose
# a native dialog here — if T3_SSH_AUTH_SECRET is missing, that's a caller bug
# and we fail loudly.
if ($null -ne $env:T3_SSH_AUTH_SECRET) {
[Console]::Out.WriteLine($env:T3_SSH_AUTH_SECRET)
exit 0
}
[Console]::Error.WriteLine("T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.")
exit 1
@@ -0,0 +1,34 @@
set -eu
STATE_KEY="$1"
STATE_DIR="$HOME/.t3/ssh-launch/$STATE_KEY"
SERVER_HOME="$STATE_DIR/server-home"
PORT_FILE="$STATE_DIR/port"
PID_FILE="$STATE_DIR/pid"
LOG_FILE="$STATE_DIR/server.log"
RUNNER_FILE="$STATE_DIR/run-t3.sh"
mkdir -p "$STATE_DIR" "$SERVER_HOME"
cat >"$RUNNER_FILE" <<'SH'
@@T3_RUNNER_SCRIPT@@
SH
chmod 700 "$RUNNER_FILE"
pick_port() {
node - "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@" <<'NODE'
@@T3_PICK_PORT_SCRIPT@@
NODE
}
REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"
if [ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then
:
else
REMOTE_PORT="$(pick_port)" || true
if [ -z "$REMOTE_PORT" ]; then
printf 'Failed to find an available port on the remote host. Ensure node is available on PATH.\n' >&2
exit 1
fi
nohup env T3CODE_NO_BROWSER=1 "$RUNNER_FILE" serve --host 127.0.0.1 --port "$REMOTE_PORT" --base-dir "$SERVER_HOME" >>"$LOG_FILE" 2>&1 < /dev/null &
REMOTE_PID="$!"
printf '%s\n' "$REMOTE_PID" >"$PID_FILE"
printf '%s\n' "$REMOTE_PORT" >"$PORT_FILE"
fi
printf '{"remotePort":%s}\n' "$REMOTE_PORT"
@@ -0,0 +1,10 @@
set -eu
STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@"
SERVER_HOME="$STATE_DIR/server-home"
RUNNER_FILE="$STATE_DIR/run-t3.sh"
mkdir -p "$STATE_DIR" "$SERVER_HOME"
cat >"$RUNNER_FILE" <<'SH'
@@T3_RUNNER_SCRIPT@@
SH
chmod 700 "$RUNNER_FILE"
"$RUNNER_FILE" auth pairing create --base-dir "$SERVER_HOME" --json
@@ -0,0 +1,31 @@
const fs = require("node:fs");
const net = require("node:net");
const filePath = process.argv[2] ?? "";
const defaultPort = Number.parseInt(process.argv[3] ?? "", 10);
const scanWindow = Number.parseInt(process.argv[4] ?? "", 10);
const raw = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8").trim() : "";
const preferred = Number.parseInt(raw, 10);
const start = Number.isInteger(preferred) ? preferred : defaultPort;
const end = start + scanWindow;
function tryPort(port) {
return new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", () => resolve(false));
server.listen(port, "127.0.0.1", () => {
server.close((error) => resolve(error ? false : port));
});
});
}
(async () => {
for (let port = start; port < end; port += 1) {
const available = await tryPort(port);
if (available) {
process.stdout.write(String(port));
return;
}
}
process.exit(1);
})().catch(() => process.exit(1));
@@ -0,0 +1,13 @@
#!/bin/sh
set -eu
if command -v t3 >/dev/null 2>&1; then
exec t3 "$@"
fi
if command -v npx >/dev/null 2>&1; then
exec npx --yes @@T3_PACKAGE_SPEC@@ "$@"
fi
if command -v npm >/dev/null 2>&1; then
exec npm exec --yes @@T3_PACKAGE_SPEC@@ -- "$@"
fi
printf 'Remote host is missing the t3 CLI and could not install @@T3_PACKAGE_SPEC@@ because npx and npm are unavailable on PATH.\n' >&2
exit 1
@@ -0,0 +1,122 @@
import { describe, expect, it } from "vitest";
import { Effect } from "effect";
import {
isTailscaleIpv4Address,
parseTailscaleMagicDnsName,
resolveTailscaleAdvertisedEndpoints,
} from "./tailscaleEndpointProvider.ts";
describe("tailscale endpoint provider", () => {
it("detects Tailnet IPv4 addresses", () => {
expect(isTailscaleIpv4Address("100.64.0.1")).toBe(true);
expect(isTailscaleIpv4Address("100.127.255.254")).toBe(true);
expect(isTailscaleIpv4Address("100.128.0.1")).toBe(false);
expect(isTailscaleIpv4Address("192.168.1.44")).toBe(false);
});
it("parses MagicDNS names from tailscale status", async () => {
expect(
Effect.runSync(
parseTailscaleMagicDnsName(JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } })),
),
).toBe("desktop.tail.ts.net");
expect(Effect.runSync(parseTailscaleMagicDnsName("{}"))).toBeNull();
await expect(Effect.runPromise(parseTailscaleMagicDnsName("not-json"))).rejects.toBeDefined();
});
it("resolves Tailscale endpoints as add-on advertised endpoints", async () => {
await expect(
resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {
tailscale0: [
{
address: "100.100.100.100",
family: "IPv4",
internal: false,
netmask: "255.192.0.0",
cidr: "100.100.100.100/10",
mac: "00:00:00:00:00:00",
},
],
},
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
}),
).resolves.toEqual([
{
id: "tailscale-ip:http://100.100.100.100:3773",
label: "Tailscale IP",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "http://100.100.100.100:3773/",
wsBaseUrl: "ws://100.100.100.100:3773/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
description: "Reachable from devices on the same Tailnet.",
},
{
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
label: "Tailscale HTTPS",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "https://desktop.tail.ts.net/",
wsBaseUrl: "wss://desktop.tail.ts.net/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "requires-configuration",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "unavailable",
description: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
},
]);
});
it("marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable", async () => {
await expect(
resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {},
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
serveEnabled: true,
probe: async () => true,
}),
).resolves.toEqual([
{
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
label: "Tailscale HTTPS",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "https://desktop.tail.ts.net/",
wsBaseUrl: "wss://desktop.tail.ts.net/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "compatible",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
description: "HTTPS endpoint served by Tailscale Serve.",
},
]);
});
});
@@ -0,0 +1,142 @@
import type { NetworkInterfaceInfo } from "node:os";
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/client-runtime";
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
import {
buildTailscaleHttpsBaseUrl,
isTailscaleIpv4Address,
parseTailscaleMagicDnsName,
probeTailscaleHttpsEndpoint,
readTailscaleStatus,
} from "@t3tools/tailscale";
import { Effect, Layer } from "effect";
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
const TailscaleDesktopLayer = Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici);
const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
};
function createTailscaleEndpoint(
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
): AdvertisedEndpoint {
return createAdvertisedEndpoint({
...input,
provider: TAILSCALE_ENDPOINT_PROVIDER,
source: "desktop-addon",
});
}
export function resolveTailscaleIpAdvertisedEndpoints(input: {
readonly port: number;
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
}): readonly AdvertisedEndpoint[] {
const seen = new Set<string>();
const endpoints: AdvertisedEndpoint[] = [];
for (const interfaceAddresses of Object.values(input.networkInterfaces)) {
if (!interfaceAddresses) continue;
for (const address of interfaceAddresses) {
if (address.internal) continue;
if (address.family !== "IPv4") continue;
if (!isTailscaleIpv4Address(address.address)) continue;
if (seen.has(address.address)) continue;
seen.add(address.address);
endpoints.push(
createTailscaleEndpoint({
id: `tailscale-ip:http://${address.address}:${input.port}`,
label: "Tailscale IP",
httpBaseUrl: `http://${address.address}:${input.port}`,
reachability: "private-network",
status: "available",
description: "Reachable from devices on the same Tailnet.",
}),
);
}
}
return endpoints;
}
export async function resolveTailscaleMagicDnsAdvertisedEndpoint(input: {
readonly dnsName: string | null;
readonly serveEnabled: boolean;
readonly servePort?: number;
readonly probe?: (baseUrl: string) => Promise<boolean>;
}): Promise<AdvertisedEndpoint | null> {
if (!input.dnsName) {
return null;
}
const httpBaseUrl = buildTailscaleHttpsBaseUrl({
magicDnsName: input.dnsName,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
});
const isReachable = input.serveEnabled
? await (input.probe?.(httpBaseUrl) ??
Effect.runPromise(
probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl }).pipe(
Effect.provide(TailscaleDesktopLayer),
),
))
: false;
return createTailscaleEndpoint({
id: `tailscale-magicdns:${httpBaseUrl}`,
label: "Tailscale HTTPS",
httpBaseUrl,
reachability: "private-network",
hostedHttpsCompatibility: isReachable ? "compatible" : "requires-configuration",
status: isReachable ? "available" : "unavailable",
description: isReachable
? "HTTPS endpoint served by Tailscale Serve."
: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
});
}
export async function resolveTailscaleAdvertisedEndpoints(input: {
readonly port: number;
readonly serveEnabled?: boolean;
readonly servePort?: number;
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
readonly statusJson?: string | null;
readonly probe?: (baseUrl: string) => Promise<boolean>;
}): Promise<readonly AdvertisedEndpoint[]> {
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
const dnsName =
input.statusJson === undefined
? await Effect.runPromise(
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed(null)),
Effect.provide(TailscaleDesktopLayer),
),
)
: input.statusJson
? await Effect.runPromise(
parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.catch(() => Effect.succeed(null)),
),
)
: null;
const magicDnsEndpoint = await resolveTailscaleMagicDnsAdvertisedEndpoint({
dnsName,
serveEnabled: input.serveEnabled === true,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
...(input.probe === undefined ? {} : { probe: input.probe }),
});
return magicDnsEndpoint ? [...ipEndpoints, magicDnsEndpoint] : ipEndpoints;
}
+74
View File
@@ -0,0 +1,74 @@
import { EventEmitter } from "node:events";
import { describe, expect, it, vi } from "vitest";
import { bindFirstRevealTrigger } from "./windowReveal.ts";
describe("bindFirstRevealTrigger", () => {
it("reveals when the first trigger fires", () => {
const window = new EventEmitter();
const webContents = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger(
[
(fire) => window.once("ready-to-show", fire),
(fire) => webContents.once("did-finish-load", fire),
],
reveal,
);
window.emit("ready-to-show");
expect(reveal).toHaveBeenCalledTimes(1);
});
it("reveals when only the fallback trigger fires (Wayland deadlock case)", () => {
const window = new EventEmitter();
const webContents = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger(
[
(fire) => window.once("ready-to-show", fire),
(fire) => webContents.once("did-finish-load", fire),
],
reveal,
);
webContents.emit("did-finish-load");
expect(reveal).toHaveBeenCalledTimes(1);
});
it("only reveals once when multiple triggers fire", () => {
const window = new EventEmitter();
const webContents = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger(
[
(fire) => window.once("ready-to-show", fire),
(fire) => webContents.once("did-finish-load", fire),
],
reveal,
);
webContents.emit("did-finish-load");
window.emit("ready-to-show");
expect(reveal).toHaveBeenCalledTimes(1);
});
it("subscribers using `once` ignore re-emitted events after reveal", () => {
const window = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger([(fire) => window.once("ready-to-show", fire)], reveal);
window.emit("ready-to-show");
window.emit("ready-to-show");
expect(reveal).toHaveBeenCalledTimes(1);
});
});
+28
View File
@@ -0,0 +1,28 @@
export type RevealSubscription = (listener: () => void) => void;
/**
* Wire a reveal callback to fire exactly once, on whichever of the provided
* event subscribers fires first. Each subscriber is responsible for binding
* its own event source.
*
* Used by the desktop main window's first-paint reveal logic. The standard
* Electron pattern is to wait for `ready-to-show` before calling `show()`,
* but on Linux/Wayland with `show: false`, `ready-to-show` only fires after
* `show()` is called, deadlocking that pattern. Subscribing to both
* `ready-to-show` and `did-finish-load` (or any other "renderer is alive"
* signal) lets the window surface reliably across platforms.
*/
export function bindFirstRevealTrigger(
subscribers: readonly RevealSubscription[],
reveal: () => void,
): void {
let revealed = false;
const fire = () => {
if (revealed) return;
revealed = true;
reveal();
};
for (const subscribe of subscribers) {
subscribe(fire);
}
}
+2 -1
View File
@@ -12,7 +12,8 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
copy: [{ from: "src/sshScripts/*", to: "dist-electron/sshScripts" }],
},
{
...shared,
@@ -58,6 +58,7 @@ import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../src/orchestration/Services/OrchestrationEngine.ts";
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
import {
@@ -351,6 +352,12 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(runtimeIngestionLayer),
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
Layer.provideMerge(
Layer.succeed(ThreadDeletionReactor, {
start: () => Effect.void,
drain: Effect.void,
}),
),
);
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
+5 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.20",
"version": "0.0.21",
"license": "MIT",
"repository": {
"type": "git",
@@ -29,6 +29,7 @@
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@opencode-ai/sdk": "^1.3.15",
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
@@ -39,9 +40,12 @@
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
+590
View File
@@ -0,0 +1,590 @@
#!/usr/bin/env bun
import { appendFileSync } from "node:fs";
import * as Effect from "effect/Effect";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as EffectAcpAgent from "effect-acp/agent";
import * as AcpError from "effect-acp/errors";
import type * as AcpSchema from "effect-acp/schema";
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
const emitInterleavedAssistantToolCalls =
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
const sessionId = "mock-session-1";
let currentModeId = "ask";
let currentModelId = "default";
let parameterizedModelPicker = false;
let currentReasoning = "medium";
let currentContext = "272k";
let currentFast = false;
const cancelledSessions = new Set<string>();
function logExit(reason: string): void {
if (!exitLogPath) {
return;
}
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
}
process.once("SIGTERM", () => {
logExit("SIGTERM");
process.exit(0);
});
process.once("SIGINT", () => {
logExit("SIGINT");
process.exit(0);
});
process.once("exit", (code) => {
logExit(`exit:${code}`);
});
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
if (parameterizedModelPicker) {
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
{
id: "mode",
name: "Mode",
category: "mode",
type: "select",
currentValue: currentModeId,
options: availableModes.map((mode) => ({
value: mode.id,
name: mode.name,
...(mode.description ? { description: mode.description } : {}),
})),
},
{
id: "model",
name: "Model",
category: "model",
type: "select",
currentValue: currentModelId,
options: [
{ value: "default", name: "Auto" },
{ value: "composer-2", name: "Composer 2" },
{ value: "gpt-5.4", name: "GPT-5.4" },
{ value: "claude-opus-4-6", name: "Opus 4.6" },
],
},
];
switch (currentModelId) {
case "gpt-5.4":
return [
...baseOptions,
{
id: "reasoning",
name: "Reasoning",
category: "thought_level",
type: "select",
currentValue: currentReasoning,
options: [
{ value: "none", name: "None" },
{ value: "low", name: "Low" },
{ value: "medium", name: "Medium" },
{ value: "high", name: "High" },
{ value: "extra-high", name: "Extra High" },
],
},
{
id: "context",
name: "Context",
category: "model_config",
type: "select",
currentValue: currentContext,
options: [
{ value: "272k", name: "272K" },
{ value: "1m", name: "1M" },
],
},
{
id: "fast",
name: "Fast",
category: "model_config",
type: "select",
currentValue: String(currentFast),
options: [
{ value: "false", name: "Off" },
{ value: "true", name: "Fast" },
],
},
];
case "composer-2":
return [
...baseOptions,
{
id: "fast",
name: "Fast",
category: "model_config",
type: "select",
currentValue: String(currentFast),
options: [
{ value: "false", name: "Off" },
{ value: "true", name: "Fast" },
],
},
];
case "claude-opus-4-6":
return [
...baseOptions,
{
id: "reasoning",
name: "Reasoning",
category: "thought_level",
type: "select",
currentValue: currentReasoning,
options: [
{ value: "low", name: "Low" },
{ value: "medium", name: "Medium" },
{ value: "high", name: "High" },
],
},
{
id: "thinking",
name: "Thinking",
category: "model_config",
type: "boolean",
currentValue: true,
},
];
default:
return baseOptions;
}
}
return [
{
id: "model",
name: "Model",
category: "model",
type: "select" as const,
currentValue: currentModelId,
options: [
{ value: "default", name: "Auto" },
{ value: "composer-2", name: "Composer 2" },
{ value: "composer-2[fast=true]", name: "Composer 2 Fast" },
{ value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
],
},
];
}
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
{
id: "ask",
name: "Ask",
description: "Request permission before making any changes",
},
{
id: "architect",
name: "Architect",
description: "Design and plan software systems without implementation",
},
{
id: "code",
name: "Code",
description: "Write and modify code with full tool access",
},
];
function modeState(): AcpSchema.SessionModeState {
return {
currentModeId,
availableModes,
};
}
const program = Effect.gen(function* () {
const agent = yield* EffectAcpAgent.AcpAgent;
yield* agent.handleInitialize((request) =>
Effect.sync(() => {
parameterizedModelPicker =
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
return {
protocolVersion: 1,
agentCapabilities: { loadSession: true },
};
}),
);
yield* agent.handleAuthenticate(() => Effect.succeed({}));
yield* agent.handleCreateSession(() =>
Effect.succeed({
sessionId,
modes: modeState(),
configOptions: configOptions(),
}),
);
yield* agent.handleLoadSession((request) =>
agent.client
.sessionUpdate({
sessionId: String(request.sessionId ?? sessionId),
update: {
sessionUpdate: "user_message_chunk",
content: { type: "text", text: "replay" },
},
})
.pipe(
Effect.as({
modes: modeState(),
configOptions: configOptions(),
}),
),
);
yield* agent.handleSetSessionConfigOption((request) =>
Effect.gen(function* () {
if (exitOnSetConfigOption) {
return yield* Effect.sync(() => {
process.exit(7);
});
}
if (failSetConfigOption) {
return yield* AcpError.AcpRequestError.invalidParams(
"Mock invalid params for session/set_config_option",
{
method: "session/set_config_option",
params: request,
},
);
}
if (request.configId === "mode" && typeof request.value === "string") {
currentModeId = request.value;
}
if (request.configId === "model" && typeof request.value === "string") {
currentModelId = request.value;
}
if (request.configId === "reasoning" && typeof request.value === "string") {
currentReasoning = request.value;
}
if (request.configId === "context" && typeof request.value === "string") {
currentContext = request.value;
}
if (request.configId === "fast") {
currentFast = request.value === true || request.value === "true";
}
return {
configOptions: configOptions(),
};
}),
);
yield* agent.handleCancel(({ sessionId }) =>
Effect.sync(() => {
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
}),
);
yield* agent.handlePrompt((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
if (emitInterleavedAssistantToolCalls) {
const toolCallId = "tool-call-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "before tool" },
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId,
title: "Terminal",
kind: "execute",
status: "pending",
rawInput: {
command: ["echo", "hello"],
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "completed",
rawOutput: {
exitCode: 0,
stdout: "hello",
stderr: "",
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "after tool" },
},
});
return { stopReason: "end_turn" };
}
if (emitToolCalls) {
const toolCallId = "tool-call-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId,
title: "Terminal",
kind: "execute",
status: "pending",
rawInput: {
command: ["cat", "server/package.json"],
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "in_progress",
},
});
const permission = yield* agent.client.requestPermission({
sessionId: requestedSessionId,
toolCall: {
toolCallId,
title: "`cat server/package.json`",
kind: "execute",
status: "pending",
content: [
{
type: "content",
content: {
type: "text",
text: "Not in allowlist: cat server/package.json",
},
},
],
},
options: [
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
],
});
const cancelled =
cancelledSessions.delete(requestedSessionId) ||
permission.outcome.outcome === "cancelled";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
title: "Terminal",
kind: "execute",
status: "completed",
rawOutput: {
exitCode: 0,
stdout: '{ "name": "t3" }',
stderr: "",
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "hello from mock" },
},
});
return { stopReason: cancelled ? "cancelled" : "end_turn" };
}
if (emitGenericToolPlaceholders) {
const toolCallId = "tool-call-generic-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId,
title: "Read File",
kind: "read",
status: "pending",
rawInput: {},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "in_progress",
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "completed",
rawOutput: {
content: "package.json\n",
},
},
});
return { stopReason: "end_turn" };
}
if (emitAskQuestion) {
yield* agent.client.extRequest("cursor/ask_question", {
toolCallId: "ask-question-tool-call-1",
title: "Question",
questions: [
{
id: "scope",
prompt: "Which scope?",
options: [
{ id: "workspace", label: "Workspace" },
{ id: "session", label: "Session" },
],
},
],
});
return { stopReason: "end_turn" };
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "plan",
entries: [
{
content: "Inspect mock ACP state",
priority: "high",
status: "completed",
},
{
content: "Implement the requested change",
priority: "high",
status: "in_progress",
},
],
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: promptResponseText ?? "hello from mock" },
},
});
return { stopReason: "end_turn" };
}),
);
yield* agent.handleUnknownExtRequest((method, params) => {
if (method !== "session/mode/set") {
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
}
const nextModeId =
typeof params === "object" &&
params !== null &&
"modeId" in params &&
typeof params.modeId === "string"
? params.modeId
: typeof params === "object" &&
params !== null &&
"mode" in params &&
typeof params.mode === "string"
? params.mode
: undefined;
const requestedSessionId =
typeof params === "object" &&
params !== null &&
"sessionId" in params &&
typeof params.sessionId === "string"
? params.sessionId
: sessionId;
if (typeof nextModeId === "string" && nextModeId.trim()) {
currentModeId = nextModeId.trim();
return agent.client
.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "current_mode_update",
currentModeId,
},
})
.pipe(Effect.as({}));
}
return Effect.succeed({});
});
return yield* Effect.never;
}).pipe(
Effect.provide(
EffectAcpAgent.layerStdio(
requestLogPath
? {
logIncoming: true,
logger: (event) => {
if (event.direction !== "incoming" || event.stage !== "raw") {
return Effect.void;
}
if (typeof event.payload !== "string") {
return Effect.void;
}
const payload = event.payload;
return Effect.sync(() => {
appendFileSync(
requestLogPath,
payload.endsWith("\n") ? payload : `${payload}\n`,
"utf8",
);
});
},
}
: {},
),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
NodeRuntime.runMain(program);
@@ -0,0 +1,435 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import process from "node:process";
import readline from "node:readline";
type JsonPrimitive = null | boolean | number | string;
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
type JsonRpcId = number | string;
type JsonRpcMessage = {
jsonrpc?: string;
id?: JsonRpcId;
method?: string;
params?: JsonValue;
result?: JsonValue;
error?: JsonValue;
headers?: JsonValue;
};
type SelectLeafOption = {
value: string;
label?: string;
name?: string;
};
type SelectGroupOption = {
label?: string;
name?: string;
options: SelectLeafOption[];
};
type SessionConfigOption = {
id: string;
name?: string;
category?: string;
type?: string;
options?: Array<SelectLeafOption | SelectGroupOption>;
};
type SessionNewResult = {
sessionId: string;
configOptions?: SessionConfigOption[];
};
type SetConfigResult = {
configOptions?: SessionConfigOption[];
};
type PendingRequest = {
method: string;
resolve: (value: JsonValue | undefined) => void;
reject: (error: Error) => void;
};
const targetCwd = process.argv[2] ?? process.cwd();
const targetModel = process.argv[3] ?? "gpt-5.4";
const promptText = process.argv[4] ?? "helo";
const targetReasoning = process.env.CURSOR_REASONING ?? "";
const targetContext = process.env.CURSOR_CONTEXT ?? "";
const targetFast = process.env.CURSOR_FAST ?? "";
const agentBin = process.env.CURSOR_AGENT_BIN ?? "agent";
const promptWaitMs = Number(process.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
const requestTimeoutMs = Number(process.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
function logSection(title: string, value: unknown) {
process.stdout.write(`\n=== ${title} ===\n`);
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
}
function fail(message: string): never {
throw new Error(message);
}
function asString(value: JsonValue | undefined): string | null {
return typeof value === "string" ? value : null;
}
function flattenSelectValues(option: SessionConfigOption | undefined): string[] {
if (!option || option.type !== "select" || !Array.isArray(option.options)) {
return [];
}
const values: string[] = [];
for (const entry of option.options) {
if (!entry || typeof entry !== "object") {
continue;
}
if ("value" in entry && typeof entry.value === "string") {
values.push(entry.value);
continue;
}
if ("options" in entry && Array.isArray(entry.options)) {
for (const nested of entry.options) {
if (nested && typeof nested === "object" && typeof nested.value === "string") {
values.push(nested.value);
}
}
}
}
return values;
}
function findConfigOption(
configOptions: SessionConfigOption[],
predicate: (option: SessionConfigOption) => boolean,
): SessionConfigOption | undefined {
return configOptions.find(predicate);
}
function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();
return haystack.includes(keyword.toLowerCase());
}
function sleep(ms: number) {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
}
class JsonRpcChild {
readonly child: ChildProcessWithoutNullStreams;
readonly pending = new Map<JsonRpcId, PendingRequest>();
nextId = 1;
closed = false;
constructor(bin: string, args: string[], cwd: string) {
this.child = spawn(bin, args, {
cwd,
shell: process.platform === "win32",
stdio: ["pipe", "pipe", "pipe"],
env: process.env,
});
this.child.on("exit", (code, signal) => {
this.closed = true;
const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
for (const pending of this.pending.values()) {
pending.reject(new Error(`${detail} while waiting for ${pending.method}`));
}
this.pending.clear();
});
this.child.on("error", (error) => {
this.closed = true;
for (const pending of this.pending.values()) {
pending.reject(error);
}
this.pending.clear();
});
const stdout = readline.createInterface({ input: this.child.stdout });
stdout.on("line", (line) => {
void this.handleStdoutLine(line);
});
const stderr = readline.createInterface({ input: this.child.stderr });
stderr.on("line", (line) => {
process.stdout.write(`[stderr] ${line}\n`);
});
}
write(message: JsonRpcMessage) {
if (this.closed) {
fail("ACP process is already closed.");
}
const payload = JSON.stringify({
jsonrpc: "2.0",
headers: [],
...message,
});
process.stdout.write(`>>> ${payload}\n`);
this.child.stdin.write(`${payload}\n`);
}
async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {
const id = this.nextId++;
const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
const timeout = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
}, timeoutMs);
this.pending.set(id, {
method,
resolve: (value) => {
clearTimeout(timeout);
resolve(value);
},
reject: (error) => {
clearTimeout(timeout);
reject(error);
},
});
});
this.write({
id,
method,
params,
});
return responsePromise;
}
notify(method: string, params: JsonValue) {
this.write({
method,
params,
});
}
respond(id: JsonRpcId, result: JsonValue) {
this.write({
id,
result,
});
}
respondError(id: JsonRpcId, code: number, message: string) {
this.write({
id,
error: {
code,
message,
},
});
}
async handleStdoutLine(line: string) {
if (line.trim().length === 0) {
return;
}
process.stdout.write(`<<< ${line}\n`);
let message: JsonRpcMessage;
try {
message = JSON.parse(line) as JsonRpcMessage;
} catch (error) {
process.stdout.write(`[parse-error] ${(error as Error).message}\n`);
return;
}
if (typeof message.id !== "undefined" && !message.method) {
const pending = this.pending.get(message.id);
if (!pending) {
return;
}
this.pending.delete(message.id);
if (typeof message.error !== "undefined") {
pending.reject(
new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),
);
return;
}
pending.resolve(message.result);
return;
}
if (message.method === "session/request_permission" && typeof message.id !== "undefined") {
this.respond(message.id, {
outcome: {
outcome: "selected",
optionId: "allow",
},
});
return;
}
if (typeof message.id !== "undefined" && message.id !== "") {
this.respondError(
message.id,
-32601,
`Unhandled server request: ${message.method ?? "unknown"}`,
);
}
}
async close() {
if (this.closed) {
return;
}
this.child.kill("SIGTERM");
await sleep(250);
if (!this.closed) {
this.child.kill("SIGKILL");
}
}
}
async function setSelectOptionIfAdvertised(
rpc: JsonRpcChild,
sessionId: string,
configOptions: SessionConfigOption[],
predicate: (option: SessionConfigOption) => boolean,
value: string,
label: string,
) {
if (value.length === 0) {
return configOptions;
}
const option = findConfigOption(configOptions, predicate);
const values = flattenSelectValues(option);
if (!option || !values.includes(value)) {
logSection(`SKIP_${label}`, {
requestedValue: value,
availableValues: values,
});
return configOptions;
}
const response = (await rpc.request("session/set_config_option", {
sessionId,
configId: option.id,
value,
})) as SetConfigResult | null | undefined;
logSection(`SET_${label}_RESPONSE`, response);
return response?.configOptions ?? configOptions;
}
async function main() {
const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);
try {
const initializeResponse = await rpc.request("initialize", {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
_meta: {
parameterizedModelPicker: true,
},
},
clientInfo: {
name: "cursor-acp-model-mismatch-probe",
version: "0.0.0",
},
});
logSection("INITIALIZE_RESPONSE", initializeResponse);
const authenticateResponse = await rpc.request("authenticate", {
methodId: "cursor_login",
});
logSection("AUTHENTICATE_RESPONSE", authenticateResponse);
const sessionResponse = (await rpc.request("session/new", {
cwd: targetCwd,
mcpServers: [],
})) as SessionNewResult;
logSection("SESSION_NEW_RESPONSE", sessionResponse);
const sessionId = asString(sessionResponse.sessionId);
if (!sessionId) {
fail("session/new did not return a sessionId.");
}
let configOptions = sessionResponse.configOptions ?? [];
const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");
const advertisedModels = flattenSelectValues(modelConfig);
logSection("ADVERTISED_MODEL_VALUES", advertisedModels);
if (!modelConfig || modelConfig.type !== "select") {
fail("Cursor ACP did not expose a select-type model config option.");
}
if (!advertisedModels.includes(targetModel)) {
fail(
`Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,
);
}
const setModelResponse = (await rpc.request("session/set_config_option", {
sessionId,
configId: modelConfig.id,
value: targetModel,
})) as SetConfigResult | null | undefined;
logSection("SET_MODEL_RESPONSE", setModelResponse);
configOptions = setModelResponse?.configOptions ?? configOptions;
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "thought_level",
targetReasoning,
"REASONING",
);
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "model_config" && matchesKeyword(option, "context"),
targetContext,
"CONTEXT",
);
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "model_config" && matchesKeyword(option, "fast"),
targetFast,
"FAST",
);
const promptResponse = await rpc.request("session/prompt", {
sessionId,
prompt: [
{
type: "text",
text: promptText,
},
],
});
logSection("PROMPT_RESPONSE", promptResponse);
await sleep(promptWaitMs);
rpc.notify("session/cancel", { sessionId });
} finally {
await rpc.close();
}
}
void main().catch((error: unknown) => {
process.stderr.write(
`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
);
process.exitCode = 1;
});
+25
View File
@@ -0,0 +1,25 @@
import { Effect, FileSystem, Path } from "effect";
import * as Random from "effect/Random";
export const writeFileStringAtomically = (input: {
readonly filePath: string;
readonly contents: string;
}) =>
Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempFileId = yield* Random.nextUUIDv4;
const targetDirectory = path.dirname(input.filePath);
yield* fs.makeDirectory(targetDirectory, { recursive: true });
const tempDirectory = yield* fs.makeTempDirectoryScoped({
directory: targetDirectory,
prefix: `${path.basename(input.filePath)}.`,
});
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
yield* fs.writeFileString(tempPath, input.contents);
yield* fs.rename(tempPath, input.filePath);
}),
);
@@ -19,6 +19,8 @@ import { GitCore } from "../../git/Services/GitCore.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -245,6 +247,7 @@ const makeCheckpointStore = Effect.gen(function* () {
operation,
cwd: input.cwd,
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
return result.stdout;
+36
View File
@@ -46,6 +46,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -87,6 +89,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -108,6 +112,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(true),
logWebSocketEvents: Option.some(true),
tailscaleServeEnabled: Option.some(true),
tailscaleServePort: Option.some(8443),
},
Option.some("Debug"),
).pipe(
@@ -149,6 +155,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
});
}),
);
@@ -161,6 +169,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
@@ -176,6 +186,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(false),
logWebSocketEvents: Option.some(false),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -212,6 +224,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -229,6 +243,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
});
@@ -246,6 +262,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -281,6 +299,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
assert.equal(join(baseDir, "dev"), resolved.stateDir);
}),
@@ -305,6 +325,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -346,6 +368,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: false,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
@@ -361,6 +385,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.some("Debug"),
).pipe(
@@ -399,6 +425,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -432,6 +460,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -463,6 +493,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -485,6 +517,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
{
@@ -522,6 +556,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
+2
View File
@@ -76,6 +76,8 @@ const makeCliTestServerConfig = (baseDir: string) =>
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
} satisfies ServerConfigShape;
});
+47
View File
@@ -78,6 +78,8 @@ const BootstrapEnvelopeSchema = Schema.Struct({
desktopBootstrapToken: Schema.optional(Schema.String),
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
logWebSocketEvents: Schema.optional(Schema.Boolean),
tailscaleServeEnabled: Schema.optional(Schema.Boolean),
tailscaleServePort: Schema.optional(PortSchema),
otlpTracesUrl: Schema.optional(Schema.String),
otlpMetricsUrl: Schema.optional(Schema.String),
});
@@ -126,6 +128,17 @@ const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
Flag.withAlias("log-ws-events"),
Flag.optional,
);
const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(
Flag.withDescription(
"Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
),
Flag.optional,
);
const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
Flag.optional,
);
const EnvServerConfig = Config.all({
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
@@ -174,6 +187,14 @@ const EnvServerConfig = Config.all({
Config.option,
Config.map(Option.getOrUndefined),
),
tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
});
interface CliServerFlags {
@@ -187,6 +208,8 @@ interface CliServerFlags {
readonly bootstrapFd: Option.Option<number>;
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
readonly logWebSocketEvents: Option.Option<boolean>;
readonly tailscaleServeEnabled: Option.Option<boolean>;
readonly tailscaleServePort: Option.Option<number>;
}
interface CliAuthLocationFlags {
@@ -233,6 +256,8 @@ export const resolveServerConfig = (
bootstrapFd: flags.bootstrapFd ?? Option.none(),
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
} satisfies CliServerFlags;
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
@@ -323,6 +348,22 @@ export const resolveServerConfig = (
),
() => Boolean(devUrl),
);
const tailscaleServeEnabled = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.tailscaleServeEnabled,
Option.fromUndefinedOr(env.tailscaleServeEnabled),
Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
),
() => false,
);
const tailscaleServePort = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.tailscaleServePort,
Option.fromUndefinedOr(env.tailscaleServePort),
Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
),
() => 443,
);
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
@@ -365,6 +406,8 @@ export const resolveServerConfig = (
desktopBootstrapToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
tailscaleServeEnabled,
tailscaleServePort,
};
return config;
@@ -386,6 +429,8 @@ const resolveCliAuthConfig = (
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
cliLogLevel,
);
@@ -766,6 +811,8 @@ const sharedServerCommandFlags = {
bootstrapFd: bootstrapFdFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
tailscaleServeEnabled: tailscaleServeFlag,
tailscaleServePort: tailscaleServePortFlag,
} as const;
const authLocationFlags = sharedServerLocationFlags;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+4
View File
@@ -65,6 +65,8 @@ export interface ServerConfigShape extends ServerDerivedPaths {
readonly desktopBootstrapToken: string | undefined;
readonly autoBootstrapProjectFromCwd: boolean;
readonly logWebSocketEvents: boolean;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
}
export const deriveServerPaths = Effect.fn(function* (
@@ -158,6 +160,8 @@ export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShap
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
@@ -30,6 +30,8 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
@@ -1,6 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
@@ -199,12 +200,10 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
thinking: false,
effort: "high",
},
...createModelSelection("claudeAgent", "claude-haiku-4-5", [
{ id: "thinking", value: false },
{ id: "effort", value: "high" },
]),
},
});
@@ -235,12 +234,10 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
diffSummary: "1 file changed",
diffPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
fastMode: true,
},
...createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
]),
},
});
@@ -11,7 +11,6 @@ import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ClaudeModelSelection } from "@t3tools/contracts";
import { resolveApiModelId } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
@@ -29,9 +28,17 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import {
getModelSelectionStringOptionValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import {
getClaudeModelCapabilities,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeEffort,
} from "../../provider/Layers/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -84,15 +91,24 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
modelSelection: ClaudeModelSelection;
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const caps = getClaudeModelCapabilities(modelSelection.model);
const descriptors = getProviderOptionDescriptors({
caps,
selections: modelSelection.options,
});
const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
const rawEffortSelection = getModelSelectionStringOptionValue(modelSelection, "effort");
const resolvedEffort = resolveClaudeEffort(caps, rawEffortSelection);
const cliEffort = normalizeClaudeCliEffort(resolvedEffort);
const thinkingDescriptor = findDescriptor("thinking");
const fastModeDescriptor = findDescriptor("fastMode");
const thinking =
thinkingDescriptor?.type === "boolean" ? thinkingDescriptor.currentValue : undefined;
const fastMode =
fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
...(fastMode ? { fastMode: true } : {}),
};
const claudeSettings = yield* Effect.map(
@@ -110,8 +126,8 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
resolveClaudeApiModelId(modelSelection),
...(cliEffort ? ["--effort", cliEffort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
@@ -1,6 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Result } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
@@ -244,14 +245,10 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "xhigh",
fastMode: true,
},
},
modelSelection: createModelSelection("codex", "gpt-5.4", [
{ id: "reasoningEffort", value: "xhigh" },
{ id: "fastMode", value: true },
]),
});
}),
),
@@ -8,6 +8,7 @@ import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shar
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import { TextGenerationError } from "@t3tools/contracts";
import {
type BranchNameGenerationInput,
@@ -28,9 +29,11 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -155,12 +158,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
modelSelection.options,
);
const reasoningEffort =
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexSettings?.binaryPath || "codex",
[
@@ -173,7 +173,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true
? ["--config", `service_tier="fast"`]
: []),
"--output-schema",
schemaPath,
"--output-last-message",
@@ -184,7 +186,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
{
env: {
...process.env,
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
...(codexSettings?.homePath
? { CODEX_HOME: expandHomePath(codexSettings.homePath) }
: {}),
},
cwd,
shell: process.platform === "win32",
@@ -0,0 +1,297 @@
import * as path from "node:path";
import * as os from "node:os";
import { fileURLToPath } from "node:url";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerSettingsError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
const binDir = path.join(dir, "bin");
const agentPath = path.join(binDir, "agent");
mkdirSync(binDir, { recursive: true });
writeFileSync(
agentPath,
[
"#!/bin/sh",
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
'if [ "$1" != "acp" ]; then',
' printf "%s\\n" "unexpected args: $*" >&2',
" exit 11",
"fi",
`exec bun ${JSON.stringify(mockAgentPath)}`,
"",
].join("\n"),
"utf8",
);
chmodSync(agentPath, 0o755);
return agentPath;
}
function withFakeAcpAgent<A, E, R>(
env: Record<string, string>,
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
return Effect.gen(function* () {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
const agentPath = makeAcpAgentWrapper(tempDir, env);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
cursor: {
binaryPath: agentPath,
},
},
});
return yield* effect.pipe(
Effect.ensuring(
serverSettings
.updateSettings({
providers: {
cursor: {
binaryPath: previousSettings.providers.cursor.binaryPath,
},
},
})
.pipe(
Effect.catch(() => Effect.void),
Effect.ensuring(
Effect.sync(() => {
rmSync(tempDir, { recursive: true, force: true });
}),
),
Effect.asVoid,
),
),
);
});
}
function waitForFileContent(path: string): Effect.Effect<string> {
return Effect.promise(async () => {
const deadline = Date.now() + 5_000;
for (;;) {
try {
return readFileSync(path, "utf8");
} catch (error) {
if (Date.now() >= deadline) {
throw error instanceof Error ? error : new Error(String(error));
}
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
});
}
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
return withFakeAcpAgent(
{
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Add generated commit message",
body: "- verify cursor acp model config path",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-text-generation",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
...createModelSelection("cursor", "gpt-5.4", [
{ id: "reasoning", value: "xhigh" },
{ id: "fastMode", value: true },
{ id: "contextWindow", value: "1m" },
]),
},
});
expect(generated.subject).toBe("Add generated commit message");
expect(generated.body).toBe("- verify cursor acp model config path");
const requests = readFileSync(requestLogPath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
expect(
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
).toMatchObject({
_meta: {
parameterizedModelPicker: true,
},
});
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "model" &&
request.params?.value === "gpt-5.4",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "reasoning" &&
request.params?.value === "extra-high",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "context" &&
request.params?.value === "1m",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "fast" &&
request.params?.value === "true",
),
).toBe(true);
expect(
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "text",
text: expect.stringContaining("Staged patch:"),
}),
]),
);
rmSync(requestLogDir, { recursive: true, force: true });
}),
);
});
it.effect("accepts json objects with extra assistant text around them", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT:
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-noisy-json",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
expect(generated.body).toBe("");
}),
),
);
it.effect("generates thread titles through Cursor ACP text generation", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
title: '"Trim reconnect spinner status after resume."',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Fix the reconnect spinner after a resumed session.",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
}),
),
);
it.effect("closes the ACP child process after text generation completes", () => {
const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
const exitLogPath = path.join(exitLogDir, "exit.log");
return withFakeAcpAgent(
{
T3_ACP_EXIT_LOG_PATH: exitLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Close runtime after generation",
body: "",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-runtime-close",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Close runtime after generation");
const exitLog = yield* waitForFileContent(exitLogPath);
expect(exitLog).toContain("exit:0");
rmSync(exitLogDir, { recursive: true, force: true });
}),
);
});
});
@@ -0,0 +1,309 @@
import { Effect, Layer, Option, Ref, Schema } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { CursorModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import {
type ThreadTitleGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
} from "../Utils.ts";
import {
applyCursorAcpModelSelection,
makeCursorAcpRuntime,
} from "../../provider/acp/CursorAcpSupport.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const CURSOR_TIMEOUT_MS = 180_000;
function mapCursorAcpError(
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
detail: string,
cause: unknown,
): TextGenerationError {
return new TextGenerationError({
operation,
detail,
...(cause !== undefined ? { cause } : {}),
});
}
function isTextGenerationError(error: unknown): error is TextGenerationError {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
error._tag === "TextGenerationError"
);
}
const makeCursorTextGeneration = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverSettingsService = yield* Effect.service(ServerSettingsService);
const runCursorJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
outputSchemaJson,
modelSelection,
}: {
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
cwd: string;
prompt: string;
outputSchemaJson: S;
modelSelection: CursorModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const cursorSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.cursor,
).pipe(Effect.catch(() => Effect.undefined));
const outputRef = yield* Ref.make("");
const runtime = yield* makeCursorAcpRuntime({
cursorSettings,
childProcessSpawner: commandSpawner,
cwd,
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
});
yield* runtime.handleSessionUpdate((notification) => {
const update = notification.update;
if (update.sessionUpdate !== "agent_message_chunk") {
return Effect.void;
}
const content = update.content;
if (content.type !== "text") {
return Effect.void;
}
return Ref.update(outputRef, (current) => current + content.text);
});
const promptResult = yield* Effect.gen(function* () {
yield* runtime.start();
yield* Effect.ignore(runtime.setMode("ask"));
yield* applyCursorAcpModelSelection({
runtime,
model: modelSelection.model,
selections: modelSelection.options,
mapError: ({ cause, configId, step }) =>
mapCursorAcpError(
operation,
step === "set-config-option"
? `Failed to set Cursor ACP config option "${configId}" for text generation.`
: "Failed to set Cursor ACP base model for text generation.",
cause,
),
});
return yield* runtime.prompt({
prompt: [{ type: "text", text: prompt }],
});
}).pipe(
Effect.timeoutOption(CURSOR_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Cursor Agent request timed out.",
}),
),
onSome: (value) => Effect.succeed(value),
}),
),
Effect.mapError((cause) =>
isTextGenerationError(cause)
? cause
: mapCursorAcpError(operation, "Cursor ACP request failed.", cause),
),
);
const rawResult = (yield* Ref.get(outputRef)).trim();
if (!rawResult) {
return yield* new TextGenerationError({
operation,
detail:
promptResult.stopReason === "cancelled"
? "Cursor ACP request was cancelled."
: "Cursor Agent returned empty output.",
});
}
return yield* Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))(
extractJsonObject(rawResult),
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Cursor Agent returned invalid structured output.",
cause,
}),
),
),
);
}).pipe(
Effect.mapError((cause) =>
isTextGenerationError(cause)
? cause
: mapCursorAcpError(operation, "Cursor ACP text generation failed.", cause),
),
Effect.scoped,
);
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"CursorTextGeneration.generateCommitMessage",
)(function* (input) {
const { prompt, outputSchema } = buildCommitMessagePrompt({
branch: input.branch,
stagedSummary: input.stagedSummary,
stagedPatch: input.stagedPatch,
includeBranch: input.includeBranch === true,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
};
});
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
"CursorTextGeneration.generatePrContent",
)(function* (input) {
const { prompt, outputSchema } = buildPrContentPrompt({
baseBranch: input.baseBranch,
headBranch: input.headBranch,
commitSummary: input.commitSummary,
diffSummary: input.diffSummary,
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
});
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
"CursorTextGeneration.generateBranchName",
)(function* (input) {
const { prompt, outputSchema } = buildBranchNamePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
branch: sanitizeBranchFragment(generated.branch),
};
});
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"CursorTextGeneration.generateThreadTitle",
)(function* (input) {
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generateThreadTitle",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizeThreadTitle(generated.title),
} satisfies ThreadTitleGenerationResult;
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
} satisfies TextGenerationShape;
});
export const CursorTextGenerationLive = Layer.effect(TextGeneration, makeCursorTextGeneration);
@@ -0,0 +1,340 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Duration, Effect, Layer } from "effect";
import { TestClock } from "effect/testing";
import { NetService } from "@t3tools/shared/Net";
import { beforeEach, expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../../provider/opencodeRuntime.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
const runtimeMock = {
state: {
startCalls: [] as string[],
promptUrls: [] as string[],
authHeaders: [] as Array<string | null>,
closeCalls: [] as string[],
promptResult: undefined as
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
| undefined,
},
reset() {
this.state.startCalls.length = 0;
this.state.promptUrls.length = 0;
this.state.authHeaders.length = 0;
this.state.closeCalls.length = 0;
this.state.promptResult = undefined;
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
startOpenCodeServerProcess: ({ binaryPath }) =>
Effect.gen(function* () {
const index = runtimeMock.state.startCalls.length + 1;
const url = `http://127.0.0.1:${4_300 + index}`;
runtimeMock.state.startCalls.push(binaryPath);
// The production runtime binds server lifetime to the caller's scope.
// Mirror that here so the closeCalls probe observes scope close.
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
runtimeMock.state.closeCalls.push(url);
}),
);
return {
url,
exitCode: Effect.never,
};
}),
connectToOpenCodeServer: ({ serverUrl }) =>
Effect.succeed({
url: serverUrl ?? "http://127.0.0.1:4301",
exitCode: null,
external: Boolean(serverUrl),
}),
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
({
session: {
create: async () => ({ data: { id: `${baseUrl}/session` } }),
prompt: async () => {
runtimeMock.state.promptUrls.push(baseUrl);
runtimeMock.state.authHeaders.push(
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
);
return (
runtimeMock.state.promptResult ?? {
data: {
parts: [
{
type: "text",
text: JSON.stringify({
subject: "Improve OpenCode reuse",
body: "Reuse one server for the full action.",
}),
},
],
},
}
);
},
},
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
loadOpenCodeInventory: () =>
Effect.fail(
new OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
cause: null,
}),
),
};
const DEFAULT_TEST_MODEL_SELECTION = {
provider: "opencode" as const,
model: "openai/gpt-5",
};
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
},
},
}),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-test-",
}),
),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
);
const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
},
},
}),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-existing-server-test-",
}),
),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
);
beforeEach(() => {
runtimeMock.reset();
});
const advanceIdleClock = Effect.gen(function* () {
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
yield* Effect.yieldNow;
});
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:4301",
"http://127.0.0.1:4301",
]);
expect(runtimeMock.state.closeCalls).toEqual([]);
yield* advanceIdleClock;
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("starts a new server after the warm server idles out", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* advanceIdleClock;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:4301",
"http://127.0.0.1:4302",
]);
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = { data: {} };
const textGeneration = yield* TextGeneration;
const error = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("OpenCode returned empty output.");
}),
);
it.effect("parses JSON returned as plain text output", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
parts: [
{
type: "text",
text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
},
],
},
};
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(result).toEqual({
subject: "Tighten OpenCode parsing",
body: "Handle JSON text output locally.",
});
}),
);
it.effect("surfaces the upstream OpenCode structured-output error message", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
info: {
error: {
name: "StructuredOutputError",
data: {
message: "Model did not produce structured output",
retries: 2,
},
},
},
},
};
const textGeneration = yield* TextGeneration;
const error = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("Model did not produce structured output");
}),
);
});
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
"OpenCodeTextGenerationLive with configured server URL",
(it) => {
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual([]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:9999",
"http://127.0.0.1:9999",
]);
expect(runtimeMock.state.authHeaders).toEqual([
`Basic ${btoa("opencode:secret-password")}`,
`Basic ${btoa("opencode:secret-password")}`,
]);
yield* advanceIdleClock;
expect(runtimeMock.state.closeCalls).toEqual([]);
}).pipe(Effect.provide(TestClock.layer())),
);
},
);
@@ -0,0 +1,511 @@
import { Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";
import * as Semaphore from "effect/Semaphore";
import {
TextGenerationError,
type ChatAttachment,
type OpenCodeModelSelection,
} from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { ServerConfig } from "../../config.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
} from "../Utils.ts";
import {
OpenCodeRuntime,
type OpenCodeServerConnection,
type OpenCodeServerProcess,
openCodeRuntimeErrorDetail,
parseOpenCodeModelSlug,
toOpenCodeFileParts,
} from "../../provider/opencodeRuntime.ts";
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
function getOpenCodePromptErrorMessage(error: unknown): string | null {
if (!error || typeof error !== "object") {
return null;
}
const message =
"data" in error &&
error.data &&
typeof error.data === "object" &&
"message" in error.data &&
typeof error.data.message === "string"
? error.data.message.trim()
: "";
if (message.length > 0) {
return message;
}
if ("name" in error && typeof error.name === "string") {
const name = error.name.trim();
return name.length > 0 ? name : null;
}
return null;
}
function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): string {
return (parts ?? [])
.flatMap((part) => {
if (!part || typeof part !== "object") {
return [];
}
if (!("type" in part) || part.type !== "text") {
return [];
}
if (!("text" in part) || typeof part.text !== "string") {
return [];
}
return [part.text];
})
.join("")
.trim();
}
interface SharedOpenCodeTextGenerationServerState {
server: OpenCodeServerProcess | null;
/**
* The scope that owns the shared server's lifetime. Closing this scope
* terminates the OpenCode child process and interrupts any fibers the
* runtime forked during startup. We don't hold a `close()` function on
* the server handle anymore — the scope is the only lifecycle handle.
*/
serverScope: Scope.Closeable | null;
binaryPath: string | null;
activeRequests: number;
idleCloseFiber: Fiber.Fiber<void, never> | null;
}
const makeOpenCodeTextGeneration = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const serverSettingsService = yield* ServerSettingsService;
const openCodeRuntime = yield* OpenCodeRuntime;
const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const sharedServerMutex = yield* Semaphore.make(1);
const sharedServerState: SharedOpenCodeTextGenerationServerState = {
server: null,
serverScope: null,
binaryPath: null,
activeRequests: 0,
idleCloseFiber: null,
};
const closeSharedServer = Effect.fn("closeSharedServer")(function* () {
const scope = sharedServerState.serverScope;
sharedServerState.server = null;
sharedServerState.serverScope = null;
sharedServerState.binaryPath = null;
if (scope !== null) {
yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);
}
});
const cancelIdleCloseFiber = Effect.fn("cancelIdleCloseFiber")(function* () {
const idleCloseFiber = sharedServerState.idleCloseFiber;
sharedServerState.idleCloseFiber = null;
if (idleCloseFiber !== null) {
yield* Fiber.interrupt(idleCloseFiber).pipe(Effect.ignore);
}
});
const scheduleIdleClose = Effect.fn("scheduleIdleClose")(function* (
server: OpenCodeServerProcess,
) {
yield* cancelIdleCloseFiber();
const fiber = yield* Effect.sleep(OPENCODE_TEXT_GENERATION_IDLE_TTL).pipe(
Effect.andThen(
sharedServerMutex.withPermit(
Effect.gen(function* () {
if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) {
return;
}
sharedServerState.idleCloseFiber = null;
yield* closeSharedServer();
}),
),
),
Effect.forkIn(idleFiberScope),
);
sharedServerState.idleCloseFiber = fiber;
});
const acquireSharedServer = (input: {
readonly binaryPath: string;
readonly operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
}) =>
sharedServerMutex.withPermit(
Effect.gen(function* () {
yield* cancelIdleCloseFiber();
const existingServer = sharedServerState.server;
if (existingServer !== null) {
if (
sharedServerState.binaryPath !== input.binaryPath &&
sharedServerState.activeRequests === 0
) {
yield* closeSharedServer();
} else {
if (sharedServerState.binaryPath !== input.binaryPath) {
yield* Effect.logWarning(
"OpenCode shared server binary path mismatch: requested " +
input.binaryPath +
" but active server uses " +
sharedServerState.binaryPath +
"; reusing existing server because there are active requests",
);
}
sharedServerState.activeRequests += 1;
return existingServer;
}
}
// Create a fresh scope that owns this shared server. The runtime
// will attach its child-process and fiber finalizers to this scope;
// closing it kills the server and interrupts those fibers.
//
// The `Scope.make` / spawn / record-or-close transitions run inside
// `uninterruptibleMask` so an interrupt arriving between any two
// steps can't orphan the scope (and the child process attached to
// it) before we either close it on failure or hand ownership to
// `sharedServerState`. `restore` keeps the actual spawn
// interruptible; an interrupt during the spawn is captured by
// `Effect.exit` and drives us through the failure branch that
// closes the fresh scope.
return yield* Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
const serverScope = yield* Scope.make();
const startedExit = yield* Effect.exit(
restore(
openCodeRuntime
.startOpenCodeServerProcess({
binaryPath: input.binaryPath,
})
.pipe(
Effect.provideService(Scope.Scope, serverScope),
Effect.mapError(
(cause) =>
new TextGenerationError({
operation: input.operation,
detail: openCodeRuntimeErrorDetail(cause),
cause,
}),
),
),
),
);
if (startedExit._tag === "Failure") {
yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore);
return yield* Effect.failCause(startedExit.cause);
}
const server = startedExit.value;
sharedServerState.server = server;
sharedServerState.serverScope = serverScope;
sharedServerState.binaryPath = input.binaryPath;
sharedServerState.activeRequests = 1;
return server;
}),
);
}),
);
const releaseSharedServer = (server: OpenCodeServerProcess) =>
sharedServerMutex.withPermit(
Effect.gen(function* () {
if (sharedServerState.server !== server) {
return;
}
sharedServerState.activeRequests = Math.max(0, sharedServerState.activeRequests - 1);
if (sharedServerState.activeRequests === 0) {
yield* scheduleIdleClose(server);
}
}),
);
// Module-level finalizer: on layer shutdown, cancel the idle close fiber
// and close the shared server scope. Consumers therefore cannot leak
// the shared OpenCode server by forgetting to call anything.
yield* Effect.addFinalizer(() =>
sharedServerMutex.withPermit(
Effect.gen(function* () {
yield* cancelIdleCloseFiber();
sharedServerState.activeRequests = 0;
yield* closeSharedServer();
}),
),
);
const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
readonly operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
readonly cwd: string;
readonly prompt: string;
readonly outputSchemaJson: S;
readonly modelSelection: OpenCodeModelSelection;
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
}) {
const parsedModel = parseOpenCodeModelSlug(input.modelSelection.model);
if (!parsedModel) {
return yield* new TextGenerationError({
operation: input.operation,
detail: "OpenCode model selection must use the 'provider/model' format.",
});
}
const settings = yield* serverSettingsService.getSettings.pipe(
Effect.map(
(value) =>
value.providers?.opencode ?? {
enabled: true,
binaryPath: "opencode",
serverUrl: "",
serverPassword: "",
customModels: [],
},
),
Effect.orElseSucceed(() => ({
enabled: true,
binaryPath: "opencode",
serverUrl: "",
serverPassword: "",
customModels: [],
})),
);
const fileParts = toOpenCodeFileParts({
attachments: input.attachments,
resolveAttachmentPath: (attachment) =>
resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
});
const runAgainstServer = (server: Pick<OpenCodeServerConnection, "url">) =>
Effect.tryPromise({
try: async () => {
const client = openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: input.cwd,
...(settings.serverUrl.length > 0 && settings.serverPassword
? { serverPassword: settings.serverPassword }
: {}),
});
const session = await client.session.create({
title: `T3 Code ${input.operation}`,
permission: [{ permission: "*", pattern: "*", action: "deny" }],
});
if (!session.data) {
throw new Error("OpenCode session.create returned no session payload.");
}
const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
const selectedVariant = getModelSelectionStringOptionValue(
input.modelSelection,
"variant",
);
const result = await client.session.prompt({
sessionID: session.data.id,
model: parsedModel,
...(selectedAgent ? { agent: selectedAgent } : {}),
...(selectedVariant ? { variant: selectedVariant } : {}),
parts: [{ type: "text", text: input.prompt }, ...fileParts],
});
const info = result.data?.info;
const errorMessage = getOpenCodePromptErrorMessage(info?.error);
if (errorMessage) {
throw new Error(errorMessage);
}
const rawText = getOpenCodeTextResponse(result.data?.parts);
if (rawText.length === 0) {
throw new Error("OpenCode returned empty output.");
}
return rawText;
},
catch: (cause) =>
new TextGenerationError({
operation: input.operation,
detail: openCodeRuntimeErrorDetail(cause),
cause,
}),
});
const rawOutput =
settings.serverUrl.length > 0
? yield* runAgainstServer({ url: settings.serverUrl })
: yield* Effect.acquireUseRelease(
acquireSharedServer({
binaryPath: settings.binaryPath,
operation: input.operation,
}),
runAgainstServer,
releaseSharedServer,
);
return yield* Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson))(
extractJsonObject(rawOutput),
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation: input.operation,
detail: "OpenCode returned invalid structured output.",
cause,
}),
),
),
);
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"OpenCodeTextGeneration.generateCommitMessage",
)(function* (input) {
if (input.modelSelection.provider !== "opencode") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const { prompt, outputSchema } = buildCommitMessagePrompt({
branch: input.branch,
stagedSummary: input.stagedSummary,
stagedPatch: input.stagedPatch,
includeBranch: input.includeBranch === true,
});
const generated = yield* runOpenCodeJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
};
});
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
"OpenCodeTextGeneration.generatePrContent",
)(function* (input) {
if (input.modelSelection.provider !== "opencode") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const { prompt, outputSchema } = buildPrContentPrompt({
baseBranch: input.baseBranch,
headBranch: input.headBranch,
commitSummary: input.commitSummary,
diffSummary: input.diffSummary,
diffPatch: input.diffPatch,
});
const generated = yield* runOpenCodeJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
});
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
"OpenCodeTextGeneration.generateBranchName",
)(function* (input) {
if (input.modelSelection.provider !== "opencode") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const { prompt, outputSchema } = buildBranchNamePrompt({
message: input.message,
attachments: input.attachments,
});
const generated = yield* runOpenCodeJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
attachments: input.attachments,
});
return {
branch: sanitizeBranchFragment(generated.branch),
};
});
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"OpenCodeTextGeneration.generateThreadTitle",
)(function* (input) {
if (input.modelSelection.provider !== "opencode") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
});
const generated = yield* runOpenCodeJson({
operation: "generateThreadTitle",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
attachments: input.attachments,
});
return {
title: sanitizeThreadTitle(generated.title),
};
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
} satisfies TextGenerationShape;
});
export const OpenCodeTextGenerationLive = Layer.effect(TextGeneration, makeOpenCodeTextGeneration);
@@ -11,13 +11,11 @@
*/
import { Effect, Layer, Context } from "effect";
import {
TextGeneration,
type TextGenerationProvider,
type TextGenerationShape,
} from "../Services/TextGeneration.ts";
import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
// ---------------------------------------------------------------------------
// Internal service tags so both concrete layers can coexist.
@@ -31,23 +29,35 @@ class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
) {}
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",
) {}
// ---------------------------------------------------------------------------
// Routing implementation
// ---------------------------------------------------------------------------
const makeRoutingTextGeneration = Effect.gen(function* () {
const codex = yield* CodexTextGen;
const claude = yield* ClaudeTextGen;
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
provider === "claudeAgent" ? claude : codex;
const byProvider = {
codex: yield* CodexTextGen,
claudeAgent: yield* ClaudeTextGen,
cursor: yield* CursorTextGen,
opencode: yield* OpenCodeTextGen,
};
return {
generateCommitMessage: (input) =>
route(input.modelSelection.provider).generateCommitMessage(input),
generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input),
generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input),
generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input),
byProvider[input.modelSelection.provider].generateCommitMessage(input),
generatePrContent: (input) =>
byProvider[input.modelSelection.provider].generatePrContent(input),
generateBranchName: (input) =>
byProvider[input.modelSelection.provider].generateBranchName(input),
generateThreadTitle: (input) =>
byProvider[input.modelSelection.provider].generateThreadTitle(input),
} satisfies TextGenerationShape;
});
@@ -67,7 +77,28 @@ const InternalClaudeLayer = Layer.effect(
}),
).pipe(Layer.provide(ClaudeTextGenerationLive));
const InternalCursorLayer = Layer.effect(
CursorTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CursorTextGenerationLive));
const InternalOpenCodeLayer = Layer.effect(
OpenCodeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(OpenCodeTextGenerationLive));
export const RoutingTextGenerationLive = Layer.effect(
TextGeneration,
makeRoutingTextGeneration,
).pipe(Layer.provide(InternalCodexLayer), Layer.provide(InternalClaudeLayer));
).pipe(
Layer.provide(InternalCodexLayer),
Layer.provide(InternalClaudeLayer),
Layer.provide(InternalCursorLayer),
Layer.provide(InternalOpenCodeLayer),
);
@@ -13,7 +13,7 @@ import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import type { TextGenerationError } from "@t3tools/contracts";
/** Providers that support git text generation (commit messages, PR content, branch names). */
export type TextGenerationProvider = "codex" | "claudeAgent";
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
export interface CommitMessageGenerationInput {
cwd: string;
+48
View File
@@ -30,6 +30,54 @@ export function limitSection(value: string, maxChars: number): string {
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
+3
View File
@@ -192,6 +192,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("modelPicker.jump.9"), "mod+9");
}),
);
+17 -6
View File
@@ -13,6 +13,7 @@ import {
KeybindingShortcut,
KeybindingWhenNode,
MAX_KEYBINDINGS_COUNT,
MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
MAX_WHEN_EXPRESSION_DEPTH,
ResolvedKeybindingRule,
ResolvedKeybindingsConfig,
@@ -45,6 +46,7 @@ import {
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config.ts";
import { writeFileStringAtomically } from "./atomicWrite.ts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
type WhenToken =
@@ -65,6 +67,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" },
{ key: "mod+shift+[", command: "thread.previous" },
{ key: "mod+shift+]", command: "thread.next" },
@@ -72,6 +75,11 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
key: `mod+${index + 1}`,
command,
})),
...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
key: `mod+${index + 1}`,
command,
when: "modelPickerOpen",
})),
];
function normalizeKeyToken(token: string): string {
@@ -663,14 +671,17 @@ const makeKeybindings = Effect.gen(function* () {
});
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
Effect.flatMap((encoded) =>
writeFileStringAtomically({
filePath: keybindingsConfigPath,
contents: encoded,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
),
),
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
@@ -17,7 +18,7 @@ describe("OrchestrationReactor", () => {
runtime = null;
});
it("starts provider ingestion, provider command, and checkpoint reactors", async () => {
it("starts provider ingestion, provider command, checkpoint, and thread deletion reactors", async () => {
const started: string[] = [];
runtime = ManagedRuntime.make(
@@ -49,10 +50,19 @@ describe("OrchestrationReactor", () => {
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ThreadDeletionReactor, {
start: () => {
started.push("thread-deletion-reactor");
return Effect.void;
},
drain: Effect.void,
}),
),
),
);
const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor));
const reactor = await runtime!.runPromise(Effect.service(OrchestrationReactor));
const scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
@@ -60,6 +70,7 @@ describe("OrchestrationReactor", () => {
"provider-runtime-ingestion",
"provider-command-reactor",
"checkpoint-reactor",
"thread-deletion-reactor",
]);
await Effect.runPromise(Scope.close(scope, Exit.void));
@@ -7,16 +7,19 @@ import {
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
export const makeOrchestrationReactor = Effect.gen(function* () {
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
const providerCommandReactor = yield* ProviderCommandReactor;
const checkpointReactor = yield* CheckpointReactor;
const threadDeletionReactor = yield* ThreadDeletionReactor;
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
yield* providerRuntimeIngestion.start();
yield* providerCommandReactor.start();
yield* checkpointReactor.start();
yield* threadDeletionReactor.start();
});
return {
@@ -3,6 +3,7 @@ import os from "node:os";
import path from "node:path";
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import {
ApprovalRequestId,
CommandId,
@@ -137,6 +138,12 @@ describe("ProviderCommandReactor", () => {
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
? input.runtimeMode
: "full-access",
...(typeof input === "object" &&
input !== null &&
"cwd" in input &&
typeof input.cwd === "string"
? { cwd: input.cwd }
: {}),
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
@@ -266,7 +273,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(layer);
runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
@@ -567,14 +574,10 @@ describe("ProviderCommandReactor", () => {
text: "hello fast mode",
attachments: [],
},
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
},
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -584,25 +587,17 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
},
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
},
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
});
});
@@ -623,13 +618,9 @@ describe("ProviderCommandReactor", () => {
text: "hello with effort",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -639,23 +630,15 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
});
});
@@ -676,13 +659,9 @@ describe("ProviderCommandReactor", () => {
text: "hello with fast mode",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
fastMode: true,
},
},
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -692,23 +671,15 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
fastMode: true,
},
},
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
fastMode: true,
},
},
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
});
});
@@ -750,6 +721,57 @@ describe("ProviderCommandReactor", () => {
});
});
it("preserves the active session model when in-session model switching is unsupported", async () => {
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-unsupported-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-unsupported-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-unsupported-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-unsupported-2"),
role: "user",
text: "second",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
});
});
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
@@ -802,57 +824,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("preserves the active session model when in-session model switching is unsupported", async () => {
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-unsupported-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-unsupported-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-unsupported-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-unsupported-2"),
role: "user",
text: "second",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
});
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -899,6 +870,76 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts the provider session when the thread workspace changes", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
});
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-workspace-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-workspace-1"),
role: "user",
text: "first in project root",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
});
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-worktree-change"),
threadId: ThreadId.make("thread-1"),
worktreePath: "/tmp/provider-project-worktree",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-workspace-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-workspace-2"),
role: "user",
text: "second in worktree",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.make("thread-1"),
cwd: "/tmp/provider-project-worktree",
resumeCursor: { opaque: "resume-1" },
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
runtimeMode: "approval-required",
});
});
it("restarts claude sessions when claude effort changes", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
@@ -916,13 +957,9 @@ describe("ProviderCommandReactor", () => {
text: "first claude turn",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "medium",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "medium" },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -943,13 +980,9 @@ describe("ProviderCommandReactor", () => {
text: "second claude turn",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -960,13 +993,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
resumeCursor: { opaque: "resume-1" },
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
});
});
@@ -1100,6 +1129,71 @@ describe("ProviderCommandReactor", () => {
});
});
it("does not stop the active session when restart fails before rebind", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access-2"),
threadId: ThreadId.make("thread-1"),
runtimeMode: "full-access",
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-restart-failure-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-restart-failure-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
harness.startSession.mockImplementationOnce(
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set-restart-failure"),
threadId: ThreadId.make("thread-1"),
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
await harness.drain();
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(1);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("full-access");
});
it("rejects provider changes after a thread is already bound to a session provider", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1172,71 +1266,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("does not stop the active session when restart fails before rebind", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access-2"),
threadId: ThreadId.make("thread-1"),
runtimeMode: "full-access",
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-restart-failure-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-restart-failure-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
harness.startSession.mockImplementationOnce(
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set-restart-failure"),
threadId: ThreadId.make("thread-1"),
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
await harness.drain();
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(1);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("full-access");
});
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -89,9 +89,16 @@ function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolea
: false;
}
function findProviderAdapterRequestError(
cause: Cause.Cause<ProviderServiceError>,
): ProviderAdapterRequestError | undefined {
const failReason = cause.reasons.find(Cause.isFailReason);
return Schema.is(ProviderAdapterRequestError)(failReason?.error) ? failReason.error : undefined;
}
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
const error = findProviderAdapterRequestError(cause);
if (error) {
const detail = error.detail.toLowerCase();
return (
detail.includes("unknown pending approval request") ||
@@ -106,8 +113,8 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
}
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
const error = findProviderAdapterRequestError(cause);
if (error) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
@@ -198,6 +205,17 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
const failReason = cause.reasons.find(Cause.isFailReason);
const providerError = Schema.is(ProviderAdapterRequestError)(failReason?.error)
? failReason.error
: undefined;
if (providerError) {
return providerError.detail;
}
return Cause.pretty(cause);
};
const setThreadSession = (input: {
readonly threadId: ThreadId;
readonly session: OrchestrationSession;
@@ -211,7 +229,30 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) {
const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly detail: string;
readonly createdAt: string;
}) {
const thread = yield* resolveThread(input.threadId);
const session = thread?.session;
if (!session) {
return;
}
yield* setThreadSession({
threadId: input.threadId,
session: {
...session,
status: session.status === "stopped" ? "stopped" : "ready",
activeTurnId: null,
lastError: input.detail,
updatedAt: input.createdAt,
},
createdAt: input.createdAt,
});
});
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
return readModel.threads.find((entry) => entry.id === threadId);
});
@@ -247,7 +288,7 @@ const make = Effect.gen(function* () {
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
});
}
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
const preferredProvider: ProviderKind = threadProvider;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
@@ -293,9 +334,7 @@ const make = Effect.gen(function* () {
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
if (existingSessionThreadId) {
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
const providerChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== currentProvider;
const cwdChanged = effectiveCwd !== activeSession?.cwd;
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
@@ -303,7 +342,7 @@ const make = Effect.gen(function* () {
const modelChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
const previousModelSelection = threadModelSelections.get(threadId);
const shouldRestartForModelSelectionChange =
currentProvider === "claudeAgent" &&
@@ -312,17 +351,16 @@ const make = Effect.gen(function* () {
if (
!runtimeModeChanged &&
!providerChanged &&
!cwdChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelSelectionChange
) {
return existingSessionThreadId;
}
const resumeCursor =
providerChanged || shouldRestartForModelChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
const resumeCursor = shouldRestartForModelChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
yield* Effect.logInfo("provider command reactor restarting provider session", {
threadId,
existingSessionThreadId,
@@ -331,7 +369,9 @@ const make = Effect.gen(function* () {
currentRuntimeMode: thread.session?.runtimeMode,
desiredRuntimeMode: thread.runtimeMode,
runtimeModeChanged,
providerChanged,
previousCwd: activeSession?.cwd,
desiredCwd: effectiveCwd,
cwdChanged,
modelChanged,
shouldRestartForModelChange,
shouldRestartForModelSelectionChange,
@@ -346,6 +386,7 @@ const make = Effect.gen(function* () {
restartedSessionThreadId: restartedSession.threadId,
provider: restartedSession.provider,
runtimeMode: restartedSession.runtimeMode,
cwd: restartedSession.cwd,
});
yield* bindSessionToThread(restartedSession);
return restartedSession.threadId;
@@ -356,7 +397,7 @@ const make = Effect.gen(function* () {
return startedSession.threadId;
});
const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: {
const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
@@ -366,7 +407,9 @@ const make = Effect.gen(function* () {
}) {
const thread = yield* resolveThread(input.threadId);
if (!thread) {
return;
return yield* Effect.die(
new Error(`Thread '${input.threadId}' was not found in read model.`),
);
}
yield* ensureSessionForThread(
input.threadId,
@@ -390,7 +433,7 @@ const make = Effect.gen(function* () {
const requestedModelSelection =
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
const modelForTurn =
sessionModelSwitch === "unsupported"
sessionModelSwitch === "unsupported" && input.modelSelection === undefined
? activeSession?.model !== undefined
? {
...requestedModelSelection,
@@ -399,13 +442,13 @@ const make = Effect.gen(function* () {
: requestedModelSelection
: input.modelSelection;
yield* providerService.sendTurn({
return {
threadId: input.threadId,
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
};
});
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(
@@ -564,7 +607,43 @@ const make = Effect.gen(function* () {
}
}
yield* sendTurnForThread({
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const detail = formatFailureDetail(cause);
return setThreadSessionErrorOnTurnStartFailure({
threadId: event.payload.threadId,
detail,
createdAt: event.payload.createdAt,
}).pipe(
Effect.flatMap(() =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail,
turnId: null,
createdAt: event.payload.createdAt,
}),
),
Effect.asVoid,
);
};
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
handleTurnStartFailure(cause).pipe(
Effect.catchCause((recoveryCause) =>
Effect.logWarning("provider command reactor failed to recover turn start failure", {
eventType: event.type,
threadId: event.payload.threadId,
cause: Cause.pretty(recoveryCause),
originalCause: Cause.pretty(cause),
}),
),
);
const sendTurnRequest = yield* buildSendTurnRequestForThread({
threadId: event.payload.threadId,
messageText: message.text,
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
@@ -574,17 +653,17 @@ const make = Effect.gen(function* () {
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
}).pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
}),
),
Effect.map(Option.some),
Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),
);
if (Option.isNone(sendTurnRequest)) {
return;
}
yield* providerService
.sendTurn(sendTurnRequest.value)
.pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
});
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
@@ -723,6 +723,146 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("preserves completed tool metadata on projected tool activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "item.completed",
eventId: asEventId("evt-tool-completed-with-data"),
provider: "cursor",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-tool-completed"),
itemId: asItemId("item-tool-completed"),
payload: {
itemType: "dynamic_tool_call",
status: "completed",
title: "Read file",
data: {
toolCallId: "tool-read-1",
kind: "read",
rawOutput: {
content: 'import * as Effect from "effect/Effect"\n',
},
},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-tool-completed-with-data",
),
);
const activity = thread.activities.find(
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-tool-completed-with-data",
);
const payload =
activity?.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: undefined;
const data =
payload?.data && typeof payload.data === "object"
? (payload.data as Record<string, unknown>)
: undefined;
const rawOutput =
data?.rawOutput && typeof data.rawOutput === "object"
? (data.rawOutput as Record<string, unknown>)
: undefined;
expect(activity?.kind).toBe("tool.completed");
expect(activity?.summary).toBe("Read file");
expect(payload?.itemType).toBe("dynamic_tool_call");
expect(payload?.detail).toBeUndefined();
expect(data?.toolCallId).toBe("tool-read-1");
expect(data?.kind).toBe("read");
expect(rawOutput?.content).toBe('import * as Effect from "effect/Effect"\n');
});
it("normalizes command execution activities to ran-command summaries", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "item.completed",
eventId: asEventId("evt-command-completed"),
provider: "cursor",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-command-completed"),
itemId: asItemId("item-command-completed"),
payload: {
itemType: "command_execution",
status: "completed",
title: "Ran command",
detail: "bun run lint",
data: {
toolCallId: "tool-command-1",
kind: "execute",
command: "bun run lint",
},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-command-completed",
),
);
const activity = thread.activities.find(
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-command-completed",
);
const payload =
activity?.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: undefined;
expect(activity?.summary).toBe("Ran command");
expect(payload?.detail).toBe("bun run lint");
});
it("uses structured read-file paths when available", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "item.completed",
eventId: asEventId("evt-read-path-completed"),
provider: "cursor",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-read-path"),
itemId: asItemId("item-read-path"),
payload: {
itemType: "dynamic_tool_call",
status: "completed",
title: "Read file",
detail: "/tmp/app.ts",
data: {
toolCallId: "tool-read-path-1",
kind: "read",
locations: [{ path: "/tmp/app.ts" }],
},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-read-path-completed",
),
);
const activity = thread.activities.find(
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-read-path-completed",
);
const payload =
activity?.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: undefined;
expect(activity?.summary).toBe("Read file");
expect(payload?.detail).toBe("/tmp/app.ts");
});
it("projects completed plan items into first-class proposed plans", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1392,6 +1532,432 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("flushes and completes buffered assistant text when an approval request opens", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-request-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-buffered-request-flush",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
itemId: asItemId("item-buffered-request-flush"),
payload: {
streamKind: "assistant_text",
delta: "visible before approval",
},
});
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-request-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
requestId: ApprovalRequestId.make("req-buffered-request-flush"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered-request-flush" &&
!message.streaming &&
message.text === "visible before approval",
),
);
const message = thread.messages.find(
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered-request-flush",
);
expect(message?.streaming).toBe(false);
});
it("flushes and completes buffered assistant text when user input is requested", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-user-input-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-buffered-user-input-flush",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-user-input-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
itemId: asItemId("item-buffered-user-input-flush"),
payload: {
streamKind: "assistant_text",
delta: "visible before user input",
},
});
harness.emit({
type: "user-input.requested",
eventId: asEventId("evt-user-input-requested-buffered-user-input-flush"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
requestId: ApprovalRequestId.make("req-buffered-user-input-flush"),
payload: {
questions: [
{
id: "choice",
header: "Choice",
question: "Pick one",
options: [{ label: "A", description: "Option A" }],
},
],
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered-user-input-flush" &&
!message.streaming &&
message.text === "visible before user input",
),
);
const message = thread.messages.find(
(entry: ProviderRuntimeTestMessage) =>
entry.id === "assistant:item-buffered-user-input-flush",
);
expect(message?.streaming).toBe(false);
});
it("does not create assistant segments for whitespace-only buffered text at approval boundaries", async () => {
const harness = await createHarness();
const startedAt = "2026-03-28T06:28:00.000Z";
const pausedAt = "2026-03-28T06:28:01.000Z";
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-whitespace-request"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-buffered-whitespace-request",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-whitespace-request"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
itemId: asItemId("item-buffered-whitespace-request"),
payload: {
streamKind: "assistant_text",
delta: "\n\n\n",
},
});
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-whitespace-request"),
provider: "codex",
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
requestId: ApprovalRequestId.make("req-buffered-whitespace-request"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
),
);
expect(
thread.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered-whitespace-request",
),
).toBe(false);
});
it("starts a new buffered assistant message segment after approval and completes without duplication", async () => {
const harness = await createHarness();
const startedAt = "2026-03-28T06:07:00.000Z";
const pausedAt = "2026-03-28T06:07:01.000Z";
const resumedAt = "2026-03-28T06:07:02.000Z";
const completedAt = "2026-03-28T06:07:03.000Z";
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-request-append"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-buffered-request-append",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-append-initial"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
itemId: asItemId("item-buffered-request-append"),
payload: {
streamKind: "assistant_text",
delta: "first half",
},
});
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-request-append"),
provider: "codex",
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
requestId: ApprovalRequestId.make("req-buffered-request-append"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
},
});
await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered-request-append" &&
!message.streaming &&
message.text === "first half",
),
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-append-followup"),
provider: "codex",
createdAt: resumedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
itemId: asItemId("item-buffered-request-append"),
payload: {
streamKind: "assistant_text",
delta: " second half",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-buffered-request-append"),
provider: "codex",
createdAt: completedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
itemId: asItemId("item-buffered-request-append"),
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-buffered-request-append:segment:1" &&
!message.streaming &&
message.text === " second half",
),
);
const firstMessage = thread.messages.find(
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered-request-append",
);
const resumedMessage = thread.messages.find(
(entry: ProviderRuntimeTestMessage) =>
entry.id === "assistant:item-buffered-request-append:segment:1",
);
expect(firstMessage?.text).toBe("first half");
expect(firstMessage?.streaming).toBe(false);
expect(resumedMessage?.text).toBe(" second half");
expect(resumedMessage?.streaming).toBe(false);
const events = await Effect.runPromise(
Stream.runCollect(harness.engine.readEvents(0)).pipe(
Effect.map((chunk) => Array.from(chunk)),
),
);
const assistantEvents = events.filter(
(event): event is Extract<(typeof events)[number], { type: "thread.message-sent" }> =>
event.type === "thread.message-sent" &&
event.payload.messageId.startsWith("assistant:item-buffered-request-append"),
);
expect(assistantEvents).toHaveLength(4);
expect(assistantEvents[0]?.payload.streaming).toBe(true);
expect(assistantEvents[0]?.payload.text).toBe("first half");
expect(assistantEvents[1]?.payload.streaming).toBe(false);
expect(assistantEvents[1]?.payload.text).toBe("");
expect(assistantEvents[2]?.payload.messageId).toBe(
"assistant:item-buffered-request-append:segment:1",
);
expect(assistantEvents[2]?.payload.streaming).toBe(true);
expect(assistantEvents[2]?.payload.text).toBe(" second half");
expect(assistantEvents[3]?.payload.messageId).toBe(
"assistant:item-buffered-request-append:segment:1",
);
expect(assistantEvents[3]?.payload.streaming).toBe(false);
expect(assistantEvents[3]?.payload.text).toBe("");
});
it("starts a new streaming assistant message segment after approval", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const startedAt = "2026-03-28T07:00:00.000Z";
const pausedAt = "2026-03-28T07:00:01.000Z";
const resumedAt = "2026-03-28T07:00:02.000Z";
const completedAt = "2026-03-28T07:00:03.000Z";
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-streaming-request-segment"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-streaming-request-segment",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-streaming-request-segment-initial"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
itemId: asItemId("item-streaming-request-segment"),
payload: {
streamKind: "assistant_text",
delta: "before approval",
},
});
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-streaming-request-segment"),
provider: "codex",
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
requestId: ApprovalRequestId.make("req-streaming-request-segment"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
},
});
await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-streaming-request-segment" &&
!message.streaming &&
message.text === "before approval",
),
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-streaming-request-segment-followup"),
provider: "codex",
createdAt: resumedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
itemId: asItemId("item-streaming-request-segment"),
payload: {
streamKind: "assistant_text",
delta: " after approval",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-streaming-request-segment"),
provider: "codex",
createdAt: completedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
itemId: asItemId("item-streaming-request-segment"),
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-streaming-request-segment:segment:1" &&
!message.streaming &&
message.text === " after approval",
),
);
expect(
thread.messages.find(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-streaming-request-segment",
)?.text,
).toBe("before approval");
expect(
thread.messages.find(
(message: ProviderRuntimeTestMessage) =>
message.id === "assistant:item-streaming-request-segment:segment:1",
)?.text,
).toBe(" after approval");
});
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const now = new Date().toISOString();
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,36 @@
import { ThreadId } from "@t3tools/contracts";
import { Cause, Effect, Exit } from "effect";
import { describe, expect, it } from "vitest";
import { logCleanupCauseUnlessInterrupted } from "./ThreadDeletionReactor.ts";
describe("logCleanupCauseUnlessInterrupted", () => {
const threadId = ThreadId.make("thread-deletion-reactor-test");
it("swallows ordinary cleanup failures", async () => {
const exit = await Effect.runPromiseExit(
logCleanupCauseUnlessInterrupted({
effect: Effect.fail("cleanup failed"),
message: "thread deletion cleanup skipped provider session stop",
threadId,
}),
);
expect(Exit.isSuccess(exit)).toBe(true);
});
it("preserves interrupt causes", async () => {
const exit = await Effect.runPromiseExit(
logCleanupCauseUnlessInterrupted({
effect: Effect.interrupt,
message: "thread deletion cleanup skipped provider session stop",
threadId,
}),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
}
});
});
@@ -0,0 +1,96 @@
import type { OrchestrationEvent } from "@t3tools/contracts";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { Cause, Effect, Layer, Stream } from "effect";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { TerminalManager } from "../../terminal/Services/Manager.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
ThreadDeletionReactor,
type ThreadDeletionReactorShape,
} from "../Services/ThreadDeletionReactor.ts";
type ThreadDeletedEvent = Extract<OrchestrationEvent, { type: "thread.deleted" }>;
export const logCleanupCauseUnlessInterrupted = <R, E>({
effect,
message,
threadId,
}: {
readonly effect: Effect.Effect<void, E, R>;
readonly message: string;
readonly threadId: ThreadDeletedEvent["payload"]["threadId"];
}): Effect.Effect<void, E, R> =>
effect.pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
return Effect.logDebug(message, {
threadId,
cause: Cause.pretty(cause),
});
}),
);
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const terminalManager = yield* TerminalManager;
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
logCleanupCauseUnlessInterrupted({
effect: providerService.stopSession({ threadId }),
message: "thread deletion cleanup skipped provider session stop",
threadId,
});
const closeThreadTerminals = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
logCleanupCauseUnlessInterrupted({
effect: terminalManager.close({ threadId, deleteHistory: true }),
message: "thread deletion cleanup skipped terminal close",
threadId,
});
const processThreadDeleted = Effect.fn("processThreadDeleted")(function* (
event: ThreadDeletedEvent,
) {
const { threadId } = event.payload;
yield* stopProviderSession(threadId);
yield* closeThreadTerminals(threadId);
});
const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>
processThreadDeleted(event).pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
return Effect.logWarning("thread deletion reactor failed to process event", {
eventType: event.type,
threadId: event.payload.threadId,
cause: Cause.pretty(cause),
});
}),
);
const worker = yield* makeDrainableWorker(processThreadDeletedSafely);
const start: ThreadDeletionReactorShape["start"] = Effect.fn("start")(function* () {
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (event.type !== "thread.deleted") {
return Effect.void;
}
return worker.enqueue(event);
}),
);
});
return {
start,
drain: worker.drain,
} satisfies ThreadDeletionReactorShape;
});
export const ThreadDeletionReactorLive = Layer.effect(ThreadDeletionReactor, make);
@@ -0,0 +1,37 @@
/**
* ThreadDeletionReactor - Thread deletion cleanup reactor service interface.
*
* Owns background workers that react to thread deletion domain events and
* perform best-effort runtime cleanup for provider sessions and terminals.
*
* @module ThreadDeletionReactor
*/
import { Context } from "effect";
import type { Effect, Scope } from "effect";
/**
* ThreadDeletionReactorShape - Service API for thread deletion cleanup.
*/
export interface ThreadDeletionReactorShape {
/**
* Start reacting to thread.deleted orchestration domain events.
*
* The returned effect must be run in a scope so all worker fibers can be
* finalized on shutdown.
*/
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>;
}
/**
* ThreadDeletionReactor - Service tag for thread deletion cleanup workers.
*/
export class ThreadDeletionReactor extends Context.Service<
ThreadDeletionReactor,
ThreadDeletionReactorShape
>()("t3/orchestration/Services/ThreadDeletionReactor") {}
@@ -0,0 +1,226 @@
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
ProjectId,
ThreadId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const asCommandId = (value: string): CommandId => CommandId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
async function seedReadModel(): Promise<OrchestrationReadModel> {
const now = new Date().toISOString();
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-delete"),
type: "project.created",
occurredAt: now,
commandId: asCommandId("cmd-project-create"),
causationEventId: null,
correlationId: asCommandId("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-delete"),
title: "Project Delete",
workspaceRoot: "/tmp/project-delete",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
}),
);
const withFirstThread = await Effect.runPromise(
projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create-1"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-1"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-1"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-1"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-1"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 1",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
return Effect.runPromise(
projectEvent(withFirstThread, {
sequence: 3,
eventId: asEventId("evt-thread-create-2"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-2"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-2"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-2"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-2"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 2",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
}
type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
function normalizeDeleteEvent(event: PlannedEvent | ReadonlyArray<PlannedEvent>) {
const events = Array.isArray(event) ? event : [event];
return events.map((entry) => {
switch (entry.type) {
case "thread.deleted":
return {
type: entry.type,
aggregateKind: entry.aggregateKind,
aggregateId: entry.aggregateId,
commandId: entry.commandId,
correlationId: entry.correlationId,
payload: {
threadId: entry.payload.threadId,
},
};
case "project.deleted":
return {
type: entry.type,
aggregateKind: entry.aggregateKind,
aggregateId: entry.aggregateId,
commandId: entry.commandId,
correlationId: entry.correlationId,
payload: {
projectId: entry.payload.projectId,
},
};
default:
return entry;
}
});
}
describe("decider deletion flows", () => {
it("rejects deleting a non-empty project without force", async () => {
const readModel = await seedReadModel();
await expect(
Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "project.delete",
commandId: asCommandId("cmd-project-delete-no-force"),
projectId: asProjectId("project-delete"),
},
readModel,
}),
),
).rejects.toThrow("cannot be deleted without force=true");
});
it("reuses thread.delete semantics when force-deleting a non-empty project", async () => {
const readModel = await seedReadModel();
const projectDeleteCommand: Extract<OrchestrationCommand, { type: "project.delete" }> = {
type: "project.delete",
commandId: asCommandId("cmd-project-delete-force"),
projectId: asProjectId("project-delete"),
force: true,
};
const forcedResult = await Effect.runPromise(
decideOrchestrationCommand({
command: projectDeleteCommand,
readModel,
}),
);
const forcedEvents = Array.isArray(forcedResult) ? forcedResult : [forcedResult];
expect(forcedEvents.map((event) => event.type)).toEqual([
"thread.deleted",
"thread.deleted",
"project.deleted",
]);
let sequentialReadModel = readModel;
let nextSequence = readModel.snapshotSequence;
const sequentialEvents: PlannedEvent[] = [];
for (const nextCommand of [
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-1"),
},
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-2"),
},
{
type: "project.delete",
commandId: projectDeleteCommand.commandId,
projectId: asProjectId("project-delete"),
},
] satisfies ReadonlyArray<OrchestrationCommand>) {
const decided = await Effect.runPromise(
decideOrchestrationCommand({
command: nextCommand,
readModel: sequentialReadModel,
}),
);
const nextEvents = Array.isArray(decided) ? decided : [decided];
sequentialEvents.push(...nextEvents);
for (const nextEvent of nextEvents) {
nextSequence += 1;
sequentialReadModel = await Effect.runPromise(
projectEvent(sequentialReadModel, {
...nextEvent,
sequence: nextSequence,
}),
);
}
}
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
});
});
@@ -6,6 +6,7 @@ import {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { describe, expect, it } from "vitest";
import { Effect } from "effect";
@@ -162,14 +163,10 @@ describe("decider project scripts", () => {
text: "hello",
attachments: [],
},
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
},
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -191,14 +188,10 @@ describe("decider project scripts", () => {
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.make("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
},
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
runtimeMode: "approval-required",
});
});
+69 -5
View File
@@ -7,6 +7,7 @@ import { Effect } from "effect";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import {
listThreadsByProjectId,
requireProject,
requireProjectAbsent,
requireThread,
@@ -14,6 +15,7 @@ import {
requireThreadAbsent,
requireThreadNotArchived,
} from "./commandInvariants.ts";
import { projectEvent } from "./projector.ts";
const nowIso = () => new Date().toISOString();
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
@@ -47,16 +49,49 @@ function withEventBase(
};
}
type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
type DecideOrchestrationCommandResult =
| PlannedOrchestrationEvent
| ReadonlyArray<PlannedOrchestrationEvent>;
const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
commands,
readModel,
}: {
readonly commands: ReadonlyArray<OrchestrationCommand>;
readonly readModel: OrchestrationReadModel;
}): Effect.fn.Return<ReadonlyArray<PlannedOrchestrationEvent>, OrchestrationCommandInvariantError> {
let nextReadModel = readModel;
let nextSequence = readModel.snapshotSequence;
const plannedEvents: PlannedOrchestrationEvent[] = [];
for (const nextCommand of commands) {
const decided = yield* decideOrchestrationCommand({
command: nextCommand,
readModel: nextReadModel,
});
const nextEvents = Array.isArray(decided) ? decided : [decided];
for (const nextEvent of nextEvents) {
plannedEvents.push(nextEvent);
nextSequence += 1;
nextReadModel = yield* projectEvent(nextReadModel, {
...nextEvent,
sequence: nextSequence,
}).pipe(Effect.orDie);
}
}
return plannedEvents;
});
export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({
command,
readModel,
}: {
readonly command: OrchestrationCommand;
readonly readModel: OrchestrationReadModel;
}): Effect.fn.Return<
Omit<OrchestrationEvent, "sequence"> | ReadonlyArray<Omit<OrchestrationEvent, "sequence">>,
OrchestrationCommandInvariantError
> {
}): Effect.fn.Return<DecideOrchestrationCommandResult, OrchestrationCommandInvariantError> {
switch (command.type) {
case "project.create": {
yield* requireProjectAbsent({
@@ -119,6 +154,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
projectId: command.projectId,
});
const activeThreads = listThreadsByProjectId(readModel, command.projectId).filter(
(thread) => thread.deletedAt === null,
);
if (activeThreads.length > 0 && command.force !== true) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Project '${command.projectId}' is not empty and cannot be deleted without force=true.`,
});
}
if (activeThreads.length > 0) {
return yield* decideCommandSequence({
readModel,
commands: [
...activeThreads.map(
(thread): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({
type: "thread.delete",
commandId: command.commandId,
threadId: thread.id,
}),
),
{
type: "project.delete",
commandId: command.commandId,
projectId: command.projectId,
},
],
});
}
const occurredAt = nowIso();
return {
...withEventBase({
@@ -127,7 +191,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
occurredAt,
commandId: command.commandId,
}),
type: "project.deleted",
type: "project.deleted" as const,
payload: {
projectId: command.projectId,
deletedAt: occurredAt,
+33
View File
@@ -0,0 +1,33 @@
import { homedir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { expandHomePath } from "./pathExpansion.ts";
describe("expandHomePath", () => {
it("returns an empty string unchanged", () => {
expect(expandHomePath("")).toBe("");
});
it("returns paths without a leading tilde unchanged", () => {
expect(expandHomePath("/absolute/path")).toBe("/absolute/path");
expect(expandHomePath("relative/path")).toBe("relative/path");
expect(expandHomePath("some~weird~path")).toBe("some~weird~path");
});
it("expands a lone tilde to the home directory", () => {
expect(expandHomePath("~")).toBe(homedir());
});
it("expands ~/ to a subpath of the home directory", () => {
expect(expandHomePath("~/.codex-work")).toBe(join(homedir(), ".codex-work"));
});
it("expands a Windows-style ~\\ prefix", () => {
expect(expandHomePath("~\\.codex")).toBe(join(homedir(), ".codex"));
});
it("does not expand ~user paths", () => {
expect(expandHomePath("~alice/foo")).toBe("~alice/foo");
});
});
+23
View File
@@ -0,0 +1,23 @@
import { homedir } from "node:os";
import { join } from "node:path";
/**
* Expand a leading `~` (or `~/…`, `~\…`) in a user-supplied path to the
* current user's home directory. Spawned processes don't get shell
* expansion, so env vars like `CODEX_HOME=~/.codex-work` would be passed
* verbatim and treated as relative paths by the receiver.
*
* Matches the behavior of the other `expandHomePath` helpers in the
* workspace layers and CLI bootstrap: `~` alone and both `~/` and `~\`
* separators are handled. Returns the input unchanged if it doesn't
* start with `~` or is empty. Does not handle `~user` (other-user)
* expansion.
*/
export function expandHomePath(value: string): string {
if (!value) return value;
if (value === "~") return homedir();
if (value.startsWith("~/") || value.startsWith("~\\")) {
return join(homedir(), value.slice(2));
}
return value;
}
@@ -38,6 +38,7 @@ import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";
import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
/**
* Migration loader with all migrations defined inline.
@@ -75,6 +76,7 @@ export const migrationEntries = [
[23, "ProjectionThreadShellSummary", Migration0023],
[24, "BackfillProjectionThreadShellSummary", Migration0024],
[25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
[26, "CanonicalizeModelSelectionOptions", Migration0026],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,450 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("026_CanonicalizeModelSelectionOptions", (it) => {
it.effect("converts legacy object-shape options into array-shape on projections and events", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 25 });
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES
(
'project-legacy',
'Legacy options project',
'/tmp/legacy',
'{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","fastMode":true}}',
'[]',
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL
),
(
'project-no-options',
'No options project',
'/tmp/no-options',
'{"provider":"codex","model":"gpt-5.4"}',
'[]',
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL
),
(
'project-null-selection',
'Null model selection project',
'/tmp/null-selection',
NULL,
'[]',
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL
),
(
'project-already-array',
'Already-canonical options project',
'/tmp/already-array',
'{"provider":"codex","model":"gpt-5.4","options":[{"id":"reasoningEffort","value":"high"}]}',
'[]',
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
deleted_at,
runtime_mode,
interaction_mode
)
VALUES
(
'thread-legacy',
'project-legacy',
'Legacy thread',
'{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","thinking":false,"contextWindow":"1m"}}',
NULL, NULL, NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL, NULL, 0, 0, 0, NULL,
'full-access', 'default'
),
(
'thread-empty-options',
'project-legacy',
'Empty options thread',
'{"provider":"codex","model":"gpt-5.4","options":{}}',
NULL, NULL, NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL, NULL, 0, 0, 0, NULL,
'full-access', 'default'
),
(
'thread-drop-garbage',
'project-legacy',
'Thread with non-scalar entries',
'{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"high","thinking":{"enabled":true,"budgetTokens":2000},"emptyStr":" ","nullish":null}}',
NULL, NULL, NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL, NULL, 0, 0, 0, NULL,
'full-access', 'default'
),
(
'thread-no-options',
'project-legacy',
'No options thread',
'{"provider":"codex","model":"gpt-5.4"}',
NULL, NULL, NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL, NULL, 0, 0, 0, NULL,
'full-access', 'default'
),
(
'thread-already-array',
'project-legacy',
'Already array thread',
'{"provider":"codex","model":"gpt-5.4","options":[{"id":"fastMode","value":true}]}',
NULL, NULL, NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL, NULL, 0, 0, 0, NULL,
'full-access', 'default'
)
`;
yield* sql`
INSERT INTO orchestration_events (
event_id,
aggregate_kind,
stream_id,
stream_version,
event_type,
occurred_at,
command_id,
causation_event_id,
correlation_id,
actor_kind,
payload_json,
metadata_json
)
VALUES
(
'event-project-created',
'project',
'project-legacy',
1,
'project.created',
'2026-01-01T00:00:00.000Z',
'cmd-pc',
NULL,
'corr-pc',
'user',
'{"projectId":"project-legacy","title":"Project","workspaceRoot":"/tmp/legacy","defaultModelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","fastMode":true}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-project-meta-updated',
'project',
'project-legacy',
2,
'project.meta-updated',
'2026-01-01T00:00:00.000Z',
'cmd-pmu',
NULL,
'corr-pmu',
'user',
'{"projectId":"project-legacy","defaultModelSelection":{"provider":"codex","model":"gpt-5.4","options":{"reasoningEffort":"low"}},"updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-project-null-selection',
'project',
'project-legacy',
3,
'project.meta-updated',
'2026-01-01T00:00:00.000Z',
'cmd-null',
NULL,
'corr-null',
'user',
'{"projectId":"project-legacy","defaultModelSelection":null,"updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-created',
'thread',
'thread-legacy',
1,
'thread.created',
'2026-01-01T00:00:00.000Z',
'cmd-tc',
NULL,
'corr-tc',
'user',
'{"threadId":"thread-legacy","projectId":"project-legacy","title":"Thread","modelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","thinking":false}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-meta-updated',
'thread',
'thread-legacy',
2,
'thread.meta-updated',
'2026-01-01T00:00:00.000Z',
'cmd-tmu',
NULL,
'corr-tmu',
'user',
'{"threadId":"thread-legacy","modelSelection":{"provider":"codex","model":"gpt-5.4","options":{"fastMode":true}},"updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-turn-start',
'thread',
'thread-legacy',
3,
'thread.turn-start-requested',
'2026-01-01T00:00:00.000Z',
'cmd-tts',
NULL,
'corr-tts',
'user',
'{"threadId":"thread-legacy","messageId":"msg-1","modelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"high","contextWindow":"1m"}},"runtimeMode":"full-access","interactionMode":"default","createdAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-already-array',
'thread',
'thread-legacy',
4,
'thread.created',
'2026-01-01T00:00:00.000Z',
'cmd-taa',
NULL,
'corr-taa',
'user',
'{"threadId":"thread-already-array","projectId":"project-legacy","title":"Already Array","modelSelection":{"provider":"codex","model":"gpt-5.4","options":[{"id":"reasoningEffort","value":"medium"}]},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-activity-append',
'thread',
'thread-legacy',
5,
'thread.activity-appended',
'2026-01-01T00:00:00.000Z',
'cmd-aa',
NULL,
'corr-aa',
'user',
'{"threadId":"thread-legacy","activity":{"id":"a","tone":"info","kind":"k","summary":"s","payload":null,"turnId":null,"createdAt":"2026-01-01T00:00:00.000Z"}}',
'{}'
)
`;
yield* runMigrations({ toMigrationInclusive: 26 });
// Projection projects
const projectRows = yield* sql<{
readonly projectId: string;
readonly defaultModelSelection: string | null;
}>`
SELECT
project_id AS "projectId",
default_model_selection_json AS "defaultModelSelection"
FROM projection_projects
ORDER BY project_id
`;
assert.deepStrictEqual(
projectRows.map((row) => ({
projectId: row.projectId,
selection: row.defaultModelSelection ? JSON.parse(row.defaultModelSelection) : null,
})),
[
{
projectId: "project-already-array",
selection: {
provider: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "high" }],
},
},
{
projectId: "project-legacy",
selection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: [
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
],
},
},
{
projectId: "project-no-options",
selection: { provider: "codex", model: "gpt-5.4" },
},
{ projectId: "project-null-selection", selection: null },
],
);
// Projection threads
const threadRows = yield* sql<{
readonly threadId: string;
readonly modelSelection: string | null;
}>`
SELECT
thread_id AS "threadId",
model_selection_json AS "modelSelection"
FROM projection_threads
ORDER BY thread_id
`;
assert.deepStrictEqual(
threadRows.map((row) => ({
threadId: row.threadId,
selection: row.modelSelection ? JSON.parse(row.modelSelection) : null,
})),
[
{
threadId: "thread-already-array",
selection: {
provider: "codex",
model: "gpt-5.4",
options: [{ id: "fastMode", value: true }],
},
},
{
threadId: "thread-drop-garbage",
selection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
// Only the scalar string survives; nested object, whitespace
// string, and null are dropped.
options: [{ id: "effort", value: "high" }],
},
},
{
threadId: "thread-empty-options",
selection: { provider: "codex", model: "gpt-5.4", options: [] },
},
{
threadId: "thread-legacy",
selection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: [
{ id: "effort", value: "max" },
{ id: "thinking", value: false },
{ id: "contextWindow", value: "1m" },
],
},
},
{
threadId: "thread-no-options",
selection: { provider: "codex", model: "gpt-5.4" },
},
],
);
// Orchestration events
const eventRows = yield* sql<{
readonly eventId: string;
readonly payloadJson: string;
}>`
SELECT event_id AS "eventId", payload_json AS "payloadJson"
FROM orchestration_events
ORDER BY event_id
`;
const payloads = Object.fromEntries(
eventRows.map((row) => [row.eventId, JSON.parse(row.payloadJson)]),
);
assert.deepStrictEqual(payloads["event-project-created"].defaultModelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: [
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
],
});
assert.deepStrictEqual(payloads["event-project-meta-updated"].defaultModelSelection, {
provider: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "low" }],
});
assert.strictEqual(payloads["event-project-null-selection"].defaultModelSelection, null);
assert.deepStrictEqual(payloads["event-thread-created"].modelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: [
{ id: "effort", value: "max" },
{ id: "thinking", value: false },
],
});
assert.deepStrictEqual(payloads["event-thread-meta-updated"].modelSelection, {
provider: "codex",
model: "gpt-5.4",
options: [{ id: "fastMode", value: true }],
});
assert.deepStrictEqual(payloads["event-thread-turn-start"].modelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: [
{ id: "effort", value: "high" },
{ id: "contextWindow", value: "1m" },
],
});
// Already-array records are left untouched.
assert.deepStrictEqual(payloads["event-thread-already-array"].modelSelection, {
provider: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "medium" }],
});
// Events with no modelSelection at all are untouched.
assert.isUndefined(payloads["event-activity-append"].modelSelection);
assert.isUndefined(payloads["event-activity-append"].defaultModelSelection);
}),
);
});
@@ -0,0 +1,138 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
/**
* Canonicalize `modelSelection.options` / `defaultModelSelection.options` from
* the legacy object shape (`{ effort: "max", fastMode: true, ... }`) to the
* current array-of-selections shape (`[{ id: "effort", value: "max" }, ...]`).
*
* Migration 016 introduced `modelSelection` with `options` stored as a
* per-provider object. Later the schema was reshaped so that options are a
* generic `Array<{ id, value }>` of user-selected option entries. Stored rows
* from before the reshape still have the object shape and fail to decode.
*
* For each value in the legacy object:
* - string values are kept if non-empty after trim
* - boolean values are always kept (true | false)
* - any other value type (number, null, nested object/array) is dropped,
* matching the permissive client-side normalizer in composerDraftStore.
*
* Touched storage:
* - `projection_threads.model_selection_json.options`
* - `projection_projects.default_model_selection_json.options`
* - `orchestration_events.payload_json.$.modelSelection.options`
* (thread.created | thread.meta-updated | thread.turn-start-requested)
* - `orchestration_events.payload_json.$.defaultModelSelection.options`
* (project.created | project.meta-updated)
*/
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
UPDATE projection_threads
SET model_selection_json = json_set(
model_selection_json,
'$.options',
(
SELECT json_group_array(
json_object(
'id', key,
'value',
CASE type
WHEN 'true' THEN json('true')
WHEN 'false' THEN json('false')
ELSE atom
END
)
)
FROM json_each(json_extract(model_selection_json, '$.options'))
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
OR type IN ('true', 'false')
)
)
WHERE model_selection_json IS NOT NULL
AND json_type(model_selection_json, '$.options') = 'object'
`;
yield* sql`
UPDATE projection_projects
SET default_model_selection_json = json_set(
default_model_selection_json,
'$.options',
(
SELECT json_group_array(
json_object(
'id', key,
'value',
CASE type
WHEN 'true' THEN json('true')
WHEN 'false' THEN json('false')
ELSE atom
END
)
)
FROM json_each(json_extract(default_model_selection_json, '$.options'))
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
OR type IN ('true', 'false')
)
)
WHERE default_model_selection_json IS NOT NULL
AND json_type(default_model_selection_json, '$.options') = 'object'
`;
yield* sql`
UPDATE orchestration_events
SET payload_json = json_set(
payload_json,
'$.modelSelection.options',
(
SELECT json_group_array(
json_object(
'id', key,
'value',
CASE type
WHEN 'true' THEN json('true')
WHEN 'false' THEN json('false')
ELSE atom
END
)
)
FROM json_each(json_extract(payload_json, '$.modelSelection.options'))
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
OR type IN ('true', 'false')
)
)
WHERE event_type IN (
'thread.created',
'thread.meta-updated',
'thread.turn-start-requested'
)
AND json_type(payload_json, '$.modelSelection.options') = 'object'
`;
yield* sql`
UPDATE orchestration_events
SET payload_json = json_set(
payload_json,
'$.defaultModelSelection.options',
(
SELECT json_group_array(
json_object(
'id', key,
'value',
CASE type
WHEN 'true' THEN json('true')
WHEN 'false' THEN json('false')
ELSE atom
END
)
)
FROM json_each(json_extract(payload_json, '$.defaultModelSelection.options'))
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
OR type IN ('true', 'false')
)
)
WHERE event_type IN ('project.created', 'project.meta-updated')
AND json_type(payload_json, '$.defaultModelSelection.options') = 'object'
`;
});
+19 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { runProcess } from "./processRunner.ts";
import { isWindowsCommandNotFound, runProcess } from "./processRunner.ts";
describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => {
@@ -21,3 +21,21 @@ describe("runProcess", () => {
expect(result.stderrTruncated).toBe(false);
});
});
describe("isWindowsCommandNotFound", () => {
it("matches the localized German cmd.exe error text", () => {
const originalPlatform = process.platform;
Object.defineProperty(process, "platform", { value: "win32", configurable: true });
try {
expect(
isWindowsCommandNotFound(
1,
"wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
),
).toBe(true);
} finally {
Object.defineProperty(process, "platform", { value: originalPlatform, configurable: true });
}
});
});
+14 -1
View File
@@ -37,10 +37,23 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
/is not recognized as an internal or external command/i,
/n.o . reconhecido como um comando interno/i,
/non . riconosciuto come comando interno o esterno/i,
/n.est pas reconnu en tant que commande interne/i,
/no se reconoce como un comando interno o externo/i,
/wird nicht als interner oder externer befehl/i,
] as const;
function hasWindowsCommandNotFoundMessage(output: string): boolean {
return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));
}
export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
if (process.platform !== "win32") return false;
if (code === 9009) return true;
return /is not recognized as an internal or external command/i.test(stderr);
return hasWindowsCommandNotFoundMessage(stderr);
}
function normalizeExitError(
@@ -27,6 +27,7 @@ const FAVICON_CANDIDATES = [
"assets/icon.png",
"assets/logo.svg",
"assets/logo.png",
".idea/icon.svg",
] as const;
// Files that may contain a <link rel="icon"> or icon metadata declaration.
@@ -0,0 +1,134 @@
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
## Mode rules (strict)
You are in **Plan Mode** until a developer message explicitly ends it.
Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.
## Plan Mode vs update_plan tool
Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error.
## Execution vs. mutation in Plan Mode
You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
### Allowed (non-mutating, plan-improving)
Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
* Reading or searching files, configs, schemas, types, manifests, and docs
* Static analysis, inspection, and repo exploration
* Dry-run style commands when they do not edit repo-tracked files
* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files
### Not allowed (mutating, plan-executing)
Actions that implement the plan or change repo-tracked state. Examples:
* Editing or writing files
* Running formatters or linters that rewrite files
* Applying patches, migrations, or codegen that updates repo-tracked files
* Side-effectful commands whose purpose is to carry out the plan rather than refine it
When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
## PHASE 1 - Ground in the environment (explore first, ask second)
Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.
Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.
Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.
Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.
## PHASE 2 - Intent chat (what they actually want)
* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.
## PHASE 3 - Implementation chat (what/how we'll build)
* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.
## Asking questions
Critical rules:
* Strongly prefer using the \`request_user_input\` tool to ask any questions.
* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.
* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.
You SHOULD ask many questions, but each question must:
* materially change the spec/plan, OR
* confirm/lock an assumption, OR
* choose between meaningful tradeoffs.
* not be answerable by non-mutating commands.
Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.
## Two kinds of unknowns (treat differently)
1. **Discoverable facts** (repo/system truth): explore first.
* Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
* Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
* If asking, present concrete candidates (paths/service names) + recommend one.
* Never ask questions you can answer from your environment (e.g., "where is this struct").
2. **Preferences/tradeoffs** (not discoverable): ask early.
* These are intent or implementation preferences that cannot be derived from exploration.
* Provide 2-4 mutually exclusive options + a recommended default.
* If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
## Finalization rule
Only output the final plan when it is decision complete and leaves no decisions to the implementer.
When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
1) The opening tag must be on its own line.
2) Start the plan content on the next line (no text on the same line as the tag).
3) The closing tag must be on its own line.
4) Use Markdown inside the block.
5) Keep the tags exactly as \`<proposed_plan>\` and \`</proposed_plan>\` (do not translate or rename them), even if the plan content is in another language.
Example:
<proposed_plan>
plan content
</proposed_plan>
plan content should be human and agent digestible. The final plan must be plan-only and include:
* A clear title
* A brief summary section
* Important changes or additions to public APIs/interfaces/types
* Test cases and scenarios
* Explicit assumptions and defaults chosen where needed
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
</collaboration_mode>`;
export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
## request_user_input availability
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
</collaboration_mode>`;
@@ -17,6 +17,7 @@ import {
type RuntimeMode,
ThreadId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { assert, describe, it } from "@effect/vitest";
import { Effect, Fiber, Layer, Random, Stream } from "effect";
@@ -333,13 +334,9 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "effort", value: "max" },
]),
runtimeMode: "full-access",
});
@@ -380,13 +377,9 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-7",
options: {
effort: "xhigh",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-7", [
{ id: "effort", value: "xhigh" },
]),
runtimeMode: "full-access",
});
@@ -405,13 +398,9 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
runtimeMode: "full-access",
});
@@ -430,13 +419,9 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
effort: "high",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [
{ id: "effort", value: "high" },
]),
runtimeMode: "full-access",
});
@@ -455,13 +440,9 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
thinking: false,
},
},
modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [
{ id: "thinking", value: false },
]),
runtimeMode: "full-access",
});
@@ -482,13 +463,9 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
thinking: false,
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "thinking", value: false },
]),
runtimeMode: "full-access",
});
@@ -507,13 +484,9 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
fastMode: true,
},
},
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
runtimeMode: "full-access",
});
@@ -534,13 +507,9 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
fastMode: true,
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "fastMode", value: true },
]),
runtimeMode: "full-access",
});
@@ -559,13 +528,9 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "ultrathink",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "ultrathink" },
]),
runtimeMode: "full-access",
});
@@ -573,13 +538,9 @@ describe("ClaudeAdapterLive", () => {
threadId: session.threadId,
input: "Investigate the edge cases",
attachments: [],
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "ultrathink",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "ultrathink" },
]),
});
const createInput = harness.getLastCreateQueryInput();
@@ -2600,6 +2561,96 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("preserves durable resume ids across Claude resume hooks", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const durableSessionId = "550e8400-e29b-41d4-a716-446655440000";
const transientHookSessionId = "7368d0c7-40a3-4d8a-bcc1-ac80c49f2719";
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
threadId: RESUME_THREAD_ID,
provider: "claudeAgent",
resumeCursor: {
threadId: RESUME_THREAD_ID,
resume: durableSessionId,
resumeSessionAt: "assistant-99",
turnCount: 3,
},
runtimeMode: "full-access",
});
harness.query.emit({
type: "system",
subtype: "hook_started",
hook_id: "resume-hook-1",
hook_name: "SessionStart:resume",
hook_event: "SessionStart",
session_id: transientHookSessionId,
uuid: "resume-hook-started",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "hook_response",
hook_id: "resume-hook-1",
hook_name: "SessionStart:resume",
hook_event: "SessionStart",
output: "",
stdout: "",
stderr: "",
outcome: "success",
session_id: transientHookSessionId,
uuid: "resume-hook-response",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "init",
apiKeySource: "none",
claude_code_version: "test",
cwd: "/tmp/claude-adapter-test",
tools: [],
mcp_servers: [],
model: "claude-sonnet-4-5",
permissionMode: "bypassPermissions",
slash_commands: [],
output_style: "default",
skills: [],
plugins: [],
session_id: durableSessionId,
uuid: "resume-init",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const threadStartedEvents = runtimeEvents.filter((event) => event.type === "thread.started");
assert.equal(threadStartedEvents.length, 1);
const threadStarted = threadStartedEvents[0];
assert.equal(threadStarted?.type, "thread.started");
if (threadStarted?.type === "thread.started") {
assert.deepEqual(threadStarted.payload, {
providerThreadId: durableSessionId,
});
}
const activeSessions = yield* adapter.listSessions();
const resumeCursor = activeSessions[0]?.resumeCursor as
| {
readonly resume?: string;
}
| undefined;
assert.equal(resumeCursor?.resume, durableSessionId);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("uses an app-generated Claude session id for fresh sessions", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -2794,13 +2845,9 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
contextWindow: "1m",
},
},
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "contextWindow", value: "1m" },
]),
attachments: [],
});
yield* adapter.sendTurn({
@@ -40,13 +40,13 @@ import {
ThreadId,
TurnId,
type UserInputQuestion,
ClaudeAgentEffort,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
resolveApiModelId,
resolveEffort,
trimOrNull,
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
getProviderOptionDescriptors,
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
import {
Cause,
@@ -66,7 +66,12 @@ import {
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "./ClaudeProvider.ts";
import {
getClaudeModelCapabilities,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeEffort,
} from "./ClaudeProvider.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
@@ -193,6 +198,18 @@ function isSyntheticClaudeThreadId(value: string): boolean {
return value.startsWith("claude-thread-");
}
function hasDurableClaudeSessionId(message: SDKMessage): boolean {
if (message.type !== "system") {
return true;
}
return (
message.subtype !== "hook_started" &&
message.subtype !== "hook_progress" &&
message.subtype !== "hook_response"
);
}
function toMessage(cause: unknown, fallback: string): string {
if (cause instanceof Error && cause.message.length > 0) {
return cause.message;
@@ -216,19 +233,9 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray
return squashed.length > 0 ? [squashed] : [];
}
function getEffectiveClaudeAgentEffort(
effort: ClaudeAgentEffort | null | undefined,
): ClaudeSdkEffort | null {
if (!effort) {
return null;
}
if (effort === "ultrathink") {
return null;
}
if (effort === "xhigh") {
return "max";
}
return effort;
function getEffectiveClaudeAgentEffort(effort: string | null | undefined): ClaudeSdkEffort | null {
const normalized = normalizeClaudeCliEffort(effort);
return normalized ? (normalized as ClaudeSdkEffort) : null;
}
function isClaudeInterruptedMessage(message: string): boolean {
@@ -560,16 +567,14 @@ const CLAUDE_SETTING_SOURCES = [
function buildPromptText(input: ProviderSendTurnInput): string {
const rawEffort =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null;
input.modelSelection?.provider === "claudeAgent"
? getModelSelectionStringOptionValue(input.modelSelection, "effort")
: null;
const claudeModel =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined;
const caps = getClaudeModelCapabilities(claudeModel);
// For prompt injection, we check if the raw effort is a prompt-injected level (e.g. "ultrathink").
// resolveEffort strips prompt-injected values (returning the default instead), so we check the raw value directly.
const trimmedEffort = trimOrNull(rawEffort);
const promptEffort =
trimmedEffort && caps.promptInjectedEffortLevels.includes(trimmedEffort) ? trimmedEffort : null;
const promptEffort = resolvePromptInjectedEffort(caps, rawEffort);
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
}
@@ -1256,6 +1261,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
if (typeof message.session_id !== "string" || message.session_id.length === 0) {
return;
}
if (!hasDurableClaudeSessionId(message)) {
return;
}
const nextThreadId = message.session_id;
context.resumeSessionId = message.session_id;
yield* updateResumeCursor(context);
@@ -2829,14 +2837,22 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
const caps = getClaudeModelCapabilities(modelSelection?.model);
const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
null) as ClaudeAgentEffort | null;
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
const thinking =
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
? modelSelection.options.thinking
: undefined;
const descriptors = getProviderOptionDescriptors({ caps });
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
const rawEffort = getModelSelectionStringOptionValue(modelSelection, "effort");
const effort = resolveClaudeEffort(caps, rawEffort) ?? null;
const fastModeSupported = descriptors.some(
(descriptor) => descriptor.type === "boolean" && descriptor.id === "fastMode",
);
const thinkingSupported = descriptors.some(
(descriptor) => descriptor.type === "boolean" && descriptor.id === "thinking",
);
const fastMode =
getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true &&
fastModeSupported;
const thinking = thinkingSupported
? getModelSelectionBooleanOptionValue(modelSelection, "thinking")
: undefined;
const effectiveEffort = getEffectiveClaudeAgentEffort(effort);
const runtimeModeToPermission: Record<string, PermissionMode> = {
"auto-accept-edits": "acceptEdits",
@@ -2853,7 +2869,13 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(apiModelId ? { model: apiModelId } : {}),
pathToClaudeCodeExecutable: claudeBinaryPath,
settingSources: [...CLAUDE_SETTING_SOURCES],
...(effectiveEffort ? { effort: effectiveEffort } : {}),
// The SDK type lags the CLI here: Opus 4.7 accepts `xhigh` even though
// the published `Options["effort"]` union currently stops at `max`.
...(effectiveEffort
? {
effort: effectiveEffort as unknown as NonNullable<ClaudeQueryOptions["effort"]>,
}
: {}),
...(permissionMode ? { permissionMode } : {}),
...(permissionMode === "bypassPermissions"
? { allowDangerouslySkipPermissions: true }
@@ -2868,6 +2890,31 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
};
yield* Effect.annotateCurrentSpan({
"provider.kind": PROVIDER,
"provider.thread_id": threadId,
"provider.runtime_mode": input.runtimeMode,
"claude.resume.source":
existingResumeSessionId !== undefined ? "resume-session" : "generated-session",
"claude.resume.thread_id": resumeState?.threadId ?? "",
"claude.resume.session_id": existingResumeSessionId ?? "",
"claude.resume.session_at": resumeState?.resumeSessionAt ?? "",
"claude.resume.turn_count": resumeState?.turnCount ?? -1,
"claude.query.cwd": input.cwd ?? "",
"claude.query.model": apiModelId ?? "",
"claude.query.effort": effectiveEffort ?? "",
"claude.query.permission_mode": permissionMode ?? "",
"claude.query.allow_dangerously_skip_permissions": permissionMode === "bypassPermissions",
"claude.query.resume": existingResumeSessionId ?? "",
"claude.query.session_id": newSessionId ?? "",
"claude.query.include_partial_messages": true,
"claude.query.additional_directories": input.cwd ? [input.cwd] : [],
"claude.query.setting_sources": [...CLAUDE_SETTING_SOURCES],
"claude.query.settings_json": JSON.stringify(settings),
"claude.query.extra_args_json": JSON.stringify(extraArgs),
"claude.query.path_to_executable": claudeBinaryPath,
});
const queryRuntime = yield* Effect.try({
try: () =>
createQuery({
@@ -3006,7 +3053,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
}
if (modelSelection?.model) {
const apiModelId = resolveApiModelId(modelSelection);
const apiModelId = resolveClaudeApiModelId(modelSelection);
if (context.currentApiModelId !== apiModelId) {
yield* Effect.tryPromise({
try: () => context.query.setModel(apiModelId),
+192 -64
View File
@@ -1,5 +1,6 @@
import type {
ClaudeSettings,
ClaudeModelSelection,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
@@ -10,13 +11,23 @@ import type {
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import {
createModelCapabilities,
getModelSelectionStringOptionValue,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import {
query as claudeQuery,
type SlashCommand as ClaudeSlashCommand,
type SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import {
buildBooleanOptionDescriptor,
buildSelectOptionDescriptor,
buildServerProvider,
AUTH_PROBE_TIMEOUT_MS,
DEFAULT_TIMEOUT_MS,
detailFromResult,
extractAuthBoolean,
@@ -32,91 +43,143 @@ import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ServerSettingsError } from "@t3tools/contracts";
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
};
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
const PROVIDER = "claudeAgent" as const;
const CLAUDE_PRESENTATION = {
displayName: "Claude",
showInteractionModeToggle: true,
} as const;
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-7",
name: "Claude Opus 4.7",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
}),
},
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildBooleanOptionDescriptor({
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
}),
},
{
slug: "claude-opus-4-5",
name: "Claude Opus 4.5",
isCustom: false,
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
],
}),
buildBooleanOptionDescriptor({
id: "fastMode",
label: "Fast Mode",
}),
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
}),
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "ultrathink", label: "Ultrathink" },
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
}),
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
} satisfies ModelCapabilities,
capabilities: createModelCapabilities({
optionDescriptors: [
buildBooleanOptionDescriptor({
id: "thinking",
label: "Thinking",
}),
],
}),
},
];
@@ -146,6 +209,47 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
);
}
export function resolveClaudeEffort(
caps: ModelCapabilities,
raw: string | null | undefined,
): string | undefined {
const descriptors = getProviderOptionDescriptors({
caps,
...(raw ? { selections: [{ id: "effort", value: raw }] } : {}),
});
const effortDescriptor = descriptors.find((descriptor) => descriptor.id === "effort");
const value = getProviderOptionCurrentValue(effortDescriptor);
return typeof value === "string" ? value : undefined;
}
/**
* Normalize a resolved Claude effort value into one suitable for the Claude
* CLI's `--effort` flag.
*
* Mirrors the mapping used when invoking the Claude Agent SDK
* ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): the Opus 4.7
* capability `"xhigh"` is rewritten to the accepted CLI value `"max"`, and
* `"ultrathink"` is filtered out because it is a prompt-prefix mode rather
* than a CLI-effort value. Returns `undefined` when no flag should be passed.
*/
export function normalizeClaudeCliEffort(effort: string | null | undefined): string | undefined {
if (!effort || effort === "ultrathink") {
return undefined;
}
if (effort === "xhigh") {
return "max";
}
return effort;
}
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
return modelSelection.model;
}
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
@@ -454,13 +558,24 @@ function dedupeSlashCommands(
return [...commandsByName.values()];
}
function waitForAbortSignal(signal: AbortSignal): Promise<void> {
if (signal.aborted) {
return Promise.resolve();
}
return new Promise((resolve) => {
signal.addEventListener("abort", () => resolve(), { once: true });
});
}
/**
* Probe account information by spawning a lightweight Claude Agent SDK
* session and reading the initialization result.
*
* The prompt is never sent to the Anthropic API — we abort immediately
* after the local initialization phase completes. This gives us the
* user's subscription type without incurring any token cost.
* We pass a never-yielding AsyncIterable as the prompt so that no user
* message is ever written to the subprocess stdin. This means the Claude
* Code subprocess completes its local initialization IPC (returning
* account info and slash commands) but never starts an API request to
* Anthropic. We read the init data and then abort the subprocess.
*
* This is used as a fallback when `claude auth status` does not include
* subscription type information.
@@ -469,12 +584,16 @@ const probeClaudeCapabilities = (binaryPath: string) => {
const abort = new AbortController();
return Effect.tryPromise(async () => {
const q = claudeQuery({
prompt: ".",
// Never yield — we only need initialization data, not a conversation.
// This prevents any prompt from reaching the Anthropic API.
// oxlint-disable-next-line require-yield
prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
await waitForAbortSignal(abort.signal);
})(),
options: {
persistSession: false,
pathToClaudeCodeExecutable: binaryPath,
abortController: abort,
maxTurns: 0,
settingSources: ["user", "project", "local"],
allowedTools: [],
stderr: () => {},
@@ -536,6 +655,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: false,
checkedAt,
models: allModels,
@@ -558,6 +678,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models: allModels,
@@ -576,6 +697,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models: allModels,
@@ -596,6 +718,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models: allModels,
@@ -632,7 +755,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
// ── Auth check + subscription detection ────────────────────────────
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
Effect.result,
);
@@ -660,6 +783,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models,
@@ -680,6 +804,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models,
@@ -698,6 +823,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models,
@@ -731,6 +857,7 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: false,
checkedAt,
models,
@@ -746,6 +873,7 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: true,
checkedAt,
models,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,275 @@
import assert from "node:assert/strict";
import { Effect, Schema } from "effect";
import { describe, it } from "vitest";
import { ThreadId } from "@t3tools/contracts";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as CodexRpc from "effect-codex-app-server/rpc";
import {
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "../CodexDeveloperInstructions.ts";
import {
buildTurnStartParams,
isRecoverableThreadResumeError,
openCodexThread,
} from "./CodexSessionRuntime.ts";
function makeThreadOpenResponse(
threadId: string,
): CodexRpc.ClientRequestResponsesByMethod["thread/start"] {
return {
cwd: "/tmp/project",
model: "gpt-5.3-codex",
modelProvider: "openai",
approvalPolicy: "never",
approvalsReviewer: "user",
sandbox: { type: "danger-full-access" },
thread: {
id: threadId,
createdAt: "2026-04-18T00:00:00.000Z",
source: { session: "cli" },
turns: [],
status: {
state: "idle",
activeFlags: [],
},
},
} as unknown as CodexRpc.ClientRequestResponsesByMethod["thread/start"];
}
describe("buildTurnStartParams", () => {
it("includes plan collaboration mode when requested", () => {
const params = Effect.runSync(
buildTurnStartParams({
threadId: "provider-thread-1",
runtimeMode: "full-access",
prompt: "Make a plan",
model: "gpt-5.3-codex",
effort: "medium",
interactionMode: "plan",
}),
);
assert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "never",
sandboxPolicy: {
type: "dangerFullAccess",
},
input: [
{
type: "text",
text: "Make a plan",
},
],
model: "gpt-5.3-codex",
effort: "medium",
collaborationMode: {
mode: "plan",
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
it("includes default collaboration mode and image attachments", () => {
const params = Effect.runSync(
buildTurnStartParams({
threadId: "provider-thread-1",
runtimeMode: "auto-accept-edits",
prompt: "Implement it",
model: "gpt-5.3-codex",
interactionMode: "default",
attachments: [
{
type: "image",
url: "data:image/png;base64,abc",
},
],
}),
);
assert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "on-request",
sandboxPolicy: {
type: "workspaceWrite",
},
input: [
{
type: "text",
text: "Implement it",
},
{
type: "image",
url: "data:image/png;base64,abc",
},
],
model: "gpt-5.3-codex",
collaborationMode: {
mode: "default",
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
it("omits collaboration mode when interaction mode is absent", () => {
const params = Effect.runSync(
buildTurnStartParams({
threadId: "provider-thread-1",
runtimeMode: "approval-required",
prompt: "Review",
}),
);
assert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "untrusted",
sandboxPolicy: {
type: "readOnly",
},
input: [
{
type: "text",
text: "Review",
},
],
});
});
});
describe("isRecoverableThreadResumeError", () => {
it("matches missing thread errors", () => {
assert.equal(
isRecoverableThreadResumeError(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "Thread does not exist",
}),
),
true,
);
});
it("ignores non-recoverable resume errors", () => {
assert.equal(
isRecoverableThreadResumeError(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "Permission denied",
}),
),
false,
);
});
it("ignores unrelated missing-resource errors that do not mention threads", () => {
assert.equal(
isRecoverableThreadResumeError(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "Config file not found",
}),
),
false,
);
assert.equal(
isRecoverableThreadResumeError(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "Model does not exist",
}),
),
false,
);
});
});
describe("openCodexThread", () => {
it("falls back to thread/start when resume fails recoverably", async () => {
const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = [];
const started = makeThreadOpenResponse("fresh-thread");
const client = {
request: <M extends "thread/start" | "thread/resume">(
method: M,
payload: CodexRpc.ClientRequestParamsByMethod[M],
) => {
calls.push({ method, payload });
if (method === "thread/resume") {
return Effect.fail(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "thread not found",
}),
);
}
return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]);
},
};
const opened = await Effect.runPromise(
openCodexThread({
client,
threadId: ThreadId.make("thread-1"),
runtimeMode: "full-access",
cwd: "/tmp/project",
requestedModel: "gpt-5.3-codex",
serviceTier: undefined,
resumeThreadId: "stale-thread",
}),
);
assert.equal(opened.thread.id, "fresh-thread");
assert.deepStrictEqual(
calls.map((call) => call.method),
["thread/resume", "thread/start"],
);
});
it("propagates non-recoverable resume failures", async () => {
const client = {
request: <M extends "thread/start" | "thread/resume">(
method: M,
_payload: CodexRpc.ClientRequestParamsByMethod[M],
) => {
if (method === "thread/resume") {
return Effect.fail(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "timed out waiting for server",
}),
);
}
return Effect.succeed(
makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M],
);
},
};
await assert.rejects(
Effect.runPromise(
openCodexThread({
client,
threadId: ThreadId.make("thread-1"),
runtimeMode: "full-access",
cwd: "/tmp/project",
requestedModel: "gpt-5.3-codex",
serviceTier: undefined,
resumeThreadId: "stale-thread",
}),
),
(error: unknown) =>
Schema.is(CodexErrors.CodexAppServerRequestError)(error) &&
error.errorMessage === "timed out waiting for server",
);
});
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,678 @@
import * as path from "node:path";
import * as os from "node:os";
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import {
buildCursorProviderSnapshot,
buildCursorCapabilitiesFromConfigOptions,
buildCursorDiscoveredModelsFromConfigOptions,
discoverCursorModelCapabilitiesViaAcp,
discoverCursorModelsViaAcp,
getCursorFallbackModels,
getCursorParameterizedModelPickerUnsupportedMessage,
parseCursorAboutOutput,
parseCursorCliConfigChannel,
parseCursorVersionDate,
resolveCursorAcpBaseModelId,
resolveCursorAcpConfigUpdates,
} from "./CursorProvider.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
function selectDescriptor(
id: string,
label: string,
options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>,
) {
return {
id,
label,
type: "select" as const,
options: [...options],
...(options.find((option) => option.isDefault)?.id
? { currentValue: options.find((option) => option.isDefault)?.id }
: {}),
};
}
function booleanDescriptor(id: string, label: string, currentValue?: boolean) {
return {
id,
label,
type: "boolean" as const,
...(typeof currentValue === "boolean" ? { currentValue } : {}),
};
}
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
const wrapperPath = path.join(dir, "fake-agent.sh");
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
.join("\n");
const script = `#!/bin/sh
${envExports}
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
`;
await writeFile(wrapperPath, script, "utf8");
await chmod(wrapperPath, 0o755);
return wrapperPath;
}
async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const content = await readFile(filePath, "utf8");
if (content.trim().length > 0) {
return content;
}
} catch {}
await new Promise((resolve) => setTimeout(resolve, 50));
}
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
const parameterizedGpt54ConfigOptions = [
{
type: "select",
currentValue: "gpt-5.4-medium-fast",
options: [{ name: "GPT-5.4", value: "gpt-5.4-medium-fast" }],
category: "model",
id: "model",
name: "Model",
},
{
type: "select",
currentValue: "medium",
options: [
{ name: "None", value: "none" },
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
{ name: "Extra High", value: "extra-high" },
],
category: "thought_level",
id: "reasoning",
name: "Reasoning",
},
{
type: "select",
currentValue: "272k",
options: [
{ name: "272K", value: "272k" },
{ name: "1M", value: "1m" },
],
category: "model_config",
id: "context",
name: "Context",
},
{
type: "select",
currentValue: "false",
options: [
{ name: "Off", value: "false" },
{ name: "Fast", value: "true" },
],
category: "model_config",
id: "fast",
name: "Fast",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const parameterizedClaudeConfigOptions = [
{
type: "select",
currentValue: "claude-4.6-opus-high-thinking",
options: [{ name: "Opus 4.6", value: "claude-4.6-opus-high-thinking" }],
category: "model",
id: "model",
name: "Model",
},
{
type: "select",
currentValue: "high",
options: [
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
],
category: "thought_level",
id: "reasoning",
name: "Reasoning",
},
{
type: "boolean",
currentValue: true,
category: "model_config",
id: "thinking",
name: "Thinking",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const parameterizedClaudeModelOptionConfigOptions = [
{
type: "select",
currentValue: "claude-opus-4-6",
options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }],
category: "model",
id: "model",
name: "Model",
},
{
type: "select",
currentValue: "high",
options: [
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
],
category: "thought_level",
id: "reasoning",
name: "Reasoning",
},
{
type: "select",
currentValue: "max",
options: [
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
{ name: "Max", value: "max" },
],
category: "model_option",
id: "effort",
name: "Effort",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: "Fast", value: "true" },
],
category: "model_config",
id: "fast",
name: "Fast",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: ":icon-brain:", value: "true" },
],
category: "model_config",
id: "thinking",
name: "Thinking",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const sessionNewCursorConfigOptions = [
{
type: "select",
currentValue: "agent",
options: [
{ name: "Agent", value: "agent", description: "Full agent capabilities with tool access" },
],
category: "mode",
id: "mode",
name: "Mode",
description: "Controls how the agent executes tasks",
},
{
type: "select",
currentValue: "composer-2",
options: [
{ name: "Auto", value: "default" },
{ name: "Composer 2", value: "composer-2" },
{ name: "GPT-5.4", value: "gpt-5.4" },
{ name: "Sonnet 4.6", value: "claude-sonnet-4-6" },
{ name: "Opus 4.6", value: "claude-opus-4-6" },
{ name: "Codex 5.3 Spark", value: "gpt-5.3-codex-spark" },
],
category: "model",
id: "model",
name: "Model",
description: "Controls which model is used for responses",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: "Fast", value: "true" },
],
category: "model_config",
id: "fast",
name: "Fast",
description: "Faster speeds.",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const baseCursorSettings: CursorSettings = {
enabled: true,
binaryPath: "agent",
apiEndpoint: "",
customModels: [],
};
const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
expect(
getCursorFallbackModels({
customModels: ["internal/cursor-model"],
}).map((model) => model.slug),
).toEqual(["internal/cursor-model"]);
});
});
describe("buildCursorProviderSnapshot", () => {
it("downgrades ready status to warning when ACP model discovery times out", () => {
expect(
buildCursorProviderSnapshot({
checkedAt: "2026-01-01T00:00:00.000Z",
cursorSettings: baseCursorSettings,
parsed: {
version: "2026.04.09-f2b0fcd",
status: "ready",
auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" },
},
discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.",
}),
).toMatchObject({
status: "warning",
message: "Cursor ACP model discovery timed out after 15000ms.",
models: [],
});
});
it("preserves provider error state while appending discovery warnings", () => {
expect(
buildCursorProviderSnapshot({
checkedAt: "2026-01-01T00:00:00.000Z",
cursorSettings: {
...baseCursorSettings,
customModels: ["claude-sonnet-4-6"],
},
parsed: {
version: "2026.04.09-f2b0fcd",
status: "error",
auth: { status: "unauthenticated" },
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
},
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
}),
).toMatchObject({
status: "error",
message:
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
models: [
{
slug: "claude-sonnet-4-6",
isCustom: true,
},
],
});
});
});
describe("buildCursorCapabilitiesFromConfigOptions", () => {
it("derives model capabilities from parameterized Cursor ACP config options", () => {
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual(
createModelCapabilities({
optionDescriptors: [
selectDescriptor("reasoning", "Reasoning", [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium", isDefault: true },
{ id: "high", label: "High" },
{ id: "xhigh", label: "Extra High" },
]),
selectDescriptor("contextWindow", "Context", [
{ id: "272k", label: "272K", isDefault: true },
{ id: "1m", label: "1M" },
]),
booleanDescriptor("fastMode", "Fast", false),
],
}),
);
});
it("detects boolean thinking toggles from model_config options", () => {
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual(
createModelCapabilities({
optionDescriptors: [
selectDescriptor("reasoning", "Reasoning", [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High", isDefault: true },
]),
booleanDescriptor("thinking", "Thinking", true),
],
}),
);
});
it("prefers the newer model_option effort control over legacy thought_level", () => {
expect(
buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
).toEqual(
createModelCapabilities({
optionDescriptors: [
selectDescriptor("reasoning", "Effort", [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High" },
{ id: "max", label: "Max", isDefault: true },
]),
booleanDescriptor("fastMode", "Fast", true),
booleanDescriptor("thinking", "Thinking", true),
],
}),
);
});
});
describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
it("publishes ACP model choices immediately from session/new config options", () => {
expect(buildCursorDiscoveredModelsFromConfigOptions(sessionNewCursorConfigOptions)).toEqual([
{
slug: "default",
name: "Auto",
isCustom: false,
capabilities: emptyCapabilities,
},
{
slug: "composer-2",
name: "Composer 2",
isCustom: false,
capabilities: createModelCapabilities({
optionDescriptors: [booleanDescriptor("fastMode", "Fast", true)],
}),
},
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: emptyCapabilities,
},
{
slug: "claude-sonnet-4-6",
name: "Sonnet 4.6",
isCustom: false,
capabilities: emptyCapabilities,
},
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: emptyCapabilities,
},
{
slug: "gpt-5.3-codex-spark",
name: "Codex 5.3 Spark",
isCustom: false,
capabilities: emptyCapabilities,
},
]);
});
});
describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await makeMockAgentWrapper();
const models = await Effect.runPromise(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
expect(models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
});
it("closes the ACP probe runtime after discovery completes", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
await Effect.runPromise(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer)),
);
const exitLog = await waitForFileContent(exitLogPath);
expect(exitLog).toContain("SIGTERM");
});
});
describe("discoverCursorModelCapabilitiesViaAcp", () => {
it("closes all ACP probe runtimes after capability enrichment completes", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
const existingModels: ReadonlyArray<ServerProviderModel> = [
{ slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
{ slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: emptyCapabilities },
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: emptyCapabilities,
},
];
const models = await Effect.runPromise(
discoverCursorModelCapabilitiesViaAcp(
{
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
},
existingModels,
).pipe(Effect.provide(NodeServices.layer)),
);
expect(models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
const exitLog = await waitForFileContent(exitLogPath);
expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);
});
});
describe("parseCursorAboutOutput", () => {
it("parses json about output and forwards subscription metadata", () => {
expect(
parseCursorAboutOutput({
code: 0,
stdout: JSON.stringify({
cliVersion: "2026.04.09-f2b0fcd",
subscriptionTier: "Team",
userEmail: "[email protected]",
}),
stderr: "",
}),
).toEqual({
version: "2026.04.09-f2b0fcd",
status: "ready",
auth: {
status: "authenticated",
type: "Team",
label: "Cursor Team Subscription",
},
});
});
it("treats json about output with a logged-out email as unauthenticated", () => {
expect(
parseCursorAboutOutput({
code: 0,
stdout: JSON.stringify({
cliVersion: "2026.04.09-f2b0fcd",
subscriptionTier: "Team",
userEmail: "Not logged in",
}),
stderr: "",
}),
).toEqual({
version: "2026.04.09-f2b0fcd",
status: "error",
auth: {
status: "unauthenticated",
},
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
});
});
it("treats json about output with a null email as unauthenticated", () => {
expect(
parseCursorAboutOutput({
code: 0,
stdout: JSON.stringify({
cliVersion: "2026.04.09-f2b0fcd",
subscriptionTier: null,
userEmail: null,
}),
stderr: "",
}),
).toEqual({
version: "2026.04.09-f2b0fcd",
status: "error",
auth: {
status: "unauthenticated",
},
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
});
});
});
describe("Cursor parameterized model picker preview gating", () => {
it("parses Cursor CLI version dates from build versions", () => {
expect(parseCursorVersionDate("2026.04.08-c4e73a3")).toBe(20260408);
expect(parseCursorVersionDate("2026.04.09")).toBe(20260409);
expect(parseCursorVersionDate("not-a-version")).toBeUndefined();
});
it("parses the Cursor CLI channel from cli-config.json", () => {
expect(parseCursorCliConfigChannel('{ "channel": "lab" }')).toBe("lab");
expect(parseCursorCliConfigChannel('{ "channel": "stable" }')).toBe("stable");
expect(parseCursorCliConfigChannel('{ "version": 1 }')).toBeUndefined();
expect(parseCursorCliConfigChannel("not-json")).toBeUndefined();
});
it("returns no warning when the preview requirements are met", () => {
expect(
getCursorParameterizedModelPickerUnsupportedMessage({
version: "2026.04.08-c4e73a3",
channel: "lab",
}),
).toBeUndefined();
});
it("explains when the Cursor Agent version is too old", () => {
expect(
getCursorParameterizedModelPickerUnsupportedMessage({
version: "2026.04.07-c4e73a3",
channel: "lab",
}),
).toContain("too old");
});
it("explains when the Cursor Agent channel is not lab", () => {
expect(
getCursorParameterizedModelPickerUnsupportedMessage({
version: "2026.04.08-c4e73a3",
channel: "stable",
}),
).toContain("lab channel");
});
});
describe("resolveCursorAcpBaseModelId", () => {
it("drops bracket traits without rewriting raw ACP model ids", () => {
expect(resolveCursorAcpBaseModelId("gpt-5.4[reasoning=medium,context=272k]")).toBe("gpt-5.4");
expect(resolveCursorAcpBaseModelId("gpt-5.4-medium-fast")).toBe("gpt-5.4-medium-fast");
expect(resolveCursorAcpBaseModelId("claude-4.6-opus-high-thinking")).toBe(
"claude-4.6-opus-high-thinking",
);
expect(resolveCursorAcpBaseModelId("composer-2")).toBe("composer-2");
expect(resolveCursorAcpBaseModelId("auto")).toBe("auto");
});
});
describe("resolveCursorAcpConfigUpdates", () => {
it("maps Cursor model options onto separate ACP config option updates", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
{ id: "reasoning", value: "xhigh" },
{ id: "fastMode", value: true },
{ id: "contextWindow", value: "1m" },
]),
).toEqual([
{ configId: "reasoning", value: "extra-high" },
{ configId: "context", value: "1m" },
{ configId: "fast", value: "true" },
]);
});
it("maps boolean thinking toggles when the model exposes them separately", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, [
{ id: "thinking", value: false },
]),
).toEqual([{ configId: "thinking", value: false }]);
});
it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
{ id: "fastMode", value: false },
]),
).toEqual([{ configId: "fast", value: "false" }]);
});
it("writes Cursor effort changes through the newer model_option config when available", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, [
{ id: "reasoning", value: "max" },
{ id: "thinking", value: false },
]),
).toEqual([
{ configId: "effort", value: "max" },
{ configId: "thinking", value: "false" },
]);
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,523 @@
import assert from "node:assert/strict";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import { beforeEach } from "vitest";
import { ThreadId } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../opencodeRuntime.ts";
import {
appendOpenCodeAssistantTextDelta,
makeOpenCodeAdapterLive,
mergeOpenCodeAssistantText,
} from "./OpenCodeAdapter.ts";
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
type MessageEntry = {
info: {
id: string;
role: "user" | "assistant";
};
parts: Array<unknown>;
};
const runtimeMock = {
state: {
startCalls: [] as string[],
sessionCreateUrls: [] as string[],
authHeaders: [] as Array<string | null>,
abortCalls: [] as string[],
closeCalls: [] as string[],
revertCalls: [] as Array<{ sessionID: string; messageID?: string }>,
promptAsyncError: null as Error | null,
closeError: null as Error | null,
messages: [] as MessageEntry[],
subscribedEvents: [] as unknown[],
},
reset() {
this.state.startCalls.length = 0;
this.state.sessionCreateUrls.length = 0;
this.state.authHeaders.length = 0;
this.state.abortCalls.length = 0;
this.state.closeCalls.length = 0;
this.state.revertCalls.length = 0;
this.state.promptAsyncError = null;
this.state.closeError = null;
this.state.messages = [];
this.state.subscribedEvents = [];
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
startOpenCodeServerProcess: ({ binaryPath }) =>
Effect.gen(function* () {
runtimeMock.state.startCalls.push(binaryPath);
const url = "http://127.0.0.1:4301";
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
runtimeMock.state.closeCalls.push(url);
if (runtimeMock.state.closeError) {
throw runtimeMock.state.closeError;
}
}),
);
return {
url,
exitCode: Effect.never,
};
}),
connectToOpenCodeServer: ({ serverUrl }) =>
Effect.gen(function* () {
const url = serverUrl ?? "http://127.0.0.1:4301";
// Unconditionally register a scope finalizer for test observability —
// preserves the `closeCalls` / `closeError` probes that the existing
// suites rely on. Production code never attaches a finalizer to an
// external server (it simply returns `Effect.succeed(...)`).
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
runtimeMock.state.closeCalls.push(url);
if (runtimeMock.state.closeError) {
throw runtimeMock.state.closeError;
}
}),
);
return {
url,
exitCode: null,
external: Boolean(serverUrl),
};
}),
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
({
session: {
create: async () => {
runtimeMock.state.sessionCreateUrls.push(baseUrl);
runtimeMock.state.authHeaders.push(
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
);
return { data: { id: `${baseUrl}/session` } };
},
abort: async ({ sessionID }: { sessionID: string }) => {
runtimeMock.state.abortCalls.push(sessionID);
},
promptAsync: async () => {
if (runtimeMock.state.promptAsyncError) {
throw runtimeMock.state.promptAsyncError;
}
},
messages: async () => ({ data: runtimeMock.state.messages }),
revert: async ({ sessionID, messageID }: { sessionID: string; messageID?: string }) => {
runtimeMock.state.revertCalls.push({
sessionID,
...(messageID ? { messageID } : {}),
});
if (!messageID) {
runtimeMock.state.messages = [];
return;
}
const targetIndex = runtimeMock.state.messages.findIndex(
(entry) => entry.info.id === messageID,
);
runtimeMock.state.messages =
targetIndex >= 0
? runtimeMock.state.messages.slice(0, targetIndex + 1)
: runtimeMock.state.messages;
},
},
event: {
subscribe: async () => ({
stream: (async function* () {
for (const event of runtimeMock.state.subscribedEvents) {
yield event;
}
})(),
}),
},
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
loadOpenCodeInventory: () =>
Effect.fail(
new OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
cause: null,
}),
),
};
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
upsert: () => Effect.void,
getProvider: () =>
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
getBinding: () => Effect.succeed(Option.none()),
listThreadIds: () => Effect.succeed([]),
listBindings: () => Effect.succeed([]),
});
const OpenCodeAdapterTestLayer = makeOpenCodeAdapterLive().pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
},
},
}),
),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
beforeEach(() => {
runtimeMock.reset();
});
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
it.effect("reuses a configured OpenCode server URL instead of spawning a local server", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const session = yield* adapter.startSession({
provider: "opencode",
threadId: asThreadId("thread-opencode"),
runtimeMode: "full-access",
});
assert.equal(session.provider, "opencode");
assert.equal(session.threadId, "thread-opencode");
assert.deepEqual(runtimeMock.state.startCalls, []);
assert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]);
assert.deepEqual(runtimeMock.state.authHeaders, [
`Basic ${btoa("opencode:secret-password")}`,
]);
}),
);
it.effect("stops a configured-server session without trying to own server lifecycle", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: "opencode",
threadId: asThreadId("thread-opencode"),
runtimeMode: "full-access",
});
yield* adapter.stopSession(asThreadId("thread-opencode"));
assert.deepEqual(runtimeMock.state.startCalls, []);
assert.deepEqual(
runtimeMock.state.abortCalls.includes("http://127.0.0.1:9999/session"),
true,
);
}),
);
it.effect("clears session state even when cleanup finalizers throw", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: "opencode",
threadId: asThreadId("thread-stop-all-a"),
runtimeMode: "full-access",
});
yield* adapter.startSession({
provider: "opencode",
threadId: asThreadId("thread-stop-all-b"),
runtimeMode: "full-access",
});
runtimeMock.state.closeError = new Error("close failed");
// `stopAll` relies on `stopOpenCodeContext`, which is typed as
// never-failing. A throwing finalizer surfaces as a defect — `Effect.exit`
// captures it so the assertions can still run. The key invariant we're
// validating is "the sessions map and close-call probes reflect cleanup
// attempts regardless of finalizer outcome".
yield* Effect.exit(adapter.stopAll());
const sessions = yield* adapter.listSessions();
assert.deepEqual(runtimeMock.state.closeCalls, [
"http://127.0.0.1:9999",
"http://127.0.0.1:9999",
]);
assert.deepEqual(sessions, []);
}),
);
it.effect("rolls back session state when sendTurn fails before OpenCode accepts the prompt", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: "opencode",
threadId: asThreadId("thread-send-turn-failure"),
runtimeMode: "full-access",
});
runtimeMock.state.promptAsyncError = new Error("prompt failed");
const error = yield* adapter
.sendTurn({
threadId: asThreadId("thread-send-turn-failure"),
input: "Fix it",
modelSelection: {
provider: "opencode",
model: "openai/gpt-5",
},
})
.pipe(Effect.flip);
const sessions = yield* adapter.listSessions();
assert.equal(error._tag, "ProviderAdapterRequestError");
if (error._tag !== "ProviderAdapterRequestError") {
throw new Error("Unexpected error type");
}
assert.equal(error.detail, "prompt failed");
assert.equal(
error.message,
"Provider adapter request failed (opencode) for session.promptAsync: prompt failed",
);
assert.equal(sessions.length, 1);
assert.equal(sessions[0]?.status, "ready");
assert.equal(sessions[0]?.activeTurnId, undefined);
assert.equal(sessions[0]?.lastError, "prompt failed");
}),
);
it.effect("reverts the full thread when rollback removes every assistant turn", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-rollback-all");
yield* adapter.startSession({
provider: "opencode",
threadId,
runtimeMode: "full-access",
});
runtimeMock.state.messages = [
{
info: { id: "assistant-1", role: "assistant" },
parts: [],
},
{
info: { id: "assistant-2", role: "assistant" },
parts: [],
},
];
const snapshot = yield* adapter.rollbackThread(threadId, 2);
assert.deepEqual(runtimeMock.state.revertCalls, [
{ sessionID: "http://127.0.0.1:9999/session" },
]);
assert.deepEqual(snapshot.turns, []);
}),
);
it.effect("deduplicates overlapping assistant text deltas after part updates", () =>
Effect.sync(() => {
const firstUpdate = mergeOpenCodeAssistantText(undefined, "Hello");
const overlapDelta = appendOpenCodeAssistantTextDelta(firstUpdate.latestText, "lo world");
const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hello world!");
assert.deepEqual(
[firstUpdate.deltaToEmit, overlapDelta.deltaToEmit, secondUpdate.deltaToEmit],
["Hello", " world", "!"],
);
assert.equal(secondUpdate.latestText, "Hello world!");
}),
);
it.effect("writes provider-native observability records using the session thread id", () =>
Effect.gen(function* () {
const nativeEvents: Array<{
readonly event?: {
readonly provider?: string;
readonly threadId?: string;
readonly providerThreadId?: string;
readonly type?: string;
};
}> = [];
const nativeThreadIds: Array<string | null> = [];
runtimeMock.state.subscribedEvents = [
{
type: "message.updated",
properties: {
info: {
id: "msg-missing-session",
role: "assistant",
},
},
},
{
type: "message.updated",
properties: {
sessionID: "http://127.0.0.1:9999/other-session",
info: {
id: "msg-other-session",
role: "assistant",
},
},
},
{
type: "message.updated",
properties: {
sessionID: "http://127.0.0.1:9999/session",
info: {
id: "msg-native-log",
role: "assistant",
},
},
},
];
const nativeEventLogger = {
filePath: "memory://opencode-native-events",
write: (event: unknown, threadId: ThreadId | null) => {
nativeEvents.push(event as (typeof nativeEvents)[number]);
nativeThreadIds.push(threadId ?? null);
return Effect.void;
},
close: () => Effect.void,
};
const adapterLayer = makeOpenCodeAdapterLive({
nativeEventLogger,
}).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
},
},
}),
),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
const session = yield* Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const started = yield* adapter.startSession({
provider: "opencode",
threadId: asThreadId("thread-native-log"),
runtimeMode: "full-access",
});
yield* sleep(10);
return started;
}).pipe(Effect.provide(adapterLayer));
assert.equal(session.threadId, "thread-native-log");
assert.equal(nativeEvents.length, 1);
assert.equal(
nativeEvents.some((record) => record.event?.provider === "opencode"),
true,
);
assert.equal(
nativeEvents.some(
(record) => record.event?.providerThreadId === "http://127.0.0.1:9999/session",
),
true,
);
assert.equal(
nativeEvents.some((record) => record.event?.threadId === "thread-native-log"),
true,
);
assert.equal(
nativeEvents.some((record) => record.event?.type === "message.updated"),
true,
);
assert.equal(
nativeThreadIds.every((threadId) => threadId === "thread-native-log"),
true,
);
}),
);
it.effect("keeps the event pump alive when native event logging fails", () =>
Effect.gen(function* () {
runtimeMock.state.subscribedEvents = [
{
type: "message.updated",
properties: {
sessionID: "http://127.0.0.1:9999/session",
info: {
id: "msg-native-log-failure",
role: "assistant",
},
},
},
];
const nativeEventLogger = {
filePath: "memory://opencode-native-events",
write: () => Effect.die(new Error("native log write failed")),
close: () => Effect.void,
};
const adapterLayer = makeOpenCodeAdapterLive({
nativeEventLogger,
}).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
},
},
}),
),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
// Capture closeCalls *inside* the provided layer scope: the adapter's
// layer finalizer now tears down any live sessions when the layer
// closes (which is exactly what we want for leak prevention), so
// inspecting closeCalls after `Effect.provide` completes would observe
// the teardown — not the behavior under test. We care that the event
// pump kept the session alive while logging was failing.
const { sessions, closeCallsDuringRun } = yield* Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: "opencode",
threadId: asThreadId("thread-native-log-failure"),
runtimeMode: "full-access",
});
yield* sleep(10);
return {
sessions: yield* adapter.listSessions(),
closeCallsDuringRun: [...runtimeMock.state.closeCalls],
};
}).pipe(Effect.provide(adapterLayer));
assert.equal(sessions.length, 1);
assert.equal(sessions[0]?.threadId, "thread-native-log-failure");
assert.deepEqual(closeCallsDuringRun, []);
}),
);
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,234 @@
import assert from "node:assert/strict";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { beforeEach } from "vitest";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../opencodeRuntime.ts";
import { OpenCodeProviderLive } from "./OpenCodeProvider.ts";
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n";
const runtimeMock = {
state: {
runVersionError: null as Error | null,
versionStdout: DEFAULT_VERSION_STDOUT,
inventoryError: null as Error | null,
inventory: {
providerList: { connected: [] as string[], all: [] as unknown[], default: {} },
agents: [] as unknown[],
} as unknown,
},
reset() {
this.state.runVersionError = null;
this.state.versionStdout = DEFAULT_VERSION_STDOUT;
this.state.inventoryError = null;
this.state.inventory = {
providerList: { connected: [], all: [] as unknown[], default: {} },
agents: [] as unknown[],
};
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
startOpenCodeServerProcess: () =>
Effect.succeed({
url: "http://127.0.0.1:4301",
exitCode: Effect.never,
}),
connectToOpenCodeServer: ({ serverUrl }) =>
Effect.succeed({
url: serverUrl ?? "http://127.0.0.1:4301",
exitCode: null,
external: Boolean(serverUrl),
}),
runOpenCodeCommand: () =>
runtimeMock.state.runVersionError
? Effect.fail(
new OpenCodeRuntimeError({
operation: "runOpenCodeCommand",
detail: runtimeMock.state.runVersionError.message,
cause: runtimeMock.state.runVersionError,
}),
)
: Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
createOpenCodeSdkClient: () =>
({}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
loadOpenCodeInventory: () =>
runtimeMock.state.inventoryError
? Effect.fail(
new OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: runtimeMock.state.inventoryError.message,
cause: runtimeMock.state.inventoryError,
}),
)
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
};
beforeEach(() => {
runtimeMock.reset();
});
const makeTestLayer = (settingsOverrides?: Parameters<typeof ServerSettingsService.layerTest>[0]) =>
OpenCodeProviderLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)),
Layer.provideMerge(NodeServices.layer),
);
it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
it.effect("shows a codex-style missing binary message", () =>
Effect.gen(function* () {
runtimeMock.state.runVersionError = new Error("spawn opencode ENOENT");
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, false);
assert.equal(snapshot.message, "OpenCode CLI (`opencode`) is not installed or not on PATH.");
}),
);
it.effect("hides generic Effect.tryPromise text for local CLI probe failures", () =>
Effect.gen(function* () {
runtimeMock.state.runVersionError = new Error("An error occurred in Effect.tryPromise");
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
assert.equal(snapshot.message, "Failed to execute OpenCode CLI health check.");
}),
);
it.effect("refuses to probe when opencode is older than the required minimum", () =>
Effect.gen(function* () {
runtimeMock.state.versionStdout = "opencode 1.4.7\n";
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
assert.equal(snapshot.version, "1.4.7");
assert.ok(snapshot.message?.includes("1.14.19"));
assert.ok(snapshot.message?.toLowerCase().includes("upgrade"));
}),
);
it.effect("refuses to probe when opencode --version output is unparseable", () =>
Effect.gen(function* () {
runtimeMock.state.versionStdout = "garbled binary output\n";
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
assert.equal(snapshot.version, null);
assert.ok(snapshot.message?.includes("1.14.19"));
}),
);
it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () =>
Effect.gen(function* () {
runtimeMock.state.inventory = {
providerList: {
connected: ["openai"],
all: [
{
id: "openai",
name: "OpenAI",
models: {
"gpt-5.4": {
id: "gpt-5.4",
name: "GPT-5.4",
variants: {
none: {},
low: {},
medium: {},
high: {},
xhigh: {},
},
},
},
},
],
default: {},
},
agents: [
{ name: "build", hidden: false, mode: "primary" },
{ name: "plan", hidden: false, mode: "primary" },
],
};
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4");
assert.ok(model);
const variantDescriptor = model.capabilities?.optionDescriptors?.find(
(descriptor) => descriptor.id === "variant" && descriptor.type === "select",
);
assert.ok(variantDescriptor && variantDescriptor.type === "select");
assert.equal(variantDescriptor.options.find((option) => option.isDefault)?.id, "medium");
const agentDescriptor = model.capabilities?.optionDescriptors?.find(
(descriptor) => descriptor.id === "agent" && descriptor.type === "select",
);
assert.ok(agentDescriptor && agentDescriptor.type === "select");
assert.equal(agentDescriptor.options.find((option) => option.isDefault)?.id, "build");
}),
);
});
it.layer(
makeTestLayer({
providers: {
opencode: {
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
},
},
}),
)("OpenCodeProviderLive with configured server URL", (it) => {
it.effect("surfaces a friendly auth error for configured servers", () =>
Effect.gen(function* () {
runtimeMock.state.inventoryError = new Error("401 Unauthorized");
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
assert.equal(
snapshot.message,
"OpenCode server rejected authentication. Check the server URL and password.",
);
}),
);
it.effect("surfaces a friendly connection error for configured servers", () =>
Effect.gen(function* () {
runtimeMock.state.inventoryError = new Error(
"fetch failed: connect ECONNREFUSED 127.0.0.1:9999",
);
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
assert.equal(
snapshot.message,
"Couldn't reach the configured OpenCode server at http://127.0.0.1:9999. Check that the server is running and the URL is correct.",
);
}),
);
});
@@ -0,0 +1,505 @@
import type {
ModelCapabilities,
OpenCodeSettings,
ServerProvider,
ServerProviderModel,
} from "@t3tools/contracts";
import { Cause, Data, Effect, Equal, Layer, Stream } from "effect";
import { createModelCapabilities } from "@t3tools/shared/model";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
buildServerProvider,
nonEmptyTrimmed,
parseGenericCliVersion,
providerModelsFromSettings,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
import {
OpenCodeRuntime,
openCodeRuntimeErrorDetail,
type OpenCodeInventory,
} from "../opencodeRuntime.ts";
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
const PROVIDER = "opencode" as const;
const OPENCODE_PRESENTATION = {
displayName: "OpenCode",
showInteractionModeToggle: false,
} as const;
const MINIMUM_OPENCODE_VERSION = "1.14.19";
class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
readonly cause: unknown;
readonly detail: string;
}> {}
function normalizeProbeMessage(message: string): string | undefined {
const trimmed = message.trim();
if (trimmed.length === 0) {
return undefined;
}
if (
trimmed === "An error occurred in Effect.tryPromise" ||
trimmed === "An error occurred in Effect.try"
) {
return undefined;
}
return trimmed;
}
function normalizedErrorMessage(cause: unknown): string | undefined {
if (cause instanceof OpenCodeProbeError) {
return normalizeProbeMessage(cause.detail);
}
if (!(cause instanceof Error)) {
return undefined;
}
return normalizeProbeMessage(cause.message);
}
function formatOpenCodeProbeError(input: {
readonly cause: unknown;
readonly isExternalServer: boolean;
readonly serverUrl: string;
}): { readonly installed: boolean; readonly message: string } {
const detail = normalizedErrorMessage(input.cause);
const lower = detail?.toLowerCase() ?? "";
if (input.isExternalServer) {
if (
lower.includes("401") ||
lower.includes("403") ||
lower.includes("unauthorized") ||
lower.includes("forbidden")
) {
return {
installed: true,
message: "OpenCode server rejected authentication. Check the server URL and password.",
};
}
if (
lower.includes("econnrefused") ||
lower.includes("enotfound") ||
lower.includes("fetch failed") ||
lower.includes("networkerror") ||
lower.includes("timed out") ||
lower.includes("timeout") ||
lower.includes("socket hang up")
) {
return {
installed: true,
message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,
};
}
return {
installed: true,
message: detail ?? "Failed to connect to the configured OpenCode server.",
};
}
if (lower.includes("enoent") || lower.includes("notfound")) {
return {
installed: false,
message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
};
}
if (lower.includes("quarantine")) {
return {
installed: true,
message:
"macOS is blocking the OpenCode binary (quarantine). Run `xattr -d com.apple.quarantine $(which opencode)` to fix this.",
};
}
if (lower.includes("invalid code signature") || lower.includes("corrupted")) {
return {
installed: true,
message:
"macOS killed the OpenCode process due to an invalid code signature. The binary may be corrupted — try reinstalling OpenCode.",
};
}
return {
installed: true,
message: detail
? `Failed to execute OpenCode CLI health check: ${detail}`
: "Failed to execute OpenCode CLI health check.",
};
}
function titleCaseSlug(value: string): string {
return value
.split(/[-_/]+/)
.filter((segment) => segment.length > 0)
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
.join(" ");
}
function inferDefaultVariant(
providerID: string,
variants: ReadonlyArray<string>,
): string | undefined {
if (variants.length === 1) {
return variants[0];
}
if (providerID === "anthropic" || providerID.startsWith("google")) {
return variants.includes("high") ? "high" : undefined;
}
if (providerID === "openai" || providerID === "opencode") {
return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
}
return undefined;
}
function inferDefaultAgent(agents: ReadonlyArray<Agent>): string | undefined {
return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined;
}
const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
function openCodeCapabilitiesForModel(input: {
readonly providerID: string;
readonly model: ProviderListResponse["all"][number]["models"][string];
readonly agents: ReadonlyArray<Agent>;
}): ModelCapabilities {
const variantValues = Object.keys(input.model.variants ?? {});
const defaultVariant = inferDefaultVariant(input.providerID, variantValues);
const variantOptions = variantValues.map((value) =>
defaultVariant === value
? { id: value, label: titleCaseSlug(value), isDefault: true as const }
: { id: value, label: titleCaseSlug(value) },
);
const primaryAgents = input.agents.filter(
(agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"),
);
const defaultAgent = inferDefaultAgent(primaryAgents);
const agentOptions = primaryAgents.map((agent) =>
defaultAgent === agent.name
? { id: agent.name, label: titleCaseSlug(agent.name), isDefault: true as const }
: { id: agent.name, label: titleCaseSlug(agent.name) },
);
return createModelCapabilities({
optionDescriptors: [
...(variantOptions.length > 0
? [
{
id: "variant",
label: "Variant",
type: "select" as const,
options: variantOptions,
...(defaultVariant ? { currentValue: defaultVariant } : {}),
},
]
: []),
...(agentOptions.length > 0
? [
{
id: "agent",
label: "Agent",
type: "select" as const,
options: agentOptions,
...(defaultAgent ? { currentValue: defaultAgent } : {}),
},
]
: []),
],
});
}
function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerProviderModel> {
const connected = new Set(input.providerList.connected);
const models: Array<ServerProviderModel> = [];
for (const provider of input.providerList.all) {
if (!connected.has(provider.id)) {
continue;
}
for (const model of Object.values(provider.models)) {
const name = nonEmptyTrimmed(model.name);
if (!name) {
continue;
}
const subProvider = nonEmptyTrimmed(provider.name);
models.push({
slug: `${provider.id}/${model.id}`,
name,
...(subProvider ? { subProvider } : {}),
isCustom: false,
capabilities: openCodeCapabilitiesForModel({
providerID: provider.id,
model,
agents: input.agents,
}),
});
}
}
return models.toSorted((left, right) => left.name.localeCompare(right.name));
}
const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): ServerProvider => {
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
[],
PROVIDER,
openCodeSettings.customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
);
if (!openCodeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message:
openCodeSettings.serverUrl.trim().length > 0
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
: "OpenCode is disabled in T3 Code settings.",
},
});
}
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: true,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "OpenCode provider status has not been checked in this session yet.",
},
});
};
export const OpenCodeProviderLive = Layer.effect(
OpenCodeProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const serverConfig = yield* ServerConfig;
const openCodeRuntime = yield* OpenCodeRuntime;
const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (input: {
readonly settings: OpenCodeSettings;
readonly cwd: string;
}): Effect.fn.Return<ServerProvider, never> {
const checkedAt = new Date().toISOString();
const customModels = input.settings.customModels;
const isExternalServer = input.settings.serverUrl.trim().length > 0;
const fallback = (cause: unknown, version: string | null = null) => {
const failure = formatOpenCodeProbeError({
cause,
isExternalServer,
serverUrl: input.settings.serverUrl,
});
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: input.settings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: failure.installed,
version,
status: "error",
auth: { status: "unknown" },
message: failure.message,
},
});
};
if (!input.settings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: isExternalServer
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
: "OpenCode is disabled in T3 Code settings.",
},
});
}
let version: string | null = null;
if (!isExternalServer) {
const versionExit = yield* Effect.exit(
openCodeRuntime
.runOpenCodeCommand({
binaryPath: input.settings.binaryPath,
args: ["--version"],
})
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
),
);
if (versionExit._tag === "Failure") {
return fallback(Cause.squash(versionExit.cause));
}
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
if (!version) {
return fallback(
new Error(
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
),
null,
);
}
if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: input.settings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
},
});
}
}
const inventoryExit = yield* Effect.exit(
Effect.scoped(
Effect.gen(function* () {
const server = yield* openCodeRuntime
.connectToOpenCodeServer({
binaryPath: input.settings.binaryPath,
serverUrl: input.settings.serverUrl,
})
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
return yield* openCodeRuntime
.loadOpenCodeInventory(
openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: input.cwd,
...(isExternalServer && input.settings.serverPassword
? { serverPassword: input.settings.serverPassword }
: {}),
}),
)
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
}),
),
);
if (inventoryExit._tag === "Failure") {
return fallback(Cause.squash(inventoryExit.cause), version);
}
const models = providerModelsFromSettings(
flattenOpenCodeModels(inventoryExit.value),
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
);
const connectedCount = inventoryExit.value.providerList.connected.length;
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: true,
checkedAt,
models,
probe: {
installed: true,
version,
status: connectedCount > 0 ? "ready" : "warning",
auth: {
status: connectedCount > 0 ? "authenticated" : "unknown",
type: "opencode",
},
message:
connectedCount > 0
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
: isExternalServer
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
: "OpenCode is available, but it did not report any connected upstream providers.",
},
});
});
const getProviderSettings = serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.opencode),
);
return yield* makeManagedServerProvider<OpenCodeSettings>({
getSettings: getProviderSettings.pipe(Effect.orDie),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.opencode),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
initialSnapshot: makePendingOpenCodeProvider,
checkProvider: getProviderSettings.pipe(
Effect.flatMap((settings) =>
checkOpenCodeProviderStatus({
settings,
cwd: serverConfig.cwd,
}),
),
),
});
}),
);
@@ -8,6 +8,10 @@ import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
import { ProviderUnsupportedError } from "../Errors.ts";
@@ -47,6 +51,40 @@ const fakeClaudeAdapter: ClaudeAdapterShape = {
streamEvents: Stream.empty,
};
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
provider: "opencode",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
readThread: vi.fn(),
rollbackThread: vi.fn(),
stopAll: vi.fn(),
streamEvents: Stream.empty,
};
const fakeCursorAdapter: CursorAdapterShape = {
provider: "cursor",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
readThread: vi.fn(),
rollbackThread: vi.fn(),
stopAll: vi.fn(),
streamEvents: Stream.empty,
};
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
@@ -54,6 +92,8 @@ const layer = it.layer(
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter),
Layer.succeed(CursorAdapter, fakeCursorAdapter),
),
),
NodeServices.layer,
@@ -66,11 +106,15 @@ layer("ProviderAdapterRegistryLive", (it) => {
const registry = yield* ProviderAdapterRegistry;
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeAgent");
const openCode = yield* registry.getByProvider("opencode");
const cursor = yield* registry.getByProvider("cursor");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
assert.equal(openCode, fakeOpenCodeAdapter);
assert.equal(cursor, fakeCursorAdapter);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex", "claudeAgent"]);
assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]);
}),
);
@@ -17,6 +17,9 @@ import {
} from "../Services/ProviderAdapterRegistry.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import { createBuiltInAdapterList } from "../builtInProviderCatalog.ts";
export interface ProviderAdapterRegistryLiveOptions {
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
@@ -25,10 +28,16 @@ export interface ProviderAdapterRegistryLiveOptions {
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
options?: ProviderAdapterRegistryLiveOptions,
) {
const cursorAdapterOption = yield* Effect.serviceOption(CursorAdapter);
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeAdapter];
: createBuiltInAdapterList({
codex: yield* CodexAdapter,
claudeAgent: yield* ClaudeAdapter,
opencode: yield* OpenCodeAdapter,
...(cursorAdapterOption._tag === "Some" ? { cursor: cursorAdapterOption.value } : {}),
});
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
File diff suppressed because it is too large. Load diff
Loaded 100 of 340 files, more files were not shown because too many files have changed in this diff. Show more