Compare commits

..
Author SHA1 Message Date
Julius Marminge b5281f994e Add composable chat and workspace layout modes
- Move thread terminal into an inline chat drawer
- Add split/paper workspace layout switching and scrolling
- Update route sync, command palette, and tests for new state
2026-04-15 17:40:23 -07:00
Julius Marminge 5c8504d602 Add composable workspace pane controls
- add workspace pane focus, split, resize, and zoom commands
- wire chat composer focus repair across workspace activation
- enable dragging threads into workspace surfaces
2026-04-14 17:47:30 -07:00
Julius Marminge d3d096c6f7 Refactor chat into composable workspace shell
- Add workspace document storage and store tests
- Route terminal and command-palette actions through workspace surfaces
- Update chat layout, sidebar, and thread terminal handling
2026-04-13 19:41:56 -07:00
533 changed files with 22471 additions and 110343 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
plans/
+4 -11
View File
@@ -2,22 +2,15 @@
"name": "T3 Code Dev",
"image": "debian:bookworm",
"features": {
"ghcr.io/devcontainers/features/git:1": {},
"ghcr.io/devcontainers-extra/features/bun:1": {
"version": "1.3.11"
},
"ghcr.io/devcontainers-extra/features/bun:1": {},
"ghcr.io/devcontainers/features/node:1": {
"version": "24.13.1"
"version": "24",
"nodeGypDependencies": true
},
"ghcr.io/devcontainers/features/python:1": {
"version": "3.10",
"installTools": false
"version": "3.12"
}
},
"overrideFeatureInstallOrder": [
"ghcr.io/devcontainers/features/git",
"ghcr.io/devcontainers-extra/features/bun"
],
"postCreateCommand": {
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
},
+4 -7
View File
@@ -9,7 +9,7 @@ on:
jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: blacksmith-4vcpu-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.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
release_smoke:
name: Release Smoke
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
@@ -92,8 +92,5 @@ 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
+47 -252
View File
@@ -1,25 +1,14 @@
name: Release
name: Release Desktop
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: false
required: true
type: string
permissions:
@@ -27,63 +16,45 @@ permissions:
id-token: write
jobs:
check_changes:
name: Check for changes since last nightly
if: github.event_name == 'schedule'
runs-on: ubuntu-24.04
outputs:
has_changes: ${{ steps.check.outputs.has_changes }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- id: check
name: Compare HEAD to last nightly tag
run: |
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
if [[ -z "$last_nightly_tag" ]]; then
echo "No previous nightly tag found. Proceeding with release."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
exit 0
fi
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
head_sha=$(git rev-parse HEAD)
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
echo "has_changes=false" >> "$GITHUB_OUTPUT"
else
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
fi
preflight:
name: Preflight
needs: [check_changes]
if: |
!failure() && !cancelled() &&
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
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
with:
fetch-depth: 0
- id: release_meta
name: Resolve release version
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -98,60 +69,6 @@ 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
@@ -161,18 +78,9 @@ 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:
@@ -180,30 +88,25 @@ jobs:
matrix:
include:
- label: macOS arm64
runner: blacksmith-12vcpu-macos-26
runner: macos-14
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: blacksmith-12vcpu-macos-26
runner: macos-15-intel
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: blacksmith-32vcpu-ubuntu-2404
runner: ubuntu-24.04
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: blacksmith-32vcpu-windows-2025
runner: windows-2022
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
@@ -227,23 +130,6 @@ 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:
@@ -320,31 +206,18 @@ jobs:
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/*.yml"; do
"release/latest*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
shopt -s nullglob
for manifest in release-publish/*-mac.yml; do
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
done
if [[ -f release-publish/latest-mac.yml ]]; then
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
fi
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:
@@ -355,8 +228,7 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
@@ -385,41 +257,24 @@ jobs:
run: bun run build --filter=@t3tools/web --filter=t3
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
release:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
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
runs-on: ubuntu-24.04
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:
@@ -429,72 +284,17 @@ jobs:
- name: Merge macOS updater manifests
run: |
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
node scripts/merge-mac-update-manifests.ts \
release-assets/latest-mac.yml \
release-assets/latest-mac-x64.yml
rm -f release-assets/latest-mac-x64.yml
- name: Publish release
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
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 }}
name: T3 Code v${{ needs.preflight.outputs.version }}
generate_release_notes: true
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
@@ -504,15 +304,13 @@ jobs:
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
release-assets/latest*.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: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- id: app_token
@@ -551,9 +349,6 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- id: update_versions
name: Update version strings
env:
+2 -11
View File
@@ -10,16 +10,7 @@
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts",
"*.icon/**"
"apps/web/src/lib/vendor/qrcodegen.ts"
],
"sortPackageJson": {},
"overrides": [
{
"files": [".devcontainer/devcontainer.json"],
"options": {
"trailingComma": "none"
}
}
]
"sortPackageJson": {}
}
+1 -1
View File
@@ -5,5 +5,5 @@
"source.fixAll.oxc": "always"
},
"oxc.unusedDisableDirectives": "warn",
"js/ts.tsdk.path": "node_modules/typescript/lib"
"typescript.tsdk": "node_modules/typescript/lib"
}
+3 -4
View File
@@ -5,12 +5,11 @@ T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more
## Installation
> [!WARNING]
> T3 Code currently supports Codex, Claude, and OpenCode.
> T3 Code currently supports Codex and Claude.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
### Run without installing
+4 -6
View File
@@ -1,15 +1,14 @@
{
"name": "@t3tools/desktop",
"version": "0.0.21",
"version": "0.0.17",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
"main": "dist-electron/main.js",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "node scripts/dev-electron.mjs",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "tsdown",
"start": "node scripts/start-electron.mjs",
"start": "bun run scripts/start-electron.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
@@ -23,7 +22,6 @@
"@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.cjs",
"dist-electron/preload.cjs",
"dist-electron/main.js",
"dist-electron/preload.js",
"../server/dist/bin.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ 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.cjs"],
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
{
cwd: desktopDir,
env: childEnv,
+38 -74
View File
@@ -6,8 +6,8 @@ import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
statSync,
writeFileSync,
@@ -19,13 +19,10 @@ 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 = 2;
const LAUNCHER_VERSION = 1;
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], {
@@ -46,68 +43,6 @@ 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);
@@ -120,6 +55,40 @@ 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"));
@@ -133,7 +102,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 = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const iconPath = join(desktopDir, "resources", "icon.icns");
const metadataPath = join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
@@ -157,6 +126,7 @@ 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;
@@ -170,11 +140,5 @@ 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.cjs");
const mainJs = resolve(desktopDir, "dist-electron/main.js");
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.cjs"], {
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
-47
View File
@@ -1,47 +0,0 @@
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
@@ -1,28 +0,0 @@
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})`,
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { resolveDesktopBackendPort } from "./backendPort.ts";
import { resolveDesktopBackendPort } from "./backendPort";
describe("resolveDesktopBackendPort", () => {
it("returns the starting port when it is available", async () => {
+1 -1
View File
@@ -4,7 +4,7 @@ import {
BackendReadinessAbortedError,
isBackendReadinessAborted,
waitForHttpReady,
} from "./backendReadiness.ts";
} from "./backendReadiness";
describe("waitForHttpReady", () => {
it("returns once the backend serves the requested readiness path", async () => {
@@ -1,58 +0,0 @@
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);
});
});
@@ -1,56 +0,0 @@
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);
},
);
});
}
+1 -8
View File
@@ -18,7 +18,7 @@ import {
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
type DesktopSecretStorage,
} from "./clientPersistence.ts";
} from "./clientPersistence";
const tempDirectories: string[] = [];
@@ -49,16 +49,9 @@ function makeSecretStorage(available: boolean): DesktopSecretStorage {
}
const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
},
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
+2 -15
View File
@@ -1,13 +1,8 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import {
ClientSettingsSchema,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { Predicate } from "effect";
import * as Schema from "effect/Schema";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
@@ -88,15 +83,7 @@ function toPersistedSavedEnvironmentRecord(
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
if (!raw) {
return null;
}
try {
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
} catch {
return null;
}
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
+1 -1
View File
@@ -11,7 +11,7 @@ vi.mock("electron", () => ({
},
}));
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
import { showDesktopConfirmDialog } from "./confirmDialog";
describe("showDesktopConfirmDialog", () => {
beforeEach(() => {
+4 -87
View File
@@ -7,11 +7,9 @@ import { afterEach, describe, expect, it } from "vitest";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
resolveDefaultDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
} from "./desktopSettings";
const tempDirectories: string[] = [];
@@ -29,15 +27,7 @@ function makeSettingsPath() {
describe("desktopSettings", () => {
it("returns defaults when no settings file exists", () => {
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,
});
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("persists and reloads the configured server exposure mode", () => {
@@ -45,14 +35,10 @@ describe("desktopSettings", () => {
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
expect(readDesktopSettings(settingsPath)).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
@@ -61,32 +47,11 @@ 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,
});
});
@@ -94,54 +59,6 @@ describe("desktopSettings", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, "{not-json", "utf8");
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,
});
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
});
+4 -45
View File
@@ -1,28 +1,15 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
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,
@@ -35,51 +22,23 @@ export function setDesktopServerExposurePreference(
};
}
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);
export function readDesktopSettings(settingsPath: string): DesktopSettings {
try {
if (!FS.existsSync(settingsPath)) {
return defaultSettings;
return DEFAULT_DESKTOP_SETTINGS;
}
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 defaultSettings;
return DEFAULT_DESKTOP_SETTINGS;
}
}
+120 -232
View File
@@ -18,14 +18,12 @@ import {
safeStorage,
shell,
} from "electron";
import type { MenuItemConstructorOptions, OpenDialogOptions } from "electron";
import type { MenuItemConstructorOptions } from "electron";
import type {
ClientSettings,
DesktopTheme,
DesktopAppBranding,
DesktopServerExposureMode,
DesktopServerExposureState,
DesktopUpdateChannel,
PersistedSavedEnvironmentRecord,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
@@ -36,14 +34,13 @@ 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.ts";
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
} from "./desktopSettings";
import {
readClientSettings,
readSavedEnvironmentRegistry,
@@ -52,15 +49,13 @@ import {
writeClientSettings,
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
} 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";
} from "./clientPersistence";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { resolveDesktopServerExposure } from "./serverExposure";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import { ServerListeningDetector } from "./serverListeningDetector";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
@@ -72,10 +67,8 @@ import {
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine.ts";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
import { resolveDesktopAppBranding } from "./appBranding.ts";
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
syncShellEnvironment();
@@ -87,11 +80,9 @@ 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";
@@ -110,11 +101,7 @@ 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 desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
isDevelopment,
appVersion: app.getVersion(),
});
const APP_DISPLAY_NAME = desktopAppBranding.displayName;
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
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";
@@ -129,32 +116,8 @@ 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;
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_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
const TITLEBAR_HEIGHT = 40;
@@ -162,35 +125,6 @@ const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linu
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"
@@ -222,7 +156,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, app.getVersion());
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
@@ -233,11 +167,7 @@ const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(
app.getVersion(),
desktopRuntimeInfo,
desktopSettings.updateChannel,
);
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
function logTimestamp(): string {
return new Date().toISOString();
@@ -461,13 +391,51 @@ function cancelBackendReadinessWait(): void {
}
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
return await waitForBackendStartupReady({
listeningPromise: backendListeningDetector?.promise ?? null,
waitForHttpReady: () =>
waitForBackendHttpReady(baseUrl, {
timeoutMs: 60_000,
}),
cancelHttpWait: cancelBackendReadinessWait,
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
timeoutMs: 60_000,
});
const listeningPromise = backendListeningDetector?.promise;
if (!listeningPromise) {
await httpReadyPromise;
return "http";
}
return await new Promise<"listening" | "http">((resolve, reject) => {
let settled = false;
const settleResolve = (source: "listening" | "http") => {
if (settled) {
return;
}
settled = true;
if (source === "listening") {
cancelBackendReadinessWait();
}
resolve(source);
};
const settleReject = (error: unknown) => {
if (settled) {
return;
}
settled = true;
reject(error);
};
listeningPromise.then(
() => settleResolve("listening"),
(error) => settleReject(error),
);
httpReadyPromise.then(
() => settleResolve("http"),
(error) => {
if (settled && isBackendReadinessAborted(error)) {
return;
}
settleReject(error);
},
);
});
}
@@ -1007,18 +975,6 @@ 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}`);
}
@@ -1118,26 +1074,6 @@ 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);
@@ -1257,7 +1193,11 @@ function configureAutoUpdater(): void {
}
const enabled = shouldEnableAutoUpdates();
setUpdateState(createBaseUpdateState(desktopSettings.updateChannel, enabled));
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
if (!enabled) {
return;
}
@@ -1265,7 +1205,10 @@ function configureAutoUpdater(): void {
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
applyAutoUpdaterChannel(desktopSettings.updateChannel);
// 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;
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
let lastLoggedDownloadMilestone = -1;
@@ -1279,15 +1222,6 @@ 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,
@@ -1552,11 +1486,6 @@ 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 = {
@@ -1670,16 +1599,15 @@ function registerIpcHandlers(): void {
});
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
const defaultPath = resolvePickFolderDefaultPath(rawOptions);
const openDialogOptions: OpenDialogOptions = {
properties: ["openDirectory", "createDirectory"],
...(defaultPath ? { defaultPath } : {}),
};
const result = owner
? await dialog.showOpenDialog(owner, openDialogOptions)
: await dialog.showOpenDialog(openDialogOptions);
? await dialog.showOpenDialog(owner, {
properties: ["openDirectory", "createDirectory"],
})
: await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
});
if (result.canceled) return null;
return result.filePaths[0] ?? null;
});
@@ -1708,7 +1636,14 @@ function registerIpcHandlers(): void {
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
const normalizedItems = normalizeContextMenuItems(items);
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,
}));
if (normalizedItems.length === 0) {
return null;
}
@@ -1729,37 +1664,28 @@ function registerIpcHandlers(): void {
if (!window) return null;
return new Promise<string | null>((resolve) => {
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);
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of normalizedItems) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
return template;
};
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
click: () => resolve(item.id),
};
if (item.destructive) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
}
}
template.push(itemOption);
}
const menu = Menu.buildFromTemplate(buildTemplate(normalizedItems));
const menu = Menu.buildFromTemplate(template);
menu.popup({
window,
...popupPosition,
@@ -1787,43 +1713,6 @@ 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();
@@ -1931,7 +1820,7 @@ function createWindow(): BrowserWindow {
title: APP_DISPLAY_NAME,
...getWindowTitleBarOptions(),
webPreferences: {
preload: Path.join(__dirname, "preload.cjs"),
preload: Path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
@@ -1999,17 +1888,16 @@ function createWindow(): BrowserWindow {
emitUpdateState();
});
// 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));
let initialRevealScheduled = false;
const revealInitialWindow = () => {
if (initialRevealScheduled) {
return;
}
initialRevealScheduled = true;
revealWindow(window);
};
window.once("ready-to-show", revealInitialWindow);
if (isDevelopment) {
void window.loadURL(resolveDesktopDevServerUrl());
@@ -2084,9 +1972,9 @@ async function bootstrap(): Promise<void> {
if (isDevelopment) {
mainWindow = createWindow();
writeDesktopLogHeader("bootstrap main window created");
void waitForBackendWindowReady(backendHttpUrl)
.then((source) => {
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
void waitForBackendHttpReady(backendHttpUrl)
.then(() => {
writeDesktopLogHeader("bootstrap backend ready");
})
.catch((error) => {
if (isBackendReadinessAborted(error)) {
+1 -11
View File
@@ -9,11 +9,9 @@ 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";
@@ -26,13 +24,6 @@ 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) {
@@ -53,7 +44,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: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
@@ -70,7 +61,6 @@ 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.ts";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
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.ts";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
describe("resolveLanAdvertisedHost", () => {
it("prefers an explicit host override", () => {
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { ServerListeningDetector } from "./serverListeningDetector.ts";
import { ServerListeningDetector } from "./serverListeningDetector";
describe("ServerListeningDetector", () => {
it("resolves when the server logs the listening line", async () => {
+3 -121
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
import { syncShellEnvironment } from "./syncShellEnvironment";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
@@ -148,7 +148,7 @@ describe("syncShellEnvironment", () => {
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
});
it("does nothing on unsupported platforms", () => {
it("does nothing outside macOS and linux", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
@@ -160,7 +160,7 @@ describe("syncShellEnvironment", () => {
}));
syncShellEnvironment(env, {
platform: "freebsd",
platform: "win32",
readEnvironment,
});
@@ -168,122 +168,4 @@ 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();
});
});
+1 -31
View File
@@ -3,19 +3,9 @@ import {
mergePathEntries,
readPathFromLaunchctl,
readEnvironmentFromLoginShell,
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",
@@ -35,39 +25,19 @@ export function syncShellEnvironment(
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 {
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;
}
if (platform !== "darwin" && platform !== "linux") return;
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
try {
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
-41
View File
@@ -1,41 +0,0 @@
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
@@ -1,18 +0,0 @@
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;
}
+7 -8
View File
@@ -11,7 +11,7 @@ import {
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine.ts";
} from "./updateMachine";
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, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
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, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
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, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
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, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
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, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
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, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "checking",
},
@@ -131,7 +131,6 @@ 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);
+2 -8
View File
@@ -1,20 +1,14 @@
import type {
DesktopRuntimeInfo,
DesktopUpdateChannel,
DesktopUpdateState,
} from "@t3tools/contracts";
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState.ts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
export function createInitialDesktopUpdateState(
currentVersion: string,
runtimeInfo: DesktopRuntimeInfo,
channel: DesktopUpdateChannel,
): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
channel,
currentVersion,
hostArch: runtimeInfo.hostArch,
appArch: runtimeInfo.appArch,
+1 -2
View File
@@ -6,12 +6,11 @@ import {
getAutoUpdateDisabledReason,
nextStatusAfterDownloadFailure,
shouldBroadcastDownloadProgress,
} from "./updateState.ts";
} from "./updateState";
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
-74
View File
@@ -1,74 +0,0 @@
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
@@ -1,28 +0,0 @@
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": ["ESNext", "DOM", "esnext.disposable"]
"lib": ["ES2023", "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: ".cjs" }),
outExtensions: () => ({ js: ".js" }),
};
export default defineConfig([
@@ -12,7 +12,7 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
noExternal: (id) => id.startsWith("@t3tools/"),
},
{
...shared,
@@ -3,8 +3,7 @@ import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
CodexSettings,
ProviderDriverKind,
ProviderKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
@@ -37,16 +36,13 @@ import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
@@ -62,7 +58,6 @@ 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 {
@@ -218,7 +213,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: ProviderDriverKind;
readonly provider?: ProviderKind;
readonly realCodex?: boolean;
}
@@ -229,7 +224,7 @@ export const makeOrchestrationIntegrationHarness = (
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const provider = options?.provider ?? "codex";
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
? null
@@ -237,10 +232,13 @@ export const makeOrchestrationIntegrationHarness = (
provider,
});
const fakeRegistry = adapterHarness
? Layer.succeed(
ProviderAdapterRegistry,
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
)
? Layer.succeed(ProviderAdapterRegistry, {
getByProvider: (resolvedProvider) =>
resolvedProvider === adapterHarness.provider
? Effect.succeed(adapterHarness.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
listProviders: () => Effect.succeed([adapterHarness.provider]),
} as typeof ProviderAdapterRegistry.Service)
: null;
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-orchestration-integration-",
@@ -265,30 +263,31 @@ export const makeOrchestrationIntegrationHarness = (
const realCodexRegistry = Layer.effect(
ProviderAdapterRegistry,
Effect.gen(function* () {
const codexSettings = Schema.decodeSync(CodexSettings)({});
const codexAdapter = yield* makeCodexAdapter(codexSettings);
return makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: codexAdapter,
});
const codexAdapter = yield* CodexAdapter;
return {
getByProvider: (resolvedProvider) =>
resolvedProvider === "codex"
? Effect.succeed(codexAdapter)
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
listProviders: () => Effect.succeed(["codex"] as const),
} as typeof ProviderAdapterRegistry.Service;
}),
).pipe(
Layer.provide(makeCodexAdapterLive()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
const providerLayer = useRealCodex
? makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(realCodexRegistry),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
)
: makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(fakeRegistry!),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
@@ -352,12 +351,6 @@ 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),
@@ -10,7 +10,7 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderDriverKind,
ProviderKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
@@ -36,7 +36,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderDriverKind;
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: ProviderDriverKind;
readonly provider: ProviderKind;
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: ProviderDriverKind;
readonly provider?: ProviderKind;
}
function nowIso(): string {
@@ -206,7 +206,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: ProviderDriverKind,
provider: ProviderKind,
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +216,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: ProviderDriverKind,
provider: ProviderKind,
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -224,7 +224,7 @@ function missingSessionEffect(
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
Effect.gen(function* () {
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const provider = options?.provider ?? "codex";
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
const sessions = new Map<ThreadId, SessionState>();
@@ -257,9 +257,6 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
const session: ProviderSession = {
provider,
...(input.providerInstanceId !== undefined
? { providerInstanceId: input.providerInstanceId }
: {}),
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
@@ -1,7 +1,7 @@
import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
const PROVIDER = ProviderDriverKind.make("codex");
const PROVIDER = "codex" as const;
const SESSION_ID = "fixture-session";
const THREAD_ID = "fixture-thread";
const TURN_ID = "fixture-turn";
@@ -4,17 +4,14 @@ import path from "node:path";
import {
ApprovalRequestId,
CommandId,
defaultInstanceIdForDriver,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderDriverKind,
ProviderKind,
ThreadId,
ModelSelection,
ProviderInstanceId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Option, Schema } from "effect";
@@ -42,9 +39,7 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = ProviderDriverKind;
const CODEX_PROVIDER = ProviderDriverKind.make("codex");
const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");
type IntegrationProvider = ProviderKind;
function nowIso() {
return new Date().toISOString();
@@ -79,11 +74,7 @@ function waitForSync<A>(
});
}
function runtimeBase(
eventId: string,
createdAt: string,
provider: IntegrationProvider = CODEX_PROVIDER,
) {
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
return {
eventId: asEventId(eventId),
provider,
@@ -93,7 +84,7 @@ function runtimeBase(
function withHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
provider: IntegrationProvider = CODEX_PROVIDER,
provider: IntegrationProvider = "codex",
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider }),
@@ -106,7 +97,7 @@ function withRealCodexHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider: CODEX_PROVIDER, realCodex: true }),
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
@@ -115,9 +106,8 @@ function withRealCodexHarness<A, E>(
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? CODEX_PROVIDER;
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
const instanceId = defaultInstanceIdForDriver(provider);
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
yield* harness.engine.dispatch({
type: "project.create",
@@ -126,7 +116,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
instanceId,
provider,
model: defaultModel,
},
createdAt,
@@ -139,7 +129,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
instanceId,
provider,
model: defaultModel,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -275,7 +265,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5.3-codex",
},
createdAt,
@@ -288,7 +278,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5.3-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -922,32 +912,20 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
events: [
{
type: "turn.started",
...runtimeBase(
"evt-claude-start-1",
"2026-02-24T10:10:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-start-2",
"2026-02-24T10:10:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase(
"evt-claude-start-3",
"2026-02-24T10:10:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -961,7 +939,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
messageId: "msg-user-claude-initial",
text: "Use Claude",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
@@ -977,7 +955,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
);
assert.equal(thread.session?.providerName, "claudeAgent");
}),
CLAUDE_AGENT_PROVIDER,
"claudeAgent",
),
);
@@ -991,32 +969,20 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
events: [
{
type: "turn.started",
...runtimeBase(
"evt-claude-recover-1",
"2026-02-24T10:11:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-recover-2",
"2026-02-24T10:11:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase(
"evt-claude-recover-3",
"2026-02-24T10:11:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1030,7 +996,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
messageId: "msg-user-claude-recover-1",
text: "Before restart",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
@@ -1052,32 +1018,20 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
events: [
{
type: "turn.started",
...runtimeBase(
"evt-claude-recover-4",
"2026-02-24T10:11:01.000Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-recover-5",
"2026-02-24T10:11:01.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase(
"evt-claude-recover-6",
"2026-02-24T10:11:01.100Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1109,7 +1063,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
CLAUDE_AGENT_PROVIDER,
"claudeAgent",
),
);
@@ -1123,21 +1077,13 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
events: [
{
type: "turn.started",
...runtimeBase(
"evt-claude-approval-1",
"2026-02-24T10:12:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase(
"evt-claude-approval-2",
"2026-02-24T10:12:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
@@ -1146,11 +1092,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
},
{
type: "turn.completed",
...runtimeBase(
"evt-claude-approval-3",
"2026-02-24T10:12:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1164,7 +1106,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
messageId: "msg-user-claude-approval",
text: "Need approval",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
@@ -1195,7 +1137,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
CLAUDE_AGENT_PROVIDER,
"claudeAgent",
),
);
@@ -1209,32 +1151,20 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
events: [
{
type: "turn.started",
...runtimeBase(
"evt-claude-interrupt-1",
"2026-02-24T10:13:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-interrupt-2",
"2026-02-24T10:13:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase(
"evt-claude-interrupt-3",
"2026-02-24T10:13:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1248,7 +1178,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
@@ -1276,7 +1206,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
);
assert.equal(interruptCalls.length, 1);
}),
CLAUDE_AGENT_PROVIDER,
"claudeAgent",
),
);
@@ -1290,32 +1220,20 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
events: [
{
type: "turn.started",
...runtimeBase(
"evt-claude-revert-1",
"2026-02-24T10:14:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-revert-2",
"2026-02-24T10:14:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase(
"evt-claude-revert-3",
"2026-02-24T10:14:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1333,7 +1251,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
@@ -1348,32 +1266,20 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
events: [
{
type: "turn.started",
...runtimeBase(
"evt-claude-revert-4",
"2026-02-24T10:14:01.000Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-revert-5",
"2026-02-24T10:14:01.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase(
"evt-claude-revert-6",
"2026-02-24T10:14:01.100Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1424,6 +1330,6 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
CLAUDE_AGENT_PROVIDER,
"claudeAgent",
),
);
@@ -1,17 +1,13 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import {
ProviderService,
@@ -33,8 +29,6 @@ import {
codexTurnTextFixture,
} from "./fixtures/providerRuntime.ts";
const codexInstanceId = ProviderInstanceId.make("codex");
const makeWorkspaceDirectory = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
@@ -53,9 +47,13 @@ const makeIntegrationFixture = Effect.gen(function* () {
const cwd = yield* makeWorkspaceDirectory;
const harness = yield* makeTestProviderAdapterHarness();
const registry = makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: harness.adapter,
});
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(harness.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
@@ -66,7 +64,6 @@ const makeIntegrationFixture = Effect.gen(function* () {
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
@@ -127,8 +124,7 @@ it.live("replays typed runtime fixture events", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
threadId: ThreadId.make("thread-integration-typed"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -146,10 +142,6 @@ it.live("replays typed runtime fixture events", () =>
observedEvents.map((event) => event.type),
codexTurnTextFixture.map((event) => event.type),
);
assert.deepEqual(
observedEvents.map((event) => event.providerInstanceId),
codexTurnTextFixture.map(() => codexInstanceId),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
@@ -164,8 +156,7 @@ it.live("replays file-changing fixture turn events", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
threadId: ThreadId.make("thread-integration-tools"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -201,8 +192,7 @@ it.live("runs multi-turn tool/approval flow", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
threadId: ThreadId.make("thread-integration-multi"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -253,8 +243,7 @@ it.live("rolls back provider conversation state only", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
threadId: ThreadId.make("thread-integration-rollback"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
+4 -9
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.21",
"version": "0.0.17",
"license": "MIT",
"repository": {
"type": "git",
@@ -15,21 +15,18 @@
],
"type": "module",
"scripts": {
"dev": "node --watch src/bin.ts",
"dev": "bun run 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: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"
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@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",
@@ -43,8 +40,6 @@
"@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
@@ -1,590 +0,0 @@
#!/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);
+20 -15
View File
@@ -147,13 +147,13 @@ const buildCmd = Command.make(
yield* Effect.log("[cli] Running tsdown...");
yield* runCommand(
ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
ChildProcess.make({
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve `.cmd` shims on PATH.
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
}),
})`bun tsdown`,
);
const webDist = path.join(repoRoot, "apps/web/dist");
@@ -203,8 +203,10 @@ const publishCmd = Command.make(
}
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.gen(function* () {
// Resolve catalog dependencies before any file mutations. If this throws,
// acquire fails and no release hook runs, so filesystem must still be untouched.
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg: PackageJson = {
name: serverPackageJson.name,
@@ -214,22 +216,25 @@ const publishCmd = Command.make(
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
dependencies: resolveCatalogDependencies(
serverPackageJson.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server",
),
overrides: resolveCatalogDependencies(
rootPackageJson.overrides,
rootPackageJson.workspaces.catalog,
"apps/server",
),
dependencies: serverPackageJson.dependencies,
overrides: rootPackageJson.overrides,
};
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
pkg.overrides = resolveCatalogDependencies(
pkg.overrides,
rootPackageJson.workspaces.catalog,
"root overrides",
);
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] Prepared package.json for publish");
yield* Effect.log("[cli] Resolved package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
@@ -1,435 +0,0 @@
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
@@ -1,25 +0,0 @@
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 type { ServerConfigShape } from "../../config.ts";
import { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
@@ -10,10 +10,8 @@ import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Lay
import {
AuthControlPlane,
AuthControlPlaneError,
DEFAULT_SESSION_SUBJECT,
} from "../Services/AuthControlPlane.ts";
import type {
AuthControlPlaneShape,
DEFAULT_SESSION_SUBJECT,
IssuedBearerSession,
IssuedPairingLink,
} from "../Services/AuthControlPlane.ts";
@@ -5,7 +5,7 @@ import type {
AuthSessionId,
} from "@t3tools/contracts";
import { Data, DateTime, Duration, Effect, Context } from "effect";
import type { SessionRole } from "./SessionCredentialService.ts";
import { SessionRole } from "./SessionCredentialService";
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { deriveAuthClientMetadata } from "./utils.ts";
import { deriveAuthClientMetadata } from "./utils";
describe("deriveAuthClientMetadata", () => {
it("labels Electron user agents as Electron instead of Chrome", () => {
+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.ts";
import packageJson from "../package.json" with { type: "json" };
import { cli } from "./cli";
import { version } from "../package.json" with { type: "json" };
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
Command.run(cli, { version: packageJson.version }).pipe(
Command.run(cli, { 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.ts";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
import { assertNone, assertSome } from "@effect/vitest/utils";
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
@@ -19,8 +19,6 @@ 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;
@@ -247,7 +245,6 @@ 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;
+2 -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.ts";
import { resolveServerConfig } from "./cli.ts";
import { deriveServerPaths } from "./config";
import { resolveServerConfig } from "./cli";
it.layer(NodeServices.layer)("cli config resolution", (it) => {
const defaultObservabilityConfig = {
+11 -12
View File
@@ -40,31 +40,30 @@ import {
RuntimeMode,
type ServerConfigShape,
type StartupPresentation,
} from "./config.ts";
import { readBootstrapEnvelope } from "./bootstrap.ts";
import { expandHomePath, resolveBaseDir } from "./os-jank.ts";
import { runServer } from "./server.ts";
} from "./config";
import { readBootstrapEnvelope } from "./bootstrap";
import { expandHomePath, resolveBaseDir } from "./os-jank";
import { runServer } from "./server";
import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";
import {
formatIssuedPairingCredential,
formatIssuedSession,
formatPairingCredentialList,
formatSessionList,
} from "./cliAuthFormat.ts";
import { AuthControlPlane } from "./auth/Services/AuthControlPlane.ts";
import type { AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
} from "./cliAuthFormat";
import { AuthControlPlane, 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.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup.ts";
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup";
import {
clearPersistedServerRuntimeState,
readPersistedServerRuntimeState,
} from "./serverRuntimeState.ts";
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
} from "./serverRuntimeState";
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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 packageJson from "../../../package.json" with { type: "json" };
import { version } from "../../../package.json" with { type: "json" };
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
@@ -77,7 +77,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
os: platformOs(),
arch: platformArch(),
},
serverVersion: packageJson.version,
serverVersion: version,
capabilities: {
repositoryIdentity: true,
},
@@ -1,18 +1,23 @@
import { ClaudeSettings, ProviderInstanceId } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Schema } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { Effect, FileSystem, Layer, Path } from "effect";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { sanitizeThreadTitle } from "../Utils.ts";
import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const ClaudeTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-claude-text-generation-test-",
}).pipe(Layer.provideMerge(NodeServices.layer));
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-claude-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeClaudeBinary(dir: string) {
return Effect.gen(function* () {
@@ -46,10 +51,6 @@ function makeFakeClaudeBinary(dir: string) {
" exit 4",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_HOME_MUST_BE" ] && [ "$HOME" != "$T3_FAKE_CLAUDE_HOME_MUST_BE" ]; then',
' printf "%s\\n" "HOME was $HOME" >&2',
" exit 5",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
"fi",
@@ -71,26 +72,23 @@ function withFakeClaudeEnv<A, E, R>(
argsMustContain?: string;
argsMustNotContain?: string;
stdinMustContain?: string;
homeMustBe?: string;
claudeConfig?: Partial<ClaudeSettings>;
},
effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
effect: Effect.Effect<A, E, R>,
) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
const binDir = yield* makeFakeClaudeBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
const previousHomeMustBe = process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
const binDir = yield* makeFakeClaudeBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
yield* Effect.acquireRelease(
Effect.sync(() => {
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
@@ -123,65 +121,60 @@ function withFakeClaudeEnv<A, E, R>(
} else {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
}
});
if (input.homeMustBe !== undefined) {
process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = input.homeMustBe;
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
previousArgsMustContain,
previousArgsMustNotContain,
previousStdinMustContain,
};
}),
() => effect,
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
} else {
delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
} else {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDERR;
} else {
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
}
if (previous.previousArgsMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
}
if (previous.previousArgsMustNotContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
}),
() =>
Effect.sync(() => {
process.env.PATH = previousPath;
if (previousOutput === undefined) {
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
} else {
process.env.T3_FAKE_CLAUDE_OUTPUT = previousOutput;
}
if (previousExitCode === undefined) {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
} else {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previousExitCode;
}
if (previousStderr === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDERR;
} else {
process.env.T3_FAKE_CLAUDE_STDERR = previousStderr;
}
if (previousArgsMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previousArgsMustContain;
}
if (previousArgsMustNotContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previousArgsMustNotContain;
}
if (previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain;
}
if (previousHomeMustBe === undefined) {
delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
} else {
process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = previousHomeMustBe;
}
}),
);
const config = Schema.decodeSync(ClaudeSettings)(input.claudeConfig ?? {});
const textGeneration = yield* makeClaudeTextGeneration(config);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
);
}
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
@@ -197,23 +190,26 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
argsMustNotContain: "--effort",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/claude-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
...createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-haiku-4-5", [
{ id: "thinking", value: false },
{ id: "effort", value: "high" },
]),
},
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.subject).toBe("Add important change");
}),
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/claude-effect",
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",
},
},
});
expect(generated.subject).toBe("Add important change");
}),
),
);
@@ -228,25 +224,28 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
}),
argsMustContain: '--effort max --settings {"fastMode":true}',
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/claude-effect",
commitSummary: "Improve orchestration",
diffSummary: "1 file changed",
diffPatch: "diff --git a/README.md b/README.md",
modelSelection: {
...createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-opus-4-6", [
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
]),
},
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe("Improve orchestration flow");
}),
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/claude-effect",
commitSummary: "Improve orchestration",
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,
},
},
});
expect(generated.title).toBe("Improve orchestration flow");
}),
),
);
@@ -261,57 +260,27 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
}),
stdinMustContain: "You write concise thread titles for coding conversations.",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate reconnect failures after restarting the session.",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe(
sanitizeThreadTitle(
'"Reconnect failures after restart because the session state does not recover"',
),
);
}),
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate reconnect failures after restarting the session.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe(
sanitizeThreadTitle(
'"Reconnect failures after restart because the session state does not recover"',
),
);
}),
),
);
it.effect("runs Claude text generation with the configured Claude HOME", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const claudeHome = path.join(process.cwd(), ".claude-work-test");
return yield* withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: "Use Claude home",
},
}),
homeMustBe: claudeHome,
claudeConfig: { homePath: claudeHome },
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "thread title",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));
}),
);
}),
);
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
withFakeClaudeEnv(
{
@@ -321,19 +290,20 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
},
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe("New thread");
}),
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe("New thread");
}),
),
);
});
@@ -7,14 +7,15 @@
*
* @module ClaudeTextGeneration
*/
import { Effect, Option, Schema, Stream } from "effect";
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";
import { ClaudeModelSelection } from "@t3tools/contracts";
import { resolveApiModelId } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
@@ -28,17 +29,9 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import {
getModelSelectionStringOptionValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import {
getClaudeModelCapabilities,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeEffort,
} from "../../provider/Layers/ClaudeProvider.ts";
import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -50,12 +43,9 @@ const ClaudeOutputEnvelope = Schema.Struct({
structured_output: Schema.Unknown,
});
export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
claudeSettings: ClaudeSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const makeClaudeTextGeneration = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
const serverSettingsService = yield* Effect.service(ServerSettingsService);
const readStreamAsString = <E>(
operation: string,
@@ -91,32 +81,28 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
cwd: string;
prompt: string;
outputSchemaJson: S;
modelSelection: ModelSelection;
modelSelection: ClaudeModelSelection;
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
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 normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
...(fastMode ? { fastMode: true } : {}),
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
const command = ChildProcess.make(
claudeSettings.binaryPath || "claude",
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
@@ -124,13 +110,12 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
"--json-schema",
jsonSchemaStr,
"--model",
resolveClaudeApiModelId(modelSelection),
...(cliEffort ? ["--effort", cliEffort] : []),
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
env: claudeEnvironment,
cwd,
shell: process.platform === "win32",
stdin: {
@@ -231,6 +216,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
includeBranch: input.includeBranch === true,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateCommitMessage",
cwd: input.cwd,
@@ -259,6 +251,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generatePrContent",
cwd: input.cwd,
@@ -281,6 +280,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
attachments: input.attachments,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateBranchName",
cwd: input.cwd,
@@ -302,6 +308,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
attachments: input.attachments,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateThreadTitle",
cwd: input.cwd,
@@ -322,3 +335,5 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
generateThreadTitle,
} satisfies TextGenerationShape;
});
export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);
@@ -1,24 +1,29 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Result, Schema } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { Effect, FileSystem, Layer, Path, Result } from "effect";
import { expect } from "vitest";
import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
ProviderInstanceId.make("codex"),
"gpt-5.4-mini",
const DEFAULT_TEST_MODEL_SELECTION = {
provider: "codex" as const,
model: "gpt-5.4-mini",
};
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-codex-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
const CodexTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-codex-text-generation-test-",
}).pipe(Layer.provideMerge(NodeServices.layer));
function makeFakeCodexBinary(
dir: string,
input: {
@@ -156,16 +161,36 @@ function withFakeCodexEnv<A, E, R>(
stdinMustContain?: string;
stdinMustNotContain?: string;
},
effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
effect: Effect.Effect<A, E, R>,
) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
const config = Schema.decodeSync(CodexSettings)({ binaryPath: codexPath });
const textGeneration = yield* makeCodexTextGeneration(config);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: codexPath,
},
},
});
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
}),
() => effect,
({ serverSettings, previousBinaryPath }) =>
serverSettings
.updateSettings({
providers: {
codex: {
binaryPath: previousBinaryPath,
},
},
})
.pipe(Effect.asVoid),
);
}
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
@@ -179,21 +204,22 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
}),
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.subject.length).toBeLessThanOrEqual(72);
expect(generated.subject.endsWith(".")).toBe(false);
expect(generated.body).toBe("- added migration\n- updated tests");
expect(generated.branch).toBeUndefined();
}),
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.subject.length).toBeLessThanOrEqual(72);
expect(generated.subject.endsWith(".")).toBe(false);
expect(generated.body).toBe("- added migration\n- updated tests");
expect(generated.branch).toBeUndefined();
}),
),
);
@@ -210,17 +236,24 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
requireReasoningEffort: "xhigh",
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
(textGeneration) =>
textGeneration.generateCommitMessage({
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
{ id: "reasoningEffort", value: "xhigh" },
{ id: "fastMode", value: true },
]),
}),
modelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "xhigh",
fastMode: true,
},
},
});
}),
),
);
@@ -233,14 +266,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
}),
requireReasoningEffort: "low",
},
(textGeneration) =>
textGeneration.generateCommitMessage({
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
}),
});
}),
),
);
@@ -254,20 +290,21 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
}),
stdinMustContain: "branch must be a short semantic git branch fragment",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
includeBranch: true,
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.subject).toBe("Add important change");
expect(generated.branch).toBe("feature/fix/important-system-change");
}),
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
includeBranch: true,
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.subject).toBe("Add important change");
expect(generated.branch).toBe("feature/fix/important-system-change");
}),
),
);
@@ -279,22 +316,23 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/codex-effect",
commitSummary: "feat: improve orchestration flow",
diffSummary: "2 files changed",
diffPatch: "diff --git a/a.ts b/a.ts",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe("Improve orchestration flow");
expect(generated.body.startsWith("## Summary")).toBe(true);
expect(generated.body.endsWith("\n\n")).toBe(false);
}),
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/codex-effect",
commitSummary: "feat: improve orchestration flow",
diffSummary: "2 files changed",
diffPatch: "diff --git a/a.ts b/a.ts",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("Improve orchestration flow");
expect(generated.body.startsWith("## Summary")).toBe(true);
expect(generated.body.endsWith("\n\n")).toBe(false);
}),
),
);
@@ -306,16 +344,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
}),
stdinMustNotContain: "Image attachments supplied to the model",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Please update session handling.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.branch).toBe("feat/session");
}),
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Please update session handling.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.branch).toBe("feat/session");
}),
),
);
@@ -327,16 +366,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate websocket reconnect regressions after a worktree restore.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
}),
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate websocket reconnect regressions after a worktree restore.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
}),
),
);
@@ -347,16 +387,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
title: ' """ """ ',
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe("New thread");
}),
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("New thread");
}),
),
);
@@ -367,16 +408,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
title: ` "' hello world '" `,
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe("hello world");
}),
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("hello world");
}),
),
);
@@ -388,16 +430,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
}),
stdinMustNotContain: "Attachment metadata:",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Fix timeout behavior.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.branch).toBe("fix/session-timeout");
}),
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Fix timeout behavior.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.branch).toBe("fix/session-timeout");
}),
),
);
@@ -410,17 +453,56 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
requireImage: true,
stdinMustContain: "Attachment metadata:",
},
(textGeneration) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
const generated = yield* textGeneration.generateBranchName({
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
});
expect(generated.branch).toBe("fix/ui-regression");
}),
),
);
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
branch: "fix/ui-regression",
}),
requireImage: true,
},
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
@@ -433,59 +515,20 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
sizeBytes: 5,
},
],
});
expect(generated.branch).toBe("fix/ui-regression");
}),
),
);
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
branch: "fix/ui-regression",
}),
requireImage: true,
},
(textGeneration) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
const generated = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(
Effect.tap(() =>
fs.stat(imagePath).pipe(
Effect.map((fileInfo) => {
expect(fileInfo.type).toBe("File");
}),
),
})
.pipe(
Effect.tap(() =>
fs.stat(imagePath).pipe(
Effect.map((fileInfo) => {
expect(fileInfo.type).toBe("File");
}),
),
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
);
),
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
);
expect(generated.branch).toBe("fix/ui-regression");
}),
expect(generated.branch).toBe("fix/ui-regression");
}),
),
);
@@ -497,38 +540,38 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
}),
requireImage: true,
},
(textGeneration) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
const result = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: missingAttachmentId,
name: "outside.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(Effect.result);
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: missingAttachmentId,
name: "outside.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(Effect.result);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("missing --image input");
}
}),
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("missing --image input");
}
}),
),
);
@@ -541,22 +584,23 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
title: "This is not a branch payload",
}),
},
(textGeneration) =>
Effect.gen(function* () {
const result = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix websocket reconnect flake",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("Codex returned invalid structured output");
}
}),
const result = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix websocket reconnect flake",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("Codex returned invalid structured output");
}
}),
),
);
@@ -567,26 +611,27 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
exitCode: 1,
stderr: "codex execution failed",
},
(textGeneration) =>
Effect.gen(function* () {
const result = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-error",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain(
"Codex CLI command failed: codex execution failed",
);
}
}),
const result = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-error",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain(
"Codex CLI command failed: codex execution failed",
);
}
}),
),
);
});
@@ -1,17 +1,19 @@
import { Effect, FileSystem, Option, Path, Random, Schema, Scope, Stream } from "effect";
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { type CodexSettings, type ModelSelection } from "@t3tools/contracts";
import { CodexModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import { TextGenerationError } from "@t3tools/contracts";
import {
type BranchNameGenerationInput,
type ThreadTitleGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
@@ -26,25 +28,18 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
/**
* Build a Codex text-generation closure bound to a specific `CodexSettings`
* payload. See `makeCodexAdapter` for the overall per-instance rationale.
*/
export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* (
codexConfig: CodexSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const makeCodexTextGeneration = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const serverSettingsService = yield* Effect.service(ServerSettingsService);
type MaterializedImageAttachments = {
readonly imagePaths: ReadonlyArray<string>;
@@ -70,23 +65,21 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
prefix: string,
content: string,
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
return Effect.gen(function* () {
const tempFileId = yield* Random.nextUUIDv4;
return yield* fileSystem
.makeTempFileScoped({
prefix: `t3code-${prefix}-${process.pid}-${tempFileId}.tmp`,
})
.pipe(Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)));
}).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file`,
cause,
}),
),
);
return fileSystem
.makeTempFileScoped({
prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
})
.pipe(
Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file`,
cause,
}),
),
);
};
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
@@ -147,7 +140,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
outputSchemaJson: S;
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
modelSelection: ModelSelection;
modelSelection: CodexModelSelection;
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const schemaPath = yield* writeTempFile(
operation,
@@ -156,25 +149,30 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const codexSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.codex,
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
modelSelection.options,
);
const reasoningEffort =
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexConfig.binaryPath || "codex",
codexSettings?.binaryPath || "codex",
[
"exec",
"--ephemeral",
"--skip-git-repo-check",
"-s",
"read-only",
"--model",
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true
? ["--config", `service_tier="fast"`]
: []),
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
"--output-schema",
schemaPath,
"--output-last-message",
@@ -184,8 +182,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
],
{
env: {
...environment,
...(codexConfig.homePath ? { CODEX_HOME: expandHomePath(codexConfig.homePath) } : {}),
...process.env,
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
cwd,
shell: process.platform === "win32",
@@ -285,6 +283,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
includeBranch: input.includeBranch === true,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateCommitMessage",
cwd: input.cwd,
@@ -313,6 +318,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generatePrContent",
cwd: input.cwd,
@@ -339,6 +351,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
attachments: input.attachments,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateBranchName",
cwd: input.cwd,
@@ -365,6 +384,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
attachments: input.attachments,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateThreadTitle",
cwd: input.cwd,
@@ -387,6 +413,4 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
} satisfies TextGenerationShape;
});
// NOTE: `CodexTextGenerationLive` (the singleton Layer) has been removed.
// `makeCodexTextGeneration(codexConfig)` is now invoked directly by
// `CodexDriver.create()` for each configured instance.
export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);
@@ -1,264 +0,0 @@
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, Schema } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { makeCursorTextGeneration } from "./CursorTextGeneration.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 = ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-text-generation-test-",
}).pipe(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>,
effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
) {
return Effect.gen(function* () {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
rmSync(tempDir, { recursive: true, force: true });
}),
);
const agentPath = makeAcpAgentWrapper(tempDir, env);
const config = Schema.decodeSync(CursorSettings)({ binaryPath: agentPath });
const textGeneration = yield* makeCursorTextGeneration(config);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
}
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",
}),
},
(textGeneration) =>
Effect.gen(function* () {
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(ProviderInstanceId.make("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.',
},
(textGeneration) =>
Effect.gen(function* () {
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: {
instanceId: ProviderInstanceId.make("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."',
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Fix the reconnect spinner after a resumed session.",
modelSelection: {
instanceId: ProviderInstanceId.make("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: "",
}),
},
(textGeneration) =>
Effect.gen(function* () {
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: {
instanceId: ProviderInstanceId.make("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 });
}),
);
});
});
@@ -1,283 +0,0 @@
import { Effect, Option, Ref, Schema } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import {
type ThreadTitleGenerationResult,
type TextGenerationShape,
} 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";
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"
);
}
/**
* Build a Cursor text-generation closure bound to a specific `CursorSettings`
* payload. See `makeCodexAdapter` for the overall per-instance rationale.
*/
export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runCursorJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
outputSchemaJson,
modelSelection,
}: {
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
cwd: string;
prompt: string;
outputSchemaJson: S;
modelSelection: ModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const outputRef = yield* Ref.make("");
const runtime = yield* makeCursorAcpRuntime({
cursorSettings,
environment,
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,
});
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,
});
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,
});
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,
});
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;
});
// NOTE: `CursorTextGenerationLive` (the singleton Layer) has been removed.
// `makeCursorTextGeneration(cursorConfig)` is now invoked directly by
// `CursorDriver.create()` so each provider instance owns its own closure.
+1 -1
View File
@@ -6,7 +6,7 @@ vi.mock("../../processRunner", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner.ts";
import { runProcess } from "../../processRunner";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { GitHubCliLive } from "./GitHubCli.ts";
+1 -1
View File
@@ -1,7 +1,7 @@
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import { runProcess } from "../../processRunner.ts";
import { runProcess } from "../../processRunner";
import { GitHubCliError } from "@t3tools/contracts";
import {
GitHubCli,
+1 -2
View File
@@ -38,8 +38,7 @@ import {
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
import type { GitStatusDetails } from "../Services/GitCore.ts";
import { GitCore, 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";
@@ -1,346 +0,0 @@
import { OpenCodeSettings, ProviderInstanceId } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Duration, Effect, Layer, Schema } from "effect";
import { TestClock } from "effect/testing";
import { NetService } from "@t3tools/shared/Net";
import { beforeEach, expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../../provider/opencodeRuntime.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { makeOpenCodeTextGeneration } 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 = {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
};
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
const OpenCodeTextGenerationTestLayer = Layer.succeed(
OpenCodeRuntime,
OpenCodeRuntimeTestDouble,
).pipe(
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-test-",
}),
),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
);
const OpenCodeTextGenerationExistingServerTestLayer = Layer.succeed(
OpenCodeRuntime,
OpenCodeRuntimeTestDouble,
).pipe(
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-existing-server-test-",
}),
),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
);
const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
binaryPath: "fake-opencode",
});
const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
binaryPath: "fake-opencode",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
});
function withOpenCodeTextGeneration<A, E, R>(
settings: OpenCodeSettings,
effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
) {
return Effect.gen(function* () {
const textGeneration = yield* makeOpenCodeTextGeneration(settings);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
}
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", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
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", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
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", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
runtimeMock.state.promptResult = { data: {} };
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", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
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 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", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
info: {
error: {
name: "StructuredOutputError",
data: {
message: "Model did not produce structured output",
retries: 2,
},
},
},
},
};
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", () =>
withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
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())),
);
},
);
@@ -1,464 +0,0 @@
import { Effect, Exit, Fiber, Schema, Scope } from "effect";
import * as Semaphore from "effect/Semaphore";
import {
TextGenerationError,
type ChatAttachment,
type ModelSelection,
type OpenCodeSettings,
} 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 {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import { type TextGenerationShape } 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;
}
export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration")(function* (
openCodeSettings: OpenCodeSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const serverConfig = yield* ServerConfig;
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,
environment,
})
.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: ModelSelection;
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 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,
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.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 =
openCodeSettings.serverUrl.length > 0
? yield* runAgainstServer({ url: openCodeSettings.serverUrl })
: yield* Effect.acquireUseRelease(
acquireSharedServer({
binaryPath: openCodeSettings.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) {
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) {
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) {
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) {
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;
});
@@ -0,0 +1,73 @@
/**
* RoutingTextGeneration – Dispatches text generation requests to either the
* Codex CLI or Claude CLI implementation based on the provider in each
* request input.
*
* When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to
* the Claude layer; for any other value (including the default `undefined`) it
* falls through to the Codex layer.
*
* @module RoutingTextGeneration
*/
import { Effect, Layer, Context } from "effect";
import {
TextGeneration,
type TextGenerationProvider,
type TextGenerationShape,
} from "../Services/TextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
// ---------------------------------------------------------------------------
// Internal service tags so both concrete layers can coexist.
// ---------------------------------------------------------------------------
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
) {}
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
// ---------------------------------------------------------------------------
// Routing implementation
// ---------------------------------------------------------------------------
const makeRoutingTextGeneration = Effect.gen(function* () {
const codex = yield* CodexTextGen;
const claude = yield* ClaudeTextGen;
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
provider === "claudeAgent" ? claude : codex;
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),
} satisfies TextGenerationShape;
});
const InternalCodexLayer = Layer.effect(
CodexTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CodexTextGenerationLive));
const InternalClaudeLayer = Layer.effect(
ClaudeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(ClaudeTextGenerationLive));
export const RoutingTextGenerationLive = Layer.effect(
TextGeneration,
makeRoutingTextGeneration,
).pipe(Layer.provide(InternalCodexLayer), Layer.provide(InternalClaudeLayer));
@@ -1,117 +0,0 @@
import { it } from "@effect/vitest";
import { Effect, PubSub, Result, Stream } from "effect";
import { describe, expect } from "vitest";
import { ProviderInstanceId } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import type { ProviderInstance } from "../../provider/ProviderDriver.ts";
import type { ProviderInstanceRegistryShape } from "../../provider/Services/ProviderInstanceRegistry.ts";
import type { TextGenerationShape } from "../Services/TextGeneration.ts";
import { makeTextGenerationFromRegistry } from "./TextGenerationLive.ts";
const makeStubTextGeneration = (overrides: Partial<TextGenerationShape>): TextGenerationShape => ({
generateCommitMessage: () =>
Effect.die("generateCommitMessage stub not configured for this test"),
generatePrContent: () => Effect.die("generatePrContent stub not configured for this test"),
generateBranchName: () => Effect.die("generateBranchName stub not configured for this test"),
generateThreadTitle: () => Effect.die("generateThreadTitle stub not configured for this test"),
...overrides,
});
const makeStubInstance = (
instanceId: ProviderInstanceId,
textGeneration: TextGenerationShape,
): ProviderInstance =>
({
instanceId,
driverKind: instanceId as unknown as ProviderInstance["driverKind"],
continuationIdentity: {
driverKind: instanceId as unknown as ProviderInstance["driverKind"],
continuationKey: `${instanceId}:test`,
},
displayName: undefined,
enabled: true,
snapshot: {} as ProviderInstance["snapshot"],
adapter: {} as ProviderInstance["adapter"],
textGeneration,
}) satisfies ProviderInstance;
const makeStubRegistry = (
instances: ReadonlyArray<ProviderInstance>,
): ProviderInstanceRegistryShape => {
const byId = new Map(instances.map((instance) => [instance.instanceId, instance] as const));
return {
getInstance: (id) => Effect.succeed(byId.get(id)),
listInstances: Effect.succeed(instances),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
// Tests never drive changes through this stub; acquire a throwaway
// subscription on an unused PubSub so the shape is satisfied.
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
PubSub.subscribe(pubsub),
),
};
};
describe("makeTextGenerationFromRegistry", () => {
it.effect("delegates to the matching instance's textGeneration closure", () =>
Effect.gen(function* () {
const personalId = ProviderInstanceId.make("codex_personal");
const personalCalls: string[] = [];
const personal = makeStubInstance(
personalId,
makeStubTextGeneration({
generateBranchName: (input) => {
personalCalls.push(input.message);
return Effect.succeed({ branch: "personal-branch" });
},
}),
);
const workId = ProviderInstanceId.make("codex_work");
const work = makeStubInstance(
workId,
makeStubTextGeneration({
generateBranchName: () => Effect.succeed({ branch: "work-branch" }),
}),
);
const tg = makeTextGenerationFromRegistry(makeStubRegistry([personal, work]));
const result = yield* tg.generateBranchName({
cwd: process.cwd(),
message: "Refactor the routing layer",
modelSelection: createModelSelection(ProviderInstanceId.make("codex_personal"), "gpt-5"),
});
expect(result.branch).toBe("personal-branch");
expect(personalCalls).toEqual(["Refactor the routing layer"]);
}),
);
it.effect("fails with TextGenerationError when the instance is unknown", () =>
Effect.gen(function* () {
const tg = makeTextGenerationFromRegistry(makeStubRegistry([]));
const result = yield* tg
.generateBranchName({
cwd: process.cwd(),
message: "anything",
modelSelection: createModelSelection(
ProviderInstanceId.make("missing_instance"),
"gpt-5",
),
})
.pipe(Effect.result);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure._tag).toBe("TextGenerationError");
expect(result.failure.operation).toBe("generateBranchName");
expect(result.failure.detail).toContain("missing_instance");
}
}),
);
});
@@ -1,101 +0,0 @@
/**
* TextGenerationLive — registry-backed implementation of the `TextGeneration`
* service tag.
*
* The `TextGeneration` tag is kept as a thin facade over
* `ProviderInstanceRegistry`. Every op pulls `modelSelection.instanceId`,
* looks up the matching `ProviderInstance`, and delegates to that instance's
* own `textGeneration` closure (built by its driver's `create()`).
*
* There is deliberately no per-driver dispatch here — the registry already
* knows which driver backs each instance, and each `ProviderInstance`
* carries the fully-bound `TextGenerationShape` produced by its driver.
* That means:
*
* - Multiple instances of the same driver (e.g. `codex_personal`,
* `codex_work`) each get their own text-generation closure bound to
* their own settings — the routing is by instance, not by driver.
* - Unknown or disabled instances surface a `TextGenerationError` with
* the missing `instanceId`, instead of silently falling back to a
* default.
*
* This replaces the old `RoutingTextGenerationLive`, which tried to route
* by driver-kind and misused `modelSelection.instanceId` as a driver-id
* literal.
*
* @module git/Layers/TextGenerationLive
*/
import { Effect, Layer } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
import type { ProviderInstanceId } from "@t3tools/contracts";
import {
ProviderInstanceRegistry,
type ProviderInstanceRegistryShape,
} from "../../provider/Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../../provider/ProviderDriver.ts";
import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";
type TextGenerationOp =
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
const resolveInstance = (
registry: ProviderInstanceRegistryShape,
operation: TextGenerationOp,
instanceId: ProviderInstanceId,
): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance
? Effect.succeed(instance.textGeneration)
: Effect.fail(
new TextGenerationError({
operation,
detail: `No provider instance registered for id '${instanceId}'.`,
}),
),
),
);
/**
* Build a `TextGenerationShape` that routes every call through the
* registry. Exposed separately from the Layer so tests can construct it
* against a stub registry without layering gymnastics.
*/
export const makeTextGenerationFromRegistry = (
registry: ProviderInstanceRegistryShape,
): TextGenerationShape => ({
generateCommitMessage: (input) =>
resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generateCommitMessage(input)),
),
generatePrContent: (input) =>
resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generatePrContent(input)),
),
generateBranchName: (input) =>
resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generateBranchName(input)),
),
generateThreadTitle: (input) =>
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generateThreadTitle(input)),
),
});
/**
* `TextGeneration` Layer wired to the `ProviderInstanceRegistry`. The rest
* of the server keeps using `yield* TextGeneration` — only the underlying
* wiring changed from kind-based routing to instance-based routing.
*/
export const TextGenerationLive = Layer.effect(
TextGeneration,
Effect.gen(function* () {
const registry = yield* ProviderInstanceRegistry;
return makeTextGenerationFromRegistry(registry);
}),
);
+1 -1
View File
@@ -8,7 +8,7 @@
import { Context } from "effect";
import type { Effect } from "effect";
import type { ProcessRunResult } from "../../processRunner.ts";
import type { ProcessRunResult } from "../../processRunner";
import type { GitHubCliError } from "@t3tools/contracts";
export interface GitHubPullRequestSummary {
@@ -13,7 +13,7 @@ import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import type { TextGenerationError } from "@t3tools/contracts";
/** Providers that support git text generation (commit messages, PR content, branch names). */
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
export type TextGenerationProvider = "codex" | "claudeAgent";
export interface CommitMessageGenerationInput {
cwd: string;
-48
View File
@@ -30,54 +30,6 @@ export function limitSection(value: string, maxChars: number): string {
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
+4 -4
View File
@@ -15,12 +15,12 @@ import {
ATTACHMENTS_ROUTE_PREFIX,
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import { resolveAttachmentPathById } from "./attachmentStore.ts";
import { resolveStaticDir, ServerConfig } from "./config.ts";
} from "./attachmentPaths";
import { resolveAttachmentPathById } from "./attachmentStore";
import { resolveStaticDir, ServerConfig } from "./config";
import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
import { respondToAuthError } from "./auth/http.ts";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
+17 -5
View File
@@ -3,7 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import { ServerConfig } from "./config.ts";
import { ServerConfig } from "./config";
import {
DEFAULT_KEYBINDINGS,
@@ -13,7 +13,7 @@ import {
compileResolvedKeybindingRule,
compileResolvedKeybindingsConfig,
parseKeybindingShortcut,
} from "./keybindings.ts";
} from "./keybindings";
import { KeybindingsConfigError } from "@t3tools/contracts";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
@@ -188,13 +188,25 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const),
);
assert.equal(defaultsByCommand.get("workspace.pane.splitRight"), "mod+d");
assert.equal(defaultsByCommand.get("workspace.pane.splitDown"), "mod+shift+d");
assert.equal(defaultsByCommand.get("workspace.pane.close"), "mod+w");
assert.equal(defaultsByCommand.get("workspace.focus.previous"), "mod+[");
assert.equal(defaultsByCommand.get("workspace.focus.next"), "mod+]");
assert.equal(defaultsByCommand.get("workspace.focus.left"), "mod+alt+arrowleft");
assert.equal(defaultsByCommand.get("workspace.focus.right"), "mod+alt+arrowright");
assert.equal(defaultsByCommand.get("workspace.focus.up"), "mod+alt+arrowup");
assert.equal(defaultsByCommand.get("workspace.focus.down"), "mod+alt+arrowdown");
assert.equal(defaultsByCommand.get("workspace.pane.toggleZoom"), "mod+shift+enter");
assert.equal(defaultsByCommand.get("workspace.pane.resizeLeft"), "mod+ctrl+arrowleft");
assert.equal(defaultsByCommand.get("workspace.pane.resizeRight"), "mod+ctrl+arrowright");
assert.equal(defaultsByCommand.get("workspace.pane.resizeUp"), "mod+ctrl+arrowup");
assert.equal(defaultsByCommand.get("workspace.pane.resizeDown"), "mod+ctrl+arrowdown");
assert.equal(defaultsByCommand.get("workspace.pane.equalize"), "mod+ctrl+=");
assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+[");
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("modelPicker.jump.9"), "mod+9");
}),
);
+24 -20
View File
@@ -13,14 +13,13 @@ import {
KeybindingShortcut,
KeybindingWhenNode,
MAX_KEYBINDINGS_COUNT,
MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
MAX_WHEN_EXPRESSION_DEPTH,
ResolvedKeybindingRule,
ResolvedKeybindingsConfig,
THREAD_JUMP_KEYBINDING_COMMANDS,
type ServerConfigIssue,
} from "@t3tools/contracts";
import type { Mutable } from "effect/Types";
import { Mutable } from "effect/Types";
import {
Array,
Cache,
@@ -45,8 +44,7 @@ import {
Stream,
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config.ts";
import { writeFileStringAtomically } from "./atomicWrite.ts";
import { ServerConfig } from "./config";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
type WhenToken =
@@ -62,12 +60,26 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ 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+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+d", command: "workspace.pane.splitRight", when: "!terminalFocus" },
{ key: "mod+shift+d", command: "workspace.pane.splitDown", when: "!terminalFocus" },
{ key: "mod+w", command: "workspace.pane.close", when: "!terminalFocus" },
{ key: "mod+[", command: "workspace.focus.previous" },
{ key: "mod+]", command: "workspace.focus.next" },
{ key: "mod+alt+arrowup", command: "workspace.focus.up" },
{ key: "mod+alt+arrowdown", command: "workspace.focus.down" },
{ key: "mod+alt+arrowleft", command: "workspace.focus.left" },
{ key: "mod+alt+arrowright", command: "workspace.focus.right" },
{ key: "mod+shift+enter", command: "workspace.pane.toggleZoom" },
{ key: "mod+ctrl+arrowup", command: "workspace.pane.resizeUp" },
{ key: "mod+ctrl+arrowdown", command: "workspace.pane.resizeDown" },
{ key: "mod+ctrl+arrowleft", command: "workspace.pane.resizeLeft" },
{ key: "mod+ctrl+arrowright", command: "workspace.pane.resizeRight" },
{ key: "mod+ctrl+=", command: "workspace.pane.equalize" },
{ key: "mod+alt+d", command: "diff.toggle", 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" },
{ key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" },
{ key: "mod+shift+[", command: "thread.previous" },
{ key: "mod+shift+]", command: "thread.next" },
@@ -75,11 +87,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
key: `mod+${index + 1}`,
command,
})),
...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
key: `mod+${index + 1}`,
command,
when: "modelPickerOpen",
})),
];
function normalizeKeyToken(token: string): string {
@@ -671,17 +678,14 @@ const makeKeybindings = Effect.gen(function* () {
});
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.flatMap((encoded) =>
writeFileStringAtomically({
filePath: keybindingsConfigPath,
contents: encoded,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
),
),
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
@@ -1,8 +1,7 @@
import type * as Exit from "effect/Exit";
import { Effect, Option, Tracer } from "effect";
import { spanToTraceRecord } from "./TraceRecord.ts";
import type { EffectTraceRecord } from "./TraceRecord.ts";
import { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts";
import { makeTraceSink, type TraceSink } from "./TraceSink.ts";
export interface LocalFileTracerOptions {
@@ -28,16 +27,12 @@ class LocalFileSpan implements Tracer.Span {
status: Tracer.SpanStatus;
attributes: Map<string, unknown>;
events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
private readonly delegate: Tracer.Span;
private readonly push: (record: EffectTraceRecord) => void;
constructor(
options: Parameters<Tracer.Tracer["span"]>[0],
delegate: Tracer.Span,
push: (record: EffectTraceRecord) => void,
private readonly delegate: Tracer.Span,
private readonly push: (record: EffectTraceRecord) => void,
) {
this.delegate = delegate;
this.push = push;
this.name = delegate.name;
this.spanId = delegate.spanId;
this.traceId = delegate.traceId;
@@ -1,5 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import { ProviderDriverKind } from "@t3tools/contracts";
import { Effect, Metric } from "effect";
import { withMetrics } from "./Metrics.ts";
@@ -76,11 +75,10 @@ describe("withMetrics", () => {
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_lazy_total");
const timer = Metric.timer("with_metrics_lazy_duration");
let provider = ProviderDriverKind.make("unknown");
const lazyInittedProvider = ProviderDriverKind.make("codex");
let provider = "unknown";
yield* Effect.sync(() => {
provider = lazyInittedProvider;
provider = "codex";
}).pipe(
withMetrics({
counter,
@@ -95,7 +93,7 @@ describe("withMetrics", () => {
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
provider: lazyInittedProvider,
provider: "codex",
operation: "lazy",
outcome: "success",
}),
@@ -103,7 +101,7 @@ describe("withMetrics", () => {
);
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
provider: lazyInittedProvider,
provider: "codex",
operation: "lazy",
}),
true,
+1 -1
View File
@@ -8,7 +8,7 @@ import {
launchDetached,
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open.ts";
} from "./open";
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
+112 -2
View File
@@ -7,9 +7,10 @@
* @module Open
*/
import { spawn } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
import { Context, Effect, Layer } from "effect";
// ==============================
@@ -17,7 +18,6 @@ import { Context, Effect, Layer } from "effect";
// ==============================
export { OpenError };
export { isCommandAvailable } from "@t3tools/shared/shell";
export interface OpenInEditorInput {
readonly cwd: string;
@@ -29,6 +29,11 @@ interface EditorLaunch {
readonly args: ReadonlyArray<string>;
}
interface CommandAvailabilityOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
}
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
function parseTargetPathAndPosition(target: string): {
@@ -101,6 +106,111 @@ function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [];
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
export function isCommandAvailable(
command: string,
options: CommandAvailabilityOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
);
}
const pathValue = resolvePathEnvironmentVariable(env);
if (pathValue.length === 0) return false;
const pathEntries = pathValue
.split(resolvePathDelimiter(platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
return true;
}
}
}
return false;
}
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
@@ -3,12 +3,7 @@ import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import {
ProviderDriverKind,
ProviderRuntimeEvent,
ProviderSession,
ProviderInstanceId,
} from "@t3tools/contracts";
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -55,7 +50,7 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderDriverKind;
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -69,7 +64,7 @@ function createProviderServiceHarness(
cwd: string,
hasSession = true,
sessionCwd = cwd,
providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"),
providerName: ProviderSession["provider"] = "codex",
) {
const now = new Date().toISOString();
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
@@ -102,17 +97,6 @@ function createProviderServiceHarness(
stopSession: () => unsupported(),
listSessions,
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
getInstanceInfo: (instanceId) =>
Effect.succeed({
instanceId,
driverKind: ProviderDriverKind.make(providerName),
displayName: undefined,
enabled: true,
continuationIdentity: {
driverKind: ProviderDriverKind.make(providerName),
continuationKey: `${providerName}:instance:${instanceId}`,
},
}),
rollbackConversation,
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
@@ -259,7 +243,7 @@ describe("CheckpointReactor", () => {
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: ProviderDriverKind;
readonly providerName?: ProviderKind;
readonly gitStatusRefreshCalls?: Array<string>;
}) {
const cwd = createGitRepository();
@@ -268,7 +252,7 @@ describe("CheckpointReactor", () => {
cwd,
options?.hasSession ?? true,
options?.providerSessionCwd ?? cwd,
options?.providerName ?? ProviderDriverKind.make("codex"),
options?.providerName ?? "codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
@@ -331,7 +315,7 @@ describe("CheckpointReactor", () => {
title: "Test Project",
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -345,7 +329,7 @@ describe("CheckpointReactor", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -412,7 +396,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-1"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -427,7 +411,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-1"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -473,7 +457,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-refresh-local-status"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-refresh-local-status"),
@@ -510,7 +494,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-main"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -526,7 +510,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-aux"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -542,7 +526,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-main"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -560,7 +544,7 @@ describe("CheckpointReactor", () => {
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: ProviderDriverKind.make("claudeAgent"),
providerName: "claudeAgent",
});
const createdAt = new Date().toISOString();
@@ -585,7 +569,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-claude-1"),
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-claude-1"),
@@ -599,7 +583,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-claude-1"),
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-claude-1"),
@@ -643,7 +627,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-missing-baseline"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -732,7 +716,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -778,7 +762,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "checkpoint.captured",
eventId: EventId.make("evt-checkpoint-captured-3"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -828,7 +812,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-runtime-capture-failure"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -839,7 +823,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-after-runtime-failure"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -934,7 +918,7 @@ describe("CheckpointReactor", () => {
});
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") });
const harness = await createHarness({ providerName: "claudeAgent" });
const createdAt = new Date().toISOString();
await Effect.runPromise(
@@ -21,8 +21,8 @@ import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import type { OrchestrationDispatchError } from "../Errors.ts";
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import { OrchestrationDispatchError } from "../Errors.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
@@ -7,7 +7,6 @@ import {
ThreadId,
TurnId,
type OrchestrationEvent,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
import { describe, expect, it } from "vitest";
@@ -105,7 +104,7 @@ describe("OrchestrationEngine", () => {
title: "Bootstrap Project",
workspaceRoot: "/tmp/project-bootstrap",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex" as const,
model: "gpt-5-codex",
},
scripts: [],
@@ -120,7 +119,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-bootstrap"),
title: "Bootstrap Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex" as const,
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -199,7 +198,7 @@ describe("OrchestrationEngine", () => {
title: "Project 1",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -213,7 +212,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -259,7 +258,7 @@ describe("OrchestrationEngine", () => {
title: "Project Archive",
workspaceRoot: "/tmp/project-archive",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -273,7 +272,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-archive"),
title: "Archive me",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -326,7 +325,7 @@ describe("OrchestrationEngine", () => {
title: "Replay Project",
workspaceRoot: "/tmp/project-replay",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -340,7 +339,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-replay"),
title: "replay",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -384,7 +383,7 @@ describe("OrchestrationEngine", () => {
title: "Stream Project",
workspaceRoot: "/tmp/project-stream",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -408,7 +407,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-stream"),
title: "domain-stream",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -445,7 +444,7 @@ describe("OrchestrationEngine", () => {
title: "Ack Project",
workspaceRoot: "/tmp/project-ack",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -460,7 +459,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-ack"),
title: "Ack Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -497,7 +496,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-missing"),
title: "Missing Project Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -534,7 +533,7 @@ describe("OrchestrationEngine", () => {
title: "Turn Diff Project",
workspaceRoot: "/tmp/project-turn-diff",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -548,7 +547,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -653,7 +652,7 @@ describe("OrchestrationEngine", () => {
title: "Flaky Project",
workspaceRoot: "/tmp/project-flaky",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -669,7 +668,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -689,7 +688,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -748,7 +747,7 @@ describe("OrchestrationEngine", () => {
title: "Atomic Project",
workspaceRoot: "/tmp/project-atomic",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -762,7 +761,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-atomic"),
title: "atomic",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -891,7 +890,7 @@ describe("OrchestrationEngine", () => {
title: "Sync Project",
workspaceRoot: "/tmp/project-sync",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -905,7 +904,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-sync"),
title: "sync-before",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -976,7 +975,7 @@ describe("OrchestrationEngine", () => {
title: "Duplicate Project",
workspaceRoot: "/tmp/project-duplicate",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -991,7 +990,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -1011,7 +1010,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -4,7 +4,6 @@ import { afterEach, describe, expect, it } from "vitest";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
@@ -18,7 +17,7 @@ describe("OrchestrationReactor", () => {
runtime = null;
});
it("starts provider ingestion, provider command, checkpoint, and thread deletion reactors", async () => {
it("starts provider ingestion, provider command, and checkpoint reactors", async () => {
const started: string[] = [];
runtime = ManagedRuntime.make(
@@ -50,19 +49,10 @@ describe("OrchestrationReactor", () => {
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ThreadDeletionReactor, {
start: () => {
started.push("thread-deletion-reactor");
return Effect.void;
},
drain: Effect.void,
}),
),
),
);
const reactor = await runtime!.runPromise(Effect.service(OrchestrationReactor));
const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor));
const scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
@@ -70,7 +60,6 @@ describe("OrchestrationReactor", () => {
"provider-runtime-ingestion",
"provider-command-reactor",
"checkpoint-reactor",
"thread-deletion-reactor",
]);
await Effect.runPromise(Scope.close(scope, Exit.void));
@@ -7,19 +7,16 @@ import {
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
export const makeOrchestrationReactor = Effect.gen(function* () {
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
const providerCommandReactor = yield* ProviderCommandReactor;
const checkpointReactor = yield* CheckpointReactor;
const threadDeletionReactor = yield* ThreadDeletionReactor;
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
yield* providerRuntimeIngestion.start();
yield* providerCommandReactor.start();
yield* checkpointReactor.start();
yield* threadDeletionReactor.start();
});
return {
@@ -7,7 +7,6 @@ import {
ProjectId,
ThreadId,
TurnId,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
@@ -93,7 +92,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-1"),
title: "Thread 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -365,7 +364,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-clear-attachments"),
title: "Thread Clear Attachments",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -493,7 +492,7 @@ it.layer(
projectId: ProjectId.make("project-overwrite"),
title: "Thread Overwrite",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -641,7 +640,7 @@ it.layer(
projectId: ProjectId.make("project-rollback"),
title: "Thread Rollback",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -770,7 +769,7 @@ it.layer(
projectId: ProjectId.make("project-revert-files"),
title: "Thread Revert Files",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -978,7 +977,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
projectId: ProjectId.make("project-delete-files"),
title: "Thread Delete Files",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1141,7 +1140,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-a"),
title: "Thread A",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1268,7 +1267,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-empty"),
title: "Thread Empty",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1408,7 +1407,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-conflict"),
title: "Thread Conflict",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1552,7 +1551,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-stale-approval"),
title: "Thread Stale Approval",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1695,7 +1694,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-nonstale-approval"),
title: "Thread Non-Stale Approval",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1875,7 +1874,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-revert"),
title: "Thread Revert",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -2196,7 +2195,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
title: "Live Project",
workspaceRoot: "/tmp/project-live",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -2234,7 +2233,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
title: "Scripts Project",
workspaceRoot: "/tmp/project-scripts",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -2254,7 +2253,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
},
],
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5",
},
});
@@ -2273,7 +2272,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
{
scriptsJson:
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
defaultModelSelection: '{"instanceId":"codex","model":"gpt-5"}',
defaultModelSelection: '{"provider":"codex","model":"gpt-5"}',
},
]);
}),
@@ -945,7 +945,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
threadId: event.payload.threadId,
status: event.payload.session.status,
providerName: event.payload.session.providerName,
providerInstanceId: event.payload.session.providerInstanceId ?? null,
runtimeMode: event.payload.session.runtimeMode,
activeTurnId: event.payload.session.activeTurnId,
lastError: event.payload.session.lastError,
@@ -1285,14 +1284,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
return;
}
// Only approval-requested activities should create pending-approval
// rows. Other activity kinds that happen to carry a requestId
// (e.g. user-input.requested / user-input.resolved) must not
// pollute this projection — they have their own accounting via
// derivePendingUserInputCountFromActivities.
if (event.payload.activity.kind !== "approval.requested") {
return;
}
if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
return;
}
@@ -1,12 +1,4 @@
import {
CheckpointRef,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -260,7 +252,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
workspaceRoot: "/tmp/project-1",
repositoryIdentity: null,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
scripts: [
@@ -283,7 +275,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: "default",
@@ -371,7 +363,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
workspaceRoot: "/tmp/project-1",
repositoryIdentity: null,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
scripts: [
@@ -393,7 +385,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: "default",
@@ -195,7 +195,6 @@ function mapSessionRow(
threadId: row.threadId,
status: row.status,
providerName: row.providerName,
...(row.providerInstanceId !== null ? { providerInstanceId: row.providerInstanceId } : {}),
runtimeMode: row.runtimeMode,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
@@ -351,7 +350,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
status,
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
provider_session_id AS "providerSessionId",
provider_thread_id AS "providerThreadId",
runtime_mode AS "runtimeMode",
@@ -610,7 +608,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
status,
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
runtime_mode AS "runtimeMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
@@ -882,9 +879,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
threadId: row.threadId,
status: row.status,
providerName: row.providerName,
...(row.providerInstanceId !== null
? { providerInstanceId: row.providerInstanceId }
: {}),
runtimeMode: row.runtimeMode,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
File diff suppressed because it is too large. Load diff
@@ -4,7 +4,7 @@ import {
EventId,
type ModelSelection,
type OrchestrationEvent,
ProviderDriverKind,
ProviderKind,
type OrchestrationSession,
ThreadId,
type ProviderSession,
@@ -19,8 +19,7 @@ import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -77,21 +76,6 @@ const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const DEFAULT_THREAD_TITLE = "New thread";
export function providerErrorLabel(value: string | undefined): string {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? normalized : "unknown";
}
export function providerErrorLabelFromInstanceHint(input: {
readonly instanceId?: string | undefined;
readonly modelSelectionInstanceId?: string | undefined;
readonly sessionProvider?: string | undefined;
}): string {
return providerErrorLabel(
input.instanceId ?? input.modelSelectionInstanceId ?? input.sessionProvider,
);
}
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
const trimmedCurrentTitle = currentTitle.trim();
if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {
@@ -104,16 +88,9 @@ function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolea
: false;
}
function findProviderAdapterRequestError(
cause: Cause.Cause<ProviderServiceError>,
): ProviderAdapterRequestError | undefined {
const failReason = cause.reasons.find(Cause.isFailReason);
return Schema.is(ProviderAdapterRequestError)(failReason?.error) ? failReason.error : undefined;
}
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = findProviderAdapterRequestError(cause);
if (error) {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
const detail = error.detail.toLowerCase();
return (
detail.includes("unknown pending approval request") ||
@@ -128,8 +105,8 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
}
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = findProviderAdapterRequestError(cause);
if (error) {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
@@ -220,17 +197,6 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
const failReason = cause.reasons.find(Cause.isFailReason);
const providerError = Schema.is(ProviderAdapterRequestError)(failReason?.error)
? failReason.error
: undefined;
if (providerError) {
return providerError.detail;
}
return Cause.pretty(cause);
};
const setThreadSession = (input: {
readonly threadId: ThreadId;
readonly session: OrchestrationSession;
@@ -244,30 +210,7 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly detail: string;
readonly createdAt: string;
}) {
const thread = yield* resolveThread(input.threadId);
const session = thread?.session;
if (!session) {
return;
}
yield* setThreadSession({
threadId: input.threadId,
session: {
...session,
status: session.status === "stopped" ? "stopped" : "ready",
activeTurnId: null,
lastError: input.detail,
updatedAt: input.createdAt,
},
createdAt: input.createdAt,
});
});
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
return readModel.threads.find((entry) => entry.id === threadId);
});
@@ -286,108 +229,42 @@ const make = Effect.gen(function* () {
}
const desiredRuntimeMode = thread.runtimeMode;
const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
thread.session?.providerName,
)
? thread.session.providerName
: undefined;
const requestedModelSelection = options?.modelSelection;
const resolveActiveSession = (threadId: ThreadId) =>
providerService
.listSessions()
.pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));
const activeSession = yield* resolveActiveSession(threadId);
const activeThreadSession =
thread.session !== null && thread.session.status !== "stopped" && activeSession
? thread.session
: null;
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
if (
activeThreadSession !== null &&
activeSession !== undefined &&
(activeThreadSession.providerInstanceId === undefined ||
activeSession.providerInstanceId === undefined)
) {
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(activeThreadSession.providerName ?? undefined),
method: "thread.turn.start",
detail: `Thread '${threadId}' has an active provider session without a provider instance id.`,
});
}
const currentInstanceId =
activeThreadSession !== null &&
activeSession !== undefined &&
activeSession.providerInstanceId !== undefined
? activeSession.providerInstanceId
: thread.modelSelection.instanceId;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const desiredInstanceId = desiredModelSelection.instanceId;
const currentInfo = yield* providerService.getInstanceInfo(currentInstanceId).pipe(
Effect.mapError(
() =>
new ProviderAdapterRequestError({
provider: providerErrorLabelFromInstanceHint({
instanceId: String(currentInstanceId),
modelSelectionInstanceId: String(thread.modelSelection.instanceId),
sessionProvider: thread.session?.providerName ?? undefined,
}),
method: "thread.turn.start",
detail: `Thread '${threadId}' references unknown provider instance '${currentInstanceId}'. The instance is not configured in this build.`,
}),
),
);
const desiredInfo = yield* providerService.getInstanceInfo(desiredInstanceId).pipe(
Effect.mapError(
() =>
new ProviderAdapterRequestError({
provider: providerErrorLabelFromInstanceHint({
instanceId: String(desiredModelSelection.instanceId),
}),
method: "thread.turn.start",
detail: `Requested provider instance '${desiredInstanceId}' is not configured in this build.`,
}),
),
);
const desiredDriverKind = desiredInfo.driverKind;
if (!Schema.is(ProviderDriverKind)(desiredDriverKind)) {
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(String(desiredDriverKind)),
method: "thread.turn.start",
detail: `Requested provider instance '${desiredInstanceId}' uses unknown provider driver '${desiredDriverKind}'. The driver is not installed in this build.`,
});
}
const preferredProvider: ProviderDriverKind = desiredDriverKind;
if (
thread.session !== null &&
requestedModelSelection !== undefined &&
requestedModelSelection.instanceId !== currentInstanceId
requestedModelSelection.provider !== threadProvider
) {
if (currentInfo.driverKind !== desiredInfo.driverKind) {
return yield* new ProviderAdapterRequestError({
provider: preferredProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to driver '${currentInfo.driverKind}' and cannot switch to '${desiredInfo.driverKind}'.`,
});
}
if (
currentInfo.continuationIdentity.continuationKey !==
desiredInfo.continuationIdentity.continuationKey
) {
return yield* new ProviderAdapterRequestError({
provider: preferredProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' cannot switch from instance '${currentInstanceId}' to '${desiredInstanceId}' because their provider resume state is incompatible.`,
});
}
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
});
}
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
});
const resolveActiveSession = (threadId: ThreadId) =>
providerService
.listSessions()
.pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));
const startProviderSession = (input?: {
readonly resumeCursor?: unknown;
readonly provider?: ProviderDriverKind;
readonly provider?: ProviderKind;
}) =>
providerService.startSession(threadId, {
threadId,
...(preferredProvider ? { provider: preferredProvider } : {}),
providerInstanceId: desiredInstanceId,
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
modelSelection: desiredModelSelection,
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
@@ -395,79 +272,66 @@ const make = Effect.gen(function* () {
});
const bindSessionToThread = (session: ProviderSession) =>
Effect.gen(function* () {
if (session.providerInstanceId === undefined) {
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(session.provider),
method: "thread.turn.start",
detail: `Provider session '${session.threadId}' started without a provider instance id.`,
});
}
yield* setThreadSession({
setThreadSession({
threadId,
session: {
threadId,
session: {
threadId,
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
providerName: session.provider,
providerInstanceId: session.providerInstanceId,
runtimeMode: desiredRuntimeMode,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
updatedAt: session.updatedAt,
},
createdAt,
});
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
providerName: session.provider,
runtimeMode: desiredRuntimeMode,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
updatedAt: session.updatedAt,
},
createdAt,
});
const activeSession = yield* resolveActiveSession(threadId);
const existingSessionThreadId =
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
if (existingSessionThreadId) {
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
const cwdChanged = effectiveCwd !== activeSession?.cwd;
const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId))
.sessionModelSwitch;
const providerChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== currentProvider;
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.model !== activeSession?.model;
const instanceChanged =
requestedModelSelection !== undefined &&
activeSession?.providerInstanceId !== requestedModelSelection.instanceId;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const previousModelSelection = threadModelSelections.get(threadId);
const shouldRestartForModelSelectionChange =
preferredProvider === "claudeAgent" &&
currentProvider === "claudeAgent" &&
requestedModelSelection !== undefined &&
!Equal.equals(previousModelSelection, requestedModelSelection);
if (
!runtimeModeChanged &&
!cwdChanged &&
!instanceChanged &&
!providerChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelSelectionChange
) {
return existingSessionThreadId;
}
const resumeCursor = shouldRestartForModelChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
const resumeCursor =
providerChanged || shouldRestartForModelChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
yield* Effect.logInfo("provider command reactor restarting provider session", {
threadId,
existingSessionThreadId,
currentProvider: activeSession?.provider,
currentInstanceId,
desiredInstanceId,
desiredProvider: desiredModelSelection.instanceId,
currentProvider,
desiredProvider: desiredModelSelection.provider,
currentRuntimeMode: thread.session?.runtimeMode,
desiredRuntimeMode: thread.runtimeMode,
runtimeModeChanged,
previousCwd: activeSession?.cwd,
desiredCwd: effectiveCwd,
cwdChanged,
providerChanged,
modelChanged,
instanceChanged,
shouldRestartForModelChange,
shouldRestartForModelSelectionChange,
hasResumeCursor: resumeCursor !== undefined,
@@ -481,7 +345,6 @@ const make = Effect.gen(function* () {
restartedSessionThreadId: restartedSession.threadId,
provider: restartedSession.provider,
runtimeMode: restartedSession.runtimeMode,
cwd: restartedSession.cwd,
});
yield* bindSessionToThread(restartedSession);
return restartedSession.threadId;
@@ -492,7 +355,7 @@ const make = Effect.gen(function* () {
return startedSession.threadId;
});
const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: {
const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: {
readonly threadId: ThreadId;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
@@ -502,9 +365,7 @@ const make = Effect.gen(function* () {
}) {
const thread = yield* resolveThread(input.threadId);
if (!thread) {
return yield* Effect.die(
new Error(`Thread '${input.threadId}' was not found in read model.`),
);
return;
}
yield* ensureSessionForThread(
input.threadId,
@@ -524,18 +385,11 @@ const make = Effect.gen(function* () {
const sessionModelSwitch =
activeSession === undefined
? "in-session"
: activeSession.providerInstanceId === undefined
? yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(activeSession.provider),
method: "thread.turn.start",
detail: `Active provider session '${activeSession.threadId}' is missing a provider instance id.`,
})
: (yield* providerService.getCapabilities(activeSession.providerInstanceId))
.sessionModelSwitch;
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
const requestedModelSelection =
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
const modelForTurn =
sessionModelSwitch === "unsupported" && input.modelSelection === undefined
sessionModelSwitch === "unsupported"
? activeSession?.model !== undefined
? {
...requestedModelSelection,
@@ -544,13 +398,13 @@ const make = Effect.gen(function* () {
: requestedModelSelection
: input.modelSelection;
return {
yield* providerService.sendTurn({
threadId: input.threadId,
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
};
});
});
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(
@@ -709,43 +563,7 @@ const make = Effect.gen(function* () {
}
}
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const detail = formatFailureDetail(cause);
return setThreadSessionErrorOnTurnStartFailure({
threadId: event.payload.threadId,
detail,
createdAt: event.payload.createdAt,
}).pipe(
Effect.flatMap(() =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail,
turnId: null,
createdAt: event.payload.createdAt,
}),
),
Effect.asVoid,
);
};
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
handleTurnStartFailure(cause).pipe(
Effect.catchCause((recoveryCause) =>
Effect.logWarning("provider command reactor failed to recover turn start failure", {
eventType: event.type,
threadId: event.payload.threadId,
cause: Cause.pretty(recoveryCause),
originalCause: Cause.pretty(cause),
}),
),
);
const sendTurnRequest = yield* buildSendTurnRequestForThread({
yield* sendTurnForThread({
threadId: event.payload.threadId,
messageText: message.text,
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
@@ -755,17 +573,17 @@ const make = Effect.gen(function* () {
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
}).pipe(
Effect.map(Option.some),
Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
}),
),
);
if (Option.isNone(sendTurnRequest)) {
return;
}
yield* providerService
.sendTurn(sendTurnRequest.value)
.pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
});
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
@@ -902,9 +720,6 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status: "stopped",
providerName: thread.session?.providerName ?? null,
...(thread.session?.providerInstanceId !== undefined
? { providerInstanceId: thread.session.providerInstanceId }
: {}),
runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
activeTurnId: null,
lastError: thread.session?.lastError ?? null,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,36 +0,0 @@
import { ThreadId } from "@t3tools/contracts";
import { Cause, Effect, Exit } from "effect";
import { describe, expect, it } from "vitest";
import { logCleanupCauseUnlessInterrupted } from "./ThreadDeletionReactor.ts";
describe("logCleanupCauseUnlessInterrupted", () => {
const threadId = ThreadId.make("thread-deletion-reactor-test");
it("swallows ordinary cleanup failures", async () => {
const exit = await Effect.runPromiseExit(
logCleanupCauseUnlessInterrupted({
effect: Effect.fail("cleanup failed"),
message: "thread deletion cleanup skipped provider session stop",
threadId,
}),
);
expect(Exit.isSuccess(exit)).toBe(true);
});
it("preserves interrupt causes", async () => {
const exit = await Effect.runPromiseExit(
logCleanupCauseUnlessInterrupted({
effect: Effect.interrupt,
message: "thread deletion cleanup skipped provider session stop",
threadId,
}),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
}
});
});
@@ -1,96 +0,0 @@
import type { OrchestrationEvent } from "@t3tools/contracts";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { Cause, Effect, Layer, Stream } from "effect";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { TerminalManager } from "../../terminal/Services/Manager.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
ThreadDeletionReactor,
type ThreadDeletionReactorShape,
} from "../Services/ThreadDeletionReactor.ts";
type ThreadDeletedEvent = Extract<OrchestrationEvent, { type: "thread.deleted" }>;
export const logCleanupCauseUnlessInterrupted = <R, E>({
effect,
message,
threadId,
}: {
readonly effect: Effect.Effect<void, E, R>;
readonly message: string;
readonly threadId: ThreadDeletedEvent["payload"]["threadId"];
}): Effect.Effect<void, E, R> =>
effect.pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
return Effect.logDebug(message, {
threadId,
cause: Cause.pretty(cause),
});
}),
);
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const terminalManager = yield* TerminalManager;
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
logCleanupCauseUnlessInterrupted({
effect: providerService.stopSession({ threadId }),
message: "thread deletion cleanup skipped provider session stop",
threadId,
});
const closeThreadTerminals = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
logCleanupCauseUnlessInterrupted({
effect: terminalManager.close({ threadId, deleteHistory: true }),
message: "thread deletion cleanup skipped terminal close",
threadId,
});
const processThreadDeleted = Effect.fn("processThreadDeleted")(function* (
event: ThreadDeletedEvent,
) {
const { threadId } = event.payload;
yield* stopProviderSession(threadId);
yield* closeThreadTerminals(threadId);
});
const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>
processThreadDeleted(event).pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
return Effect.logWarning("thread deletion reactor failed to process event", {
eventType: event.type,
threadId: event.payload.threadId,
cause: Cause.pretty(cause),
});
}),
);
const worker = yield* makeDrainableWorker(processThreadDeletedSafely);
const start: ThreadDeletionReactorShape["start"] = Effect.fn("start")(function* () {
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (event.type !== "thread.deleted") {
return Effect.void;
}
return worker.enqueue(event);
}),
);
});
return {
start,
drain: worker.drain,
} satisfies ThreadDeletionReactorShape;
});
export const ThreadDeletionReactorLive = Layer.effect(ThreadDeletionReactor, make);
Loaded 100 of 533 files, more files were not shown because too many files have changed in this diff. Show more