Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex 387a577e3c Fix Windows gh PR title args
Co-authored-by: codex <[email protected]>
2026-04-29 16:37:52 -07: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
Julius Marminge f297e30e4c Clean up invalid pending approval projections (#2106) 2026-04-16 23:26:28 -07:00
Evan YuandJulius Marminge a7a44d0662 Fix Windows PATH hydration and repair (#1729)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-17 06:12:17 +00:00
Jono Kemball d8d329691a Show thread status in command palette (#2107) 2026-04-16 22:21:57 -07:00
Julius Marminge 54179c86b8 Update workflow to use ubuntu-24.04 runner (#2110) 2026-04-16 22:16:13 -07:00
Julius Marminge 8dba2d6484 Adopt Node-native TypeScript for desktop and server (#2098) 2026-04-16 22:14:35 -07:00
Nathan HarmonandJulius Marminge ed6b7fbf27 fix(server): honor gitignored files in workspace search (#2078)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 21:19:14 -07:00
Julius Marminge b991b9b9e6 Revert to Github Runner for Windows (#2103) 2026-04-16 20:35:56 -07:00
Julius Marminge 505db9f696 try out blacksmith for releases (#2101) 2026-04-16 20:12:09 -07:00
t3-code[bot] 2d87574e62 chore(release): prepare v0.0.20 2026-04-17 03:00:57 +00:00
Julius Marminge b2cca674df ci(release): install deps before finalize version bump (#2100) 2026-04-16 19:42:17 -07:00
Julius Marminge 549043863a fix: guard against missing sidebarProjectGroupingOverrides in client settings (#2099) 2026-04-17 02:36:39 +00:00
Julius Marminge b7df3dfca0 [codex] Fix Windows release manifest publishing (#2095) 2026-04-16 17:56:16 -07:00
Evan YuandJulius Marminge 6891c77d3e Build for Windows ARM (#2080)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 17:01:27 -07:00
m9d5m d90e15d1d7 fix(server): extend negative repository identity cache ttl (#2083) 2026-04-16 16:57:39 -07:00
e0117b271a Fix Claude Process leak[MEMORY INTENSIVE], archiving, and stale claude session monitoring. (#2042)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-16 16:30:56 -07:00
188a40c315 feat: configurable project grouping (#2055)
Co-authored-by: tlh38 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-16 16:29:25 -07:00
Utkarsh Patil 7a08fcf2e8 fix(server): drop stale text generation options when resetting text-gen model selection (#2076) 2026-04-16 20:01:35 +00:00
Utkarsh Patil 19d47408a5 fix(web): prevent composer controls overlap on narrow windows (make plan sidebar responsive) (#1198) 2026-04-16 11:13:59 -07:00
Ibrahim ElkamaliandJulius Marminge 3e07f5a6a4 feat: add Claude Opus 4.7 to built-in models (#2072)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 11:11:59 -07:00
Marcus Grando d22c6f5280 fix: prevent user-input activities from leaking into pending approvals projection (#2051) 2026-04-16 05:09:29 +00:00
Marcus Grando 5e13f53571 fix: remove trailing newline from CLAUDE.md symlink (#2052) 2026-04-15 22:05:10 -07:00
f9580ff088 Default nightly desktop builds to the nightly update channel (#2049)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-15 21:31:24 -07:00
AndreiandJulius Marminge 5e1dd56d2c feat: add Launch Args setting for Claude provider (#1971)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 21:26:36 +00:00
legsandJulius Marminge 68061af042 Improve markdown file link UX (#1956)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 14:20:28 -07:00
Guilherme Vieira 28cb9db20b feat(web): add tooltip to composer file mention pill (#1944) 2026-04-15 13:29:13 -07:00
SakethandJulius Marminge 7968f278ee Fix terminal Cmd+Backspace on macOS (#2027)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 06:29:45 +00:00
44afe784a3 Add filesystem browse API and command palette project picker (#2024)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-14 23:26:05 -07:00
Julius Marmingeandcodex 9ff31f8c35 Fix nightly desktop product name (#2025)
Co-authored-by: codex <[email protected]>
2026-04-14 19:12:36 -07:00
409ff90a14 Nightly release channel (#2012)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-14 18:18:37 -07:00
0d280262f6 fix(claude): emit plan events for TodoWrite during input streaming (#1541)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-13 19:35:40 -07:00
Julius MarmingeandCursor Agent c9b07d665d Backfill projected shell summaries and stale approval cleanup (#2004)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-13 18:10:13 -07:00
2e42f3fdf6 Improve shell PATH hydration and fallback detection (#1799)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-13 16:31:43 -07:00
008ac5c3e5 Cache provider status and gate desktop startup (#1962)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-13 15:29:08 -07:00
Julius Marminge 9dcea68bce Refresh git status after branch rename and worktree setup (#2005) 2026-04-13 14:58:03 -07:00
Julius Marminge 5f7ec73a22 Fix new-thread draft reuse for worktree defaults (#2003) 2026-04-13 14:57:46 -07:00
Julius MarmingeandCursor Agent 569fea87a9 Warm sidebar thread detail subscriptions (#2001)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-13 13:55:20 -07:00
Julius Marminge 33dadb5aec Fix thread timeline autoscroll and simplify branch state (#2002) 2026-04-13 13:51:12 -07:00
Ashvin Nihalani d18e43b674 fix: lost provider session recovery (#1938) 2026-04-13 13:34:02 -07:00
Julius Marminge 6f699346e4 Use latest user message time for thread timestamps (#1996) 2026-04-13 13:20:10 -07:00
Julius Marminge f5ecca4480 Clear tracked RPCs on reconnect (#2000) 2026-04-13 20:16:08 +00:00
Utkarsh Patil cadd708646 feat: show full thread title in a tooltip when hovering sidebar thread names (#1994) 2026-04-13 12:26:41 -07:00
Ashvin NihalaniandJulius Marminge 5f7becf386 feat: Add Kiro editor support to open picker (#1974)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-13 19:16:00 +00:00
Ashvin Nihalani 9b29be916b docs: Document environment prep before local development (#1975) 2026-04-13 12:14:27 -07:00
Utkarsh Patil 047a0a697c fix: add pointer cursor to the permissions mode select trigger (#1997) 2026-04-13 12:13:44 -07:00
Julius Marmingeandcodex 77fcad3586 Prevent live thread branches from regressing to temp worktree names (#1995)
Co-authored-by: codex <[email protected]>
2026-04-13 19:04:56 +00:00
Julius Marminge 801b83e937 Allow empty server threads to bootstrap new worktrees (#1936) 2026-04-13 11:52:59 -07:00
Julius Marminge f2205bdc42 Pad composer model picker to prevent ring clipping (#1992) 2026-04-13 17:59:31 +00:00
Barry Michael Doyle 1bf048eb8b fix: avoid copy button overlapping long code blocks (#1985) 2026-04-13 09:59:22 -07:00
f7fa62aaf9 Add shell snapshot queries for orchestration state (#1973)
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-13 08:50:50 -07:00
Guilherme Vieira 57d7746a5d fix(web): replace turn strip overlay gradients with mask-image fade (#1949) 2026-04-13 01:11:34 -07:00
rowalth 850c912556 fix(desktop): increase backend readiness timeout from 10s to 30s (#1979) 2026-04-13 08:10:53 +00:00
Tarasandjulius dff8784aef window controls overlay (windows&linux) (#1969)
Co-authored-by: julius <[email protected]>
2026-04-13 07:21:40 +00:00
Julius MarmingeandCursor Agent 96c9306dbd Migrate chat scrolling and branch lists to LegendList (#1953)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-12 23:23:14 -07:00
Julius Marminge 94d13a2b75 Preserve live stream subscriptions across explicit reconnects (#1972) 2026-04-12 18:22:38 -07:00
7a008461fc fix: Align token usage metrics for both Claude and Codex (#1943)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-04-12 01:03:36 -07:00
Ashvin Nihalani f59ee36bf1 fix(web): allow concurrent browser tests to retry ports (#1951) 2026-04-12 07:46:44 +00:00
Ishan 2fce84a1d4 fix: quote editor launch args on Windows to support paths with spaces (#1805) 2026-04-12 00:41:11 -07:00
Julius Marmingeandcodex f9019cd63f Coalesce status refreshes by remote (#1940)
Co-authored-by: codex <[email protected]>
2026-04-11 18:51:04 -07:00
Adam Mansfield f9372a4c3d chore(desktop): separate dev AppUserModelID on Windows (#1934) 2026-04-12 00:18:59 +00:00
934037cb66 feat(web): add extensible command palette (#1103)
Co-authored-by: Hugo Blom <[email protected]>
Co-authored-by: eggfriedrice <[email protected]>
Co-authored-by: Jono Kemball <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-04-11 11:02:06 -07:00
Ishan 5467d11980 fix(web): prevent number-key shortcuts from hijacking input in focused editor (#1810) 2026-04-10 20:13:58 -07:00
Oliver Sargison 1f4a3f65bf Fix opening urls wrapped across lines in the terminal (#1913) 2026-04-10 19:30:25 -07:00
shivamandJulius Marminge 26cc1fffb3 Add assistant message copy action and harden related test/storage fallbacks (#1211)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-11 02:27:29 +00:00
Mike OlsonandJulius Marminge 97880e8870 fix(web): resolve logical-to-physical key mismatch in project drag reorder (#1904)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-10 19:25:43 -07:00
Julius MarmingeandCursor Agent b80e8476b8 Memoize derived thread reads (#1908)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-10 19:06:10 -07:00
Julius Marminge e0e01b4a54 Handle deleted git directories as non-repositories (#1907) 2026-04-10 18:31:24 -07:00
58e5f714b0 Add provider skill discovery (#1905)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-10 17:19:23 -07:00
Julius Marminge 4ae9de311b Stabilize auth session cookies per server mode (#1898) 2026-04-10 16:33:25 -07:00
shivam 5fa09fa2d9 [codex] fix composer footer compact layout (#1894) 2026-04-10 16:09:27 -07:00
Guilherme Vieira 12c3af7821 feat(desktop): add "Copy Image" to right-click context menu (#1052) 2026-04-10 15:02:07 -07:00
Julius Marminge e2316814da Fix worktree base branch updates for active draft (#1900) 2026-04-10 15:01:17 -07:00
Julius Marminge 678f827f0b Remove Claude subscription-based model adjustment (#1899) 2026-04-10 15:00:47 -07:00
t3-code[bot] a3dadf311e chore(release): prepare v0.0.17 2026-04-10 20:25:34 +00:00
Julius Marmingeandcodex e3004ae806 Harden secret store and resolve catalog overrides (#1891)
Co-authored-by: codex <[email protected]>
2026-04-10 13:09:39 -07:00
Ibrahim Elkamali 9385314d26 Persist changed-files expansion state per thread (#1858) 2026-04-10 10:41:41 -07:00
t3-code[bot] a3f292770e chore(release): prepare v0.0.16 2026-04-10 17:09:07 +00:00
Julius Marminge 2028d57e88 Fix server publish check for bin entrypoint (#1885) 2026-04-10 16:47:35 +00:00
3405a64dd8 bump effect to latest beta (#1866)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-10 01:51:31 -07:00
Julius Marminge 1cba2f64d3 Harden workspace git indexing against repo-configured fsmonitor execution (#1873) 2026-04-10 01:07:05 -07:00
614 changed files with 110417 additions and 19595 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"
},
+7 -4
View File
@@ -9,7 +9,7 @@ on:
jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -71,12 +71,12 @@ jobs:
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
release_smoke:
name: Release Smoke
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -92,5 +92,8 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+252 -47
View File
@@ -1,14 +1,25 @@
name: Release Desktop
name: Release
on:
push:
tags:
- "v*.*.*"
- "!v*-nightly.*"
schedule:
- cron: "0 */3 * * *"
workflow_dispatch:
inputs:
channel:
description: "Release channel"
required: false
default: stable
type: choice
options:
- stable
- nightly
version:
description: "Release version (for example 1.2.3 or v1.2.3)"
required: true
required: false
type: string
permissions:
@@ -16,45 +27,63 @@ 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
runs-on: ubuntu-24.04
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:
release_channel: ${{ steps.release_meta.outputs.release_channel }}
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
release_name: ${{ steps.release_meta.outputs.name }}
short_sha: ${{ steps.release_meta.outputs.short_sha }}
previous_tag: ${{ steps.previous_tag.outputs.previous_tag }}
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
make_latest: ${{ steps.release_meta.outputs.make_latest }}
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
- id: release_meta
name: Resolve release version
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
with:
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -69,6 +98,60 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- id: release_meta
name: Resolve release version
shell: bash
env:
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
DISPATCH_VERSION: ${{ github.event.inputs.version }}
NIGHTLY_DATE: ${{ github.run_started_at }}
NIGHTLY_SHA: ${{ github.sha }}
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
run: |
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
nightly_date="$(date -u -d "$NIGHTLY_DATE" +%Y%m%d)"
node scripts/resolve-nightly-release.ts \
--date "$nightly_date" \
--run-number "$NIGHTLY_RUN_NUMBER" \
--sha "$NIGHTLY_SHA" \
--github-output
echo "release_channel=nightly" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=nightly" >> "$GITHUB_OUTPUT"
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
else
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${DISPATCH_VERSION}"
if [[ -z "$raw" ]]; then
echo "workflow_dispatch stable releases require the version input." >&2
exit 1
fi
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "release_channel=stable" >> "$GITHUB_OUTPUT"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
echo "name=T3 Code v$version" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=latest" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
fi
- name: Lint
run: bun run lint
@@ -78,9 +161,18 @@ jobs:
- name: Test
run: bun run test
- id: previous_tag
name: Resolve previous release tag
run: |
node scripts/resolve-previous-release-tag.ts \
--channel "${{ steps.release_meta.outputs.release_channel }}" \
--current-tag "${{ steps.release_meta.outputs.tag }}" \
--github-output
build:
name: Build ${{ matrix.label }}
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
strategy:
@@ -88,25 +180,30 @@ jobs:
matrix:
include:
- label: macOS arm64
runner: macos-14
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: macos-15-intel
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: ubuntu-24.04
runner: blacksmith-32vcpu-ubuntu-2404
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: windows-2022
runner: blacksmith-32vcpu-windows-2025
platform: win
target: nsis
arch: x64
# - label: Windows arm64
# runner: windows-11-arm
# platform: win
# target: nsis
# arch: arm64
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -130,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:
@@ -206,18 +320,31 @@ jobs:
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/latest*.yml"; do
"release/*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
if [[ -f release-publish/latest-mac.yml ]]; then
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
fi
shopt -s nullglob
for manifest in release-publish/*-mac.yml; do
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
done
fi
# Enable if Windows arm64 builds are enabled.
# Windows updater metadata is channel-specific (for example
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
# release job can merge matching arm64/x64 manifests back into one
# canonical manifest per channel.
# if [[ "${{ matrix.platform }}" == "win" ]]; then
# shopt -s nullglob
# for manifest in release-publish/*.yml; do
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
# done
# fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
@@ -228,7 +355,8 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
runs-on: ubuntu-24.04
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -257,24 +385,41 @@ jobs:
run: bun run build --filter=@t3tools/web --filter=t3
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
release:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
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:
@@ -284,17 +429,72 @@ jobs:
- name: Merge macOS updater manifests
run: |
node scripts/merge-mac-update-manifests.ts \
release-assets/latest-mac.yml \
release-assets/latest-mac-x64.yml
rm -f release-assets/latest-mac-x64.yml
shopt -s nullglob
for x64_manifest in release-assets/*-mac-x64.yml; do
arm64_manifest="${x64_manifest%-x64.yml}.yml"
if [[ -f "$arm64_manifest" ]]; then
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
rm -f "$x64_manifest"
fi
done
# - name: Merge Windows updater manifests
# run: |
# shopt -s nullglob
# found_windows_manifest=false
# for x64_manifest in release-assets/*-win-x64.yml; do
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
# continue
# fi
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
# if [[ ! -f "$arm64_manifest" ]]; then
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
# exit 1
# fi
# found_windows_manifest=true
# node scripts/merge-update-manifests.ts --platform win \
# "$arm64_manifest" \
# "$x64_manifest" \
# "$output_manifest"
# rm -f "$arm64_manifest" "$x64_manifest"
# done
# if [[ "$found_windows_manifest" != true ]]; then
# echo "No Windows updater manifests found to merge." >&2
# exit 1
# fi
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: T3 Code v${{ needs.preflight.outputs.version }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
previous_tag: ${{ needs.preflight.outputs.previous_tag }}
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
files: |
release-assets/*.dmg
release-assets/*.zip
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
@@ -304,13 +504,15 @@ jobs:
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/latest*.yml
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
finalize:
name: Finalize release
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
needs: [preflight, release]
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- id: app_token
@@ -349,6 +551,9 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- id: update_versions
name: Update version strings
env:
+11 -2
View File
@@ -10,7 +10,16 @@
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts"
"apps/web/src/lib/vendor/qrcodegen.ts",
"*.icon/**"
],
"sortPackageJson": {}
"sortPackageJson": {},
"overrides": [
{
"files": [".devcontainer/devcontainer.json"],
"options": {
"trailingComma": "none"
}
}
]
}
+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"
}
+2
View File
@@ -23,6 +23,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
@@ -50,6 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `commandPalette.toggle`: open or close the global command palette
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
- `editor.openFavorite`: open current project/worktree in the last-used editor
+8
View File
@@ -49,6 +49,14 @@ Observability guide: [docs/observability.md](./docs/observability.md)
## If you REALLY want to contribute still.... read this first
Before local development, prepare the environment and install dependencies:
```bash
# Optional: only needed if you use mise for dev tool management.
mise install
bun install .
```
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
+6 -4
View File
@@ -1,14 +1,15 @@
{
"name": "@t3tools/desktop",
"version": "0.0.15",
"version": "0.0.20",
"private": true,
"main": "dist-electron/main.js",
"type": "module",
"main": "dist-electron/main.cjs",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"dev:electron": "node scripts/dev-electron.mjs",
"build": "tsdown",
"start": "bun run scripts/start-electron.mjs",
"start": "node scripts/start-electron.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
@@ -22,6 +23,7 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
+4 -4
View File
@@ -17,12 +17,12 @@ if (!Number.isInteger(port) || port <= 0) {
}
const requiredFiles = [
"dist-electron/main.js",
"dist-electron/preload.js",
"dist-electron/main.cjs",
"dist-electron/preload.cjs",
"../server/dist/bin.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
@@ -69,7 +69,7 @@ function startApp() {
const app = spawn(
resolveElectronPath(),
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
{
cwd: desktopDir,
env: childEnv,
+74 -38
View File
@@ -6,8 +6,8 @@ import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
statSync,
writeFileSync,
@@ -19,10 +19,13 @@ import { fileURLToPath } from "node:url";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LAUNCHER_VERSION = 1;
const LAUNCHER_VERSION = 2;
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
const repoRoot = resolve(desktopDir, "..", "..");
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
@@ -43,6 +46,68 @@ function setPlistString(plistPath, key, value) {
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
}
function runChecked(command, args) {
const result = spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
return;
}
const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
if (!existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
}
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
return generatedIconPath;
}
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = join(iconsetRoot, "icon.iconset");
mkdirSync(iconsetDir, { recursive: true });
try {
for (const size of [16, 32, 128, 256, 512]) {
runChecked("sips", [
"-z",
String(size),
String(size),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}.png`),
]);
const retinaSize = size * 2;
runChecked("sips", [
"-z",
String(retinaSize),
String(retinaSize),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
}
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
return generatedIconPath;
} catch (error) {
console.warn(
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
error,
);
return defaultIconPath;
} finally {
rmSync(iconsetRoot, { recursive: true, force: true });
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
@@ -55,40 +120,6 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
if (!existsSync(frameworksDir)) {
return;
}
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
continue;
}
if (!entry.name.startsWith("Electron Helper")) {
continue;
}
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
if (!existsSync(helperPlistPath)) {
continue;
}
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
const helperName = suffix
? `${APP_DISPLAY_NAME} Helper ${suffix}`
: `${APP_DISPLAY_NAME} Helper`;
const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");
const helperBundleId = helperIdSuffix
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
: `${APP_BUNDLE_ID}.helper`;
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
setPlistString(helperPlistPath, "CFBundleName", helperName);
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
}
}
function readJson(path) {
try {
return JSON.parse(readFileSync(path, "utf8"));
@@ -102,7 +133,7 @@ function buildMacLauncher(electronBinaryPath) {
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = join(desktopDir, "resources", "icon.icns");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
@@ -126,7 +157,6 @@ function buildMacLauncher(electronBinaryPath) {
rmSync(targetAppBundlePath, { recursive: true, force: true });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
return targetBinaryPath;
@@ -140,5 +170,11 @@ export function resolveElectronPath() {
return electronBinaryPath;
}
// Dev launches do not need a renamed app bundle badly enough to risk breaking
// Electron helper resource lookup on macOS.
if (isDevelopment) {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.js");
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
console.log("\nLaunching Electron smoke test...");
+1 -1
View File
@@ -5,7 +5,7 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding.ts";
describe("resolveDesktopAppStageLabel", () => {
it("uses Dev in desktop development", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: true,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toBe("Dev");
});
it("uses Nightly for packaged nightly builds", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: false,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toBe("Nightly");
});
it("uses Alpha for packaged stable builds", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: false,
appVersion: "0.0.17",
}),
).toBe("Alpha");
});
});
describe("resolveDesktopAppBranding", () => {
it("returns a complete desktop branding payload", () => {
expect(
resolveDesktopAppBranding({
isDevelopment: false,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toEqual({
baseName: "T3 Code",
stageLabel: "Nightly",
displayName: "T3 Code (Nightly)",
});
});
});
+28
View File
@@ -0,0 +1,28 @@
import type { DesktopAppBranding, DesktopAppStageLabel } from "@t3tools/contracts";
import { isNightlyDesktopVersion } from "./updateChannels.ts";
const APP_BASE_NAME = "T3 Code";
export function resolveDesktopAppStageLabel(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppStageLabel {
if (input.isDevelopment) {
return "Dev";
}
return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Alpha";
}
export function resolveDesktopAppBranding(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppBranding {
const stageLabel = resolveDesktopAppStageLabel(input);
return {
baseName: APP_BASE_NAME,
stageLabel,
displayName: `${APP_BASE_NAME} (${stageLabel})`,
};
}
+55 -2
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { resolveDesktopBackendPort } from "./backendPort";
import { resolveDesktopBackendPort } from "./backendPort.ts";
describe("resolveDesktopBackendPort", () => {
it("returns the starting port when it is available", async () => {
@@ -36,6 +36,57 @@ describe("resolveDesktopBackendPort", () => {
]);
});
it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
const canListenOnHost = vi.fn(async (port: number, host: string) => {
if (port === 3773 && host === "127.0.0.1") return true;
if (port === 3773 && host === "0.0.0.0") return false;
return port === 3774;
});
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
requiredHosts: ["0.0.0.0"],
startPort: 3773,
canListenOnHost,
}),
).resolves.toBe(3774);
expect(canListenOnHost.mock.calls).toEqual([
[3773, "127.0.0.1"],
[3773, "0.0.0.0"],
[3774, "127.0.0.1"],
[3774, "0.0.0.0"],
]);
});
it("checks overlapping hosts sequentially to avoid self-interference", async () => {
let inFlightCount = 0;
const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
inFlightCount += 1;
const overlapped = inFlightCount > 1;
await Promise.resolve();
inFlightCount -= 1;
return !overlapped;
});
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
requiredHosts: ["0.0.0.0", "::"],
startPort: 3773,
maxPort: 3773,
canListenOnHost,
}),
).resolves.toBe(3773);
expect(canListenOnHost.mock.calls).toEqual([
[3773, "127.0.0.1"],
[3773, "0.0.0.0"],
[3773, "::"],
]);
});
it("fails when the scan range is exhausted", async () => {
const canListenOnHost = vi.fn(async () => false);
@@ -46,7 +97,9 @@ describe("resolveDesktopBackendPort", () => {
maxPort: 65535,
canListenOnHost,
}),
).rejects.toThrow("No desktop backend port is available on 127.0.0.1 between 65534 and 65535");
).rejects.toThrow(
"No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
);
expect(canListenOnHost.mock.calls).toEqual([
[65534, "127.0.0.1"],
+32 -2
View File
@@ -8,6 +8,7 @@ export interface ResolveDesktopBackendPortOptions {
readonly host: string;
readonly startPort?: number;
readonly maxPort?: number;
readonly requiredHosts?: ReadonlyArray<string>;
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
}
@@ -21,10 +22,37 @@ const defaultCanListenOnHost = async (port: number, host: string): Promise<boole
const isValidPort = (port: number): boolean =>
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
const normalizeHosts = (
host: string,
requiredHosts: ReadonlyArray<string>,
): ReadonlyArray<string> =>
Array.from(
new Set(
[host, ...requiredHosts]
.map((candidate) => candidate.trim())
.filter((candidate) => candidate.length > 0),
),
);
async function canListenOnAllHosts(
port: number,
hosts: ReadonlyArray<string>,
canListenOnHost: (port: number, host: string) => Promise<boolean>,
): Promise<boolean> {
for (const candidateHost of hosts) {
if (!(await canListenOnHost(port, candidateHost))) {
return false;
}
}
return true;
}
export async function resolveDesktopBackendPort({
host,
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
maxPort = MAX_TCP_PORT,
requiredHosts = [],
canListenOnHost = defaultCanListenOnHost,
}: ResolveDesktopBackendPortOptions): Promise<number> {
if (!isValidPort(startPort)) {
@@ -39,15 +67,17 @@ export async function resolveDesktopBackendPort({
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
}
const hostsToCheck = normalizeHosts(host, requiredHosts);
// Keep desktop startup predictable across app restarts by probing upward from
// the same preferred port instead of picking a fresh ephemeral port.
for (let port = startPort; port <= maxPort; port += 1) {
if (await canListenOnHost(port, host)) {
if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) {
return port;
}
}
throw new Error(
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
`No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`,
);
}
+33 -2
View File
@@ -4,10 +4,10 @@ import {
BackendReadinessAbortedError,
isBackendReadinessAborted,
waitForHttpReady,
} from "./backendReadiness";
} from "./backendReadiness.ts";
describe("waitForHttpReady", () => {
it("returns once the backend reports a successful session endpoint", async () => {
it("returns once the backend serves the requested readiness path", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response(null, { status: 503 }))
@@ -20,6 +20,11 @@ describe("waitForHttpReady", () => {
});
expect(fetchImpl).toHaveBeenCalledTimes(2);
expect(fetchImpl).toHaveBeenNthCalledWith(
1,
"http://127.0.0.1:3773/",
expect.objectContaining({ redirect: "manual" }),
);
});
it("retries after a readiness request stalls past the per-request timeout", async () => {
@@ -80,4 +85,30 @@ describe("waitForHttpReady", () => {
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
});
it("supports custom readiness predicates", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response(null, { status: 200 }))
.mockResolvedValueOnce(new Response(null, { status: 204 }));
await waitForHttpReady("http://127.0.0.1:3773", {
fetchImpl,
timeoutMs: 1_000,
intervalMs: 0,
path: "/api/healthz",
isReady: (response) => response.status === 204,
});
expect(fetchImpl).toHaveBeenNthCalledWith(
1,
"http://127.0.0.1:3773/api/healthz",
expect.objectContaining({ redirect: "manual" }),
);
expect(fetchImpl).toHaveBeenNthCalledWith(
2,
"http://127.0.0.1:3773/api/healthz",
expect.objectContaining({ redirect: "manual" }),
);
});
});
+7 -3
View File
@@ -4,9 +4,11 @@ export interface WaitForHttpReadyOptions {
readonly requestTimeoutMs?: number;
readonly fetchImpl?: typeof fetch;
readonly signal?: AbortSignal;
readonly path?: string;
readonly isReady?: (response: Response) => boolean;
}
const DEFAULT_TIMEOUT_MS = 10_000;
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_INTERVAL_MS = 100;
const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
@@ -57,6 +59,8 @@ export async function waitForHttpReady(
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const readinessPath = options?.path ?? "/";
const isReady = options?.isReady ?? ((response: Response) => response.ok);
const deadline = Date.now() + timeoutMs;
for (;;) {
@@ -74,11 +78,11 @@ export async function waitForHttpReady(
signal?.addEventListener("abort", abortRequest, { once: true });
try {
const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
const response = await fetchImpl(new URL(readinessPath, baseUrl).toString(), {
redirect: "manual",
signal: requestController.signal,
});
if (response.ok) {
if (isReady(response)) {
return;
}
} catch (error) {
@@ -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);
},
);
});
}
+7 -2
View File
@@ -18,7 +18,7 @@ import {
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
type DesktopSecretStorage,
} from "./clientPersistence";
} from "./clientPersistence.ts";
const tempDirectories: string[] = [];
@@ -52,13 +52,18 @@ const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
favorites: [],
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
},
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
};
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
environmentId: EnvironmentId.makeUnsafe("environment-1"),
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
+15 -2
View File
@@ -1,8 +1,13 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import {
ClientSettingsSchema,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { Predicate } from "effect";
import * as Schema from "effect/Schema";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
@@ -83,7 +88,15 @@ function toPersistedSavedEnvironmentRecord(
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
if (!raw) {
return null;
}
try {
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
} catch {
return null;
}
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
+1 -1
View File
@@ -11,7 +11,7 @@ vi.mock("electron", () => ({
},
}));
import { showDesktopConfirmDialog } from "./confirmDialog";
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
describe("showDesktopConfirmDialog", () => {
beforeEach(() => {
+87 -4
View File
@@ -7,9 +7,11 @@ import { afterEach, describe, expect, it } from "vitest";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
resolveDefaultDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings";
} from "./desktopSettings.ts";
const tempDirectories: string[] = [];
@@ -27,7 +29,15 @@ function makeSettingsPath() {
describe("desktopSettings", () => {
it("returns defaults when no settings file exists", () => {
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
expect(readDesktopSettings(makeSettingsPath(), "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("defaults packaged nightly builds to the nightly update channel", () => {
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("persists and reloads the configured server exposure mode", () => {
@@ -35,10 +45,14 @@ describe("desktopSettings", () => {
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath)).toEqual({
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
@@ -47,11 +61,32 @@ describe("desktopSettings", () => {
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
"network-accessible",
),
).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("persists the requested nightly update channel", () => {
expect(
setDesktopUpdateChannelPreference(
{
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
"nightly",
),
).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
});
});
@@ -59,6 +94,54 @@ describe("desktopSettings", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, "{not-json", "utf8");
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("falls back to the nightly channel for legacy nightly settings without an update track", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, JSON.stringify({ serverExposureMode: "local-only" }), "utf8");
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("migrates legacy implicit stable settings to nightly when running a nightly build", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
serverExposureMode: "local-only",
updateChannel: "latest",
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("preserves an explicit stable choice on nightly builds", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
});
+45 -4
View File
@@ -1,15 +1,28 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
}
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
};
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
return {
...DEFAULT_DESKTOP_SETTINGS,
updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
};
}
export function setDesktopServerExposurePreference(
settings: DesktopSettings,
requestedMode: DesktopServerExposureMode,
@@ -22,23 +35,51 @@ export function setDesktopServerExposurePreference(
};
}
export function readDesktopSettings(settingsPath: string): DesktopSettings {
export function setDesktopUpdateChannelPreference(
settings: DesktopSettings,
requestedChannel: DesktopUpdateChannel,
): DesktopSettings {
return {
...settings,
updateChannel: requestedChannel,
updateChannelConfiguredByUser: true,
};
}
export function readDesktopSettings(settingsPath: string, appVersion: string): DesktopSettings {
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
try {
if (!FS.existsSync(settingsPath)) {
return DEFAULT_DESKTOP_SETTINGS;
return defaultSettings;
}
const raw = FS.readFileSync(settingsPath, "utf8");
const parsed = JSON.parse(raw) as {
readonly serverExposureMode?: unknown;
readonly updateChannel?: unknown;
readonly updateChannelConfiguredByUser?: unknown;
};
const parsedUpdateChannel =
parsed.updateChannel === "nightly" || parsed.updateChannel === "latest"
? parsed.updateChannel
: null;
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
const updateChannelConfiguredByUser =
parsed.updateChannelConfiguredByUser === true ||
(isLegacySettings && parsedUpdateChannel === "nightly");
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
updateChannel:
updateChannelConfiguredByUser && parsedUpdateChannel !== null
? parsedUpdateChannel
: defaultSettings.updateChannel,
updateChannelConfiguredByUser,
};
} catch {
return DEFAULT_DESKTOP_SETTINGS;
return defaultSettings;
}
}
+372 -97
View File
@@ -7,6 +7,7 @@ import * as Path from "node:path";
import {
app,
BrowserWindow,
type BrowserWindowConstructorOptions,
clipboard,
dialog,
ipcMain,
@@ -17,12 +18,14 @@ import {
safeStorage,
shell,
} from "electron";
import type { MenuItemConstructorOptions } from "electron";
import type { MenuItemConstructorOptions, OpenDialogOptions } from "electron";
import type {
ClientSettings,
DesktopTheme,
DesktopAppBranding,
DesktopServerExposureMode,
DesktopServerExposureState,
DesktopUpdateChannel,
PersistedSavedEnvironmentRecord,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
@@ -33,13 +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 { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings";
} from "./desktopSettings.ts";
import {
readClientSettings,
readSavedEnvironmentRegistry,
@@ -48,12 +52,15 @@ import {
writeClientSettings,
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
} from "./clientPersistence";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { resolveDesktopServerExposure } from "./serverExposure";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
} from "./clientPersistence.ts";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
import { resolveDesktopServerExposure } from "./serverExposure.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";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
@@ -65,8 +72,10 @@ import {
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
} from "./updateMachine.ts";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
import { resolveDesktopAppBranding } from "./appBranding.ts";
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
syncShellEnvironment();
@@ -78,9 +87,11 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -99,8 +110,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);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
isDevelopment,
appVersion: app.getVersion(),
});
const APP_DISPLAY_NAME = desktopAppBranding.displayName;
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
@@ -114,9 +129,72 @@ const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
const DESKTOP_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
function resolvePickFolderDefaultPath(rawOptions: unknown): string | undefined {
if (typeof rawOptions !== "object" || rawOptions === null) {
return undefined;
}
const { initialPath } = rawOptions as { initialPath?: unknown };
if (typeof initialPath !== "string") {
return undefined;
}
const trimmedPath = initialPath.trim();
if (trimmedPath.length === 0) {
return undefined;
}
if (trimmedPath === "~") {
return OS.homedir();
}
if (trimmedPath.startsWith("~/") || trimmedPath.startsWith("~\\")) {
return Path.join(OS.homedir(), trimmedPath.slice(2));
}
return Path.resolve(trimmedPath);
}
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
for (const sourceItem of source) {
if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
destructive: sourceItem.destructive === true,
disabled: sourceItem.disabled === true,
};
if (sourceItem.children) {
const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
if (normalizedChildren.length === 0) {
continue;
}
normalizedItem.children = normalizedChildren;
}
normalizedItems.push(normalizedItem);
}
return normalizedItems;
}
type WindowTitleBarOptions = Pick<
BrowserWindowConstructorOptions,
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
>;
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
type LinuxDesktopNamedApp = Electron.App & {
@@ -133,6 +211,8 @@ let backendWsUrl = "";
let backendEndpointUrl: string | null = null;
let backendAdvertisedHost: string | null = null;
let backendReadinessAbortController: AbortController | null = null;
let backendInitialWindowOpenInFlight: Promise<void> | null = null;
let backendListeningDetector: ServerListeningDetector | null = null;
let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
@@ -142,7 +222,7 @@ let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH, app.getVersion());
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
@@ -153,7 +233,11 @@ const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
createInitialDesktopUpdateState(
app.getVersion(),
desktopRuntimeInfo,
desktopSettings.updateChannel,
);
function logTimestamp(): string {
return new Date().toISOString();
@@ -351,13 +435,17 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
return null;
}
async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
async function waitForBackendHttpReady(
baseUrl: string,
options?: Parameters<typeof waitForHttpReady>[1],
): Promise<void> {
cancelBackendReadinessWait();
const controller = new AbortController();
backendReadinessAbortController = controller;
try {
await waitForHttpReady(baseUrl, {
...options,
signal: controller.signal,
});
} finally {
@@ -372,6 +460,50 @@ function cancelBackendReadinessWait(): void {
backendReadinessAbortController = null;
}
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
return await waitForBackendStartupReady({
listeningPromise: backendListeningDetector?.promise ?? null,
waitForHttpReady: () =>
waitForBackendHttpReady(baseUrl, {
timeoutMs: 60_000,
}),
cancelHttpWait: cancelBackendReadinessWait,
});
}
function ensureInitialBackendWindowOpen(): void {
const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0] ?? null;
if (isDevelopment || existingWindow !== null || backendInitialWindowOpenInFlight !== null) {
return;
}
const nextOpen = waitForBackendWindowReady(backendHttpUrl)
.then((source) => {
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
if (mainWindow ?? BrowserWindow.getAllWindows()[0]) {
return;
}
mainWindow = createWindow();
writeDesktopLogHeader("bootstrap main window created");
})
.catch((error) => {
if (isBackendReadinessAborted(error)) {
return;
}
writeDesktopLogHeader(
`bootstrap backend readiness warning message=${formatErrorMessage(error)}`,
);
console.warn("[desktop] backend readiness check timed out during packaged bootstrap", error);
})
.finally(() => {
if (backendInitialWindowOpenInFlight === nextOpen) {
backendInitialWindowOpenInFlight = null;
}
});
backendInitialWindowOpenInFlight = nextOpen;
}
function writeDesktopStreamChunk(
streamName: "stdout" | "stderr",
chunk: unknown,
@@ -449,14 +581,16 @@ function initializePackagedLogging(): void {
}
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
if (!app.isPackaged || backendLogSink === null) return;
const writeChunk = (chunk: unknown): void => {
if (!backendLogSink) return;
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
backendLogSink.write(buffer);
const attachStream = (stream: NodeJS.ReadableStream | null | undefined): void => {
stream?.on("data", (chunk: unknown) => {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
backendLogSink?.write(buffer);
backendListeningDetector?.push(buffer);
});
};
child.stdout?.on("data", writeChunk);
child.stderr?.on("data", writeChunk);
attachStream(child.stdout);
attachStream(child.stderr);
}
initializePackagedLogging();
@@ -873,6 +1007,18 @@ function resolveResourcePath(fileName: string): string | null {
}
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
if (isDevelopment && process.platform === "darwin" && ext === "png") {
const developmentDockIconPath = Path.join(
ROOT_DIR,
"assets",
"dev",
"blueprint-macos-1024.png",
);
if (FS.existsSync(developmentDockIconPath)) {
return developmentDockIconPath;
}
}
return resolveResourcePath(`icon.${ext}`);
}
@@ -972,6 +1118,26 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
emitUpdateState();
}
function createBaseUpdateState(
channel: DesktopUpdateChannel,
enabled: boolean,
): DesktopUpdateState {
return {
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo, channel),
enabled,
status: enabled ? "idle" : "disabled",
};
}
function applyAutoUpdaterChannel(channel: DesktopUpdateChannel): void {
autoUpdater.channel = channel;
autoUpdater.allowPrerelease = channel === "nightly";
autoUpdater.allowDowngrade = channel === "nightly";
console.info(
`[desktop-updater] Using update channel '${channel}' (allowPrerelease=${channel === "nightly"}, allowDowngrade=${channel === "nightly"}).`,
);
}
function shouldEnableAutoUpdates(): boolean {
const hasUpdateFeedConfig =
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
@@ -1091,11 +1257,7 @@ function configureAutoUpdater(): void {
}
const enabled = shouldEnableAutoUpdates();
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
setUpdateState(createBaseUpdateState(desktopSettings.updateChannel, enabled));
if (!enabled) {
return;
}
@@ -1103,10 +1265,7 @@ function configureAutoUpdater(): void {
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
// Keep alpha branding, but force all installs onto the stable update track.
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
autoUpdater.allowDowngrade = false;
applyAutoUpdaterChannel(desktopSettings.updateChannel);
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
let lastLoggedDownloadMilestone = -1;
@@ -1120,6 +1279,15 @@ function configureAutoUpdater(): void {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
if (!doesVersionMatchDesktopUpdateChannel(info.version, updateState.channel)) {
console.info(
`[desktop-updater] Ignoring ${info.version} because it does not match the selected '${updateState.channel}' channel.`,
);
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
lastLoggedDownloadMilestone = -1;
return;
}
setUpdateState(
reduceDesktopUpdateStateOnUpdateAvailable(
updateState,
@@ -1211,7 +1379,7 @@ function startBackend(): void {
return;
}
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
const captureBackendLogs = !isDevelopment;
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
cwd: resolveBackendCwd(),
// In Electron main, process.execPath points to the Electron binary.
@@ -1248,6 +1416,8 @@ function startBackend(): void {
scheduleBackendRestart("missing desktop bootstrap pipe");
return;
}
const listeningDetector = new ServerListeningDetector();
backendListeningDetector = listeningDetector;
backendProcess = child;
let backendSessionClosed = false;
const closeBackendSession = (details: string) => {
@@ -1266,6 +1436,10 @@ function startBackend(): void {
});
child.on("error", (error) => {
if (backendListeningDetector === listeningDetector) {
listeningDetector.fail(error);
backendListeningDetector = null;
}
const wasExpected = expectedBackendExitChildren.has(child);
if (backendProcess === child) {
backendProcess = null;
@@ -1278,6 +1452,14 @@ function startBackend(): void {
});
child.on("exit", (code, signal) => {
if (backendListeningDetector === listeningDetector) {
listeningDetector.fail(
new Error(
`backend exited before logging readiness (code=${code ?? "null"} signal=${signal ?? "null"})`,
),
);
backendListeningDetector = null;
}
const wasExpected = expectedBackendExitChildren.has(child);
if (backendProcess === child) {
backendProcess = null;
@@ -1289,10 +1471,13 @@ function startBackend(): void {
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
scheduleBackendRestart(reason);
});
ensureInitialBackendWindowOpen();
}
function stopBackend(): void {
cancelBackendReadinessWait();
backendListeningDetector = null;
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
@@ -1367,6 +1552,11 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
}
function registerIpcHandlers(): void {
ipcMain.removeAllListeners(GET_APP_BRANDING_CHANNEL);
ipcMain.on(GET_APP_BRANDING_CHANNEL, (event) => {
event.returnValue = desktopAppBranding;
});
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
event.returnValue = {
@@ -1480,15 +1670,16 @@ function registerIpcHandlers(): void {
});
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
const defaultPath = resolvePickFolderDefaultPath(rawOptions);
const openDialogOptions: OpenDialogOptions = {
properties: ["openDirectory", "createDirectory"],
...(defaultPath ? { defaultPath } : {}),
};
const result = owner
? await dialog.showOpenDialog(owner, {
properties: ["openDirectory", "createDirectory"],
})
: await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
});
? await dialog.showOpenDialog(owner, openDialogOptions)
: await dialog.showOpenDialog(openDialogOptions);
if (result.canceled) return null;
return result.filePaths[0] ?? null;
});
@@ -1517,14 +1708,7 @@ function registerIpcHandlers(): void {
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
const normalizedItems = items
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
.map((item) => ({
id: item.id,
label: item.label,
destructive: item.destructive === true,
disabled: item.disabled === true,
}));
const normalizedItems = normalizeContextMenuItems(items);
if (normalizedItems.length === 0) {
return null;
}
@@ -1545,28 +1729,37 @@ function registerIpcHandlers(): void {
if (!window) return null;
return new Promise<string | null>((resolve) => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of normalizedItems) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
click: () => resolve(item.id),
};
if (item.destructive) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
const buildTemplate = (
entries: readonly ContextMenuItem[],
): MenuItemConstructorOptions[] => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children);
} else {
itemOption.click = () => resolve(item.id);
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
}
}
template.push(itemOption);
}
template.push(itemOption);
}
return template;
};
const menu = Menu.buildFromTemplate(template);
const menu = Menu.buildFromTemplate(buildTemplate(normalizedItems));
menu.popup({
window,
...popupPosition,
@@ -1594,6 +1787,43 @@ function registerIpcHandlers(): void {
ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
ipcMain.removeHandler(UPDATE_SET_CHANNEL_CHANNEL);
ipcMain.handle(UPDATE_SET_CHANNEL_CHANNEL, async (_event, rawChannel: unknown) => {
if (rawChannel !== "latest" && rawChannel !== "nightly") {
throw new Error("Invalid desktop update channel input.");
}
if (updateCheckInFlight || updateDownloadInFlight || updateInstallInFlight) {
throw new Error("Cannot change update tracks while an update action is in progress.");
}
const nextChannel = rawChannel as DesktopUpdateChannel;
desktopSettings = setDesktopUpdateChannelPreference(desktopSettings, nextChannel);
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
if (nextChannel === updateState.channel) {
return updateState;
}
const enabled = shouldEnableAutoUpdates();
setUpdateState(createBaseUpdateState(nextChannel, enabled));
if (!enabled || !updaterConfigured) {
return updateState;
}
applyAutoUpdaterChannel(nextChannel);
const allowDowngrade = autoUpdater.allowDowngrade;
// An explicit channel switch should allow the immediate nightly->stable rollback path.
autoUpdater.allowDowngrade = true;
try {
await checkForUpdates("channel-change");
} finally {
autoUpdater.allowDowngrade = allowDowngrade;
}
return updateState;
});
ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
const result = await downloadAvailableUpdate();
@@ -1648,21 +1878,60 @@ function getInitialWindowBackgroundColor(): string {
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
}
function getWindowTitleBarOptions(): WindowTitleBarOptions {
if (process.platform === "darwin") {
return {
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 16, y: 18 },
};
}
return {
titleBarStyle: "hidden",
titleBarOverlay: {
color: TITLEBAR_COLOR,
height: TITLEBAR_HEIGHT,
symbolColor: nativeTheme.shouldUseDarkColors
? TITLEBAR_DARK_SYMBOL_COLOR
: TITLEBAR_LIGHT_SYMBOL_COLOR,
},
};
}
function syncWindowAppearance(window: BrowserWindow): void {
if (window.isDestroyed()) {
return;
}
window.setBackgroundColor(getInitialWindowBackgroundColor());
const { titleBarOverlay } = getWindowTitleBarOptions();
if (typeof titleBarOverlay === "object") {
window.setTitleBarOverlay(titleBarOverlay);
}
}
function syncAllWindowAppearance(): void {
for (const window of BrowserWindow.getAllWindows()) {
syncWindowAppearance(window);
}
}
nativeTheme.on("updated", syncAllWindowAppearance);
function createWindow(): BrowserWindow {
const window = new BrowserWindow({
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: isDevelopment,
show: false,
autoHideMenuBar: true,
backgroundColor: getInitialWindowBackgroundColor(),
...getIconOption(),
title: APP_DISPLAY_NAME,
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 16, y: 18 },
...getWindowTitleBarOptions(),
webPreferences: {
preload: Path.join(__dirname, "preload.js"),
preload: Path.join(__dirname, "preload.cjs"),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
@@ -1695,6 +1964,14 @@ function createWindow(): BrowserWindow {
);
}
if (params.mediaType === "image") {
menuTemplate.push({
label: "Copy Image",
click: () => window.webContents.copyImageAt(params.x, params.y),
});
menuTemplate.push({ type: "separator" });
}
menuTemplate.push(
{ role: "cut", enabled: params.editFlags.canCut },
{ role: "copy", enabled: params.editFlags.canCopy },
@@ -1721,20 +1998,24 @@ function createWindow(): BrowserWindow {
window.setTitle(APP_DISPLAY_NAME);
emitUpdateState();
});
if (!isDevelopment) {
window.once("ready-to-show", () => {
revealWindow(window);
});
// 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());
window.webContents.openDevTools({ mode: "detach" });
setImmediate(() => {
revealWindow(window);
});
} else {
void window.loadURL(resolveDesktopWindowUrl());
void window.loadURL(backendHttpUrl);
}
window.on("closed", () => {
@@ -1746,14 +2027,6 @@ function createWindow(): BrowserWindow {
return window;
}
function resolveDesktopWindowUrl(): string {
if (backendHttpUrl) {
return backendHttpUrl;
}
return `${DESKTOP_SCHEME}://app`;
}
// Override Electron's userData path before the `ready` event so that
// Chromium session data uses a filesystem-friendly directory name.
// Must be called synchronously at the top level — before `app.whenReady()`.
@@ -1773,6 +2046,7 @@ async function bootstrap(): Promise<void> {
(await resolveDesktopBackendPort({
host: DESKTOP_LOOPBACK_HOST,
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
requiredHosts: DESKTOP_REQUIRED_PORT_PROBE_HOSTS,
}));
writeDesktopLogHeader(
configuredBackendPort === undefined
@@ -1810,9 +2084,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)) {
@@ -1826,10 +2100,7 @@ async function bootstrap(): Promise<void> {
return;
}
await waitForBackendHttpReady(backendHttpUrl);
writeDesktopLogHeader("bootstrap backend ready");
mainWindow = createWindow();
writeDesktopLogHeader("bootstrap main window created");
ensureInitialBackendWindowOpen();
}
app.on("before-quit", () => {
@@ -1863,7 +2134,11 @@ app
revealWindow(existingWindow);
return;
}
mainWindow = createWindow();
if (isDevelopment) {
mainWindow = createWindow();
return;
}
ensureInitialBackendWindowOpen();
});
})
.catch((error) => {
+11 -1
View File
@@ -9,9 +9,11 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -24,6 +26,13 @@ const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
const result = ipcRenderer.sendSync(GET_APP_BRANDING_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
@@ -44,7 +53,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
@@ -61,6 +70,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) => ipcRenderer.invoke(UPDATE_SET_CHANNEL_CHANNEL, channel),
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
describe("resolveDesktopRuntimeInfo", () => {
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
describe("resolveLanAdvertisedHost", () => {
it("prefers an explicit host override", () => {
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { ServerListeningDetector } from "./serverListeningDetector.ts";
describe("ServerListeningDetector", () => {
it("resolves when the server logs the listening line", async () => {
const detector = new ServerListeningDetector();
detector.push("[01:23:30.571] INFO (#148): Listening on http://0.0.0.0:7011\n");
await expect(detector.promise).resolves.toBeUndefined();
});
it("resolves when the listening line arrives across multiple chunks", async () => {
const detector = new ServerListeningDetector();
detector.push("[01:23:30.571] INFO (#148): Listen");
detector.push("ing on http://0.0.0.0:7011\n");
await expect(detector.promise).resolves.toBeUndefined();
});
it("rejects when the server exits before logging readiness", async () => {
const detector = new ServerListeningDetector();
const error = new Error("server exited");
detector.fail(error);
await expect(detector.promise).rejects.toBe(error);
});
});
@@ -0,0 +1,56 @@
const LISTENING_LOG_FRAGMENT = "Listening on http://";
const MAX_BUFFER_CHARS = 8_192;
export class ServerListeningDetector {
private buffer = "";
private settled = false;
private readonly resolvePromise: () => void;
private readonly rejectPromise: (error: unknown) => void;
readonly promise: Promise<void>;
constructor() {
let resolvePromise: (() => void) | null = null;
let rejectPromise: ((error: unknown) => void) | null = null;
this.promise = new Promise<void>((resolve, reject) => {
resolvePromise = resolve;
rejectPromise = reject;
});
this.resolvePromise = () => {
if (this.settled) {
return;
}
this.settled = true;
resolvePromise?.();
};
this.rejectPromise = (error) => {
if (this.settled) {
return;
}
this.settled = true;
rejectPromise?.(error);
};
}
push(chunk: unknown): void {
if (this.settled) {
return;
}
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
this.buffer = `${this.buffer}${text.replace(/\r/g, "")}`;
if (this.buffer.includes(LISTENING_LOG_FRAGMENT)) {
this.resolvePromise();
return;
}
if (this.buffer.length > MAX_BUFFER_CHARS) {
this.buffer = this.buffer.slice(-MAX_BUFFER_CHARS);
}
}
fail(error: unknown): void {
this.rejectPromise(error);
}
}
+191 -7
View File
@@ -1,16 +1,17 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
PATH: "/Users/test/.local/bin:/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
HOMEBREW_PREFIX: "/opt/homebrew",
}));
syncShellEnvironment(env, {
@@ -18,9 +19,18 @@ describe("syncShellEnvironment", () => {
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
"PATH",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
]);
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
expect(env.HOMEBREW_PREFIX).toBe("/opt/homebrew");
});
it("preserves an inherited SSH_AUTH_SOCK value", () => {
@@ -77,12 +87,68 @@ describe("syncShellEnvironment", () => {
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
"PATH",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
]);
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("does nothing outside macOS and linux", () => {
it("falls back to launchctl PATH on macOS when shell probing does not return one", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/opt/homebrew/bin/nu",
PATH: "/usr/bin",
};
const readEnvironment = vi
.fn()
.mockImplementationOnce(() => {
throw new Error("unknown flag");
})
.mockImplementationOnce(() => ({}));
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
const logWarning = vi.fn();
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
readLaunchctlPath,
userShell: "/bin/zsh",
logWarning,
});
expect(readEnvironment).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu", [
"PATH",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
]);
expect(readEnvironment).toHaveBeenNthCalledWith(2, "/bin/zsh", [
"PATH",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
]);
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
expect(logWarning).toHaveBeenCalledWith(
"Failed to read login shell environment from /opt/homebrew/bin/nu.",
expect.any(Error),
);
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
});
it("does nothing on unsupported platforms", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
@@ -94,7 +160,7 @@ describe("syncShellEnvironment", () => {
}));
syncShellEnvironment(env, {
platform: "win32",
platform: "freebsd",
readEnvironment,
});
@@ -102,4 +168,122 @@ describe("syncShellEnvironment", () => {
expect(env.PATH).toBe("C:\\Windows\\System32");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("hydrates PATH on Windows by merging PowerShell PATH with inherited PATH", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(() => ({
PATH: "C:\\Custom\\Bin;C:\\Windows\\System32",
}));
const isWindowsCommandAvailable = vi.fn(() => true);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(readWindowsEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
expect(env.PATH).toBe(
[
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
expect(isWindowsCommandAvailable).toHaveBeenCalledTimes(1);
});
it("loads the PowerShell profile on Windows when node is not available", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
options?.loadProfile
? {
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
}
: { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" },
);
const isWindowsCommandAvailable = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(env.PATH).toBe(
[
"C:\\Profile\\Node",
"C:\\Windows\\System32",
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
].join(";"),
);
expect(env.FNM_DIR).toBe("C:\\Users\\testuser\\AppData\\Roaming\\fnm");
expect(env.FNM_MULTISHELL_PATH).toBe(
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
);
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(
2,
["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
{ loadProfile: true },
);
});
it("preserves baseline Windows env when the profile probe fails", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => {
if (options?.loadProfile) {
throw new Error("profile load failed");
}
return { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" };
},
);
const isWindowsCommandAvailable = vi.fn(() => false);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(env.PATH).toBe(
[
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
expect(env.SSH_AUTH_SOCK).toBeUndefined();
});
});
+86 -13
View File
@@ -1,36 +1,109 @@
import {
listLoginShellCandidates,
mergePathEntries,
readPathFromLaunchctl,
readEnvironmentFromLoginShell,
resolveLoginShell,
ShellEnvironmentReader,
resolveWindowsEnvironment,
} from "@t3tools/shared/shell";
import type {
CommandAvailabilityOptions,
ShellEnvironmentReader,
WindowsShellEnvironmentReader,
} from "@t3tools/shared/shell";
type WindowsCommandAvailabilityChecker = (
command: string,
options?: CommandAvailabilityOptions,
) => boolean;
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
] as const;
function logShellEnvironmentWarning(message: string, error?: unknown): void {
console.warn(`[desktop] ${message}`, error instanceof Error ? error.message : (error ?? ""));
}
export function syncShellEnvironment(
env: NodeJS.ProcessEnv = process.env,
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
readWindowsEnvironment?: WindowsShellEnvironmentReader;
isWindowsCommandAvailable?: WindowsCommandAvailabilityChecker;
readLaunchctlPath?: typeof readPathFromLaunchctl;
userShell?: string;
logWarning?: (message: string, error?: unknown) => void;
} = {},
): void {
const platform = options.platform ?? process.platform;
if (platform !== "darwin" && platform !== "linux") return;
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
const shellEnvironment: Partial<Record<string, string>> = {};
try {
const shell = resolveLoginShell(platform, env.SHELL);
if (!shell) return;
if (platform === "win32") {
const repairedEnvironment = resolveWindowsEnvironment(env, {
...(options.readWindowsEnvironment
? { readEnvironment: options.readWindowsEnvironment }
: {}),
...(options.isWindowsCommandAvailable
? { commandAvailable: options.isWindowsCommandAvailable }
: {}),
});
for (const [key, value] of Object.entries(repairedEnvironment)) {
if (value !== undefined) {
env[key] = value;
}
}
return;
}
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
"PATH",
"SSH_AUTH_SOCK",
]);
if (platform !== "darwin" && platform !== "linux") return;
if (shellEnvironment.PATH) {
env.PATH = shellEnvironment.PATH;
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
try {
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
if (shellEnvironment.PATH) {
break;
}
} catch (error) {
logWarning(`Failed to read login shell environment from ${shell}.`, error);
}
}
const launchctlPath =
platform === "darwin" && !shellEnvironment.PATH
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
: undefined;
const mergedPath = mergePathEntries(shellEnvironment.PATH ?? launchctlPath, env.PATH, platform);
if (mergedPath) {
env.PATH = mergedPath;
}
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
} catch {
// Keep inherited environment if shell lookup fails.
for (const name of [
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
] as const) {
if (!env[name] && shellEnvironment[name]) {
env[name] = shellEnvironment[name];
}
}
} catch (error) {
logWarning("Failed to synchronize the desktop shell environment.", error);
}
}
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import {
doesVersionMatchDesktopUpdateChannel,
isNightlyDesktopVersion,
resolveDefaultDesktopUpdateChannel,
} from "./updateChannels.ts";
describe("isNightlyDesktopVersion", () => {
it("detects packaged nightly versions", () => {
expect(isNightlyDesktopVersion("0.0.17-nightly.20260415.1")).toBe(true);
});
it("does not flag stable versions as nightly", () => {
expect(isNightlyDesktopVersion("0.0.17")).toBe(false);
});
});
describe("resolveDefaultDesktopUpdateChannel", () => {
it("defaults stable builds to latest", () => {
expect(resolveDefaultDesktopUpdateChannel("0.0.17")).toBe("latest");
});
it("defaults nightly builds to nightly", () => {
expect(resolveDefaultDesktopUpdateChannel("0.0.17-nightly.20260415.1")).toBe("nightly");
});
});
describe("doesVersionMatchDesktopUpdateChannel", () => {
it("accepts nightly releases on the nightly channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "nightly")).toBe(true);
});
it("rejects stable releases on the nightly channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17", "nightly")).toBe(false);
});
it("rejects nightly releases on the stable channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "latest")).toBe(false);
});
});
+18
View File
@@ -0,0 +1,18 @@
import type { DesktopUpdateChannel } from "@t3tools/contracts";
const NIGHTLY_VERSION_PATTERN = /-nightly\.\d{8}\.\d+$/;
export function isNightlyDesktopVersion(version: string): boolean {
return NIGHTLY_VERSION_PATTERN.test(version);
}
export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
return isNightlyDesktopVersion(appVersion) ? "nightly" : "latest";
}
export function doesVersionMatchDesktopUpdateChannel(
version: string,
channel: DesktopUpdateChannel,
): boolean {
return resolveDefaultDesktopUpdateChannel(version) === channel;
}
+8 -7
View File
@@ -11,7 +11,7 @@ import {
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
} from "./updateMachine.ts";
const runtimeInfo = {
hostArch: "x64",
@@ -23,7 +23,7 @@ describe("updateMachine", () => {
it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "error",
message: "network",
@@ -42,7 +42,7 @@ describe("updateMachine", () => {
it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "checking",
},
@@ -58,7 +58,7 @@ describe("updateMachine", () => {
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -76,7 +76,7 @@ describe("updateMachine", () => {
it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -98,7 +98,7 @@ describe("updateMachine", () => {
it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "error",
availableVersion: "1.1.0",
@@ -120,7 +120,7 @@ describe("updateMachine", () => {
it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "checking",
},
@@ -131,6 +131,7 @@ describe("updateMachine", () => {
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
expect(available.status).toBe("available");
expect(available.channel).toBe("latest");
expect(downloading.status).toBe("downloading");
expect(downloading.downloadPercent).toBe(0);
expect(progress.downloadPercent).toBe(55.5);
+8 -2
View File
@@ -1,14 +1,20 @@
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
import type {
DesktopRuntimeInfo,
DesktopUpdateChannel,
DesktopUpdateState,
} from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState.ts";
export function createInitialDesktopUpdateState(
currentVersion: string,
runtimeInfo: DesktopRuntimeInfo,
channel: DesktopUpdateChannel,
): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
channel,
currentVersion,
hostArch: runtimeInfo.hostArch,
appArch: runtimeInfo.appArch,
+2 -1
View File
@@ -6,11 +6,12 @@ import {
getAutoUpdateDisabledReason,
nextStatusAfterDownloadFailure,
shouldBroadcastDownloadProgress,
} from "./updateState";
} from "./updateState.ts";
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
+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);
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
"compilerOptions": {
"composite": true,
"types": ["node", "electron"],
"lib": ["ES2023", "DOM", "esnext.disposable"]
"lib": ["ESNext", "DOM", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
}
+2 -2
View File
@@ -4,7 +4,7 @@ const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".js" }),
outExtensions: () => ({ js: ".cjs" }),
};
export default defineConfig([
@@ -12,7 +12,7 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
},
{
...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),
@@ -438,7 +445,7 @@ export const makeOrchestrationIntegrationHarness = (
) =>
waitFor(
pendingApprovalRepository
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
.pipe(
Effect.map((row) =>
Option.match(row, {
@@ -289,7 +289,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
const turnId = TurnId.make(`turn-${turnCount}`);
const response = state.queuedResponses.shift();
if (!response) {
@@ -307,7 +307,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
provider,
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
sessionId: RuntimeSessionId.make(String(input.threadId)),
createdAt: nowIso(),
};
rawEvent.threadId = state.snapshot.threadId;
@@ -363,7 +363,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.makeUnsafe(randomUUID()),
eventId: EventId.make(randomUUID()),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
@@ -5,14 +5,14 @@ const PROVIDER = "codex" as const;
const SESSION_ID = "fixture-session";
const THREAD_ID = "fixture-thread";
const TURN_ID = "fixture-turn";
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
const REQUEST_ID = RuntimeRequestId.make("req-1");
function baseEvent(
eventId: string,
createdAt: string,
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
return {
eventId: EventId.makeUnsafe(eventId),
eventId: EventId.make(eventId),
provider: PROVIDER,
sessionId: SESSION_ID,
createdAt,
@@ -30,14 +30,13 @@ import type {
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId =>
ApprovalRequestId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const THREAD_ID = ThreadId.make("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = ProviderKind;
@@ -112,7 +111,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
yield* harness.engine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe("cmd-project-create"),
commandId: CommandId.make("cmd-project-create"),
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
@@ -125,7 +124,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
yield* harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create"),
commandId: CommandId.make("cmd-thread-create"),
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
@@ -150,7 +149,7 @@ const startTurn = (input: {
}) =>
input.harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe(input.commandId),
commandId: CommandId.make(input.commandId),
threadId: THREAD_ID,
message: {
messageId: asMessageId(input.messageId),
@@ -261,7 +260,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
yield* harness.engine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
commandId: CommandId.make("cmd-project-create-real-codex"),
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
@@ -274,7 +273,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
yield* harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
commandId: CommandId.make("cmd-thread-create-real-codex"),
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
@@ -291,7 +290,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),
commandId: CommandId.make("cmd-turn-start-real-codex-1"),
threadId: THREAD_ID,
message: {
messageId: asMessageId("msg-real-codex-1"),
@@ -318,7 +317,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),
commandId: CommandId.make("cmd-turn-start-real-codex-2"),
threadId: THREAD_ID,
message: {
messageId: asMessageId("msg-real-codex-2"),
@@ -583,7 +582,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
commandId: CommandId.make("cmd-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
@@ -815,7 +814,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
commandId: CommandId.make("cmd-checkpoint-revert"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
@@ -875,7 +874,7 @@ it.live(
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
commandId: CommandId.make("cmd-checkpoint-revert-no-session"),
threadId: THREAD_ID,
turnCount: 0,
createdAt: nowIso(),
@@ -1119,7 +1118,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
commandId: CommandId.make("cmd-claude-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
@@ -1192,7 +1191,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
yield* harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
commandId: CommandId.make("cmd-turn-interrupt-claude"),
threadId: THREAD_ID,
createdAt: nowIso(),
});
@@ -1309,7 +1308,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
@@ -122,15 +122,12 @@ it.live("replays typed runtime fixture events", () =>
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-typed"),
{
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
},
);
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
threadId: ThreadId.make("thread-integration-typed"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
const observedEvents = yield* runTurn({
@@ -157,15 +154,12 @@ it.live("replays file-changing fixture turn events", () =>
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-tools"),
{
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
},
);
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
threadId: ThreadId.make("thread-integration-tools"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
const observedEvents = yield* runTurn({
@@ -196,15 +190,12 @@ it.live("runs multi-turn tool/approval flow", () =>
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-multi"),
{
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
},
);
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
threadId: ThreadId.make("thread-integration-multi"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
const firstTurnEvents = yield* runTurn({
@@ -250,15 +241,12 @@ it.live("rolls back provider conversation state only", () =>
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-rollback"),
{
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
},
);
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
threadId: ThreadId.make("thread-integration-rollback"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
yield* runTurn({
+9 -4
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.15",
"version": "0.0.20",
"license": "MIT",
"repository": {
"type": "git",
@@ -15,18 +15,21 @@
],
"type": "module",
"scripts": {
"dev": "bun run src/bin.ts",
"dev": "node --watch src/bin.ts",
"build": "node scripts/cli.ts build",
"build:bundle": "tsdown",
"start": "node dist/bin.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
"test": "vitest run",
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
"@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",
@@ -40,6 +43,8 @@
"@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);
+33 -16
View File
@@ -14,6 +14,22 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
interface PackageJson {
name: string;
repository: {
type: string;
url: string;
directory: string;
};
bin: Record<string, string>;
type: string;
version: string;
engines: Record<string, string>;
files: string[];
dependencies: Record<string, string>;
overrides: Record<string, string>;
}
class CliError extends Data.TaggedError("CliError")<{
readonly message: string;
readonly cause?: unknown;
@@ -131,13 +147,13 @@ const buildCmd = Command.make(
yield* Effect.log("[cli] Running tsdown...");
yield* runCommand(
ChildProcess.make({
ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
// Windows needs shell mode to resolve `.cmd` shims on PATH.
shell: process.platform === "win32",
})`bun tsdown`,
}),
);
const webDist = path.join(repoRoot, "apps/web/dist");
@@ -177,7 +193,7 @@ const publishCmd = Command.make(
const backupPath = `${packageJsonPath}.bak`;
// Assert build assets exist
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
@@ -187,12 +203,10 @@ const publishCmd = Command.make(
}
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
Effect.gen(function* () {
// Resolve catalog dependencies before any file mutations. If this throws,
// acquire fails and no release hook runs, so filesystem must still be untouched.
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = {
const pkg: PackageJson = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
bin: serverPackageJson.bin,
@@ -200,19 +214,22 @@ const publishCmd = Command.make(
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
dependencies: resolveCatalogDependencies(
serverPackageJson.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server",
),
overrides: resolveCatalogDependencies(
rootPackageJson.overrides,
rootPackageJson.workspaces.catalog,
"apps/server",
),
};
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Resolved package.json for publish");
yield* Effect.log("[cli] Prepared package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
@@ -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);
}),
);
@@ -2,7 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ServerConfigShape } from "../../config.ts";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
@@ -10,8 +10,10 @@ import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Lay
import {
AuthControlPlane,
AuthControlPlaneError,
AuthControlPlaneShape,
DEFAULT_SESSION_SUBJECT,
} from "../Services/AuthControlPlane.ts";
import type {
AuthControlPlaneShape,
IssuedBearerSession,
IssuedPairingLink,
} from "../Services/AuthControlPlane.ts";
+11 -1
View File
@@ -20,7 +20,10 @@ import {
AuthError,
type ServerAuthShape,
} from "../Services/ServerAuth.ts";
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
import {
SessionCredentialError,
SessionCredentialService,
} from "../Services/SessionCredentialService.ts";
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
type BootstrapExchangeResult = {
@@ -65,6 +68,13 @@ export const makeServerAuth = Effect.gen(function* () {
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
sessions.verify(token).pipe(
Effect.tapError((cause: SessionCredentialError) =>
Effect.logWarning("Rejected authenticated session credential.").pipe(
Effect.annotateLogs({
reason: cause.message,
}),
),
),
Effect.map((session) => ({
sessionId: session.sessionId,
subject: session.subject,
@@ -33,10 +33,12 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
expect(descriptor.policy).toBe("desktop-managed-local");
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
}).pipe(
Effect.provide(
makeServerAuthPolicyLayer({
mode: "desktop",
port: 3773,
}),
),
),
@@ -66,6 +68,7 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
expect(descriptor.policy).toBe("loopback-browser");
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
expect(descriptor.sessionCookieName).toBe("t3_session");
}).pipe(
Effect.provide(
makeServerAuthPolicyLayer({
@@ -3,7 +3,7 @@ import { Effect, Layer } from "effect";
import { ServerConfig } from "../../config.ts";
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
import { SESSION_COOKIE_NAME } from "../utils.ts";
import { resolveSessionCookieName } from "../utils.ts";
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
export const makeServerAuthPolicy = Effect.gen(function* () {
@@ -30,7 +30,10 @@ export const makeServerAuthPolicy = Effect.gen(function* () {
policy,
bootstrapMethods,
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
sessionCookieName: SESSION_COOKIE_NAME,
sessionCookieName: resolveSessionCookieName({
mode: config.mode,
port: config.port,
}),
};
return {
@@ -1,6 +1,6 @@
import * as Crypto from "node:crypto";
import { Effect, FileSystem, Layer, Path } from "effect";
import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
import * as PlatformError from "effect/PlatformError";
import { ServerConfig } from "../../config.ts";
@@ -28,17 +28,14 @@ export const makeServerSecretStore = Effect.gen(function* () {
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
const isMissingSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
cause instanceof PlatformError.PlatformError && cause.reason._tag === "NotFound";
const isAlreadyExistsSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
cause instanceof PlatformError.PlatformError && cause.reason._tag === "AlreadyExists";
const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
Predicate.isTagged(u, "PlatformError");
const get: ServerSecretStoreShape["get"] = (name) =>
fileSystem.readFile(resolveSecretPath(name)).pipe(
Effect.map((bytes) => Uint8Array.from(bytes)),
Effect.catch((cause) =>
isMissingSecretFileError(cause)
cause.reason._tag === "NotFound"
? Effect.succeed(null)
: Effect.fail(
new SecretStoreError({
@@ -108,7 +105,7 @@ export const makeServerSecretStore = Effect.gen(function* () {
return create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTag("SecretStoreError", (error) =>
isAlreadyExistsSecretFileError(error.cause)
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
? get(name).pipe(
Effect.flatMap((created) =>
created !== null
@@ -129,7 +126,7 @@ export const makeServerSecretStore = Effect.gen(function* () {
const remove: ServerSecretStoreShape["remove"] = (name) =>
fileSystem.remove(resolveSecretPath(name)).pipe(
Effect.catch((cause) =>
isMissingSecretFileError(cause)
cause.reason._tag === "NotFound"
? Effect.void
: Effect.fail(
new SecretStoreError({
@@ -2,10 +2,10 @@ import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
import { Option } from "effect";
import { ServerConfig } from "../../config.ts";
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
import { SESSION_COOKIE_NAME } from "../utils.ts";
import {
SessionCredentialError,
SessionCredentialService,
@@ -17,6 +17,7 @@ import {
import {
base64UrlDecodeUtf8,
base64UrlEncode,
resolveSessionCookieName,
signPayload,
timingSafeEqualBase64Url,
} from "../utils.ts";
@@ -81,11 +82,16 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
}
export const makeSessionCredentialService = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const secretStore = yield* ServerSecretStore;
const authSessions = yield* AuthSessionRepository;
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
const cookieName = resolveSessionCookieName({
mode: serverConfig.mode,
port: serverConfig.port,
});
const toSessionCredentialError = (message: string) => (cause: unknown) =>
new SessionCredentialError({
@@ -188,7 +194,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
const issue: SessionCredentialServiceShape["issue"] = (input) =>
Effect.gen(function* () {
const sessionId = AuthSessionId.makeUnsafe(crypto.randomUUID());
const sessionId = AuthSessionId.make(crypto.randomUUID());
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
@@ -472,7 +478,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
return {
cookieName: SESSION_COOKIE_NAME,
cookieName,
issue,
verify,
issueWebSocketToken,
@@ -4,8 +4,8 @@ import type {
AuthPairingLink,
AuthSessionId,
} from "@t3tools/contracts";
import { Data, DateTime, Duration, Effect, ServiceMap } from "effect";
import { SessionRole } from "./SessionCredentialService";
import { Data, DateTime, Duration, Effect, Context } from "effect";
import type { SessionRole } from "./SessionCredentialService.ts";
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
@@ -64,6 +64,6 @@ export interface AuthControlPlaneShape {
) => Effect.Effect<number, AuthControlPlaneError>;
}
export class AuthControlPlane extends ServiceMap.Service<AuthControlPlane, AuthControlPlaneShape>()(
export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
"t3/AuthControlPlane",
) {}
@@ -1,5 +1,5 @@
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
import { Data, DateTime, Duration, ServiceMap } from "effect";
import { Data, DateTime, Duration, Context } from "effect";
import type { Effect, Stream } from "effect";
export type BootstrapCredentialRole = "owner" | "client";
@@ -51,7 +51,7 @@ export interface BootstrapCredentialServiceShape {
readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
}
export class BootstrapCredentialService extends ServiceMap.Service<
export class BootstrapCredentialService extends Context.Service<
BootstrapCredentialService,
BootstrapCredentialServiceShape
>()("t3/auth/Services/BootstrapCredentialService") {}
+2 -2
View File
@@ -12,7 +12,7 @@ import type {
ServerAuthSessionMethod,
AuthWebSocketTokenResult,
} from "@t3tools/contracts";
import { Data, DateTime, ServiceMap } from "effect";
import { Data, DateTime, Context } from "effect";
import type { Effect } from "effect";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import type { SessionRole } from "./SessionCredentialService.ts";
@@ -79,6 +79,6 @@ export interface ServerAuthShape {
readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
}
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
export class ServerAuth extends Context.Service<ServerAuth, ServerAuthShape>()(
"t3/auth/Services/ServerAuth",
) {}
@@ -1,11 +1,11 @@
import type { ServerAuthDescriptor } from "@t3tools/contracts";
import { ServiceMap } from "effect";
import { Context } from "effect";
import type { Effect } from "effect";
export interface ServerAuthPolicyShape {
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
}
export class ServerAuthPolicy extends ServiceMap.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
export class ServerAuthPolicy extends Context.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
"t3/auth/Services/ServerAuthPolicy",
) {}
@@ -1,4 +1,4 @@
import { Data, ServiceMap } from "effect";
import { Data, Context } from "effect";
import type { Effect } from "effect";
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
@@ -16,7 +16,6 @@ export interface ServerSecretStoreShape {
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
}
export class ServerSecretStore extends ServiceMap.Service<
ServerSecretStore,
ServerSecretStoreShape
>()("t3/auth/Services/ServerSecretStore") {}
export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(
"t3/auth/Services/ServerSecretStore",
) {}
@@ -4,7 +4,7 @@ import type {
AuthSessionId,
ServerAuthSessionMethod,
} from "@t3tools/contracts";
import { Data, DateTime, Duration, ServiceMap } from "effect";
import { Data, DateTime, Duration, Context } from "effect";
import type { Effect, Stream } from "effect";
export type SessionRole = "owner" | "client";
@@ -81,7 +81,7 @@ export interface SessionCredentialServiceShape {
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
}
export class SessionCredentialService extends ServiceMap.Service<
export class SessionCredentialService extends Context.Service<
SessionCredentialService,
SessionCredentialServiceShape
>()("t3/auth/Services/SessionCredentialService") {}
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { deriveAuthClientMetadata } from "./utils";
import { deriveAuthClientMetadata } from "./utils.ts";
describe("deriveAuthClientMetadata", () => {
it("labels Electron user agents as Electron instead of Chrome", () => {
+12 -1
View File
@@ -2,7 +2,18 @@ import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as Crypto from "node:crypto";
export const SESSION_COOKIE_NAME = "t3_session";
const SESSION_COOKIE_NAME = "t3_session";
export function resolveSessionCookieName(input: {
readonly mode: "web" | "desktop";
readonly port: number;
}): string {
if (input.mode !== "desktop") {
return SESSION_COOKIE_NAME;
}
return `${SESSION_COOKIE_NAME}_${input.port}`;
}
export function base64UrlEncode(input: string | Uint8Array): string {
const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
+3 -3
View File
@@ -5,12 +5,12 @@ import * as Layer from "effect/Layer";
import { Command } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import { cli } from "./cli";
import { version } from "../package.json" with { type: "json" };
import { cli } from "./cli.ts";
import packageJson from "../package.json" with { type: "json" };
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
Command.run(cli, { version }).pipe(
Command.run(cli, { version: packageJson.version }).pipe(
Effect.scoped,
Effect.provide(CliRuntimeLayer),
NodeRuntime.runMain,
+1 -1
View File
@@ -10,7 +10,7 @@ import * as Fiber from "effect/Fiber";
import { TestClock } from "effect/testing";
import { vi } from "vitest";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap.ts";
import { assertNone, assertSome } from "@effect/vitest/utils";
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
@@ -26,7 +26,7 @@ function makeThreadCheckpointContext(input: {
worktreePath: input.worktreePath,
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
turnId: TurnId.make("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
@@ -40,8 +40,8 @@ function makeThreadCheckpointContext(input: {
describe("CheckpointDiffQueryLive", () => {
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
const projectId = ProjectId.makeUnsafe("project-1");
const threadId = ThreadId.makeUnsafe("thread-1");
const projectId = ProjectId.make("project-1");
const threadId = ThreadId.make("thread-1");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
const diffCheckpointsCalls: Array<{
@@ -82,10 +82,15 @@ describe("CheckpointDiffQueryLive", () => {
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
),
);
@@ -119,7 +124,7 @@ describe("CheckpointDiffQueryLive", () => {
});
it("fails when the thread is missing from the snapshot", async () => {
const threadId = ThreadId.makeUnsafe("thread-missing");
const threadId = ThreadId.make("thread-missing");
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
@@ -136,10 +141,15 @@ describe("CheckpointDiffQueryLive", () => {
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
),
);
@@ -93,7 +93,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore;
const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
const threadId = ThreadId.make("thread-checkpoint-store");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
@@ -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;
@@ -12,7 +12,7 @@ import type {
OrchestrationGetTurnDiffInput,
OrchestrationGetTurnDiffResult,
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import { Context } from "effect";
import type { Effect } from "effect";
import type { CheckpointServiceError } from "../Errors.ts";
@@ -43,7 +43,7 @@ export interface CheckpointDiffQueryShape {
/**
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
*/
export class CheckpointDiffQuery extends ServiceMap.Service<
export class CheckpointDiffQuery extends Context.Service<
CheckpointDiffQuery,
CheckpointDiffQueryShape
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
@@ -5,12 +5,12 @@
* workspace thread timeline. It does not store user-facing checkpoint metadata
* and does not coordinate provider conversation rollback.
*
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
* Uses Effect `Context.Service` for dependency injection and exposes typed
* domain errors for checkpoint storage operations.
*
* @module CheckpointStore
*/
import { ServiceMap } from "effect";
import { Context } from "effect";
import type { Effect } from "effect";
import type { CheckpointStoreError } from "../Errors.ts";
@@ -95,6 +95,6 @@ export interface CheckpointStoreShape {
/**
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
*/
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
export class CheckpointStore extends Context.Service<CheckpointStore, CheckpointStoreShape>()(
"t3/checkpointing/Services/CheckpointStore",
) {}
+1 -1
View File
@@ -4,7 +4,7 @@ import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
return CheckpointRef.makeUnsafe(
return CheckpointRef.make(
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
);
}
+65 -2
View File
@@ -5,8 +5,8 @@ import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect"
import { NetService } from "@t3tools/shared/Net";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { deriveServerPaths } from "./config";
import { resolveServerConfig } from "./cli";
import { deriveServerPaths } from "./config.ts";
import { resolveServerConfig } from "./cli.ts";
it.layer(NodeServices.layer)("cli config resolution", (it) => {
const defaultObservabilityConfig = {
@@ -153,6 +153,69 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
}),
);
it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags");
const fd = yield* openBootstrapFd({
noBrowser: true,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const resolved = yield* resolveServerConfig(
{
mode: Option.some("web"),
port: Option.some(8788),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.some(false),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(false),
logWebSocketEvents: Option.some(false),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_BOOTSTRAP_FD: String(fd),
T3CODE_NO_BROWSER: "true",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
T3CODE_LOG_WS_EVENTS: "true",
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Info",
...defaultObservabilityConfig,
mode: "web",
port: 8788,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: false,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
}),
);
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
+4
View File
@@ -152,6 +152,10 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
runCliWithRuntime(["--log-level", "debug", "--version"]),
);
it.effect("accepts canonical --no-<flag> boolean negation", () =>
runCliWithRuntime(["--no-log-websocket-events", "--version"]),
);
it.effect("rejects invalid log-level casing before launching the server", () =>
Effect.gen(function* () {
const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
+49 -79
View File
@@ -40,30 +40,31 @@ import {
RuntimeMode,
type ServerConfigShape,
type StartupPresentation,
} from "./config";
import { readBootstrapEnvelope } from "./bootstrap";
import { expandHomePath, resolveBaseDir } from "./os-jank";
import { runServer } from "./server";
} from "./config.ts";
import { readBootstrapEnvelope } from "./bootstrap.ts";
import { expandHomePath, resolveBaseDir } from "./os-jank.ts";
import { runServer } from "./server.ts";
import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";
import {
formatIssuedPairingCredential,
formatIssuedSession,
formatPairingCredentialList,
formatSessionList,
} from "./cliAuthFormat";
import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
} from "./cliAuthFormat.ts";
import { AuthControlPlane } from "./auth/Services/AuthControlPlane.ts";
import type { AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup";
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup.ts";
import {
clearPersistedServerRuntimeState,
readPersistedServerRuntimeState,
} from "./serverRuntimeState";
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
} from "./serverRuntimeState.ts";
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
@@ -193,9 +194,6 @@ interface CliAuthLocationFlags {
readonly devUrl?: Option.Option<URL>;
}
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
const resolveOptionPrecedence = <Value>(
...values: ReadonlyArray<Option.Option<Value>>
): Option.Option<Value> => Option.firstSomeOf(values);
@@ -241,12 +239,13 @@ export const resolveServerConfig = (
bootstrapFd !== undefined
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
: Option.none();
const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
const mode: RuntimeMode = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.mode,
Option.fromUndefinedOr(env.mode),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
Option.fromUndefinedOr(bootstrap?.mode),
),
() => "web",
);
@@ -255,7 +254,7 @@ export const resolveServerConfig = (
resolveOptionPrecedence(
normalizedFlags.port,
Option.fromUndefinedOr(env.port),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
Option.fromUndefinedOr(bootstrap?.port),
),
{
onSome: (value) => Effect.succeed(value),
@@ -271,7 +270,7 @@ export const resolveServerConfig = (
resolveOptionPrecedence(
normalizedFlags.devUrl,
Option.fromUndefinedOr(env.devUrl),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
Option.fromUndefinedOr(bootstrap?.devUrl),
),
() => undefined,
);
@@ -280,9 +279,7 @@ export const resolveServerConfig = (
resolveOptionPrecedence(
normalizedFlags.baseDir,
Option.fromUndefinedOr(env.t3Home),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.t3Home),
),
Option.fromUndefinedOr(bootstrap?.t3Home),
),
),
);
@@ -297,60 +294,41 @@ export const resolveServerConfig = (
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
const startupPresentation = options?.startupPresentation ?? "browser";
const noBrowser =
startupPresentation === "headless"
? true
: resolveBooleanFlag(
normalizedFlags.noBrowser,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.noBrowser),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.noBrowser),
),
),
() => mode === "desktop",
),
);
const desktopBootstrapToken = Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.desktopBootstrapToken),
const isHeadlessStartup = startupPresentation === "headless";
const noBrowser = Option.getOrElse(
resolveOptionPrecedence(
isHeadlessStartup ? Option.some(true) : Option.none(),
normalizedFlags.noBrowser,
Option.fromUndefinedOr(env.noBrowser),
Option.fromUndefinedOr(bootstrap?.noBrowser),
),
() => mode === "desktop",
);
const autoBootstrapProjectFromCwd =
options?.forceAutoBootstrapProjectFromCwd ??
(startupPresentation === "headless"
? false
: resolveBooleanFlag(
normalizedFlags.autoBootstrapProjectFromCwd,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
),
),
() => mode === "web",
),
));
const logWebSocketEvents = resolveBooleanFlag(
normalizedFlags.logWebSocketEvents,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.logWebSocketEvents),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
),
),
() => Boolean(devUrl),
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
const autoBootstrapProjectFromCwd = Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
isHeadlessStartup ? Option.some(false) : Option.none(),
normalizedFlags.autoBootstrapProjectFromCwd,
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd),
),
() => mode === "web",
);
const logWebSocketEvents = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.logWebSocketEvents,
Option.fromUndefinedOr(env.logWebSocketEvents),
Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
),
() => Boolean(devUrl),
);
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.host,
Option.fromUndefinedOr(env.host),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
Option.fromUndefinedOr(bootstrap?.host),
),
() => (mode === "desktop" ? "127.0.0.1" : undefined),
);
@@ -365,19 +343,11 @@ export const resolveServerConfig = (
traceMaxFiles: env.traceMaxFiles,
otlpTracesUrl:
env.otlpTracesUrl ??
Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.otlpTracesUrl),
),
) ??
bootstrap?.otlpTracesUrl ??
persistedObservabilitySettings.otlpTracesUrl,
otlpMetricsUrl:
env.otlpMetricsUrl ??
Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.otlpMetricsUrl),
),
) ??
bootstrap?.otlpMetricsUrl ??
persistedObservabilitySettings.otlpMetricsUrl,
otlpExportIntervalMs: env.otlpExportIntervalMs,
otlpServiceName: env.otlpServiceName,
@@ -1030,10 +1000,10 @@ const projectAddCommand = Command.make("add", {
}
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
const projectId = ProjectId.makeUnsafe(crypto.randomUUID());
const projectId = ProjectId.make(crypto.randomUUID());
yield* dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
commandId: CommandId.make(crypto.randomUUID()),
projectId,
title,
workspaceRoot,
@@ -1071,7 +1041,7 @@ const projectRemoveCommand = Command.make("remove", {
});
yield* dispatch({
type: "project.delete",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
commandId: CommandId.make(crypto.randomUUID()),
projectId: project.id,
});
return `Removed project ${project.id} (${project.title}).`;
@@ -1111,7 +1081,7 @@ const projectRenameCommand = Command.make("rename", {
yield* dispatch({
type: "project.meta.update",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
commandId: CommandId.make(crypto.randomUUID()),
projectId: project.id,
title: nextTitle,
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+6 -2
View File
@@ -6,7 +6,7 @@
*
* @module ServerConfig
*/
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
export const DEFAULT_PORT = 3773;
@@ -24,6 +24,7 @@ export interface ServerDerivedPaths {
readonly dbPath: string;
readonly keybindingsConfigPath: string;
readonly settingsPath: string;
readonly providerStatusCacheDir: string;
readonly worktreesDir: string;
readonly attachmentsDir: string;
readonly logsDir: string;
@@ -76,11 +77,13 @@ export const deriveServerPaths = Effect.fn(function* (
const attachmentsDir = join(stateDir, "attachments");
const logsDir = join(stateDir, "logs");
const providerLogsDir = join(logsDir, "provider");
const providerStatusCacheDir = join(baseDir, "caches");
return {
stateDir,
dbPath,
keybindingsConfigPath: join(stateDir, "keybindings.json"),
settingsPath: join(stateDir, "settings.json"),
providerStatusCacheDir,
worktreesDir: join(baseDir, "worktrees"),
attachmentsDir,
logsDir,
@@ -110,6 +113,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
],
@@ -120,7 +124,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
/**
* ServerConfig - Service tag for server runtime configuration.
*/
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShape>()(
"t3/config/ServerConfig",
) {
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
@@ -3,7 +3,7 @@ import { Effect, FileSystem, Layer, Path, Random } from "effect";
import { ServerConfig } from "../../config.ts";
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
import { version } from "../../../package.json" with { type: "json" };
import packageJson from "../../../package.json" with { type: "json" };
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
@@ -64,7 +64,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
return generated;
});
const environmentId = EnvironmentId.makeUnsafe(environmentIdRaw);
const environmentId = EnvironmentId.make(environmentIdRaw);
const cwdBaseName = path.basename(serverConfig.cwd).trim();
const label = yield* resolveServerEnvironmentLabel({
cwdBaseName,
@@ -77,7 +77,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
os: platformOs(),
arch: platformArch(),
},
serverVersion: version,
serverVersion: packageJson.version,
capabilities: {
repositoryIdentity: true,
},
@@ -51,11 +51,13 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
command: string,
args: readonly string[],
) {
const result = yield* Effect.tryPromise(() =>
runProcess(command, args, {
allowNonZeroExit: true,
}),
).pipe(Effect.orElseSucceed(() => null));
const result = yield* Effect.tryPromise({
try: () =>
runProcess(command, args, {
allowNonZeroExit: true,
}),
catch: () => null,
}).pipe(Effect.orElseSucceed(() => null));
if (!result || result.code !== 0) {
return null;
@@ -1,5 +1,5 @@
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import { ServiceMap } from "effect";
import { Context } from "effect";
import type { Effect } from "effect";
export interface ServerEnvironmentShape {
@@ -7,7 +7,6 @@ export interface ServerEnvironmentShape {
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
}
export class ServerEnvironment extends ServiceMap.Service<
ServerEnvironment,
ServerEnvironmentShape
>()("t3/environment/Services/ServerEnvironment") {}
export class ServerEnvironment extends Context.Service<ServerEnvironment, ServerEnvironmentShape>()(
"t3/environment/Services/ServerEnvironment",
) {}
@@ -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,24 +158,24 @@ 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",
[
"exec",
"--ephemeral",
"--skip-git-repo-check",
"-s",
"read-only",
"--model",
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",
@@ -183,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);
+181 -62
View File
@@ -40,6 +40,24 @@ function writeTextFile(
});
}
function removePath(
targetPath: string,
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
});
}
function makeDirectory(
dirPath: string,
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
});
}
/** Run a raw git command for test setup (not under test). */
function git(
cwd: string,
@@ -219,7 +237,10 @@ it.layer(TestLayer)("git integration", (it) => {
const seenChunks: string[][] = [];
const core = yield* makeIsolatedGitCore((input) => {
if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") {
if (
input.args.join(" ") !==
"-c core.fsmonitor=false -c core.untrackedCache=false check-ignore --no-index -z --stdin"
) {
return Effect.fail(
new GitCommandError({
operation: input.operation,
@@ -252,6 +273,35 @@ it.layer(TestLayer)("git integration", (it) => {
expect(result).toEqual(expectedPaths);
}),
);
it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () =>
Effect.gen(function* () {
const core = yield* makeIsolatedGitCore((input) => {
expect(input.args).toEqual([
"-c",
"core.fsmonitor=false",
"-c",
"core.untrackedCache=false",
"ls-files",
"--cached",
"--others",
"--exclude-standard",
"-z",
]);
return Effect.succeed({
code: 0,
stdout: "src/index.ts\0README.md\0",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
});
const result = yield* core.listWorkspaceFiles("/virtual/repo");
expect(result.paths).toEqual(["src/index.ts", "README.md"]);
expect(result.truncated).toBe(false);
}),
);
});
// ── listGitBranches ──
@@ -267,6 +317,21 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("returns isRepo: false for deleted directories", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const deletedDir = path.join(tmp, "deleted-repo");
yield* makeDirectory(deletedDir);
yield* removePath(deletedDir);
const result = yield* (yield* GitCore).listBranches({ cwd: deletedDir });
expect(result.isRepo).toBe(false);
expect(result.hasOriginRemote).toBe(false);
expect(result.branches).toEqual([]);
}),
);
it.effect("returns the current branch with current: true", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -617,8 +682,8 @@ it.layer(TestLayer)("git integration", (it) => {
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
Effect.gen(function* () {
const services = yield* Effect.services();
const runPromise = Effect.runPromiseWith(services);
const context = yield* Effect.context<never>();
const runPromise = Effect.runPromiseWith(context);
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -761,7 +826,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () =>
Effect.gen(function* () {
const ok = (stdout = "") =>
Effect.succeed({
@@ -780,7 +845,9 @@ it.layer(TestLayer)("git integration", (it) => {
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok("origin/main\n");
return ok(
input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n",
);
}
if (input.args[0] === "remote") {
return ok("origin\n");
@@ -791,10 +858,22 @@ it.layer(TestLayer)("git integration", (it) => {
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
expect(input.cwd).toBe("/repo");
expect(input.args).toEqual([
"--git-dir",
"/repo/.git",
"fetch",
"--quiet",
"--no-tags",
"origin",
]);
return ok();
}
if (input.operation === "GitCore.statusDetails.status") {
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
return ok(
input.cwd === "/repo/worktrees/pr-123"
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
);
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
@@ -821,70 +900,80 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
Effect.gen(function* () {
const ok = (stdout = "") =>
Effect.succeed({
code: 0,
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
it.effect(
"briefly backs off failed upstream refreshes across sibling worktrees on one remote",
() =>
Effect.gen(function* () {
const ok = (stdout = "") =>
Effect.succeed({
code: 0,
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
let fetchCount = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (
input.args[0] === "rev-parse" &&
input.args[1] === "--abbrev-ref" &&
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok("origin/main\n");
}
if (input.args[0] === "remote") {
return ok("origin\n");
}
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
return ok("/repo/.git\n");
}
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
let fetchCount = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (
input.args[0] === "rev-parse" &&
input.args[1] === "--abbrev-ref" &&
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok(
input.cwd === "/repo/worktrees/pr-123"
? "origin/feature/pr-123\n"
: "origin/main\n",
);
}
if (input.args[0] === "remote") {
return ok("origin\n");
}
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
return ok("/repo/.git\n");
}
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "simulated fetch timeout",
}),
);
}
if (input.operation === "GitCore.statusDetails.status") {
return ok(
input.cwd === "/repo/worktrees/pr-123"
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
);
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
input.operation === "GitCore.statusDetails.stagedNumstat"
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "simulated fetch timeout",
detail: "Unexpected git command in refresh failure cooldown test.",
}),
);
}
if (input.operation === "GitCore.statusDetails.status") {
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
input.operation === "GitCore.statusDetails.stagedNumstat"
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "Unexpected git command in refresh failure cooldown test.",
}),
);
});
});
yield* core.statusDetails("/repo/worktrees/main");
yield* core.statusDetails("/repo/worktrees/pr-123");
expect(fetchCount).toBe(1);
}),
yield* core.statusDetails("/repo/worktrees/main");
yield* core.statusDetails("/repo/worktrees/pr-123");
expect(fetchCount).toBe(1);
}),
);
it.effect("throws when branch does not exist", () =>
@@ -982,7 +1071,6 @@ it.layer(TestLayer)("git integration", (it) => {
"--quiet",
"--no-tags",
remoteName,
`+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
]);
}),
);
@@ -1594,6 +1682,37 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("returns a non-repo status for deleted directories", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const deletedDir = path.join(tmp, "deleted-repo");
yield* makeDirectory(deletedDir);
yield* removePath(deletedDir);
const core = yield* GitCore;
const status = yield* core.statusDetails(deletedDir);
const localStatus = yield* core.statusDetailsLocal(deletedDir);
expect(status).toEqual({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
upstreamRef: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
});
expect(localStatus).toEqual(status);
}),
);
it.effect("computes ahead count against base branch when no upstream is configured", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
+78 -28
View File
@@ -27,6 +27,7 @@ import {
type ExecuteGitProgress,
type GitCommitOptions,
type GitCoreShape,
type GitStatusDetails,
type ExecuteGitInput,
type ExecuteGitResult,
} from "../Services/GitCore.ts";
@@ -47,23 +48,39 @@ const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
"-c",
"core.fsmonitor=false",
"-c",
"core.untrackedCache=false",
] as const;
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitStatusDetails>({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
upstreamRef: null,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
});
type TraceTailState = {
processedChars: number;
remainder: string;
};
class StatusUpstreamRefreshCacheKey extends Data.Class<{
class StatusRemoteRefreshCacheKey extends Data.Class<{
gitCommonDir: string;
upstreamRef: string;
remoteName: string;
upstreamBranch: string;
}> {}
interface ExecuteGitOptions {
@@ -353,6 +370,16 @@ function quoteGitCommand(args: ReadonlyArray<string>): string {
return `git ${args.join(" ")}`;
}
function isMissingGitCwdError(error: GitCommandError): boolean {
const normalized = `${error.detail}\n${error.message}`.toLowerCase();
return (
normalized.includes("no such file or directory") ||
normalized.includes("notfound: filesystem.access") ||
normalized.includes("enoent") ||
normalized.includes("not a directory")
);
}
function toGitCommandError(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
detail: string,
@@ -890,17 +917,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
);
});
const fetchUpstreamRefForStatus = (
const fetchRemoteForStatus = (
gitCommonDir: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
remoteName: string,
): Effect.Effect<void, GitCommandError> => {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
const fetchCwd =
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
return executeGit(
"GitCore.fetchUpstreamRefForStatus",
"GitCore.fetchRemoteForStatus",
fetchCwd,
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
{
allowNonZeroExit: true,
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
@@ -916,20 +942,15 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
});
const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
cacheKey: StatusUpstreamRefreshCacheKey,
const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
cacheKey: StatusRemoteRefreshCacheKey,
) {
yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {
upstreamRef: cacheKey.upstreamRef,
remoteName: cacheKey.remoteName,
upstreamBranch: cacheKey.upstreamBranch,
});
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
return true as const;
});
const statusUpstreamRefreshCache = yield* Cache.makeWith({
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
lookup: refreshStatusUpstreamCacheEntry,
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
timeToLive: (exit) =>
Exit.isSuccess(exit)
@@ -944,12 +965,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
if (!upstream) return;
const gitCommonDir = yield* resolveGitCommonDir(cwd);
yield* Cache.get(
statusUpstreamRefreshCache,
new StatusUpstreamRefreshCacheKey({
statusRemoteRefreshCache,
new StatusRemoteRefreshCacheKey({
gitCommonDir,
upstreamRef: upstream.upstreamRef,
remoteName: upstream.remoteName,
upstreamBranch: upstream.upstreamBranch,
}),
);
});
@@ -1185,7 +1204,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
{
allowNonZeroExit: true,
},
);
).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
if (statusResult === null) {
return NON_REPOSITORY_STATUS_DETAILS;
}
if (statusResult.code !== 0) {
const stderr = statusResult.stderr.trim();
@@ -1317,7 +1340,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
);
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
Effect.ignoreCause({ log: true }),
);
return yield* readStatusDetailsLocal(cwd);
});
@@ -1619,7 +1645,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
executeGit(
"GitCore.listWorkspaceFiles",
cwd,
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
[
...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
"ls-files",
"--cached",
"--others",
"--exclude-standard",
"-z",
],
{
allowNonZeroExit: true,
timeoutMs: 20_000,
@@ -1637,7 +1670,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
createGitCommandError(
"GitCore.listWorkspaceFiles",
cwd,
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
[
...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
"ls-files",
"--cached",
"--others",
"--exclude-standard",
"-z",
],
result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",
),
),
@@ -1657,7 +1697,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const result = yield* executeGit(
"GitCore.filterIgnoredPaths",
cwd,
["check-ignore", "--no-index", "-z", "--stdin"],
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
{
stdin: `${chunk.join("\0")}\0`,
allowNonZeroExit: true,
@@ -1671,7 +1711,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return yield* createGitCommandError(
"GitCore.filterIgnoredPaths",
cwd,
["check-ignore", "--no-index", "-z", "--stdin"],
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",
);
}
@@ -1700,6 +1740,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
timeoutMs: 10_000,
allowNonZeroExit: true,
},
).pipe(
Effect.catchIf(isMissingGitCwdError, () =>
Effect.succeed({
code: 128,
stdout: "",
stderr: "fatal: not a git repository",
stdoutTruncated: false,
stderrTruncated: false,
}),
),
);
if (localBranchResult.code !== 0) {
@@ -1982,7 +2032,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
"GitCore.removeWorktree",
input.cwd,
args,
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error.message}`,
error,
),
),
+144 -1
View File
@@ -6,7 +6,7 @@ vi.mock("../../processRunner", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner";
import { runProcess } from "../../processRunner.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { GitHubCliLive } from "./GitHubCli.ts";
@@ -76,6 +76,105 @@ layer("GitHubCliLive", (it) => {
}),
);
it.effect("trims pull request fields decoded from gh json", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: JSON.stringify({
number: 42,
title: " Add PR thread creation \n",
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
baseRefName: " main ",
headRefName: "\tfeature/pr-threads\t",
state: "OPEN",
mergedAt: null,
isCrossRepository: true,
headRepository: {
nameWithOwner: " octocat/codething-mvp ",
},
headRepositoryOwner: {
login: " octocat ",
},
}),
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "#42",
});
});
assert.deepStrictEqual(result, {
number: 42,
title: "Add PR thread creation",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/pr-threads",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
});
}),
);
it.effect("skips invalid entries when parsing pr lists", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: JSON.stringify([
{
number: 0,
title: "invalid",
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
baseRefName: "main",
headRefName: "feature/invalid",
},
{
number: 43,
title: " Valid PR ",
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
baseRefName: " main ",
headRefName: " feature/pr-list ",
headRepository: {
nameWithOwner: " ",
},
headRepositoryOwner: {
login: " ",
},
},
]),
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.listOpenPullRequests({
cwd: "/repo",
headSelector: "feature/pr-list",
});
});
assert.deepStrictEqual(result, [
{
number: 43,
title: "Valid PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/43",
baseRefName: "main",
headRefName: "feature/pr-list",
state: "open",
},
]);
}),
);
it.effect("reads repository clone URLs", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
@@ -106,6 +205,50 @@ layer("GitHubCliLive", (it) => {
}),
);
it.effect("creates pull requests with the title passed as a single argv value", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: "https://github.com/pingdotgg/codething-mvp/pull/42\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
yield* gh.createPullRequest({
cwd: "/repo",
baseBranch: "main",
headSelector: "dev",
title: "Stabilize map selection, pricing badges, and camera handling",
bodyFile:
"C:\\Users\\leo20\\AppData\\Local\\Temp\\t3code-pr-body-38228-73481782-d57c-4b4d-ab5e-9906dc728b2b.md",
});
});
expect(mockedRunProcess).toHaveBeenCalledWith(
"gh",
[
"pr",
"create",
"--base",
"main",
"--head",
"dev",
"--title",
"Stabilize map selection, pricing badges, and camera handling",
"--body-file",
"C:\\Users\\leo20\\AppData\\Local\\Temp\\t3code-pr-body-38228-73481782-d57c-4b4d-ab5e-9906dc728b2b.md",
],
expect.objectContaining({
cwd: "/repo",
shell: false,
}),
);
}),
);
it.effect("surfaces a friendly error when the pull request is not found", () =>
Effect.gen(function* () {
mockedRunProcess.mockRejectedValueOnce(
+42 -82
View File
@@ -1,14 +1,18 @@
import { Effect, Layer, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import { runProcess } from "../../processRunner";
import { runProcess } from "../../processRunner.ts";
import { GitHubCliError } from "@t3tools/contracts";
import {
GitHubCli,
type GitHubRepositoryCloneUrls,
type GitHubCliShape,
type GitHubPullRequestSummary,
} from "../Services/GitHubCli.ts";
import {
decodeGitHubPullRequestJson,
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../githubPullRequests.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
@@ -63,76 +67,12 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
});
}
function normalizePullRequestState(input: {
state?: string | null | undefined;
mergedAt?: string | null | undefined;
}): "open" | "closed" | "merged" {
const mergedAt = input.mergedAt;
const state = input.state;
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
return "merged";
}
if (state === "CLOSED") {
return "closed";
}
return "open";
}
const RawGitHubPullRequestSchema = Schema.Struct({
number: PositiveInt,
title: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
baseRefName: TrimmedNonEmptyString,
headRefName: TrimmedNonEmptyString,
state: Schema.optional(Schema.NullOr(Schema.String)),
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
isCrossRepository: Schema.optional(Schema.Boolean),
headRepository: Schema.optional(
Schema.NullOr(
Schema.Struct({
nameWithOwner: Schema.String,
}),
),
),
headRepositoryOwner: Schema.optional(
Schema.NullOr(
Schema.Struct({
login: Schema.String,
}),
),
),
});
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
nameWithOwner: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
sshUrl: TrimmedNonEmptyString,
});
function normalizePullRequestSummary(
raw: Schema.Schema.Type<typeof RawGitHubPullRequestSchema>,
): GitHubPullRequestSummary {
const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null;
const headRepositoryOwnerLogin =
raw.headRepositoryOwner?.login ??
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
: null);
return {
number: raw.number,
title: raw.title,
url: raw.url,
baseRefName: raw.baseRefName,
headRefName: raw.headRefName,
state: normalizePullRequestState(raw),
...(typeof raw.isCrossRepository === "boolean"
? { isCrossRepository: raw.isCrossRepository }
: {}),
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
): GitHubRepositoryCloneUrls {
@@ -154,7 +94,7 @@ function decodeGitHubJson<S extends Schema.Top>(
(error) =>
new GitHubCliError({
operation,
detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
cause: error,
}),
),
@@ -167,8 +107,8 @@ const makeGitHubCli = Effect.sync(() => {
try: () =>
runProcess("gh", input.args, {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
shell: false,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
}),
catch: (error) => normalizeGitHubCliError("execute", error),
});
@@ -195,14 +135,24 @@ const makeGitHubCli = Effect.sync(() => {
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: decodeGitHubJson(
raw,
Schema.Array(RawGitHubPullRequestSchema),
"listOpenPullRequests",
"GitHub CLI returned invalid PR list JSON.",
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubCliError({
operation: "listOpenPullRequests",
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
}
return Effect.succeed(
decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
);
}),
),
),
Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
),
getPullRequest: (input) =>
execute({
@@ -217,14 +167,24 @@ const makeGitHubCli = Effect.sync(() => {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitHubJson(
raw,
RawGitHubPullRequestSchema,
"getPullRequest",
"GitHub CLI returned invalid pull request JSON.",
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubCliError({
operation: "getPullRequest",
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
}
return Effect.succeed(
(({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
);
}),
),
),
Effect.map(normalizePullRequestSummary),
),
getRepositoryCloneUrls: (input) =>
execute({
@@ -186,6 +186,24 @@ function makeTempDir(
});
}
function removePath(
targetPath: string,
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
});
}
function makeDirectory(
dirPath: string,
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
});
}
function runGit(
cwd: string,
args: readonly string[],
@@ -694,6 +712,144 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status trims PR metadata returned by gh before publishing it", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/status-trimmed-pr"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-trimmed-pr"]);
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 14,
title: " Existing PR title \n",
url: " https://github.com/pingdotgg/codething-mvp/pull/14 ",
baseRefName: " main ",
headRefName: "\tfeature/status-trimmed-pr\t",
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.pr).toEqual({
number: 14,
title: "Existing PR title",
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
baseBranch: "main",
headBranch: "feature/status-trimmed-pr",
state: "open",
});
}),
);
it.effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/status-valid-pr-entry"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-valid-pr-entry"]);
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 0,
title: "invalid",
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
baseRefName: "main",
headRefName: "feature/invalid",
},
{
number: 15,
title: " Valid PR title ",
url: " https://github.com/pingdotgg/codething-mvp/pull/15 ",
baseRefName: " main ",
headRefName: "\tfeature/status-valid-pr-entry\t",
headRepository: {
nameWithOwner: " ",
},
headRepositoryOwner: {
login: " ",
},
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.pr).toEqual({
number: 15,
title: "Valid PR title",
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
baseBranch: "main",
headBranch: "feature/status-valid-pr-entry",
state: "open",
});
}),
);
it.effect("status preserves lowercase merged and closed PR states from gh json", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/status-lowercase-state"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-lowercase-state"]);
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 16,
title: "Closed PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/16",
baseRefName: "main",
headRefName: "feature/status-lowercase-state",
state: "closed",
updatedAt: "2026-01-01T00:00:00.000Z",
},
{
number: 17,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
baseRefName: "main",
headRefName: "feature/status-lowercase-state",
state: "merged",
updatedAt: "2026-01-02T00:00:00.000Z",
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.pr).toEqual({
number: 17,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
baseBranch: "main",
headBranch: "feature/status-lowercase-state",
state: "merged",
});
}),
);
it.effect("status returns an explicit non-repo result for non-git directories", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
@@ -720,6 +876,35 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status returns an explicit non-repo result for deleted directories", () =>
Effect.gen(function* () {
const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-");
const cwd = path.join(rootDir, "deleted-repo");
yield* makeDirectory(cwd);
yield* removePath(cwd);
const { manager } = yield* makeManager();
const status = yield* manager.status({ cwd });
expect(status).toEqual({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
pr: null,
});
}),
);
it.effect("status briefly caches repeated lookups for the same cwd", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+36 -91
View File
@@ -1,7 +1,18 @@
import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import { Cache, Duration, Effect, Exit, FileSystem, Layer, Option, Path, Ref } from "effect";
import {
Cache,
Duration,
Effect,
Exit,
FileSystem,
Layer,
Option,
Path,
Ref,
Result,
} from "effect";
import {
GitActionProgressEvent,
GitActionProgressPhase,
@@ -27,13 +38,18 @@ import {
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitCore, GitStatusDetails } from "../Services/GitCore.ts";
import { GitCore } from "../Services/GitCore.ts";
import type { GitStatusDetails } from "../Services/GitCore.ts";
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
import {
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../githubPullRequests.ts";
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
@@ -240,85 +256,6 @@ function matchesBranchHeadContext(
return true;
}
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
if (!Array.isArray(raw)) return [];
const parsed: PullRequestInfo[] = [];
for (const entry of raw) {
if (!entry || typeof entry !== "object") continue;
const record = entry as Record<string, unknown>;
const number = record.number;
const title = record.title;
const url = record.url;
const baseRefName = record.baseRefName;
const headRefName = record.headRefName;
const state = record.state;
const mergedAt = record.mergedAt;
const updatedAt = record.updatedAt;
const isCrossRepository = record.isCrossRepository;
const headRepositoryRecord =
typeof record.headRepository === "object" && record.headRepository !== null
? (record.headRepository as Record<string, unknown>)
: null;
const headRepositoryOwnerRecord =
typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null
? (record.headRepositoryOwner as Record<string, unknown>)
: null;
const headRepositoryNameWithOwner =
typeof record.headRepositoryNameWithOwner === "string"
? record.headRepositoryNameWithOwner
: typeof headRepositoryRecord?.nameWithOwner === "string"
? headRepositoryRecord.nameWithOwner
: null;
const headRepositoryOwnerLogin =
typeof record.headRepositoryOwnerLogin === "string"
? record.headRepositoryOwnerLogin
: typeof headRepositoryOwnerRecord?.login === "string"
? headRepositoryOwnerRecord.login
: null;
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
continue;
}
if (
typeof title !== "string" ||
typeof url !== "string" ||
typeof baseRefName !== "string" ||
typeof headRefName !== "string"
) {
continue;
}
let normalizedState: "open" | "closed" | "merged";
if (
(typeof mergedAt === "string" && mergedAt.trim().length > 0) ||
state === "MERGED" ||
state === "merged"
) {
normalizedState = "merged";
} else if (state === "OPEN" || state === "open" || state === undefined || state === null) {
normalizedState = "open";
} else if (state === "CLOSED" || state === "closed") {
normalizedState = "closed";
} else {
continue;
}
parsed.push({
number,
title,
url,
baseRefName,
headRefName,
state: normalizedState,
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
});
}
return parsed;
}
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
return {
number: summary.number,
@@ -731,9 +668,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
workingTree: details.workingTree,
} satisfies GitStatusLocalResult;
});
const localStatusResultCache = yield* Cache.makeWith({
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
capacity: STATUS_RESULT_CACHE_CAPACITY,
lookup: readLocalStatus,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateLocalStatusResultCache = (cwd: string) =>
@@ -764,9 +700,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
pr,
} satisfies GitStatusRemoteResult;
});
const remoteStatusResultCache = yield* Cache.makeWith({
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
capacity: STATUS_RESULT_CACHE_CAPACITY,
lookup: readRemoteStatus,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateRemoteStatusResultCache = (cwd: string) =>
@@ -949,13 +884,23 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
continue;
}
const parsedJson = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
});
const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
gitManagerError(
"findLatestPr",
`GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
decoded.failure,
),
);
}
for (const pr of parsePullRequestList(parsedJson)) {
return Effect.succeed(decoded.success);
}),
);
for (const pr of pullRequests) {
if (!matchesBranchHeadContext(pr, headContext)) {
continue;
}
@@ -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);
@@ -9,45 +9,55 @@
*
* @module RoutingTextGeneration
*/
import { Effect, Layer, ServiceMap } from "effect";
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.
// ---------------------------------------------------------------------------
class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
) {}
class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(
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),
);
Loaded 100 of 614 files, more files were not shown because too many files have changed in this diff. Show more