Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
788a70087a | ||
|
|
66c326b8c4 | ||
|
|
8dbcf92a0d | ||
|
|
37965da01d | ||
|
|
57b59b5bf2 | ||
|
|
20f346d8ef | ||
|
|
c83bc5d48a | ||
|
|
9df3c64021 | ||
|
|
8ac57f7944 | ||
|
|
29cb917ac4 | ||
|
|
9c64f12ea0 | ||
|
|
0f184c28b0 | ||
|
|
a3b1df5224 | ||
|
|
4e0c003e78 | ||
|
|
60387f67e9 | ||
|
|
ce94feeea1 | ||
|
|
39ca3ee858 | ||
|
|
52a6067802 | ||
|
|
721b6b4c6f | ||
|
|
40009735ee | ||
|
|
df9d34004f | ||
|
|
f297e30e4c | ||
|
|
a7a44d0662 | ||
|
|
d8d329691a | ||
|
|
54179c86b8 | ||
|
|
8dba2d6484 | ||
|
|
ed6b7fbf27 | ||
|
|
b991b9b9e6 |
No files matched your search
@@ -2,15 +2,22 @@
|
||||
"name": "T3 Code Dev",
|
||||
"image": "debian:bookworm",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {},
|
||||
"ghcr.io/devcontainers/features/git:1": {},
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {
|
||||
"version": "1.3.11"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "24",
|
||||
"nodeGypDependencies": true
|
||||
"version": "24.13.1"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/python:1": {
|
||||
"version": "3.12"
|
||||
"version": "3.10",
|
||||
"installTools": false
|
||||
}
|
||||
},
|
||||
"overrideFeatureInstallOrder": [
|
||||
"ghcr.io/devcontainers/features/git",
|
||||
"ghcr.io/devcontainers-extra/features/bun"
|
||||
],
|
||||
"postCreateCommand": {
|
||||
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
||||
},
|
||||
|
||||
@@ -71,8 +71,8 @@ jobs:
|
||||
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
test -f apps/desktop/dist-electron/preload.cjs
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
|
||||
|
||||
release_smoke:
|
||||
name: Release Smoke
|
||||
|
||||
@@ -4,8 +4,9 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
- "!v*-nightly.*"
|
||||
schedule:
|
||||
- cron: "0 9 * * *"
|
||||
- cron: "0 */3 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
@@ -26,8 +27,45 @@ permissions:
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
check_changes:
|
||||
name: Check for changes since last nightly
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: check
|
||||
name: Compare HEAD to last nightly tag
|
||||
run: |
|
||||
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
|
||||
if [[ -z "$last_nightly_tag" ]]; then
|
||||
echo "No previous nightly tag found. Proceeding with release."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
|
||||
head_sha=$(git rev-parse HEAD)
|
||||
|
||||
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
|
||||
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
|
||||
echo "has_changes=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
preflight:
|
||||
name: Preflight
|
||||
needs: [check_changes]
|
||||
if: |
|
||||
!failure() && !cancelled() &&
|
||||
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
@@ -134,6 +172,7 @@ jobs:
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
@@ -188,6 +227,23 @@ jobs:
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Install Spectre-mitigated MSVC libs
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
$installPath = & $vswhere -products * -latest -property installationPath
|
||||
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
|
||||
$proc = Start-Process -FilePath $setupExe `
|
||||
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
|
||||
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
|
||||
-Wait -PassThru -NoNewWindow
|
||||
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
|
||||
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
|
||||
Write-Error "Visual Studio Installer failed with exit code $code"
|
||||
exit $code
|
||||
}
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
@@ -299,7 +355,8 @@ jobs:
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -333,19 +390,36 @@ jobs:
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -412,6 +486,7 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
- name: Publish first release
|
||||
if: needs.preflight.outputs.previous_tag == ''
|
||||
@@ -431,10 +506,11 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: needs.preflight.outputs.release_channel == 'stable'
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
|
||||
needs: [preflight, release]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
|
||||
+9
-1
@@ -13,5 +13,13 @@
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts",
|
||||
"*.icon/**"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
"sortPackageJson": {},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [".devcontainer/devcontainer.json"],
|
||||
"options": {
|
||||
"trailingComma": "none"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+1
-1
@@ -5,5 +5,5 @@
|
||||
"source.fixAll.oxc": "always"
|
||||
},
|
||||
"oxc.unusedDisableDirectives": "warn",
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib"
|
||||
}
|
||||
@@ -2,13 +2,14 @@
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.20",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"dev:electron": "node scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "bun run scripts/start-electron.mjs",
|
||||
"start": "node scripts/start-electron.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
@@ -22,6 +23,7 @@
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -17,12 +17,12 @@ if (!Number.isInteger(port) || port <= 0) {
|
||||
}
|
||||
|
||||
const requiredFiles = [
|
||||
"dist-electron/main.js",
|
||||
"dist-electron/preload.js",
|
||||
"dist-electron/main.cjs",
|
||||
"dist-electron/preload.cjs",
|
||||
"../server/dist/bin.mjs",
|
||||
];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
|
||||
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
@@ -69,7 +69,7 @@ function startApp() {
|
||||
|
||||
const app = spawn(
|
||||
resolveElectronPath(),
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
@@ -20,7 +19,7 @@ import { fileURLToPath } from "node:url";
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 1;
|
||||
const LAUNCHER_VERSION = 2;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
@@ -121,40 +120,6 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
|
||||
if (!existsSync(frameworksDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
|
||||
continue;
|
||||
}
|
||||
if (!entry.name.startsWith("Electron Helper")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
|
||||
if (!existsSync(helperPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
|
||||
const helperName = suffix
|
||||
? `${APP_DISPLAY_NAME} Helper ${suffix}`
|
||||
: `${APP_DISPLAY_NAME} Helper`;
|
||||
const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");
|
||||
const helperBundleId = helperIdSuffix
|
||||
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
|
||||
: `${APP_BUNDLE_ID}.helper`;
|
||||
|
||||
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
@@ -192,7 +157,6 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
|
||||
return targetBinaryPath;
|
||||
@@ -206,5 +170,11 @@ export function resolveElectronPath() {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
// Dev launches do not need a renamed app bundle badly enough to risk breaking
|
||||
// Electron helper resource lookup on macOS.
|
||||
if (isDevelopment) {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.js");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding";
|
||||
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding.ts";
|
||||
|
||||
describe("resolveDesktopAppStageLabel", () => {
|
||||
it("uses Dev in desktop development", () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { DesktopAppBranding, DesktopAppStageLabel } from "@t3tools/contracts";
|
||||
|
||||
import { isNightlyDesktopVersion } from "./updateChannels";
|
||||
import { isNightlyDesktopVersion } from "./updateChannels.ts";
|
||||
|
||||
const APP_BASE_NAME = "T3 Code";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { resolveDesktopBackendPort } from "./backendPort";
|
||||
import { resolveDesktopBackendPort } from "./backendPort.ts";
|
||||
|
||||
describe("resolveDesktopBackendPort", () => {
|
||||
it("returns the starting port when it is available", async () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
BackendReadinessAbortedError,
|
||||
isBackendReadinessAborted,
|
||||
waitForHttpReady,
|
||||
} from "./backendReadiness";
|
||||
} from "./backendReadiness.ts";
|
||||
|
||||
describe("waitForHttpReady", () => {
|
||||
it("returns once the backend serves the requested readiness path", async () => {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { BackendReadinessAbortedError } from "./backendReadiness.ts";
|
||||
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
||||
|
||||
describe("waitForBackendStartupReady", () => {
|
||||
it("falls back to the HTTP probe when no listening signal exists", async () => {
|
||||
const waitForHttpReady = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
|
||||
const cancelHttpWait = vi.fn();
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
waitForHttpReady,
|
||||
cancelHttpWait,
|
||||
}),
|
||||
).resolves.toBe("http");
|
||||
|
||||
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
|
||||
expect(cancelHttpWait).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the listening signal and cancels the HTTP probe", async () => {
|
||||
let rejectHttpWait: ((error: unknown) => void) | null = null;
|
||||
const waitForHttpReady = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((_resolve, reject) => {
|
||||
rejectHttpWait = reject;
|
||||
}),
|
||||
);
|
||||
const cancelHttpWait = vi.fn(() => {
|
||||
rejectHttpWait?.(new BackendReadinessAbortedError());
|
||||
});
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
listeningPromise: Promise.resolve(),
|
||||
waitForHttpReady,
|
||||
cancelHttpWait,
|
||||
}),
|
||||
).resolves.toBe("listening");
|
||||
|
||||
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
|
||||
expect(cancelHttpWait).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects when the listening signal fails before HTTP readiness", async () => {
|
||||
const error = new Error("backend exited");
|
||||
const waitForHttpReady = vi.fn(() => new Promise<void>(() => {}));
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
listeningPromise: Promise.reject(error),
|
||||
waitForHttpReady,
|
||||
cancelHttpWait: vi.fn(),
|
||||
}),
|
||||
).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { isBackendReadinessAborted } from "./backendReadiness.ts";
|
||||
|
||||
export interface WaitForBackendStartupReadyOptions {
|
||||
readonly listeningPromise?: Promise<void> | null;
|
||||
readonly waitForHttpReady: () => Promise<void>;
|
||||
readonly cancelHttpWait: () => void;
|
||||
}
|
||||
|
||||
export async function waitForBackendStartupReady(
|
||||
options: WaitForBackendStartupReadyOptions,
|
||||
): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = options.waitForHttpReady();
|
||||
const listeningPromise = options.listeningPromise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
options.cancelHttpWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
type DesktopSecretStorage,
|
||||
} from "./clientPersistence";
|
||||
} from "./clientPersistence.ts";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
@@ -52,6 +52,7 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
|
||||
@@ -11,7 +11,7 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||
|
||||
describe("showDesktopConfirmDialog", () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings";
|
||||
} from "./desktopSettings.ts";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
|
||||
|
||||
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
|
||||
+25
-62
@@ -36,14 +36,14 @@ import { autoUpdater } from "electron-updater";
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
|
||||
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings";
|
||||
} from "./desktopSettings.ts";
|
||||
import {
|
||||
readClientSettings,
|
||||
readSavedEnvironmentRegistry,
|
||||
@@ -52,14 +52,15 @@ import {
|
||||
writeClientSettings,
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
} from "./clientPersistence";
|
||||
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
} from "./clientPersistence.ts";
|
||||
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure.ts";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
||||
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
|
||||
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector.ts";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
@@ -71,9 +72,9 @@ import {
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
import { resolveDesktopAppBranding } from "./appBranding";
|
||||
} from "./updateMachine.ts";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
||||
import { resolveDesktopAppBranding } from "./appBranding.ts";
|
||||
|
||||
syncShellEnvironment();
|
||||
|
||||
@@ -459,51 +460,13 @@ function cancelBackendReadinessWait(): void {
|
||||
}
|
||||
|
||||
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
});
|
||||
const listeningPromise = backendListeningDetector?.promise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
cancelBackendReadinessWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
return await waitForBackendStartupReady({
|
||||
listeningPromise: backendListeningDetector?.promise ?? null,
|
||||
waitForHttpReady: () =>
|
||||
waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
}),
|
||||
cancelHttpWait: cancelBackendReadinessWait,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1967,7 +1930,7 @@ function createWindow(): BrowserWindow {
|
||||
title: APP_DISPLAY_NAME,
|
||||
...getWindowTitleBarOptions(),
|
||||
webPreferences: {
|
||||
preload: Path.join(__dirname, "preload.js"),
|
||||
preload: Path.join(__dirname, "preload.cjs"),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
@@ -2119,9 +2082,9 @@ async function bootstrap(): Promise<void> {
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
void waitForBackendHttpReady(backendHttpUrl)
|
||||
.then(() => {
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
void waitForBackendWindowReady(backendHttpUrl)
|
||||
.then((source) => {
|
||||
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
||||
|
||||
describe("resolveDesktopRuntimeInfo", () => {
|
||||
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
|
||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
|
||||
|
||||
describe("resolveLanAdvertisedHost", () => {
|
||||
it("prefers an explicit host override", () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector.ts";
|
||||
|
||||
describe("ServerListeningDetector", () => {
|
||||
it("resolves when the server logs the listening line", async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
||||
|
||||
describe("syncShellEnvironment", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||
@@ -148,7 +148,7 @@ describe("syncShellEnvironment", () => {
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
it("does nothing on unsupported platforms", () => {
|
||||
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: "win32",
|
||||
platform: "freebsd",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
@@ -168,4 +168,122 @@ describe("syncShellEnvironment", () => {
|
||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("hydrates PATH on Windows by merging PowerShell PATH with inherited PATH", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(() => ({
|
||||
PATH: "C:\\Custom\\Bin;C:\\Windows\\System32",
|
||||
}));
|
||||
const isWindowsCommandAvailable = vi.fn(() => true);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(readWindowsEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
"C:\\Windows\\System32",
|
||||
].join(";"),
|
||||
);
|
||||
expect(isWindowsCommandAvailable).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("loads the PowerShell profile on Windows when node is not available", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(
|
||||
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
|
||||
options?.loadProfile
|
||||
? {
|
||||
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
|
||||
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
|
||||
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
|
||||
}
|
||||
: { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" },
|
||||
);
|
||||
const isWindowsCommandAvailable = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Profile\\Node",
|
||||
"C:\\Windows\\System32",
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
].join(";"),
|
||||
);
|
||||
expect(env.FNM_DIR).toBe("C:\\Users\\testuser\\AppData\\Roaming\\fnm");
|
||||
expect(env.FNM_MULTISHELL_PATH).toBe(
|
||||
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
|
||||
);
|
||||
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
|
||||
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
|
||||
{ loadProfile: true },
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves baseline Windows env when the profile probe fails", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(
|
||||
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => {
|
||||
if (options?.loadProfile) {
|
||||
throw new Error("profile load failed");
|
||||
}
|
||||
return { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" };
|
||||
},
|
||||
);
|
||||
const isWindowsCommandAvailable = vi.fn(() => false);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
"C:\\Windows\\System32",
|
||||
].join(";"),
|
||||
);
|
||||
expect(env.SSH_AUTH_SOCK).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -3,8 +3,18 @@ import {
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readEnvironmentFromLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
resolveWindowsEnvironment,
|
||||
} from "@t3tools/shared/shell";
|
||||
import type {
|
||||
CommandAvailabilityOptions,
|
||||
ShellEnvironmentReader,
|
||||
WindowsShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
type WindowsCommandAvailabilityChecker = (
|
||||
command: string,
|
||||
options?: CommandAvailabilityOptions,
|
||||
) => boolean;
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
@@ -25,19 +35,39 @@ 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));
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
doesVersionMatchDesktopUpdateChannel,
|
||||
isNightlyDesktopVersion,
|
||||
resolveDefaultDesktopUpdateChannel,
|
||||
} from "./updateChannels";
|
||||
} from "./updateChannels.ts";
|
||||
|
||||
describe("isNightlyDesktopVersion", () => {
|
||||
it("detects packaged nightly versions", () => {
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
} from "./updateMachine.ts";
|
||||
|
||||
const runtimeInfo = {
|
||||
hostArch: "x64",
|
||||
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState.ts";
|
||||
|
||||
export function createInitialDesktopUpdateState(
|
||||
currentVersion: string,
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
getAutoUpdateDisabledReason,
|
||||
nextStatusAfterDownloadFailure,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState";
|
||||
} from "./updateState.ts";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"types": ["node", "electron"],
|
||||
"lib": ["ES2023", "DOM", "esnext.disposable"]
|
||||
"lib": ["ESNext", "DOM", "esnext.disposable"]
|
||||
},
|
||||
"include": ["src", "tsdown.config.ts"]
|
||||
}
|
||||
@@ -4,7 +4,7 @@ const shared = {
|
||||
format: "cjs" as const,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".js" }),
|
||||
outExtensions: () => ({ js: ".cjs" }),
|
||||
};
|
||||
|
||||
export default defineConfig([
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
@@ -58,6 +58,7 @@ import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../src/orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
|
||||
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -351,6 +352,12 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadDeletionReactor, {
|
||||
start: () => Effect.void,
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const layer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
|
||||
@@ -15,8 +15,9 @@
|
||||
],
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun run src/bin.ts",
|
||||
"dev": "node --watch src/bin.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"build:bundle": "tsdown",
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
@@ -24,10 +25,11 @@
|
||||
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.114",
|
||||
"@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",
|
||||
@@ -41,6 +43,7 @@
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
#!/usr/bin/env bun
|
||||
import { appendFileSync } from "node:fs";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
|
||||
import * as EffectAcpAgent from "effect-acp/agent";
|
||||
import * as AcpError from "effect-acp/errors";
|
||||
import type * as AcpSchema from "effect-acp/schema";
|
||||
|
||||
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
|
||||
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
|
||||
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
|
||||
const emitInterleavedAssistantToolCalls =
|
||||
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
let currentModeId = "ask";
|
||||
let currentModelId = "default";
|
||||
let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function logExit(reason: string): void {
|
||||
if (!exitLogPath) {
|
||||
return;
|
||||
}
|
||||
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
logExit("SIGINT");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("exit", (code) => {
|
||||
logExit(`exit:${code}`);
|
||||
});
|
||||
|
||||
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
if (parameterizedModelPicker) {
|
||||
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: currentModeId,
|
||||
options: availableModes.map((mode) => ({
|
||||
value: mode.id,
|
||||
name: mode.name,
|
||||
...(mode.description ? { description: mode.description } : {}),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ value: "claude-opus-4-6", name: "Opus 4.6" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
switch (currentModelId) {
|
||||
case "gpt-5.4":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "none", name: "None" },
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
{ value: "extra-high", name: "Extra High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "context",
|
||||
name: "Context",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: currentContext,
|
||||
options: [
|
||||
{ value: "272k", name: "272K" },
|
||||
{ value: "1m", name: "1M" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "composer-2":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "claude-opus-4-6":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
category: "model_config",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
},
|
||||
];
|
||||
default:
|
||||
return baseOptions;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select" as const,
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "composer-2[fast=true]", name: "Composer 2 Fast" },
|
||||
{ value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
|
||||
{
|
||||
id: "ask",
|
||||
name: "Ask",
|
||||
description: "Request permission before making any changes",
|
||||
},
|
||||
{
|
||||
id: "architect",
|
||||
name: "Architect",
|
||||
description: "Design and plan software systems without implementation",
|
||||
},
|
||||
{
|
||||
id: "code",
|
||||
name: "Code",
|
||||
description: "Write and modify code with full tool access",
|
||||
},
|
||||
];
|
||||
|
||||
function modeState(): AcpSchema.SessionModeState {
|
||||
return {
|
||||
currentModeId,
|
||||
availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const agent = yield* EffectAcpAgent.AcpAgent;
|
||||
|
||||
yield* agent.handleInitialize((request) =>
|
||||
Effect.sync(() => {
|
||||
parameterizedModelPicker =
|
||||
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
|
||||
return {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleAuthenticate(() => Effect.succeed({}));
|
||||
|
||||
yield* agent.handleCreateSession(() =>
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleLoadSession((request) =>
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionConfigOption((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (exitOnSetConfigOption) {
|
||||
return yield* Effect.sync(() => {
|
||||
process.exit(7);
|
||||
});
|
||||
}
|
||||
if (failSetConfigOption) {
|
||||
return yield* AcpError.AcpRequestError.invalidParams(
|
||||
"Mock invalid params for session/set_config_option",
|
||||
{
|
||||
method: "session/set_config_option",
|
||||
params: request,
|
||||
},
|
||||
);
|
||||
}
|
||||
if (request.configId === "mode" && typeof request.value === "string") {
|
||||
currentModeId = request.value;
|
||||
}
|
||||
if (request.configId === "model" && typeof request.value === "string") {
|
||||
currentModelId = request.value;
|
||||
}
|
||||
if (request.configId === "reasoning" && typeof request.value === "string") {
|
||||
currentReasoning = request.value;
|
||||
}
|
||||
if (request.configId === "context" && typeof request.value === "string") {
|
||||
currentContext = request.value;
|
||||
}
|
||||
if (request.configId === "fast") {
|
||||
currentFast = request.value === true || request.value === "true";
|
||||
}
|
||||
return {
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "before tool" },
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["echo", "hello"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: "hello",
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "after tool" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["cat", "server/package.json"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
const permission = yield* agent.client.requestPermission({
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId,
|
||||
title: "`cat server/package.json`",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Not in allowlist: cat server/package.json",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
|
||||
const cancelled =
|
||||
cancelledSessions.delete(requestedSessionId) ||
|
||||
permission.outcome.outcome === "cancelled";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: cancelled ? "cancelled" : "end_turn" };
|
||||
}
|
||||
|
||||
if (emitGenericToolPlaceholders) {
|
||||
const toolCallId = "tool-call-generic-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Read File",
|
||||
kind: "read",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
content: "package.json\n",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitAskQuestion) {
|
||||
yield* agent.client.extRequest("cursor/ask_question", {
|
||||
toolCallId: "ask-question-tool-call-1",
|
||||
title: "Question",
|
||||
questions: [
|
||||
{
|
||||
id: "scope",
|
||||
prompt: "Which scope?",
|
||||
options: [
|
||||
{ id: "workspace", label: "Workspace" },
|
||||
{ id: "session", label: "Session" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect mock ACP state",
|
||||
priority: "high",
|
||||
status: "completed",
|
||||
},
|
||||
{
|
||||
content: "Implement the requested change",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: promptResponseText ?? "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleUnknownExtRequest((method, params) => {
|
||||
if (method !== "session/mode/set") {
|
||||
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
}
|
||||
|
||||
const nextModeId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"modeId" in params &&
|
||||
typeof params.modeId === "string"
|
||||
? params.modeId
|
||||
: typeof params === "object" &&
|
||||
params !== null &&
|
||||
"mode" in params &&
|
||||
typeof params.mode === "string"
|
||||
? params.mode
|
||||
: undefined;
|
||||
const requestedSessionId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"sessionId" in params &&
|
||||
typeof params.sessionId === "string"
|
||||
? params.sessionId
|
||||
: sessionId;
|
||||
|
||||
if (typeof nextModeId === "string" && nextModeId.trim()) {
|
||||
currentModeId = nextModeId.trim();
|
||||
return agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
},
|
||||
})
|
||||
.pipe(Effect.as({}));
|
||||
}
|
||||
|
||||
return Effect.succeed({});
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EffectAcpAgent.layerStdio(
|
||||
requestLogPath
|
||||
? {
|
||||
logIncoming: true,
|
||||
logger: (event) => {
|
||||
if (event.direction !== "incoming" || event.stage !== "raw") {
|
||||
return Effect.void;
|
||||
}
|
||||
if (typeof event.payload !== "string") {
|
||||
return Effect.void;
|
||||
}
|
||||
const payload = event.payload;
|
||||
return Effect.sync(() => {
|
||||
appendFileSync(
|
||||
requestLogPath,
|
||||
payload.endsWith("\n") ? payload : `${payload}\n`,
|
||||
"utf8",
|
||||
);
|
||||
});
|
||||
},
|
||||
}
|
||||
: {},
|
||||
),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
NodeRuntime.runMain(program);
|
||||
+15
-20
@@ -147,13 +147,13 @@ const buildCmd = Command.make(
|
||||
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
|
||||
// Windows needs shell mode to resolve `.cmd` shims on PATH.
|
||||
shell: process.platform === "win32",
|
||||
})`bun tsdown`,
|
||||
}),
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
@@ -203,10 +203,8 @@ const publishCmd = Command.make(
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
// Resolve catalog dependencies before any file mutations. If this throws,
|
||||
// acquire fails and no release hook runs, so filesystem must still be untouched.
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg: PackageJson = {
|
||||
name: serverPackageJson.name,
|
||||
@@ -216,25 +214,22 @@ const publishCmd = Command.make(
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies,
|
||||
overrides: rootPackageJson.overrides,
|
||||
dependencies: resolveCatalogDependencies(
|
||||
serverPackageJson.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server",
|
||||
),
|
||||
overrides: resolveCatalogDependencies(
|
||||
rootPackageJson.overrides,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server",
|
||||
),
|
||||
};
|
||||
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
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] Resolved package.json for publish");
|
||||
yield* Effect.log("[cli] Prepared package.json for publish");
|
||||
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import process from "node:process";
|
||||
import readline from "node:readline";
|
||||
|
||||
type JsonPrimitive = null | boolean | number | string;
|
||||
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
|
||||
|
||||
type JsonRpcId = number | string;
|
||||
|
||||
type JsonRpcMessage = {
|
||||
jsonrpc?: string;
|
||||
id?: JsonRpcId;
|
||||
method?: string;
|
||||
params?: JsonValue;
|
||||
result?: JsonValue;
|
||||
error?: JsonValue;
|
||||
headers?: JsonValue;
|
||||
};
|
||||
|
||||
type SelectLeafOption = {
|
||||
value: string;
|
||||
label?: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
type SelectGroupOption = {
|
||||
label?: string;
|
||||
name?: string;
|
||||
options: SelectLeafOption[];
|
||||
};
|
||||
|
||||
type SessionConfigOption = {
|
||||
id: string;
|
||||
name?: string;
|
||||
category?: string;
|
||||
type?: string;
|
||||
options?: Array<SelectLeafOption | SelectGroupOption>;
|
||||
};
|
||||
|
||||
type SessionNewResult = {
|
||||
sessionId: string;
|
||||
configOptions?: SessionConfigOption[];
|
||||
};
|
||||
|
||||
type SetConfigResult = {
|
||||
configOptions?: SessionConfigOption[];
|
||||
};
|
||||
|
||||
type PendingRequest = {
|
||||
method: string;
|
||||
resolve: (value: JsonValue | undefined) => void;
|
||||
reject: (error: Error) => void;
|
||||
};
|
||||
|
||||
const targetCwd = process.argv[2] ?? process.cwd();
|
||||
const targetModel = process.argv[3] ?? "gpt-5.4";
|
||||
const promptText = process.argv[4] ?? "helo";
|
||||
const targetReasoning = process.env.CURSOR_REASONING ?? "";
|
||||
const targetContext = process.env.CURSOR_CONTEXT ?? "";
|
||||
const targetFast = process.env.CURSOR_FAST ?? "";
|
||||
const agentBin = process.env.CURSOR_AGENT_BIN ?? "agent";
|
||||
const promptWaitMs = Number(process.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
|
||||
const requestTimeoutMs = Number(process.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
|
||||
|
||||
function logSection(title: string, value: unknown) {
|
||||
process.stdout.write(`\n=== ${title} ===\n`);
|
||||
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
||||
}
|
||||
|
||||
function fail(message: string): never {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
function asString(value: JsonValue | undefined): string | null {
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function flattenSelectValues(option: SessionConfigOption | undefined): string[] {
|
||||
if (!option || option.type !== "select" || !Array.isArray(option.options)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const values: string[] = [];
|
||||
for (const entry of option.options) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
continue;
|
||||
}
|
||||
if ("value" in entry && typeof entry.value === "string") {
|
||||
values.push(entry.value);
|
||||
continue;
|
||||
}
|
||||
if ("options" in entry && Array.isArray(entry.options)) {
|
||||
for (const nested of entry.options) {
|
||||
if (nested && typeof nested === "object" && typeof nested.value === "string") {
|
||||
values.push(nested.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function findConfigOption(
|
||||
configOptions: SessionConfigOption[],
|
||||
predicate: (option: SessionConfigOption) => boolean,
|
||||
): SessionConfigOption | undefined {
|
||||
return configOptions.find(predicate);
|
||||
}
|
||||
|
||||
function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
|
||||
const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();
|
||||
return haystack.includes(keyword.toLowerCase());
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
class JsonRpcChild {
|
||||
readonly child: ChildProcessWithoutNullStreams;
|
||||
readonly pending = new Map<JsonRpcId, PendingRequest>();
|
||||
nextId = 1;
|
||||
closed = false;
|
||||
|
||||
constructor(bin: string, args: string[], cwd: string) {
|
||||
this.child = spawn(bin, args, {
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
this.child.on("exit", (code, signal) => {
|
||||
this.closed = true;
|
||||
const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.reject(new Error(`${detail} while waiting for ${pending.method}`));
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
|
||||
this.child.on("error", (error) => {
|
||||
this.closed = true;
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.reject(error);
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
|
||||
const stdout = readline.createInterface({ input: this.child.stdout });
|
||||
stdout.on("line", (line) => {
|
||||
void this.handleStdoutLine(line);
|
||||
});
|
||||
|
||||
const stderr = readline.createInterface({ input: this.child.stderr });
|
||||
stderr.on("line", (line) => {
|
||||
process.stdout.write(`[stderr] ${line}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
write(message: JsonRpcMessage) {
|
||||
if (this.closed) {
|
||||
fail("ACP process is already closed.");
|
||||
}
|
||||
const payload = JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
headers: [],
|
||||
...message,
|
||||
});
|
||||
process.stdout.write(`>>> ${payload}\n`);
|
||||
this.child.stdin.write(`${payload}\n`);
|
||||
}
|
||||
|
||||
async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {
|
||||
const id = this.nextId++;
|
||||
|
||||
const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
|
||||
}, timeoutMs);
|
||||
|
||||
this.pending.set(id, {
|
||||
method,
|
||||
resolve: (value) => {
|
||||
clearTimeout(timeout);
|
||||
resolve(value);
|
||||
},
|
||||
reject: (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
this.write({
|
||||
id,
|
||||
method,
|
||||
params,
|
||||
});
|
||||
|
||||
return responsePromise;
|
||||
}
|
||||
|
||||
notify(method: string, params: JsonValue) {
|
||||
this.write({
|
||||
method,
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
respond(id: JsonRpcId, result: JsonValue) {
|
||||
this.write({
|
||||
id,
|
||||
result,
|
||||
});
|
||||
}
|
||||
|
||||
respondError(id: JsonRpcId, code: number, message: string) {
|
||||
this.write({
|
||||
id,
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async handleStdoutLine(line: string) {
|
||||
if (line.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.stdout.write(`<<< ${line}\n`);
|
||||
|
||||
let message: JsonRpcMessage;
|
||||
try {
|
||||
message = JSON.parse(line) as JsonRpcMessage;
|
||||
} catch (error) {
|
||||
process.stdout.write(`[parse-error] ${(error as Error).message}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.id !== "undefined" && !message.method) {
|
||||
const pending = this.pending.get(message.id);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
this.pending.delete(message.id);
|
||||
if (typeof message.error !== "undefined") {
|
||||
pending.reject(
|
||||
new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.resolve(message.result);
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.method === "session/request_permission" && typeof message.id !== "undefined") {
|
||||
this.respond(message.id, {
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "allow",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.id !== "undefined" && message.id !== "") {
|
||||
this.respondError(
|
||||
message.id,
|
||||
-32601,
|
||||
`Unhandled server request: ${message.method ?? "unknown"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
this.child.kill("SIGTERM");
|
||||
await sleep(250);
|
||||
if (!this.closed) {
|
||||
this.child.kill("SIGKILL");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function setSelectOptionIfAdvertised(
|
||||
rpc: JsonRpcChild,
|
||||
sessionId: string,
|
||||
configOptions: SessionConfigOption[],
|
||||
predicate: (option: SessionConfigOption) => boolean,
|
||||
value: string,
|
||||
label: string,
|
||||
) {
|
||||
if (value.length === 0) {
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
const option = findConfigOption(configOptions, predicate);
|
||||
const values = flattenSelectValues(option);
|
||||
if (!option || !values.includes(value)) {
|
||||
logSection(`SKIP_${label}`, {
|
||||
requestedValue: value,
|
||||
availableValues: values,
|
||||
});
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
const response = (await rpc.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: option.id,
|
||||
value,
|
||||
})) as SetConfigResult | null | undefined;
|
||||
|
||||
logSection(`SET_${label}_RESPONSE`, response);
|
||||
return response?.configOptions ?? configOptions;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);
|
||||
|
||||
try {
|
||||
const initializeResponse = await rpc.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
},
|
||||
clientInfo: {
|
||||
name: "cursor-acp-model-mismatch-probe",
|
||||
version: "0.0.0",
|
||||
},
|
||||
});
|
||||
logSection("INITIALIZE_RESPONSE", initializeResponse);
|
||||
|
||||
const authenticateResponse = await rpc.request("authenticate", {
|
||||
methodId: "cursor_login",
|
||||
});
|
||||
logSection("AUTHENTICATE_RESPONSE", authenticateResponse);
|
||||
|
||||
const sessionResponse = (await rpc.request("session/new", {
|
||||
cwd: targetCwd,
|
||||
mcpServers: [],
|
||||
})) as SessionNewResult;
|
||||
logSection("SESSION_NEW_RESPONSE", sessionResponse);
|
||||
|
||||
const sessionId = asString(sessionResponse.sessionId);
|
||||
if (!sessionId) {
|
||||
fail("session/new did not return a sessionId.");
|
||||
}
|
||||
|
||||
let configOptions = sessionResponse.configOptions ?? [];
|
||||
const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");
|
||||
const advertisedModels = flattenSelectValues(modelConfig);
|
||||
logSection("ADVERTISED_MODEL_VALUES", advertisedModels);
|
||||
|
||||
if (!modelConfig || modelConfig.type !== "select") {
|
||||
fail("Cursor ACP did not expose a select-type model config option.");
|
||||
}
|
||||
|
||||
if (!advertisedModels.includes(targetModel)) {
|
||||
fail(
|
||||
`Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
const setModelResponse = (await rpc.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: modelConfig.id,
|
||||
value: targetModel,
|
||||
})) as SetConfigResult | null | undefined;
|
||||
logSection("SET_MODEL_RESPONSE", setModelResponse);
|
||||
|
||||
configOptions = setModelResponse?.configOptions ?? configOptions;
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "thought_level",
|
||||
targetReasoning,
|
||||
"REASONING",
|
||||
);
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "model_config" && matchesKeyword(option, "context"),
|
||||
targetContext,
|
||||
"CONTEXT",
|
||||
);
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "model_config" && matchesKeyword(option, "fast"),
|
||||
targetFast,
|
||||
"FAST",
|
||||
);
|
||||
|
||||
const promptResponse = await rpc.request("session/prompt", {
|
||||
sessionId,
|
||||
prompt: [
|
||||
{
|
||||
type: "text",
|
||||
text: promptText,
|
||||
},
|
||||
],
|
||||
});
|
||||
logSection("PROMPT_RESPONSE", promptResponse);
|
||||
|
||||
await sleep(promptWaitMs);
|
||||
rpc.notify("session/cancel", { sessionId });
|
||||
} finally {
|
||||
await rpc.close();
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
process.stderr.write(
|
||||
`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerConfigShape } from "../../config.ts";
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
|
||||
@@ -10,8 +10,10 @@ import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Lay
|
||||
import {
|
||||
AuthControlPlane,
|
||||
AuthControlPlaneError,
|
||||
AuthControlPlaneShape,
|
||||
DEFAULT_SESSION_SUBJECT,
|
||||
} from "../Services/AuthControlPlane.ts";
|
||||
import type {
|
||||
AuthControlPlaneShape,
|
||||
IssuedBearerSession,
|
||||
IssuedPairingLink,
|
||||
} from "../Services/AuthControlPlane.ts";
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
AuthSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Effect, Context } from "effect";
|
||||
import { SessionRole } from "./SessionCredentialService";
|
||||
import type { SessionRole } from "./SessionCredentialService.ts";
|
||||
|
||||
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { deriveAuthClientMetadata } from "./utils";
|
||||
import { deriveAuthClientMetadata } from "./utils.ts";
|
||||
|
||||
describe("deriveAuthClientMetadata", () => {
|
||||
it("labels Electron user agents as Electron instead of Chrome", () => {
|
||||
|
||||
@@ -5,12 +5,12 @@ import * as Layer from "effect/Layer";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { cli } from "./cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
import { cli } from "./cli.ts";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
Command.run(cli, { version }).pipe(
|
||||
Command.run(cli, { version: packageJson.version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
|
||||
@@ -10,7 +10,7 @@ import * as Fiber from "effect/Fiber";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap.ts";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
||||
|
||||
@@ -19,6 +19,8 @@ import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
|
||||
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
|
||||
|
||||
const makeCheckpointStore = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -245,6 +247,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
|
||||
return result.stdout;
|
||||
|
||||
@@ -5,8 +5,8 @@ import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect"
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { deriveServerPaths } from "./config";
|
||||
import { resolveServerConfig } from "./cli";
|
||||
import { deriveServerPaths } from "./config.ts";
|
||||
import { resolveServerConfig } from "./cli.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const defaultObservabilityConfig = {
|
||||
|
||||
+12
-11
@@ -40,30 +40,31 @@ import {
|
||||
RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
type StartupPresentation,
|
||||
} from "./config";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { expandHomePath, resolveBaseDir } from "./os-jank";
|
||||
import { runServer } from "./server";
|
||||
} from "./config.ts";
|
||||
import { readBootstrapEnvelope } from "./bootstrap.ts";
|
||||
import { expandHomePath, resolveBaseDir } from "./os-jank.ts";
|
||||
import { runServer } from "./server.ts";
|
||||
import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";
|
||||
import {
|
||||
formatIssuedPairingCredential,
|
||||
formatIssuedSession,
|
||||
formatPairingCredentialList,
|
||||
formatSessionList,
|
||||
} from "./cliAuthFormat";
|
||||
import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
|
||||
} from "./cliAuthFormat.ts";
|
||||
import { AuthControlPlane } from "./auth/Services/AuthControlPlane.ts";
|
||||
import type { AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
|
||||
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup";
|
||||
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup.ts";
|
||||
import {
|
||||
clearPersistedServerRuntimeState,
|
||||
readPersistedServerRuntimeState,
|
||||
} from "./serverRuntimeState";
|
||||
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
|
||||
} from "./serverRuntimeState.ts";
|
||||
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
normalizeCodexModelSlug,
|
||||
readCodexAccountSnapshot,
|
||||
resolveCodexModelForAccount,
|
||||
} from "./codexAppServerManager";
|
||||
} from "./codexAppServerManager.ts";
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
|
||||
@@ -25,16 +25,17 @@ import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "./provider/codexCliVersion";
|
||||
} from "./provider/codexCliVersion.ts";
|
||||
import {
|
||||
readCodexAccountSnapshot,
|
||||
resolveCodexModelForAccount,
|
||||
type CodexAccountSnapshot,
|
||||
} from "./provider/codexAccount";
|
||||
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
|
||||
} from "./provider/codexAccount.ts";
|
||||
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer.ts";
|
||||
import { expandHomePath } from "./pathExpansion.ts";
|
||||
|
||||
export { buildCodexInitializeParams } from "./provider/codexAppServer";
|
||||
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
|
||||
export { buildCodexInitializeParams } from "./provider/codexAppServer.ts";
|
||||
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount.ts";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -493,7 +494,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
...(codexHomePath ? { CODEX_HOME: expandHomePath(codexHomePath) } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
@@ -1571,7 +1572,7 @@ function assertSupportedCodexCliVersion(input: {
|
||||
cwd: input.cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
|
||||
...(input.homePath ? { CODEX_HOME: expandHomePath(input.homePath) } : {}),
|
||||
},
|
||||
encoding: "utf8",
|
||||
shell: process.platform === "win32",
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Effect, FileSystem, Layer, Path, Random } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
|
||||
import { version } from "../../../package.json" with { type: "json" };
|
||||
import packageJson from "../../../package.json" with { type: "json" };
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
|
||||
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
|
||||
@@ -77,7 +77,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
|
||||
os: platformOs(),
|
||||
arch: platformArch(),
|
||||
},
|
||||
serverVersion: version,
|
||||
serverVersion: packageJson.version,
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
},
|
||||
|
||||
@@ -11,7 +11,6 @@ import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
@@ -30,6 +29,7 @@ import {
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||
import { resolveClaudeApiModelId } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
|
||||
@@ -110,7 +110,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
"--json-schema",
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
resolveApiModelId(modelSelection),
|
||||
resolveClaudeApiModelId(modelSelection),
|
||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
|
||||
@@ -8,6 +8,7 @@ import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shar
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
@@ -184,7 +185,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
...(codexSettings?.homePath
|
||||
? { CODEX_HOME: expandHomePath(codexSettings.homePath) }
|
||||
: {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
|
||||
function shellSingleQuote(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-cursor-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
|
||||
const binDir = path.join(dir, "bin");
|
||||
const agentPath = path.join(binDir, "agent");
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
writeFileSync(
|
||||
agentPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
|
||||
'if [ "$1" != "acp" ]; then',
|
||||
' printf "%s\\n" "unexpected args: $*" >&2',
|
||||
" exit 11",
|
||||
"fi",
|
||||
`exec bun ${JSON.stringify(mockAgentPath)}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
chmodSync(agentPath, 0o755);
|
||||
return agentPath;
|
||||
}
|
||||
|
||||
function withFakeAcpAgent<A, E, R>(
|
||||
env: Record<string, string>,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
|
||||
return Effect.gen(function* () {
|
||||
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
|
||||
const agentPath = makeAcpAgentWrapper(tempDir, env);
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const previousSettings = yield* serverSettings.getSettings;
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
cursor: {
|
||||
binaryPath: agentPath,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return yield* effect.pipe(
|
||||
Effect.ensuring(
|
||||
serverSettings
|
||||
.updateSettings({
|
||||
providers: {
|
||||
cursor: {
|
||||
binaryPath: previousSettings.providers.cursor.binaryPath,
|
||||
},
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch(() => Effect.void),
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForFileContent(path: string): Effect.Effect<string> {
|
||||
return Effect.promise(async () => {
|
||||
const deadline = Date.now() + 5_000;
|
||||
for (;;) {
|
||||
try {
|
||||
return readFileSync(path, "utf8");
|
||||
} catch (error) {
|
||||
if (Date.now() >= deadline) {
|
||||
throw error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
|
||||
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
|
||||
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
|
||||
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
|
||||
|
||||
return withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
subject: "Add generated commit message",
|
||||
body: "- verify cursor acp model config path",
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/cursor-text-generation",
|
||||
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoning: "xhigh",
|
||||
fastMode: true,
|
||||
contextWindow: "1m",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add generated commit message");
|
||||
expect(generated.body).toBe("- verify cursor acp model config path");
|
||||
|
||||
const requests = readFileSync(requestLogPath, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
|
||||
|
||||
expect(
|
||||
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
|
||||
).toMatchObject({
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_config_option" &&
|
||||
request.params?.configId === "model" &&
|
||||
request.params?.value === "gpt-5.4",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_config_option" &&
|
||||
request.params?.configId === "reasoning" &&
|
||||
request.params?.value === "extra-high",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_config_option" &&
|
||||
request.params?.configId === "context" &&
|
||||
request.params?.value === "1m",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_config_option" &&
|
||||
request.params?.configId === "fast" &&
|
||||
request.params?.value === "true",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: "text",
|
||||
text: expect.stringContaining("Staged patch:"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
rmSync(requestLogDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("accepts json objects with extra assistant text around them", () =>
|
||||
withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT:
|
||||
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/cursor-noisy-json",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "composer-2",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
|
||||
expect(generated.body).toBe("");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates thread titles through Cursor ACP text generation", () =>
|
||||
withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
title: '"Trim reconnect spinner status after resume."',
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix the reconnect spinner after a resumed session.",
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "composer-2",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("closes the ACP child process after text generation completes", () => {
|
||||
const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
|
||||
const exitLogPath = path.join(exitLogDir, "exit.log");
|
||||
|
||||
return withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
subject: "Close runtime after generation",
|
||||
body: "",
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/cursor-runtime-close",
|
||||
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "composer-2",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Close runtime after generation");
|
||||
|
||||
const exitLog = yield* waitForFileContent(exitLogPath);
|
||||
expect(exitLog).toContain("exit:0");
|
||||
|
||||
rmSync(exitLogDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,309 @@
|
||||
import { Effect, Layer, Option, Ref, Schema } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { CursorModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
type ThreadTitleGenerationResult,
|
||||
type TextGenerationShape,
|
||||
TextGeneration,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "../Prompts.ts";
|
||||
import {
|
||||
extractJsonObject,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
} from "../Utils.ts";
|
||||
import {
|
||||
applyCursorAcpModelSelection,
|
||||
makeCursorAcpRuntime,
|
||||
} from "../../provider/acp/CursorAcpSupport.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const CURSOR_TIMEOUT_MS = 180_000;
|
||||
|
||||
function mapCursorAcpError(
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
detail: string,
|
||||
cause: unknown,
|
||||
): TextGenerationError {
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function isTextGenerationError(error: unknown): error is TextGenerationError {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "TextGenerationError"
|
||||
);
|
||||
}
|
||||
|
||||
const makeCursorTextGeneration = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||
|
||||
const runCursorJson = <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: CursorModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const cursorSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.cursor,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const outputRef = yield* Ref.make("");
|
||||
const runtime = yield* makeCursorAcpRuntime({
|
||||
cursorSettings,
|
||||
childProcessSpawner: commandSpawner,
|
||||
cwd,
|
||||
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
|
||||
});
|
||||
|
||||
yield* runtime.handleSessionUpdate((notification) => {
|
||||
const update = notification.update;
|
||||
if (update.sessionUpdate !== "agent_message_chunk") {
|
||||
return Effect.void;
|
||||
}
|
||||
const content = update.content;
|
||||
if (content.type !== "text") {
|
||||
return Effect.void;
|
||||
}
|
||||
return Ref.update(outputRef, (current) => current + content.text);
|
||||
});
|
||||
|
||||
const promptResult = yield* Effect.gen(function* () {
|
||||
yield* runtime.start();
|
||||
yield* Effect.ignore(runtime.setMode("ask"));
|
||||
yield* applyCursorAcpModelSelection({
|
||||
runtime,
|
||||
model: modelSelection.model,
|
||||
modelOptions: modelSelection.options,
|
||||
mapError: ({ cause, configId, step }) =>
|
||||
mapCursorAcpError(
|
||||
operation,
|
||||
step === "set-config-option"
|
||||
? `Failed to set Cursor ACP config option "${configId}" for text generation.`
|
||||
: "Failed to set Cursor ACP base model for text generation.",
|
||||
cause,
|
||||
),
|
||||
});
|
||||
|
||||
return yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: prompt }],
|
||||
});
|
||||
}).pipe(
|
||||
Effect.timeoutOption(CURSOR_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Cursor Agent request timed out.",
|
||||
}),
|
||||
),
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: mapCursorAcpError(operation, "Cursor ACP request failed.", cause),
|
||||
),
|
||||
);
|
||||
|
||||
const rawResult = (yield* Ref.get(outputRef)).trim();
|
||||
if (!rawResult) {
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
promptResult.stopReason === "cancelled"
|
||||
? "Cursor ACP request was cancelled."
|
||||
: "Cursor Agent returned empty output.",
|
||||
});
|
||||
}
|
||||
|
||||
return yield* Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))(
|
||||
extractJsonObject(rawResult),
|
||||
).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Cursor Agent returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: mapCursorAcpError(operation, "Cursor ACP text generation failed.", cause),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"CursorTextGeneration.generateCommitMessage",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||
branch: input.branch,
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "cursor") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateCommitMessage",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
||||
"CursorTextGeneration.generatePrContent",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||
baseBranch: input.baseBranch,
|
||||
headBranch: input.headBranch,
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "cursor") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generatePrContent",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
});
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
||||
"CursorTextGeneration.generateBranchName",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "cursor") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||
"CursorTextGeneration.generateThreadTitle",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "cursor") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
} satisfies ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
export const CursorTextGenerationLive = Layer.effect(TextGeneration, makeCursorTextGeneration);
|
||||
@@ -6,7 +6,7 @@ vi.mock("../../processRunner", () => ({
|
||||
runProcess: vi.fn(),
|
||||
}));
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { GitHubCli } from "../Services/GitHubCli.ts";
|
||||
import { GitHubCliLive } from "./GitHubCli.ts";
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { GitHubCliError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitHubCli,
|
||||
|
||||
@@ -38,7 +38,8 @@ import {
|
||||
type GitManagerShape,
|
||||
type GitRunStackedActionOptions,
|
||||
} from "../Services/GitManager.ts";
|
||||
import { GitCore, GitStatusDetails } from "../Services/GitCore.ts";
|
||||
import { GitCore } from "../Services/GitCore.ts";
|
||||
import type { GitStatusDetails } from "../Services/GitCore.ts";
|
||||
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Duration, Effect, Layer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { beforeEach, expect, vi } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
|
||||
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
const 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,
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.startCalls.length = 0;
|
||||
state.promptUrls.length = 0;
|
||||
state.authHeaders.length = 0;
|
||||
state.closeCalls.length = 0;
|
||||
state.promptResult = undefined;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../provider/opencodeRuntime.ts", async () => {
|
||||
const actual = await vi.importActual<typeof import("../../provider/opencodeRuntime.ts")>(
|
||||
"../../provider/opencodeRuntime.ts",
|
||||
);
|
||||
|
||||
return {
|
||||
...actual,
|
||||
startOpenCodeServerProcess: vi.fn(async ({ binaryPath }: { binaryPath: string }) => {
|
||||
const index = runtimeMock.state.startCalls.length + 1;
|
||||
const url = `http://127.0.0.1:${4_300 + index}`;
|
||||
runtimeMock.state.startCalls.push(binaryPath);
|
||||
return {
|
||||
url,
|
||||
process: {} as ChildProcess,
|
||||
close: () => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
},
|
||||
};
|
||||
}),
|
||||
createOpenCodeSdkClient: vi.fn(
|
||||
({ baseUrl, serverPassword }: { baseUrl: string; serverPassword?: string }) => ({
|
||||
session: {
|
||||
create: vi.fn(async () => ({ data: { id: `${baseUrl}/session` } })),
|
||||
prompt: vi.fn(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.",
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
);
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
provider: "opencode" as const,
|
||||
model: "openai/gpt-5",
|
||||
};
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
|
||||
|
||||
const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-opencode-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-opencode-text-generation-existing-server-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMock.reset();
|
||||
});
|
||||
|
||||
const advanceIdleClock = Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
|
||||
yield* Effect.yieldNow;
|
||||
});
|
||||
|
||||
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
|
||||
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
|
||||
expect(runtimeMock.state.promptUrls).toEqual([
|
||||
"http://127.0.0.1:4301",
|
||||
"http://127.0.0.1:4301",
|
||||
]);
|
||||
expect(runtimeMock.state.closeCalls).toEqual([]);
|
||||
|
||||
yield* advanceIdleClock;
|
||||
|
||||
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("starts a new server after the warm server idles out", () =>
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
yield* advanceIdleClock;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
|
||||
expect(runtimeMock.state.promptUrls).toEqual([
|
||||
"http://127.0.0.1:4301",
|
||||
"http://127.0.0.1:4302",
|
||||
]);
|
||||
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.promptResult = { data: {} };
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("OpenCode returned empty output.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("parses JSON returned as plain text output", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.promptResult = {
|
||||
data: {
|
||||
parts: [
|
||||
{
|
||||
type: "text",
|
||||
text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const result = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
subject: "Tighten OpenCode parsing",
|
||||
body: "Handle JSON text output locally.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces the upstream OpenCode structured-output error message", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.promptResult = {
|
||||
data: {
|
||||
info: {
|
||||
error: {
|
||||
name: "StructuredOutputError",
|
||||
data: {
|
||||
message: "Model did not produce structured output",
|
||||
retries: 2,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("Model did not produce structured output");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
|
||||
"OpenCodeTextGenerationLive with configured server URL",
|
||||
(it) => {
|
||||
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(runtimeMock.state.startCalls).toEqual([]);
|
||||
expect(runtimeMock.state.promptUrls).toEqual([
|
||||
"http://127.0.0.1:9999",
|
||||
"http://127.0.0.1:9999",
|
||||
]);
|
||||
expect(runtimeMock.state.authHeaders).toEqual([
|
||||
`Basic ${btoa("opencode:secret-password")}`,
|
||||
`Basic ${btoa("opencode:secret-password")}`,
|
||||
]);
|
||||
|
||||
yield* advanceIdleClock;
|
||||
|
||||
expect(runtimeMock.state.closeCalls).toEqual([]);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,468 @@
|
||||
import { Duration, Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import {
|
||||
TextGenerationError,
|
||||
type ChatAttachment,
|
||||
type OpenCodeModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "../Prompts.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
extractJsonObject,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
} from "../Utils.ts";
|
||||
import {
|
||||
createOpenCodeSdkClient,
|
||||
type OpenCodeServerConnection,
|
||||
type OpenCodeServerProcess,
|
||||
parseOpenCodeModelSlug,
|
||||
startOpenCodeServerProcess,
|
||||
toOpenCodeFileParts,
|
||||
} from "../../provider/opencodeRuntime.ts";
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
|
||||
|
||||
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;
|
||||
binaryPath: string | null;
|
||||
activeRequests: number;
|
||||
idleCloseFiber: Fiber.Fiber<void, never> | null;
|
||||
}
|
||||
|
||||
const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const sharedServerMutex = yield* Semaphore.make(1);
|
||||
const sharedServerState: SharedOpenCodeTextGenerationServerState = {
|
||||
server: null,
|
||||
binaryPath: null,
|
||||
activeRequests: 0,
|
||||
idleCloseFiber: null,
|
||||
};
|
||||
|
||||
const closeSharedServer = (server: OpenCodeServerProcess) => {
|
||||
if (sharedServerState.server === server) {
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
}
|
||||
server.close();
|
||||
};
|
||||
|
||||
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(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS)).pipe(
|
||||
Effect.andThen(
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.sync(() => {
|
||||
if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) {
|
||||
return;
|
||||
}
|
||||
sharedServerState.idleCloseFiber = null;
|
||||
closeSharedServer(server);
|
||||
}),
|
||||
),
|
||||
),
|
||||
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
|
||||
) {
|
||||
closeSharedServer(existingServer);
|
||||
} 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;
|
||||
}
|
||||
}
|
||||
|
||||
const server = yield* Effect.tryPromise({
|
||||
try: () => startOpenCodeServerProcess({ binaryPath: input.binaryPath }),
|
||||
catch: (cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: cause instanceof Error ? cause.message : "Failed to start OpenCode server.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
sharedServerState.server = server;
|
||||
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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
yield* cancelIdleCloseFiber();
|
||||
const server = sharedServerState.server;
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
sharedServerState.activeRequests = 0;
|
||||
if (server !== null) {
|
||||
server.close();
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
|
||||
readonly operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
readonly cwd: string;
|
||||
readonly prompt: string;
|
||||
readonly outputSchemaJson: S;
|
||||
readonly modelSelection: OpenCodeModelSelection;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}) {
|
||||
const parsedModel = parseOpenCodeModelSlug(input.modelSelection.model);
|
||||
if (!parsedModel) {
|
||||
return yield* new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: "OpenCode model selection must use the 'provider/model' format.",
|
||||
});
|
||||
}
|
||||
|
||||
const settings = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.map(
|
||||
(value) =>
|
||||
value.providers?.opencode ?? {
|
||||
enabled: true,
|
||||
binaryPath: "opencode",
|
||||
serverUrl: "",
|
||||
serverPassword: "",
|
||||
customModels: [],
|
||||
},
|
||||
),
|
||||
Effect.orElseSucceed(() => ({
|
||||
enabled: true,
|
||||
binaryPath: "opencode",
|
||||
serverUrl: "",
|
||||
serverPassword: "",
|
||||
customModels: [],
|
||||
})),
|
||||
);
|
||||
|
||||
const fileParts = toOpenCodeFileParts({
|
||||
attachments: input.attachments,
|
||||
resolveAttachmentPath: (attachment) =>
|
||||
resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
|
||||
});
|
||||
|
||||
const runAgainstServer = (server: Pick<OpenCodeServerConnection, "url">) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const client = createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(settings.serverUrl.length > 0 && settings.serverPassword
|
||||
? { serverPassword: settings.serverPassword }
|
||||
: {}),
|
||||
});
|
||||
const session = await client.session.create({
|
||||
title: `T3 Code ${input.operation}`,
|
||||
permission: [{ permission: "*", pattern: "*", action: "deny" }],
|
||||
});
|
||||
if (!session.data) {
|
||||
throw new Error("OpenCode session.create returned no session payload.");
|
||||
}
|
||||
|
||||
const result = await client.session.prompt({
|
||||
sessionID: session.data.id,
|
||||
model: parsedModel,
|
||||
...(input.modelSelection.options?.agent
|
||||
? { agent: input.modelSelection.options.agent }
|
||||
: {}),
|
||||
...(input.modelSelection.options?.variant
|
||||
? { variant: input.modelSelection.options.variant }
|
||||
: {}),
|
||||
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:
|
||||
cause instanceof Error ? cause.message : "OpenCode text generation request failed.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const rawOutput =
|
||||
settings.serverUrl.length > 0
|
||||
? yield* runAgainstServer({ url: settings.serverUrl })
|
||||
: yield* Effect.acquireUseRelease(
|
||||
acquireSharedServer({
|
||||
binaryPath: settings.binaryPath,
|
||||
operation: input.operation,
|
||||
}),
|
||||
runAgainstServer,
|
||||
releaseSharedServer,
|
||||
);
|
||||
|
||||
return yield* Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson))(
|
||||
extractJsonObject(rawOutput),
|
||||
).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: "OpenCode returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"OpenCodeTextGeneration.generateCommitMessage",
|
||||
)(function* (input) {
|
||||
if (input.modelSelection.provider !== "opencode") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateCommitMessage",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||
branch: input.branch,
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
||||
"OpenCodeTextGeneration.generatePrContent",
|
||||
)(function* (input) {
|
||||
if (input.modelSelection.provider !== "opencode") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generatePrContent",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||
baseBranch: input.baseBranch,
|
||||
headBranch: input.headBranch,
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
});
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
||||
"OpenCodeTextGeneration.generateBranchName",
|
||||
)(function* (input) {
|
||||
if (input.modelSelection.provider !== "opencode") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||
"OpenCodeTextGeneration.generateThreadTitle",
|
||||
)(function* (input) {
|
||||
if (input.modelSelection.provider !== "opencode") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
export const OpenCodeTextGenerationLive = Layer.effect(TextGeneration, makeOpenCodeTextGeneration);
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
} from "../Services/TextGeneration.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
|
||||
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal service tags so both concrete layers can coexist.
|
||||
@@ -31,6 +33,14 @@ class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>(
|
||||
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
|
||||
) {}
|
||||
|
||||
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
|
||||
) {}
|
||||
|
||||
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",
|
||||
) {}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Routing implementation
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -38,9 +48,17 @@ class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>(
|
||||
const makeRoutingTextGeneration = Effect.gen(function* () {
|
||||
const codex = yield* CodexTextGen;
|
||||
const claude = yield* ClaudeTextGen;
|
||||
const cursor = yield* CursorTextGen;
|
||||
const openCode = yield* OpenCodeTextGen;
|
||||
|
||||
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
|
||||
provider === "claudeAgent" ? claude : codex;
|
||||
provider === "claudeAgent"
|
||||
? claude
|
||||
: provider === "opencode"
|
||||
? openCode
|
||||
: provider === "cursor"
|
||||
? cursor
|
||||
: codex;
|
||||
|
||||
return {
|
||||
generateCommitMessage: (input) =>
|
||||
@@ -67,7 +85,28 @@ const InternalClaudeLayer = Layer.effect(
|
||||
}),
|
||||
).pipe(Layer.provide(ClaudeTextGenerationLive));
|
||||
|
||||
const InternalCursorLayer = Layer.effect(
|
||||
CursorTextGen,
|
||||
Effect.gen(function* () {
|
||||
const svc = yield* TextGeneration;
|
||||
return svc;
|
||||
}),
|
||||
).pipe(Layer.provide(CursorTextGenerationLive));
|
||||
|
||||
const InternalOpenCodeLayer = Layer.effect(
|
||||
OpenCodeTextGen,
|
||||
Effect.gen(function* () {
|
||||
const svc = yield* TextGeneration;
|
||||
return svc;
|
||||
}),
|
||||
).pipe(Layer.provide(OpenCodeTextGenerationLive));
|
||||
|
||||
export const RoutingTextGenerationLive = Layer.effect(
|
||||
TextGeneration,
|
||||
makeRoutingTextGeneration,
|
||||
).pipe(Layer.provide(InternalCodexLayer), Layer.provide(InternalClaudeLayer));
|
||||
).pipe(
|
||||
Layer.provide(InternalCodexLayer),
|
||||
Layer.provide(InternalClaudeLayer),
|
||||
Layer.provide(InternalCursorLayer),
|
||||
Layer.provide(InternalOpenCodeLayer),
|
||||
);
|
||||
@@ -8,7 +8,7 @@
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProcessRunResult } from "../../processRunner";
|
||||
import type { ProcessRunResult } from "../../processRunner.ts";
|
||||
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";
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
|
||||
|
||||
export interface CommitMessageGenerationInput {
|
||||
cwd: string;
|
||||
|
||||
@@ -30,6 +30,54 @@ export function limitSection(value: string, maxChars: number): string {
|
||||
return `${truncated}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
export function extractJsonObject(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const start = trimmed.indexOf("{");
|
||||
if (start < 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
let depth = 0;
|
||||
let inString = false;
|
||||
let escaping = false;
|
||||
for (let index = start; index < trimmed.length; index += 1) {
|
||||
const char = trimmed[index];
|
||||
if (inString) {
|
||||
if (escaping) {
|
||||
escaping = false;
|
||||
} else if (char === "\\") {
|
||||
escaping = true;
|
||||
} else if (char === '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === '"') {
|
||||
inString = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "{") {
|
||||
depth += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
return trimmed.slice(start, index + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return trimmed.slice(start);
|
||||
}
|
||||
|
||||
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
|
||||
export function sanitizeCommitSubject(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
|
||||
@@ -15,12 +15,12 @@ import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths";
|
||||
import { resolveAttachmentPathById } from "./attachmentStore";
|
||||
import { resolveStaticDir, ServerConfig } from "./config";
|
||||
} from "./attachmentPaths.ts";
|
||||
import { resolveAttachmentPathById } from "./attachmentStore.ts";
|
||||
import { resolveStaticDir, ServerConfig } from "./config.ts";
|
||||
import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
|
||||
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
|
||||
import { respondToAuthError } from "./auth/http.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
|
||||
@@ -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";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
compileResolvedKeybindingRule,
|
||||
compileResolvedKeybindingsConfig,
|
||||
parseKeybindingShortcut,
|
||||
} from "./keybindings";
|
||||
} from "./keybindings.ts";
|
||||
import { KeybindingsConfigError } from "@t3tools/contracts";
|
||||
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
@@ -192,6 +192,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.9"), "mod+9");
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -13,13 +13,14 @@ 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 { Mutable } from "effect/Types";
|
||||
import type { Mutable } from "effect/Types";
|
||||
import {
|
||||
Array,
|
||||
Cache,
|
||||
@@ -44,7 +45,7 @@ import {
|
||||
Stream,
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
type WhenToken =
|
||||
@@ -65,6 +66,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+o", command: "editor.openFavorite" },
|
||||
{ key: "mod+shift+[", command: "thread.previous" },
|
||||
{ key: "mod+shift+]", command: "thread.next" },
|
||||
@@ -72,6 +74,11 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
key: `mod+${index + 1}`,
|
||||
command,
|
||||
})),
|
||||
...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
|
||||
key: `mod+${index + 1}`,
|
||||
command,
|
||||
when: "modelPickerOpen",
|
||||
})),
|
||||
];
|
||||
|
||||
function normalizeKeyToken(token: string): string {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type * as Exit from "effect/Exit";
|
||||
import { Effect, Option, Tracer } from "effect";
|
||||
|
||||
import { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts";
|
||||
import { spanToTraceRecord } from "./TraceRecord.ts";
|
||||
import type { EffectTraceRecord } from "./TraceRecord.ts";
|
||||
import { makeTraceSink, type TraceSink } from "./TraceSink.ts";
|
||||
|
||||
export interface LocalFileTracerOptions {
|
||||
@@ -27,12 +28,16 @@ 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],
|
||||
private readonly delegate: Tracer.Span,
|
||||
private readonly push: (record: EffectTraceRecord) => void,
|
||||
delegate: Tracer.Span,
|
||||
push: (record: EffectTraceRecord) => void,
|
||||
) {
|
||||
this.delegate = delegate;
|
||||
this.push = push;
|
||||
this.name = delegate.name;
|
||||
this.spanId = delegate.spanId;
|
||||
this.traceId = delegate.traceId;
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
launchDetached,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
} from "./open.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
|
||||
+2
-112
@@ -7,10 +7,9 @@
|
||||
* @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";
|
||||
|
||||
// ==============================
|
||||
@@ -18,6 +17,7 @@ import { Context, Effect, Layer } from "effect";
|
||||
// ==============================
|
||||
|
||||
export { OpenError };
|
||||
export { isCommandAvailable } from "@t3tools/shared/shell";
|
||||
|
||||
export interface OpenInEditorInput {
|
||||
readonly cwd: string;
|
||||
@@ -29,11 +29,6 @@ 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): {
|
||||
@@ -106,111 +101,6 @@ 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,
|
||||
|
||||
@@ -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 { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import type { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
|
||||
|
||||
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
|
||||
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
|
||||
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
|
||||
|
||||
@@ -17,7 +18,7 @@ describe("OrchestrationReactor", () => {
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
it("starts provider ingestion, provider command, and checkpoint reactors", async () => {
|
||||
it("starts provider ingestion, provider command, checkpoint, and thread deletion reactors", async () => {
|
||||
const started: string[] = [];
|
||||
|
||||
runtime = ManagedRuntime.make(
|
||||
@@ -49,10 +50,19 @@ describe("OrchestrationReactor", () => {
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadDeletionReactor, {
|
||||
start: () => {
|
||||
started.push("thread-deletion-reactor");
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor));
|
||||
const reactor = await runtime!.runPromise(Effect.service(OrchestrationReactor));
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
||||
|
||||
@@ -60,6 +70,7 @@ describe("OrchestrationReactor", () => {
|
||||
"provider-runtime-ingestion",
|
||||
"provider-command-reactor",
|
||||
"checkpoint-reactor",
|
||||
"thread-deletion-reactor",
|
||||
]);
|
||||
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
|
||||
@@ -7,16 +7,19 @@ import {
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
|
||||
|
||||
export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
|
||||
const providerCommandReactor = yield* ProviderCommandReactor;
|
||||
const checkpointReactor = yield* CheckpointReactor;
|
||||
const threadDeletionReactor = yield* ThreadDeletionReactor;
|
||||
|
||||
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
yield* providerRuntimeIngestion.start();
|
||||
yield* providerCommandReactor.start();
|
||||
yield* checkpointReactor.start();
|
||||
yield* threadDeletionReactor.start();
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -266,7 +266,7 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
||||
@@ -750,6 +750,57 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the active session model when in-session model switching is unsupported", async () => {
|
||||
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-unsupported-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-unsupported-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
|
||||
@@ -802,57 +853,6 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the active session model when in-session model switching is unsupported", async () => {
|
||||
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-unsupported-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-unsupported-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -1100,6 +1100,71 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not stop the active session when restart fails before rebind", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-restart-failure-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-restart-failure-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
harness.startSession.mockImplementationOnce(
|
||||
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-restart-failure"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await harness.drain();
|
||||
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("rejects provider changes after a thread is already bound to a session provider", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -1172,71 +1237,6 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not stop the active session when restart fails before rebind", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-restart-failure-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-restart-failure-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
harness.startSession.mockImplementationOnce(
|
||||
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-restart-failure"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await harness.drain();
|
||||
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -19,7 +19,8 @@ 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, ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import type { 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";
|
||||
@@ -88,9 +89,16 @@ function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolea
|
||||
: false;
|
||||
}
|
||||
|
||||
function findProviderAdapterRequestError(
|
||||
cause: Cause.Cause<ProviderServiceError>,
|
||||
): ProviderAdapterRequestError | undefined {
|
||||
const failReason = cause.reasons.find(Cause.isFailReason);
|
||||
return Schema.is(ProviderAdapterRequestError)(failReason?.error) ? failReason.error : undefined;
|
||||
}
|
||||
|
||||
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = Cause.squash(cause);
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
const error = findProviderAdapterRequestError(cause);
|
||||
if (error) {
|
||||
const detail = error.detail.toLowerCase();
|
||||
return (
|
||||
detail.includes("unknown pending approval request") ||
|
||||
@@ -105,8 +113,8 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
|
||||
}
|
||||
|
||||
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = Cause.squash(cause);
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
const error = findProviderAdapterRequestError(cause);
|
||||
if (error) {
|
||||
return error.detail.toLowerCase().includes("unknown pending user-input request");
|
||||
}
|
||||
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
|
||||
@@ -197,6 +205,17 @@ const make = Effect.gen(function* () {
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
|
||||
const failReason = cause.reasons.find(Cause.isFailReason);
|
||||
const providerError = Schema.is(ProviderAdapterRequestError)(failReason?.error)
|
||||
? failReason.error
|
||||
: undefined;
|
||||
if (providerError) {
|
||||
return providerError.detail;
|
||||
}
|
||||
return Cause.pretty(cause);
|
||||
};
|
||||
|
||||
const setThreadSession = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly session: OrchestrationSession;
|
||||
@@ -210,7 +229,30 @@ const make = Effect.gen(function* () {
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) {
|
||||
const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
const session = thread?.session;
|
||||
if (!session) {
|
||||
return;
|
||||
}
|
||||
yield* setThreadSession({
|
||||
threadId: input.threadId,
|
||||
session: {
|
||||
...session,
|
||||
status: session.status === "stopped" ? "stopped" : "ready",
|
||||
activeTurnId: null,
|
||||
lastError: input.detail,
|
||||
updatedAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
return readModel.threads.find((entry) => entry.id === threadId);
|
||||
});
|
||||
@@ -246,7 +288,7 @@ const make = Effect.gen(function* () {
|
||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
|
||||
const preferredProvider: ProviderKind = threadProvider;
|
||||
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
@@ -292,9 +334,6 @@ const make = Effect.gen(function* () {
|
||||
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
@@ -302,7 +341,7 @@ const make = Effect.gen(function* () {
|
||||
const modelChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.model !== activeSession?.model;
|
||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
|
||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
|
||||
const previousModelSelection = threadModelSelections.get(threadId);
|
||||
const shouldRestartForModelSelectionChange =
|
||||
currentProvider === "claudeAgent" &&
|
||||
@@ -311,17 +350,15 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (
|
||||
!runtimeModeChanged &&
|
||||
!providerChanged &&
|
||||
!shouldRestartForModelChange &&
|
||||
!shouldRestartForModelSelectionChange
|
||||
) {
|
||||
return existingSessionThreadId;
|
||||
}
|
||||
|
||||
const resumeCursor =
|
||||
providerChanged || shouldRestartForModelChange
|
||||
? undefined
|
||||
: (activeSession?.resumeCursor ?? undefined);
|
||||
const resumeCursor = shouldRestartForModelChange
|
||||
? undefined
|
||||
: (activeSession?.resumeCursor ?? undefined);
|
||||
yield* Effect.logInfo("provider command reactor restarting provider session", {
|
||||
threadId,
|
||||
existingSessionThreadId,
|
||||
@@ -330,7 +367,6 @@ const make = Effect.gen(function* () {
|
||||
currentRuntimeMode: thread.session?.runtimeMode,
|
||||
desiredRuntimeMode: thread.runtimeMode,
|
||||
runtimeModeChanged,
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
shouldRestartForModelChange,
|
||||
shouldRestartForModelSelectionChange,
|
||||
@@ -355,7 +391,7 @@ const make = Effect.gen(function* () {
|
||||
return startedSession.threadId;
|
||||
});
|
||||
|
||||
const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: {
|
||||
const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
@@ -365,7 +401,9 @@ const make = Effect.gen(function* () {
|
||||
}) {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
return yield* Effect.die(
|
||||
new Error(`Thread '${input.threadId}' was not found in read model.`),
|
||||
);
|
||||
}
|
||||
yield* ensureSessionForThread(
|
||||
input.threadId,
|
||||
@@ -389,7 +427,7 @@ const make = Effect.gen(function* () {
|
||||
const requestedModelSelection =
|
||||
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
|
||||
const modelForTurn =
|
||||
sessionModelSwitch === "unsupported"
|
||||
sessionModelSwitch === "unsupported" && input.modelSelection === undefined
|
||||
? activeSession?.model !== undefined
|
||||
? {
|
||||
...requestedModelSelection,
|
||||
@@ -398,13 +436,13 @@ const make = Effect.gen(function* () {
|
||||
: requestedModelSelection
|
||||
: input.modelSelection;
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
...(normalizedInput ? { input: normalizedInput } : {}),
|
||||
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
|
||||
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
|
||||
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
||||
});
|
||||
};
|
||||
});
|
||||
|
||||
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(
|
||||
@@ -563,7 +601,43 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
yield* sendTurnForThread({
|
||||
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const detail = formatFailureDetail(cause);
|
||||
return setThreadSessionErrorOnTurnStartFailure({
|
||||
threadId: event.payload.threadId,
|
||||
detail,
|
||||
createdAt: event.payload.createdAt,
|
||||
}).pipe(
|
||||
Effect.flatMap(() =>
|
||||
appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail,
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
};
|
||||
|
||||
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
|
||||
handleTurnStartFailure(cause).pipe(
|
||||
Effect.catchCause((recoveryCause) =>
|
||||
Effect.logWarning("provider command reactor failed to recover turn start failure", {
|
||||
eventType: event.type,
|
||||
threadId: event.payload.threadId,
|
||||
cause: Cause.pretty(recoveryCause),
|
||||
originalCause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const sendTurnRequest = yield* buildSendTurnRequestForThread({
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
@@ -573,17 +647,17 @@ const make = Effect.gen(function* () {
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
}),
|
||||
),
|
||||
Effect.map(Option.some),
|
||||
Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),
|
||||
);
|
||||
|
||||
if (Option.isNone(sendTurnRequest)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* providerService
|
||||
.sendTurn(sendTurnRequest.value)
|
||||
.pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
|
||||
});
|
||||
|
||||
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
|
||||
|
||||
@@ -723,6 +723,146 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves completed tool metadata on projected tool activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-tool-completed-with-data"),
|
||||
provider: "cursor",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-tool-completed"),
|
||||
itemId: asItemId("item-tool-completed"),
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
status: "completed",
|
||||
title: "Read file",
|
||||
data: {
|
||||
toolCallId: "tool-read-1",
|
||||
kind: "read",
|
||||
rawOutput: {
|
||||
content: 'import * as Effect from "effect/Effect"\n',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-tool-completed-with-data",
|
||||
),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-tool-completed-with-data",
|
||||
);
|
||||
const payload =
|
||||
activity?.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
const data =
|
||||
payload?.data && typeof payload.data === "object"
|
||||
? (payload.data as Record<string, unknown>)
|
||||
: undefined;
|
||||
const rawOutput =
|
||||
data?.rawOutput && typeof data.rawOutput === "object"
|
||||
? (data.rawOutput as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
expect(activity?.kind).toBe("tool.completed");
|
||||
expect(activity?.summary).toBe("Read file");
|
||||
expect(payload?.itemType).toBe("dynamic_tool_call");
|
||||
expect(payload?.detail).toBeUndefined();
|
||||
expect(data?.toolCallId).toBe("tool-read-1");
|
||||
expect(data?.kind).toBe("read");
|
||||
expect(rawOutput?.content).toBe('import * as Effect from "effect/Effect"\n');
|
||||
});
|
||||
|
||||
it("normalizes command execution activities to ran-command summaries", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-command-completed"),
|
||||
provider: "cursor",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-command-completed"),
|
||||
itemId: asItemId("item-command-completed"),
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
detail: "bun run lint",
|
||||
data: {
|
||||
toolCallId: "tool-command-1",
|
||||
kind: "execute",
|
||||
command: "bun run lint",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-command-completed",
|
||||
),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-command-completed",
|
||||
);
|
||||
const payload =
|
||||
activity?.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
expect(activity?.summary).toBe("Ran command");
|
||||
expect(payload?.detail).toBe("bun run lint");
|
||||
});
|
||||
|
||||
it("uses structured read-file paths when available", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-read-path-completed"),
|
||||
provider: "cursor",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-read-path"),
|
||||
itemId: asItemId("item-read-path"),
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
status: "completed",
|
||||
title: "Read file",
|
||||
detail: "/tmp/app.ts",
|
||||
data: {
|
||||
toolCallId: "tool-read-path-1",
|
||||
kind: "read",
|
||||
locations: [{ path: "/tmp/app.ts" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-read-path-completed",
|
||||
),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-read-path-completed",
|
||||
);
|
||||
const payload =
|
||||
activity?.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
expect(activity?.summary).toBe("Read file");
|
||||
expect(payload?.detail).toBe("/tmp/app.ts");
|
||||
});
|
||||
|
||||
it("projects completed plan items into first-class proposed plans", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -1392,6 +1532,432 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("flushes and completes buffered assistant text when an approval request opens", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffered-request-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-flush"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-request-flush",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered-request-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-flush"),
|
||||
itemId: asItemId("item-buffered-request-flush"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "visible before approval",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "request.opened",
|
||||
eventId: asEventId("evt-request-opened-buffered-request-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-flush"),
|
||||
requestId: ApprovalRequestId.make("req-buffered-request-flush"),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "pwd",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-flush" &&
|
||||
!message.streaming &&
|
||||
message.text === "visible before approval",
|
||||
),
|
||||
);
|
||||
const message = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered-request-flush",
|
||||
);
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("flushes and completes buffered assistant text when user input is requested", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffered-user-input-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-user-input-flush"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-user-input-flush",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered-user-input-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-user-input-flush"),
|
||||
itemId: asItemId("item-buffered-user-input-flush"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "visible before user input",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "user-input.requested",
|
||||
eventId: asEventId("evt-user-input-requested-buffered-user-input-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-user-input-flush"),
|
||||
requestId: ApprovalRequestId.make("req-buffered-user-input-flush"),
|
||||
payload: {
|
||||
questions: [
|
||||
{
|
||||
id: "choice",
|
||||
header: "Choice",
|
||||
question: "Pick one",
|
||||
options: [{ label: "A", description: "Option A" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-user-input-flush" &&
|
||||
!message.streaming &&
|
||||
message.text === "visible before user input",
|
||||
),
|
||||
);
|
||||
const message = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) =>
|
||||
entry.id === "assistant:item-buffered-user-input-flush",
|
||||
);
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("does not create assistant segments for whitespace-only buffered text at approval boundaries", async () => {
|
||||
const harness = await createHarness();
|
||||
const startedAt = "2026-03-28T06:28:00.000Z";
|
||||
const pausedAt = "2026-03-28T06:28:01.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffered-whitespace-request"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-whitespace-request"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-whitespace-request",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered-whitespace-request"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-whitespace-request"),
|
||||
itemId: asItemId("item-buffered-whitespace-request"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "\n\n\n",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "request.opened",
|
||||
eventId: asEventId("evt-request-opened-buffered-whitespace-request"),
|
||||
provider: "codex",
|
||||
createdAt: pausedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-whitespace-request"),
|
||||
requestId: ApprovalRequestId.make("req-buffered-whitespace-request"),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "pwd",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
|
||||
),
|
||||
);
|
||||
expect(
|
||||
thread.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-whitespace-request",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("starts a new buffered assistant message segment after approval and completes without duplication", async () => {
|
||||
const harness = await createHarness();
|
||||
const startedAt = "2026-03-28T06:07:00.000Z";
|
||||
const pausedAt = "2026-03-28T06:07:01.000Z";
|
||||
const resumedAt = "2026-03-28T06:07:02.000Z";
|
||||
const completedAt = "2026-03-28T06:07:03.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffered-request-append"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-request-append",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered-request-append-initial"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
itemId: asItemId("item-buffered-request-append"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "first half",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "request.opened",
|
||||
eventId: asEventId("evt-request-opened-buffered-request-append"),
|
||||
provider: "codex",
|
||||
createdAt: pausedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
requestId: ApprovalRequestId.make("req-buffered-request-append"),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "pwd",
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-append" &&
|
||||
!message.streaming &&
|
||||
message.text === "first half",
|
||||
),
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered-request-append-followup"),
|
||||
provider: "codex",
|
||||
createdAt: resumedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
itemId: asItemId("item-buffered-request-append"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: " second half",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-message-completed-buffered-request-append"),
|
||||
provider: "codex",
|
||||
createdAt: completedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
itemId: asItemId("item-buffered-request-append"),
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-append:segment:1" &&
|
||||
!message.streaming &&
|
||||
message.text === " second half",
|
||||
),
|
||||
);
|
||||
const firstMessage = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered-request-append",
|
||||
);
|
||||
const resumedMessage = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) =>
|
||||
entry.id === "assistant:item-buffered-request-append:segment:1",
|
||||
);
|
||||
expect(firstMessage?.text).toBe("first half");
|
||||
expect(firstMessage?.streaming).toBe(false);
|
||||
expect(resumedMessage?.text).toBe(" second half");
|
||||
expect(resumedMessage?.streaming).toBe(false);
|
||||
|
||||
const events = await Effect.runPromise(
|
||||
Stream.runCollect(harness.engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk) => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
const assistantEvents = events.filter(
|
||||
(event): event is Extract<(typeof events)[number], { type: "thread.message-sent" }> =>
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.messageId.startsWith("assistant:item-buffered-request-append"),
|
||||
);
|
||||
expect(assistantEvents).toHaveLength(4);
|
||||
expect(assistantEvents[0]?.payload.streaming).toBe(true);
|
||||
expect(assistantEvents[0]?.payload.text).toBe("first half");
|
||||
expect(assistantEvents[1]?.payload.streaming).toBe(false);
|
||||
expect(assistantEvents[1]?.payload.text).toBe("");
|
||||
expect(assistantEvents[2]?.payload.messageId).toBe(
|
||||
"assistant:item-buffered-request-append:segment:1",
|
||||
);
|
||||
expect(assistantEvents[2]?.payload.streaming).toBe(true);
|
||||
expect(assistantEvents[2]?.payload.text).toBe(" second half");
|
||||
expect(assistantEvents[3]?.payload.messageId).toBe(
|
||||
"assistant:item-buffered-request-append:segment:1",
|
||||
);
|
||||
expect(assistantEvents[3]?.payload.streaming).toBe(false);
|
||||
expect(assistantEvents[3]?.payload.text).toBe("");
|
||||
});
|
||||
|
||||
it("starts a new streaming assistant message segment after approval", async () => {
|
||||
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||
const startedAt = "2026-03-28T07:00:00.000Z";
|
||||
const pausedAt = "2026-03-28T07:00:01.000Z";
|
||||
const resumedAt = "2026-03-28T07:00:02.000Z";
|
||||
const completedAt = "2026-03-28T07:00:03.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-streaming-request-segment"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-streaming-request-segment",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-streaming-request-segment-initial"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
itemId: asItemId("item-streaming-request-segment"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "before approval",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "request.opened",
|
||||
eventId: asEventId("evt-request-opened-streaming-request-segment"),
|
||||
provider: "codex",
|
||||
createdAt: pausedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
requestId: ApprovalRequestId.make("req-streaming-request-segment"),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "pwd",
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment" &&
|
||||
!message.streaming &&
|
||||
message.text === "before approval",
|
||||
),
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-streaming-request-segment-followup"),
|
||||
provider: "codex",
|
||||
createdAt: resumedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
itemId: asItemId("item-streaming-request-segment"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: " after approval",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-message-completed-streaming-request-segment"),
|
||||
provider: "codex",
|
||||
createdAt: completedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
itemId: asItemId("item-streaming-request-segment"),
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment:segment:1" &&
|
||||
!message.streaming &&
|
||||
message.text === " after approval",
|
||||
),
|
||||
);
|
||||
expect(
|
||||
thread.messages.find(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment",
|
||||
)?.text,
|
||||
).toBe("before approval");
|
||||
expect(
|
||||
thread.messages.find(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment:segment:1",
|
||||
)?.text,
|
||||
).toBe(" after approval");
|
||||
});
|
||||
|
||||
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
|
||||
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,36 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Exit } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { logCleanupCauseUnlessInterrupted } from "./ThreadDeletionReactor.ts";
|
||||
|
||||
describe("logCleanupCauseUnlessInterrupted", () => {
|
||||
const threadId = ThreadId.make("thread-deletion-reactor-test");
|
||||
|
||||
it("swallows ordinary cleanup failures", async () => {
|
||||
const exit = await Effect.runPromiseExit(
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: Effect.fail("cleanup failed"),
|
||||
message: "thread deletion cleanup skipped provider session stop",
|
||||
threadId,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Exit.isSuccess(exit)).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves interrupt causes", async () => {
|
||||
const exit = await Effect.runPromiseExit(
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: Effect.interrupt,
|
||||
message: "thread deletion cleanup skipped provider session stop",
|
||||
threadId,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { OrchestrationEvent } from "@t3tools/contracts";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import { Cause, Effect, Layer, Stream } from "effect";
|
||||
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ThreadDeletionReactor,
|
||||
type ThreadDeletionReactorShape,
|
||||
} from "../Services/ThreadDeletionReactor.ts";
|
||||
|
||||
type ThreadDeletedEvent = Extract<OrchestrationEvent, { type: "thread.deleted" }>;
|
||||
|
||||
export const logCleanupCauseUnlessInterrupted = <R, E>({
|
||||
effect,
|
||||
message,
|
||||
threadId,
|
||||
}: {
|
||||
readonly effect: Effect.Effect<void, E, R>;
|
||||
readonly message: string;
|
||||
readonly threadId: ThreadDeletedEvent["payload"]["threadId"];
|
||||
}): Effect.Effect<void, E, R> =>
|
||||
effect.pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logDebug(message, {
|
||||
threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
|
||||
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: providerService.stopSession({ threadId }),
|
||||
message: "thread deletion cleanup skipped provider session stop",
|
||||
threadId,
|
||||
});
|
||||
|
||||
const closeThreadTerminals = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: terminalManager.close({ threadId, deleteHistory: true }),
|
||||
message: "thread deletion cleanup skipped terminal close",
|
||||
threadId,
|
||||
});
|
||||
|
||||
const processThreadDeleted = Effect.fn("processThreadDeleted")(function* (
|
||||
event: ThreadDeletedEvent,
|
||||
) {
|
||||
const { threadId } = event.payload;
|
||||
yield* stopProviderSession(threadId);
|
||||
yield* closeThreadTerminals(threadId);
|
||||
});
|
||||
|
||||
const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>
|
||||
processThreadDeleted(event).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("thread deletion reactor failed to process event", {
|
||||
eventType: event.type,
|
||||
threadId: event.payload.threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const worker = yield* makeDrainableWorker(processThreadDeletedSafely);
|
||||
|
||||
const start: ThreadDeletionReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (event.type !== "thread.deleted") {
|
||||
return Effect.void;
|
||||
}
|
||||
return worker.enqueue(event);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
drain: worker.drain,
|
||||
} satisfies ThreadDeletionReactorShape;
|
||||
});
|
||||
|
||||
export const ThreadDeletionReactorLive = Layer.effect(ThreadDeletionReactor, make);
|
||||
@@ -6,10 +6,10 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore";
|
||||
import { ServerConfig } from "../config";
|
||||
import { parseBase64DataUrl } from "../imageMime";
|
||||
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths";
|
||||
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { parseBase64DataUrl } from "../imageMime.ts";
|
||||
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
|
||||
|
||||
export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* ThreadDeletionReactor - Thread deletion cleanup reactor service interface.
|
||||
*
|
||||
* Owns background workers that react to thread deletion domain events and
|
||||
* perform best-effort runtime cleanup for provider sessions and terminals.
|
||||
*
|
||||
* @module ThreadDeletionReactor
|
||||
*/
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
|
||||
/**
|
||||
* ThreadDeletionReactorShape - Service API for thread deletion cleanup.
|
||||
*/
|
||||
export interface ThreadDeletionReactorShape {
|
||||
/**
|
||||
* Start reacting to thread.deleted orchestration domain events.
|
||||
*
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Resolves when the internal processing queue is empty and idle.
|
||||
* Intended for test use to replace timing-sensitive sleeps.
|
||||
*/
|
||||
readonly drain: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ThreadDeletionReactor - Service tag for thread deletion cleanup workers.
|
||||
*/
|
||||
export class ThreadDeletionReactor extends Context.Service<
|
||||
ThreadDeletionReactor,
|
||||
ThreadDeletionReactorShape
|
||||
>()("t3/orchestration/Services/ThreadDeletionReactor") {}
|
||||
@@ -0,0 +1,226 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
const asCommandId = (value: string): CommandId => CommandId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
async function seedReadModel(): Promise<OrchestrationReadModel> {
|
||||
const now = new Date().toISOString();
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withProject = await Effect.runPromise(
|
||||
projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-delete"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-delete"),
|
||||
title: "Project Delete",
|
||||
workspaceRoot: "/tmp/project-delete",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const withFirstThread = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-delete-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-thread-create-1"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-create-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-delete-1"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
title: "Thread Delete 1",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.runPromise(
|
||||
projectEvent(withFirstThread, {
|
||||
sequence: 3,
|
||||
eventId: asEventId("evt-thread-create-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-delete-2"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-thread-create-2"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-create-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-delete-2"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
title: "Thread Delete 2",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
|
||||
|
||||
function normalizeDeleteEvent(event: PlannedEvent | ReadonlyArray<PlannedEvent>) {
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
return events.map((entry) => {
|
||||
switch (entry.type) {
|
||||
case "thread.deleted":
|
||||
return {
|
||||
type: entry.type,
|
||||
aggregateKind: entry.aggregateKind,
|
||||
aggregateId: entry.aggregateId,
|
||||
commandId: entry.commandId,
|
||||
correlationId: entry.correlationId,
|
||||
payload: {
|
||||
threadId: entry.payload.threadId,
|
||||
},
|
||||
};
|
||||
case "project.deleted":
|
||||
return {
|
||||
type: entry.type,
|
||||
aggregateKind: entry.aggregateKind,
|
||||
aggregateId: entry.aggregateId,
|
||||
commandId: entry.commandId,
|
||||
correlationId: entry.correlationId,
|
||||
payload: {
|
||||
projectId: entry.payload.projectId,
|
||||
},
|
||||
};
|
||||
default:
|
||||
return entry;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
describe("decider deletion flows", () => {
|
||||
it("rejects deleting a non-empty project without force", async () => {
|
||||
const readModel = await seedReadModel();
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.delete",
|
||||
commandId: asCommandId("cmd-project-delete-no-force"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("cannot be deleted without force=true");
|
||||
});
|
||||
|
||||
it("reuses thread.delete semantics when force-deleting a non-empty project", async () => {
|
||||
const readModel = await seedReadModel();
|
||||
const projectDeleteCommand: Extract<OrchestrationCommand, { type: "project.delete" }> = {
|
||||
type: "project.delete",
|
||||
commandId: asCommandId("cmd-project-delete-force"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
force: true,
|
||||
};
|
||||
|
||||
const forcedResult = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: projectDeleteCommand,
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
const forcedEvents = Array.isArray(forcedResult) ? forcedResult : [forcedResult];
|
||||
|
||||
expect(forcedEvents.map((event) => event.type)).toEqual([
|
||||
"thread.deleted",
|
||||
"thread.deleted",
|
||||
"project.deleted",
|
||||
]);
|
||||
|
||||
let sequentialReadModel = readModel;
|
||||
let nextSequence = readModel.snapshotSequence;
|
||||
const sequentialEvents: PlannedEvent[] = [];
|
||||
for (const nextCommand of [
|
||||
{
|
||||
type: "thread.delete",
|
||||
commandId: projectDeleteCommand.commandId,
|
||||
threadId: asThreadId("thread-delete-1"),
|
||||
},
|
||||
{
|
||||
type: "thread.delete",
|
||||
commandId: projectDeleteCommand.commandId,
|
||||
threadId: asThreadId("thread-delete-2"),
|
||||
},
|
||||
{
|
||||
type: "project.delete",
|
||||
commandId: projectDeleteCommand.commandId,
|
||||
projectId: asProjectId("project-delete"),
|
||||
},
|
||||
] satisfies ReadonlyArray<OrchestrationCommand>) {
|
||||
const decided = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: nextCommand,
|
||||
readModel: sequentialReadModel,
|
||||
}),
|
||||
);
|
||||
const nextEvents = Array.isArray(decided) ? decided : [decided];
|
||||
sequentialEvents.push(...nextEvents);
|
||||
for (const nextEvent of nextEvents) {
|
||||
nextSequence += 1;
|
||||
sequentialReadModel = await Effect.runPromise(
|
||||
projectEvent(sequentialReadModel, {
|
||||
...nextEvent,
|
||||
sequence: nextSequence,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { Effect } from "effect";
|
||||
|
||||
import { OrchestrationCommandInvariantError } from "./Errors.ts";
|
||||
import {
|
||||
listThreadsByProjectId,
|
||||
requireProject,
|
||||
requireProjectAbsent,
|
||||
requireThread,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
requireThreadAbsent,
|
||||
requireThreadNotArchived,
|
||||
} from "./commandInvariants.ts";
|
||||
import { projectEvent } from "./projector.ts";
|
||||
|
||||
const nowIso = () => new Date().toISOString();
|
||||
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
||||
@@ -47,16 +49,49 @@ function withEventBase(
|
||||
};
|
||||
}
|
||||
|
||||
type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
|
||||
|
||||
type DecideOrchestrationCommandResult =
|
||||
| PlannedOrchestrationEvent
|
||||
| ReadonlyArray<PlannedOrchestrationEvent>;
|
||||
|
||||
const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
|
||||
commands,
|
||||
readModel,
|
||||
}: {
|
||||
readonly commands: ReadonlyArray<OrchestrationCommand>;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
}): Effect.fn.Return<ReadonlyArray<PlannedOrchestrationEvent>, OrchestrationCommandInvariantError> {
|
||||
let nextReadModel = readModel;
|
||||
let nextSequence = readModel.snapshotSequence;
|
||||
const plannedEvents: PlannedOrchestrationEvent[] = [];
|
||||
|
||||
for (const nextCommand of commands) {
|
||||
const decided = yield* decideOrchestrationCommand({
|
||||
command: nextCommand,
|
||||
readModel: nextReadModel,
|
||||
});
|
||||
const nextEvents = Array.isArray(decided) ? decided : [decided];
|
||||
for (const nextEvent of nextEvents) {
|
||||
plannedEvents.push(nextEvent);
|
||||
nextSequence += 1;
|
||||
nextReadModel = yield* projectEvent(nextReadModel, {
|
||||
...nextEvent,
|
||||
sequence: nextSequence,
|
||||
}).pipe(Effect.orDie);
|
||||
}
|
||||
}
|
||||
|
||||
return plannedEvents;
|
||||
});
|
||||
|
||||
export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({
|
||||
command,
|
||||
readModel,
|
||||
}: {
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
}): Effect.fn.Return<
|
||||
Omit<OrchestrationEvent, "sequence"> | ReadonlyArray<Omit<OrchestrationEvent, "sequence">>,
|
||||
OrchestrationCommandInvariantError
|
||||
> {
|
||||
}): Effect.fn.Return<DecideOrchestrationCommandResult, OrchestrationCommandInvariantError> {
|
||||
switch (command.type) {
|
||||
case "project.create": {
|
||||
yield* requireProjectAbsent({
|
||||
@@ -119,6 +154,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
command,
|
||||
projectId: command.projectId,
|
||||
});
|
||||
const activeThreads = listThreadsByProjectId(readModel, command.projectId).filter(
|
||||
(thread) => thread.deletedAt === null,
|
||||
);
|
||||
if (activeThreads.length > 0 && command.force !== true) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Project '${command.projectId}' is not empty and cannot be deleted without force=true.`,
|
||||
});
|
||||
}
|
||||
if (activeThreads.length > 0) {
|
||||
return yield* decideCommandSequence({
|
||||
readModel,
|
||||
commands: [
|
||||
...activeThreads.map(
|
||||
(thread): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({
|
||||
type: "thread.delete",
|
||||
commandId: command.commandId,
|
||||
threadId: thread.id,
|
||||
}),
|
||||
),
|
||||
{
|
||||
type: "project.delete",
|
||||
commandId: command.commandId,
|
||||
projectId: command.projectId,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const occurredAt = nowIso();
|
||||
return {
|
||||
...withEventBase({
|
||||
@@ -127,7 +191,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "project.deleted",
|
||||
type: "project.deleted" as const,
|
||||
payload: {
|
||||
projectId: command.projectId,
|
||||
deletedAt: occurredAt,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { fixPath } from "./os-jank";
|
||||
import { fixPath } from "./os-jank.ts";
|
||||
|
||||
describe("fixPath", () => {
|
||||
it("hydrates PATH on linux using the resolved login shell", () => {
|
||||
@@ -53,7 +53,120 @@ describe("fixPath", () => {
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux even when SHELL is set", () => {
|
||||
it("repairs 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);
|
||||
|
||||
fixPath({
|
||||
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(";"),
|
||||
);
|
||||
});
|
||||
|
||||
it("applies profile-derived fnm variables on Windows when node is missing", () => {
|
||||
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);
|
||||
|
||||
fixPath({
|
||||
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",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves baseline PATH on Windows 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);
|
||||
|
||||
fixPath({
|
||||
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(";"),
|
||||
);
|
||||
});
|
||||
|
||||
it("does nothing on unsupported platforms", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
PATH: "C:\\Windows\\System32",
|
||||
@@ -62,7 +175,7 @@ describe("fixPath", () => {
|
||||
|
||||
fixPath({
|
||||
env,
|
||||
platform: "win32",
|
||||
platform: "freebsd",
|
||||
readPath,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import {
|
||||
readPathFromLoginShell,
|
||||
readEnvironmentFromWindowsShell,
|
||||
resolveWindowsEnvironment,
|
||||
type CommandAvailabilityOptions,
|
||||
type WindowsShellEnvironmentReader,
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readPathFromLoginShell,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
type WindowsCommandAvailabilityChecker = (
|
||||
command: string,
|
||||
options?: CommandAvailabilityOptions,
|
||||
) => boolean;
|
||||
|
||||
function logPathHydrationWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[server] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
@@ -16,19 +25,36 @@ export function fixPath(
|
||||
env?: NodeJS.ProcessEnv;
|
||||
platform?: NodeJS.Platform;
|
||||
readPath?: typeof readPathFromLoginShell;
|
||||
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 env = options.env ?? process.env;
|
||||
const logWarning = options.logWarning ?? logPathHydrationWarning;
|
||||
const readPath = options.readPath ?? readPathFromLoginShell;
|
||||
|
||||
try {
|
||||
if (platform === "win32") {
|
||||
const repairedEnvironment = resolveWindowsEnvironment(env, {
|
||||
readEnvironment: options.readWindowsEnvironment ?? readEnvironmentFromWindowsShell,
|
||||
...(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;
|
||||
|
||||
let shellPath: string | undefined;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { expandHomePath } from "./pathExpansion.ts";
|
||||
|
||||
describe("expandHomePath", () => {
|
||||
it("returns an empty string unchanged", () => {
|
||||
expect(expandHomePath("")).toBe("");
|
||||
});
|
||||
|
||||
it("returns paths without a leading tilde unchanged", () => {
|
||||
expect(expandHomePath("/absolute/path")).toBe("/absolute/path");
|
||||
expect(expandHomePath("relative/path")).toBe("relative/path");
|
||||
expect(expandHomePath("some~weird~path")).toBe("some~weird~path");
|
||||
});
|
||||
|
||||
it("expands a lone tilde to the home directory", () => {
|
||||
expect(expandHomePath("~")).toBe(homedir());
|
||||
});
|
||||
|
||||
it("expands ~/ to a subpath of the home directory", () => {
|
||||
expect(expandHomePath("~/.codex-work")).toBe(join(homedir(), ".codex-work"));
|
||||
});
|
||||
|
||||
it("expands a Windows-style ~\\ prefix", () => {
|
||||
expect(expandHomePath("~\\.codex")).toBe(join(homedir(), ".codex"));
|
||||
});
|
||||
|
||||
it("does not expand ~user paths", () => {
|
||||
expect(expandHomePath("~alice/foo")).toBe("~alice/foo");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
/**
|
||||
* Expand a leading `~` (or `~/…`, `~\…`) in a user-supplied path to the
|
||||
* current user's home directory. Spawned processes don't get shell
|
||||
* expansion, so env vars like `CODEX_HOME=~/.codex-work` would be passed
|
||||
* verbatim and treated as relative paths by the receiver.
|
||||
*
|
||||
* Matches the behavior of the other `expandHomePath` helpers in the
|
||||
* workspace layers and CLI bootstrap: `~` alone and both `~/` and `~\`
|
||||
* separators are handled. Returns the input unchanged if it doesn't
|
||||
* start with `~` or is empty. Does not handle `~user` (other-user)
|
||||
* expansion.
|
||||
*/
|
||||
export function expandHomePath(value: string): string {
|
||||
if (!value) return value;
|
||||
if (value === "~") return homedir();
|
||||
if (value.startsWith("~/") || value.startsWith("~\\")) {
|
||||
return join(homedir(), value.slice(2));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -37,6 +37,7 @@ import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts";
|
||||
import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
|
||||
import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
|
||||
import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
|
||||
import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -73,6 +74,7 @@ export const migrationEntries = [
|
||||
[22, "AuthSessionLastConnectedAt", Migration0022],
|
||||
[23, "ProjectionThreadShellSummary", Migration0023],
|
||||
[24, "BackfillProjectionThreadShellSummary", Migration0024],
|
||||
[25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("025_CleanupInvalidProjectionPendingApprovals", (it) => {
|
||||
it.effect("removes pending-approval rows that do not come from approval requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 24 });
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
deleted_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'thread-valid',
|
||||
'project-1',
|
||||
'Valid thread',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'approval-required',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-valid',
|
||||
'2026-04-13T00:00:00.000Z',
|
||||
'2026-04-13T00:00:00.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
2,
|
||||
0,
|
||||
0,
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'thread-invalid',
|
||||
'project-1',
|
||||
'Invalid thread',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'approval-required',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-invalid',
|
||||
'2026-04-13T00:00:00.000Z',
|
||||
'2026-04-13T00:00:00.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
sequence,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'activity-approval-requested',
|
||||
'thread-valid',
|
||||
'turn-valid',
|
||||
'approval',
|
||||
'approval.requested',
|
||||
'Command approval requested',
|
||||
'{"requestId":"approval-valid","requestKind":"command"}',
|
||||
NULL,
|
||||
'2026-04-13T00:01:00.000Z'
|
||||
),
|
||||
(
|
||||
'activity-user-input-requested',
|
||||
'thread-invalid',
|
||||
'turn-invalid',
|
||||
'info',
|
||||
'user-input.requested',
|
||||
'User input requested',
|
||||
'{"requestId":"input-invalid","questions":[{"id":"scope","header":"Scope","question":"What should I inspect?","options":[{"label":"Server","description":"Inspect server code."}]}]}',
|
||||
NULL,
|
||||
'2026-04-13T00:02:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_pending_approvals (
|
||||
request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
status,
|
||||
decision,
|
||||
created_at,
|
||||
resolved_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'approval-valid',
|
||||
'thread-valid',
|
||||
'turn-valid',
|
||||
'pending',
|
||||
NULL,
|
||||
'2026-04-13T00:01:00.000Z',
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'input-invalid',
|
||||
'thread-invalid',
|
||||
'turn-invalid',
|
||||
'pending',
|
||||
NULL,
|
||||
'2026-04-13T00:02:00.000Z',
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'input-invalid-resolved',
|
||||
'thread-valid',
|
||||
'turn-valid',
|
||||
'resolved',
|
||||
NULL,
|
||||
'2026-04-13T00:03:00.000Z',
|
||||
'2026-04-13T00:04:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 25 });
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly requestId: string;
|
||||
readonly status: string;
|
||||
}>`
|
||||
SELECT
|
||||
request_id AS "requestId",
|
||||
status
|
||||
FROM projection_pending_approvals
|
||||
ORDER BY request_id ASC
|
||||
`;
|
||||
assert.deepStrictEqual(approvalRows, [
|
||||
{
|
||||
requestId: "approval-valid",
|
||||
status: "pending",
|
||||
},
|
||||
]);
|
||||
|
||||
const threadCounts = yield* sql<{
|
||||
readonly threadId: string;
|
||||
readonly pendingApprovalCount: number;
|
||||
}>`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
pending_approval_count AS "pendingApprovalCount"
|
||||
FROM projection_threads
|
||||
ORDER BY thread_id ASC
|
||||
`;
|
||||
assert.deepStrictEqual(threadCounts, [
|
||||
{
|
||||
threadId: "thread-invalid",
|
||||
pendingApprovalCount: 0,
|
||||
},
|
||||
{
|
||||
threadId: "thread-valid",
|
||||
pendingApprovalCount: 1,
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
DELETE FROM projection_pending_approvals
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_activities AS activity
|
||||
WHERE activity.kind = 'approval.requested'
|
||||
AND json_extract(activity.payload_json, '$.requestId')
|
||||
= projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET pending_approval_count = COALESCE((
|
||||
SELECT COUNT(*)
|
||||
FROM projection_pending_approvals
|
||||
WHERE projection_pending_approvals.thread_id = projection_threads.thread_id
|
||||
AND projection_pending_approvals.status = 'pending'
|
||||
), 0)
|
||||
`;
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runProcess } from "./processRunner";
|
||||
import { runProcess } from "./processRunner.ts";
|
||||
|
||||
describe("runProcess", () => {
|
||||
it("fails when output exceeds max buffer in default mode", async () => {
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
type SDKResultMessage,
|
||||
type SettingSource,
|
||||
type SDKUserMessage,
|
||||
ModelUsage,
|
||||
type ModelUsage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { parseCliArgs } from "@t3tools/shared/cliArgs";
|
||||
import {
|
||||
@@ -42,12 +42,7 @@ import {
|
||||
type UserInputQuestion,
|
||||
ClaudeAgentEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
resolveApiModelId,
|
||||
resolveEffort,
|
||||
trimOrNull,
|
||||
} from "@t3tools/shared/model";
|
||||
import { applyClaudePromptEffortPrefix, resolveEffort, trimOrNull } from "@t3tools/shared/model";
|
||||
import {
|
||||
Cause,
|
||||
DateTime,
|
||||
@@ -66,7 +61,7 @@ import {
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { getClaudeModelCapabilities } from "./ClaudeProvider.ts";
|
||||
import { getClaudeModelCapabilities, resolveClaudeApiModelId } from "./ClaudeProvider.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
@@ -78,6 +73,8 @@ import {
|
||||
import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
import packageJson from "../../../package.json" with { type: "json" };
|
||||
|
||||
const PROVIDER = "claudeAgent" as const;
|
||||
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
|
||||
type ClaudeToolResultStreamKind = Extract<
|
||||
@@ -2829,7 +2826,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const modelSelection =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
|
||||
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
|
||||
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
|
||||
null) as ClaudeAgentEffort | null;
|
||||
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
|
||||
@@ -2862,8 +2859,12 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}),
|
||||
...(newSessionId ? { sessionId: newSessionId } : {}),
|
||||
includePartialMessages: true,
|
||||
persistSession: true,
|
||||
canUseTool,
|
||||
env: process.env,
|
||||
env: {
|
||||
...process.env,
|
||||
CLAUDE_AGENT_SDK_CLIENT_APP: `t3code/${packageJson.version}`,
|
||||
},
|
||||
...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
|
||||
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
|
||||
};
|
||||
@@ -3006,7 +3007,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
}
|
||||
|
||||
if (modelSelection?.model) {
|
||||
const apiModelId = resolveApiModelId(modelSelection);
|
||||
const apiModelId = resolveClaudeApiModelId(modelSelection);
|
||||
if (context.currentApiModelId !== apiModelId) {
|
||||
yield* Effect.tryPromise({
|
||||
try: () => context.query.setModel(apiModelId),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
ClaudeSettings,
|
||||
ClaudeModelSelection,
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
@@ -13,6 +14,7 @@ import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import {
|
||||
query as claudeQuery,
|
||||
type SlashCommand as ClaudeSlashCommand,
|
||||
type SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
import {
|
||||
@@ -25,11 +27,11 @@ import {
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
} from "../providerSnapshot";
|
||||
import { compareCliVersions } from "../cliVersion";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
import { ClaudeProvider } from "../Services/ClaudeProvider";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
} from "../providerSnapshot.ts";
|
||||
import { compareCliVersions } from "../cliVersion.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = {
|
||||
@@ -86,6 +88,23 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-5",
|
||||
name: "Claude Opus 4.5",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Claude Sonnet 4.6",
|
||||
@@ -146,6 +165,14 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
|
||||
switch (modelSelection.options?.contextWindow) {
|
||||
case "1m":
|
||||
return `${modelSelection.model}[1m]`;
|
||||
default:
|
||||
return modelSelection.model;
|
||||
}
|
||||
}
|
||||
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly auth: Pick<ServerProviderAuth, "status">;
|
||||
@@ -454,13 +481,24 @@ function dedupeSlashCommands(
|
||||
return [...commandsByName.values()];
|
||||
}
|
||||
|
||||
function waitForAbortSignal(signal: AbortSignal): Promise<void> {
|
||||
if (signal.aborted) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
signal.addEventListener("abort", () => resolve(), { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe account information by spawning a lightweight Claude Agent SDK
|
||||
* session and reading the initialization result.
|
||||
*
|
||||
* The prompt is never sent to the Anthropic API — we abort immediately
|
||||
* after the local initialization phase completes. This gives us the
|
||||
* user's subscription type without incurring any token cost.
|
||||
* We pass a never-yielding AsyncIterable as the prompt so that no user
|
||||
* message is ever written to the subprocess stdin. This means the Claude
|
||||
* Code subprocess completes its local initialization IPC (returning
|
||||
* account info and slash commands) but never starts an API request to
|
||||
* Anthropic. We read the init data and then abort the subprocess.
|
||||
*
|
||||
* This is used as a fallback when `claude auth status` does not include
|
||||
* subscription type information.
|
||||
@@ -469,12 +507,16 @@ const probeClaudeCapabilities = (binaryPath: string) => {
|
||||
const abort = new AbortController();
|
||||
return Effect.tryPromise(async () => {
|
||||
const q = claudeQuery({
|
||||
prompt: ".",
|
||||
// Never yield — we only need initialization data, not a conversation.
|
||||
// This prevents any prompt from reaching the Anthropic API.
|
||||
// oxlint-disable-next-line require-yield
|
||||
prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
|
||||
await waitForAbortSignal(abort.signal);
|
||||
})(),
|
||||
options: {
|
||||
persistSession: false,
|
||||
pathToClaudeCodeExecutable: binaryPath,
|
||||
abortController: abort,
|
||||
maxTurns: 0,
|
||||
settingSources: ["user", "project", "local"],
|
||||
allowedTools: [],
|
||||
stderr: () => {},
|
||||
|
||||
@@ -144,7 +144,6 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
remove: () => Effect.void,
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
@@ -32,22 +32,23 @@ import {
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
} from "../providerSnapshot";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
} from "../providerSnapshot.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "../codexCliVersion";
|
||||
} from "../codexCliVersion.ts";
|
||||
import {
|
||||
adjustCodexModelsForAccount,
|
||||
codexAuthSubLabel,
|
||||
codexAuthSubType,
|
||||
type CodexAccountSnapshot,
|
||||
} from "../codexAccount";
|
||||
import { probeCodexDiscovery } from "../codexAppServer";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
} from "../codexAccount.ts";
|
||||
import { probeCodexDiscovery } from "../codexAppServer.ts";
|
||||
import { CodexProvider } from "../Services/CodexProvider.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = {
|
||||
@@ -325,7 +326,7 @@ const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyAr
|
||||
shell: process.platform === "win32",
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
...(codexSettings.homePath ? { CODEX_HOME: expandHomePath(codexSettings.homePath) } : {}),
|
||||
},
|
||||
});
|
||||
return yield* spawnAndCollect(codexSettings.binaryPath, command);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,687 @@
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildCursorProviderSnapshot,
|
||||
buildCursorCapabilitiesFromConfigOptions,
|
||||
buildCursorDiscoveredModelsFromConfigOptions,
|
||||
discoverCursorModelCapabilitiesViaAcp,
|
||||
discoverCursorModelsViaAcp,
|
||||
getCursorFallbackModels,
|
||||
getCursorParameterizedModelPickerUnsupportedMessage,
|
||||
parseCursorAboutOutput,
|
||||
parseCursorCliConfigChannel,
|
||||
parseCursorVersionDate,
|
||||
resolveCursorAcpBaseModelId,
|
||||
resolveCursorAcpConfigUpdates,
|
||||
} from "./CursorProvider.ts";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
|
||||
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
|
||||
const wrapperPath = path.join(dir, "fake-agent.sh");
|
||||
const envExports = Object.entries(extraEnv ?? {})
|
||||
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
|
||||
.join("\n");
|
||||
const script = `#!/bin/sh
|
||||
${envExports}
|
||||
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
`;
|
||||
await writeFile(wrapperPath, script, "utf8");
|
||||
await chmod(wrapperPath, 0o755);
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
try {
|
||||
const content = await readFile(filePath, "utf8");
|
||||
if (content.trim().length > 0) {
|
||||
return content;
|
||||
}
|
||||
} catch {}
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
throw new Error(`Timed out waiting for file content at ${filePath}`);
|
||||
}
|
||||
|
||||
const parameterizedGpt54ConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "gpt-5.4-medium-fast",
|
||||
options: [{ name: "GPT-5.4", value: "gpt-5.4-medium-fast" }],
|
||||
category: "model",
|
||||
id: "model",
|
||||
name: "Model",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "medium",
|
||||
options: [
|
||||
{ name: "None", value: "none" },
|
||||
{ name: "Low", value: "low" },
|
||||
{ name: "Medium", value: "medium" },
|
||||
{ name: "High", value: "high" },
|
||||
{ name: "Extra High", value: "extra-high" },
|
||||
],
|
||||
category: "thought_level",
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "272k",
|
||||
options: [
|
||||
{ name: "272K", value: "272k" },
|
||||
{ name: "1M", value: "1m" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "context",
|
||||
name: "Context",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "false",
|
||||
options: [
|
||||
{ name: "Off", value: "false" },
|
||||
{ name: "Fast", value: "true" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const parameterizedClaudeConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "claude-4.6-opus-high-thinking",
|
||||
options: [{ name: "Opus 4.6", value: "claude-4.6-opus-high-thinking" }],
|
||||
category: "model",
|
||||
id: "model",
|
||||
name: "Model",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "high",
|
||||
options: [
|
||||
{ name: "Low", value: "low" },
|
||||
{ name: "Medium", value: "medium" },
|
||||
{ name: "High", value: "high" },
|
||||
],
|
||||
category: "thought_level",
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
},
|
||||
{
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
category: "model_config",
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const parameterizedClaudeModelOptionConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "claude-opus-4-6",
|
||||
options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }],
|
||||
category: "model",
|
||||
id: "model",
|
||||
name: "Model",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "high",
|
||||
options: [
|
||||
{ name: "Low", value: "low" },
|
||||
{ name: "Medium", value: "medium" },
|
||||
{ name: "High", value: "high" },
|
||||
],
|
||||
category: "thought_level",
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "max",
|
||||
options: [
|
||||
{ name: "Low", value: "low" },
|
||||
{ name: "Medium", value: "medium" },
|
||||
{ name: "High", value: "high" },
|
||||
{ name: "Max", value: "max" },
|
||||
],
|
||||
category: "model_option",
|
||||
id: "effort",
|
||||
name: "Effort",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "true",
|
||||
options: [
|
||||
{ name: "Off", value: "false" },
|
||||
{ name: "Fast", value: "true" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "true",
|
||||
options: [
|
||||
{ name: "Off", value: "false" },
|
||||
{ name: ":icon-brain:", value: "true" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const sessionNewCursorConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "agent",
|
||||
options: [
|
||||
{ name: "Agent", value: "agent", description: "Full agent capabilities with tool access" },
|
||||
],
|
||||
category: "mode",
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
description: "Controls how the agent executes tasks",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "composer-2",
|
||||
options: [
|
||||
{ name: "Auto", value: "default" },
|
||||
{ name: "Composer 2", value: "composer-2" },
|
||||
{ name: "GPT-5.4", value: "gpt-5.4" },
|
||||
{ name: "Sonnet 4.6", value: "claude-sonnet-4-6" },
|
||||
{ name: "Opus 4.6", value: "claude-opus-4-6" },
|
||||
{ name: "Codex 5.3 Spark", value: "gpt-5.3-codex-spark" },
|
||||
],
|
||||
category: "model",
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: "Controls which model is used for responses",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "true",
|
||||
options: [
|
||||
{ name: "Off", value: "false" },
|
||||
{ name: "Fast", value: "true" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
description: "Faster speeds.",
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const baseCursorSettings: CursorSettings = {
|
||||
enabled: true,
|
||||
binaryPath: "agent",
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
};
|
||||
|
||||
const emptyCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} as const;
|
||||
|
||||
describe("getCursorFallbackModels", () => {
|
||||
it("does not publish any built-in cursor models before ACP discovery", () => {
|
||||
expect(
|
||||
getCursorFallbackModels({
|
||||
customModels: ["internal/cursor-model"],
|
||||
}).map((model) => model.slug),
|
||||
).toEqual(["internal/cursor-model"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCursorProviderSnapshot", () => {
|
||||
it("downgrades ready status to warning when ACP model discovery times out", () => {
|
||||
expect(
|
||||
buildCursorProviderSnapshot({
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
cursorSettings: baseCursorSettings,
|
||||
parsed: {
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" },
|
||||
},
|
||||
discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "warning",
|
||||
message: "Cursor ACP model discovery timed out after 15000ms.",
|
||||
models: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves provider error state while appending discovery warnings", () => {
|
||||
expect(
|
||||
buildCursorProviderSnapshot({
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
cursorSettings: {
|
||||
...baseCursorSettings,
|
||||
customModels: ["claude-sonnet-4-6"],
|
||||
},
|
||||
parsed: {
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
},
|
||||
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "error",
|
||||
message:
|
||||
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
isCustom: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCursorCapabilitiesFromConfigOptions", () => {
|
||||
it("derives model capabilities from parameterized Cursor ACP config options", () => {
|
||||
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual({
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium", isDefault: true },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "272k", label: "272K", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
promptInjectedEffortLevels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("detects boolean thinking toggles from model_config options", () => {
|
||||
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual({
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the newer model_option effort control over legacy thought_level", () => {
|
||||
expect(
|
||||
buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
|
||||
).toEqual({
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "max", label: "Max", isDefault: true },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
|
||||
it("publishes ACP model choices immediately from session/new config options", () => {
|
||||
expect(buildCursorDiscoveredModelsFromConfigOptions(sessionNewCursorConfigOptions)).toEqual([
|
||||
{
|
||||
slug: "default",
|
||||
name: "Auto",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "composer-2",
|
||||
name: "Composer 2",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Sonnet 4.6",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex-spark",
|
||||
name: "Codex 5.3 Spark",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("discoverCursorModelsViaAcp", () => {
|
||||
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
|
||||
const wrapperPath = await makeMockAgentWrapper();
|
||||
|
||||
const models = await Effect.runPromise(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
"default",
|
||||
"composer-2",
|
||||
"gpt-5.4",
|
||||
"claude-opus-4-6",
|
||||
]);
|
||||
});
|
||||
|
||||
it("closes the ACP probe runtime after discovery completes", async () => {
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));
|
||||
const exitLogPath = path.join(tempDir, "exit.log");
|
||||
const wrapperPath = await makeMockAgentWrapper({
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
});
|
||||
|
||||
await Effect.runPromise(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
const exitLog = await waitForFileContent(exitLogPath);
|
||||
expect(exitLog).toContain("SIGTERM");
|
||||
});
|
||||
});
|
||||
|
||||
describe("discoverCursorModelCapabilitiesViaAcp", () => {
|
||||
it("closes all ACP probe runtimes after capability enrichment completes", async () => {
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));
|
||||
const exitLogPath = path.join(tempDir, "exit.log");
|
||||
const wrapperPath = await makeMockAgentWrapper({
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
});
|
||||
const existingModels: ReadonlyArray<ServerProviderModel> = [
|
||||
{ slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
|
||||
{ slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: emptyCapabilities },
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
},
|
||||
];
|
||||
|
||||
const models = await Effect.runPromise(
|
||||
discoverCursorModelCapabilitiesViaAcp(
|
||||
{
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
},
|
||||
existingModels,
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
"default",
|
||||
"composer-2",
|
||||
"gpt-5.4",
|
||||
"claude-opus-4-6",
|
||||
]);
|
||||
|
||||
const exitLog = await waitForFileContent(exitLogPath);
|
||||
expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCursorAboutOutput", () => {
|
||||
it("parses json about output and forwards subscription metadata", () => {
|
||||
expect(
|
||||
parseCursorAboutOutput({
|
||||
code: 0,
|
||||
stdout: JSON.stringify({
|
||||
cliVersion: "2026.04.09-f2b0fcd",
|
||||
subscriptionTier: "Team",
|
||||
userEmail: "[email protected]",
|
||||
}),
|
||||
stderr: "",
|
||||
}),
|
||||
).toEqual({
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "ready",
|
||||
auth: {
|
||||
status: "authenticated",
|
||||
type: "Team",
|
||||
label: "Cursor Team Subscription",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("treats json about output with a logged-out email as unauthenticated", () => {
|
||||
expect(
|
||||
parseCursorAboutOutput({
|
||||
code: 0,
|
||||
stdout: JSON.stringify({
|
||||
cliVersion: "2026.04.09-f2b0fcd",
|
||||
subscriptionTier: "Team",
|
||||
userEmail: "Not logged in",
|
||||
}),
|
||||
stderr: "",
|
||||
}),
|
||||
).toEqual({
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "error",
|
||||
auth: {
|
||||
status: "unauthenticated",
|
||||
},
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
});
|
||||
});
|
||||
|
||||
it("treats json about output with a null email as unauthenticated", () => {
|
||||
expect(
|
||||
parseCursorAboutOutput({
|
||||
code: 0,
|
||||
stdout: JSON.stringify({
|
||||
cliVersion: "2026.04.09-f2b0fcd",
|
||||
subscriptionTier: null,
|
||||
userEmail: null,
|
||||
}),
|
||||
stderr: "",
|
||||
}),
|
||||
).toEqual({
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "error",
|
||||
auth: {
|
||||
status: "unauthenticated",
|
||||
},
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cursor parameterized model picker preview gating", () => {
|
||||
it("parses Cursor CLI version dates from build versions", () => {
|
||||
expect(parseCursorVersionDate("2026.04.08-c4e73a3")).toBe(20260408);
|
||||
expect(parseCursorVersionDate("2026.04.09")).toBe(20260409);
|
||||
expect(parseCursorVersionDate("not-a-version")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("parses the Cursor CLI channel from cli-config.json", () => {
|
||||
expect(parseCursorCliConfigChannel('{ "channel": "lab" }')).toBe("lab");
|
||||
expect(parseCursorCliConfigChannel('{ "channel": "stable" }')).toBe("stable");
|
||||
expect(parseCursorCliConfigChannel('{ "version": 1 }')).toBeUndefined();
|
||||
expect(parseCursorCliConfigChannel("not-json")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns no warning when the preview requirements are met", () => {
|
||||
expect(
|
||||
getCursorParameterizedModelPickerUnsupportedMessage({
|
||||
version: "2026.04.08-c4e73a3",
|
||||
channel: "lab",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("explains when the Cursor Agent version is too old", () => {
|
||||
expect(
|
||||
getCursorParameterizedModelPickerUnsupportedMessage({
|
||||
version: "2026.04.07-c4e73a3",
|
||||
channel: "lab",
|
||||
}),
|
||||
).toContain("too old");
|
||||
});
|
||||
|
||||
it("explains when the Cursor Agent channel is not lab", () => {
|
||||
expect(
|
||||
getCursorParameterizedModelPickerUnsupportedMessage({
|
||||
version: "2026.04.08-c4e73a3",
|
||||
channel: "stable",
|
||||
}),
|
||||
).toContain("lab channel");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveCursorAcpBaseModelId", () => {
|
||||
it("drops bracket traits without rewriting raw ACP model ids", () => {
|
||||
expect(resolveCursorAcpBaseModelId("gpt-5.4[reasoning=medium,context=272k]")).toBe("gpt-5.4");
|
||||
expect(resolveCursorAcpBaseModelId("gpt-5.4-medium-fast")).toBe("gpt-5.4-medium-fast");
|
||||
expect(resolveCursorAcpBaseModelId("claude-4.6-opus-high-thinking")).toBe(
|
||||
"claude-4.6-opus-high-thinking",
|
||||
);
|
||||
expect(resolveCursorAcpBaseModelId("composer-2")).toBe("composer-2");
|
||||
expect(resolveCursorAcpBaseModelId("auto")).toBe("auto");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveCursorAcpConfigUpdates", () => {
|
||||
it("maps Cursor model options onto separate ACP config option updates", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, {
|
||||
reasoning: "xhigh",
|
||||
fastMode: true,
|
||||
contextWindow: "1m",
|
||||
}),
|
||||
).toEqual([
|
||||
{ configId: "reasoning", value: "extra-high" },
|
||||
{ configId: "context", value: "1m" },
|
||||
{ configId: "fast", value: "true" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps boolean thinking toggles when the model exposes them separately", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, {
|
||||
thinking: false,
|
||||
}),
|
||||
).toEqual([{ configId: "thinking", value: false }]);
|
||||
});
|
||||
|
||||
it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, {
|
||||
fastMode: false,
|
||||
}),
|
||||
).toEqual([{ configId: "fast", value: "false" }]);
|
||||
});
|
||||
|
||||
it("writes Cursor effort changes through the newer model_option config when available", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, {
|
||||
reasoning: "max",
|
||||
thinking: false,
|
||||
}),
|
||||
).toEqual([
|
||||
{ configId: "effort", value: "max" },
|
||||
{ configId: "thinking", value: "false" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,486 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { beforeEach, vi } from "vitest";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
import {
|
||||
appendOpenCodeAssistantTextDelta,
|
||||
makeOpenCodeAdapterLive,
|
||||
mergeOpenCodeAssistantText,
|
||||
} from "./OpenCodeAdapter.ts";
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
type MessageEntry = {
|
||||
info: {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
};
|
||||
parts: Array<unknown>;
|
||||
};
|
||||
|
||||
const state = {
|
||||
startCalls: [] as string[],
|
||||
sessionCreateUrls: [] as string[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
abortCalls: [] as string[],
|
||||
closeCalls: [] as string[],
|
||||
revertCalls: [] as Array<{ sessionID: string; messageID?: string }>,
|
||||
promptAsyncError: null as Error | null,
|
||||
closeError: null as Error | null,
|
||||
messages: [] as MessageEntry[],
|
||||
subscribedEvents: [] as unknown[],
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.startCalls.length = 0;
|
||||
state.sessionCreateUrls.length = 0;
|
||||
state.authHeaders.length = 0;
|
||||
state.abortCalls.length = 0;
|
||||
state.closeCalls.length = 0;
|
||||
state.revertCalls.length = 0;
|
||||
state.promptAsyncError = null;
|
||||
state.closeError = null;
|
||||
state.messages = [];
|
||||
state.subscribedEvents = [];
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../opencodeRuntime.ts", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("../opencodeRuntime.ts")>("../opencodeRuntime.ts");
|
||||
|
||||
return {
|
||||
...actual,
|
||||
startOpenCodeServerProcess: vi.fn(async ({ binaryPath }: { binaryPath: string }) => {
|
||||
runtimeMock.state.startCalls.push(binaryPath);
|
||||
return {
|
||||
url: "http://127.0.0.1:4301",
|
||||
process: {
|
||||
once() {},
|
||||
},
|
||||
close() {},
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: vi.fn(async ({ serverUrl }: { serverUrl?: string }) => ({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
process: null,
|
||||
external: Boolean(serverUrl),
|
||||
close() {
|
||||
runtimeMock.state.closeCalls.push(serverUrl ?? "http://127.0.0.1:4301");
|
||||
if (runtimeMock.state.closeError) {
|
||||
throw runtimeMock.state.closeError;
|
||||
}
|
||||
},
|
||||
})),
|
||||
createOpenCodeSdkClient: vi.fn(
|
||||
({ baseUrl, serverPassword }: { baseUrl: string; serverPassword?: string }) => ({
|
||||
session: {
|
||||
create: vi.fn(async () => {
|
||||
runtimeMock.state.sessionCreateUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return { data: { id: `${baseUrl}/session` } };
|
||||
}),
|
||||
abort: vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
runtimeMock.state.abortCalls.push(sessionID);
|
||||
}),
|
||||
promptAsync: vi.fn(async () => {
|
||||
if (runtimeMock.state.promptAsyncError) {
|
||||
throw runtimeMock.state.promptAsyncError;
|
||||
}
|
||||
}),
|
||||
messages: vi.fn(async () => ({ data: runtimeMock.state.messages })),
|
||||
revert: vi.fn(
|
||||
async ({ sessionID, messageID }: { sessionID: string; messageID?: string }) => {
|
||||
runtimeMock.state.revertCalls.push({
|
||||
sessionID,
|
||||
...(messageID ? { messageID } : {}),
|
||||
});
|
||||
if (!messageID) {
|
||||
runtimeMock.state.messages = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const targetIndex = runtimeMock.state.messages.findIndex(
|
||||
(entry) => entry.info.id === messageID,
|
||||
);
|
||||
runtimeMock.state.messages =
|
||||
targetIndex >= 0
|
||||
? runtimeMock.state.messages.slice(0, targetIndex + 1)
|
||||
: runtimeMock.state.messages;
|
||||
},
|
||||
),
|
||||
},
|
||||
event: {
|
||||
subscribe: vi.fn(async () => ({
|
||||
stream: (async function* () {
|
||||
for (const event of runtimeMock.state.subscribedEvents) {
|
||||
yield event;
|
||||
}
|
||||
})(),
|
||||
})),
|
||||
},
|
||||
}),
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
const OpenCodeAdapterTestLayer = makeOpenCodeAdapterLive().pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMock.reset();
|
||||
});
|
||||
|
||||
const sleep = (ms: number) =>
|
||||
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
||||
|
||||
it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
it.effect("reuses a configured OpenCode server URL instead of spawning a local server", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-opencode"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.equal(session.provider, "opencode");
|
||||
assert.equal(session.threadId, "thread-opencode");
|
||||
assert.deepEqual(runtimeMock.state.startCalls, []);
|
||||
assert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]);
|
||||
assert.deepEqual(runtimeMock.state.authHeaders, [
|
||||
`Basic ${btoa("opencode:secret-password")}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stops a configured-server session without trying to own server lifecycle", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-opencode"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(asThreadId("thread-opencode"));
|
||||
|
||||
assert.deepEqual(runtimeMock.state.startCalls, []);
|
||||
assert.deepEqual(
|
||||
runtimeMock.state.abortCalls.includes("http://127.0.0.1:9999/session"),
|
||||
true,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears session state when stopAll cleanup fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-stop-all-a"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-stop-all-b"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
runtimeMock.state.closeError = new Error("close failed");
|
||||
const error = yield* adapter.stopAll().pipe(Effect.flip);
|
||||
const sessions = yield* adapter.listSessions();
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterProcessError");
|
||||
assert.equal(error.detail, "Failed to stop 2 OpenCode sessions.");
|
||||
assert.deepEqual(runtimeMock.state.closeCalls, [
|
||||
"http://127.0.0.1:9999",
|
||||
"http://127.0.0.1:9999",
|
||||
]);
|
||||
assert.deepEqual(sessions, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rolls back session state when sendTurn fails before OpenCode accepts the prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-send-turn-failure"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
runtimeMock.state.promptAsyncError = new Error("prompt failed");
|
||||
const error = yield* adapter
|
||||
.sendTurn({
|
||||
threadId: asThreadId("thread-send-turn-failure"),
|
||||
input: "Fix it",
|
||||
modelSelection: {
|
||||
provider: "opencode",
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
const sessions = yield* adapter.listSessions();
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
if (error._tag !== "ProviderAdapterRequestError") {
|
||||
throw new Error("Unexpected error type");
|
||||
}
|
||||
assert.equal(error.detail, "prompt failed");
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Provider adapter request failed (opencode) for session.promptAsync: prompt failed",
|
||||
);
|
||||
assert.equal(sessions.length, 1);
|
||||
assert.equal(sessions[0]?.status, "ready");
|
||||
assert.equal(sessions[0]?.activeTurnId, undefined);
|
||||
assert.equal(sessions[0]?.lastError, "prompt failed");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reverts the full thread when rollback removes every assistant turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-rollback-all");
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
runtimeMock.state.messages = [
|
||||
{
|
||||
info: { id: "assistant-1", role: "assistant" },
|
||||
parts: [],
|
||||
},
|
||||
{
|
||||
info: { id: "assistant-2", role: "assistant" },
|
||||
parts: [],
|
||||
},
|
||||
];
|
||||
|
||||
const snapshot = yield* adapter.rollbackThread(threadId, 2);
|
||||
|
||||
assert.deepEqual(runtimeMock.state.revertCalls, [
|
||||
{ sessionID: "http://127.0.0.1:9999/session" },
|
||||
]);
|
||||
assert.deepEqual(snapshot.turns, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("deduplicates overlapping assistant text deltas after part updates", () =>
|
||||
Effect.sync(() => {
|
||||
const firstUpdate = mergeOpenCodeAssistantText(undefined, "Hello");
|
||||
const overlapDelta = appendOpenCodeAssistantTextDelta(firstUpdate.latestText, "lo world");
|
||||
const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hello world!");
|
||||
|
||||
assert.deepEqual(
|
||||
[firstUpdate.deltaToEmit, overlapDelta.deltaToEmit, secondUpdate.deltaToEmit],
|
||||
["Hello", " world", "!"],
|
||||
);
|
||||
assert.equal(secondUpdate.latestText, "Hello world!");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("writes provider-native observability records using the session thread id", () =>
|
||||
Effect.gen(function* () {
|
||||
const nativeEvents: Array<{
|
||||
readonly event?: {
|
||||
readonly provider?: string;
|
||||
readonly threadId?: string;
|
||||
readonly providerThreadId?: string;
|
||||
readonly type?: string;
|
||||
};
|
||||
}> = [];
|
||||
const nativeThreadIds: Array<string | null> = [];
|
||||
runtimeMock.state.subscribedEvents = [
|
||||
{
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
info: {
|
||||
id: "msg-missing-session",
|
||||
role: "assistant",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/other-session",
|
||||
info: {
|
||||
id: "msg-other-session",
|
||||
role: "assistant",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "msg-native-log",
|
||||
role: "assistant",
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const nativeEventLogger = {
|
||||
filePath: "memory://opencode-native-events",
|
||||
write: (event: unknown, threadId: ThreadId | null) => {
|
||||
nativeEvents.push(event as (typeof nativeEvents)[number]);
|
||||
nativeThreadIds.push(threadId ?? null);
|
||||
return Effect.void;
|
||||
},
|
||||
close: () => Effect.void,
|
||||
};
|
||||
|
||||
const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const session = yield* Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const started = yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-native-log"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* sleep(10);
|
||||
return started;
|
||||
}).pipe(Effect.provide(adapterLayer));
|
||||
|
||||
assert.equal(session.threadId, "thread-native-log");
|
||||
assert.equal(nativeEvents.length, 1);
|
||||
assert.equal(
|
||||
nativeEvents.some((record) => record.event?.provider === "opencode"),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeEvents.some(
|
||||
(record) => record.event?.providerThreadId === "http://127.0.0.1:9999/session",
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeEvents.some((record) => record.event?.threadId === "thread-native-log"),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeEvents.some((record) => record.event?.type === "message.updated"),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeThreadIds.every((threadId) => threadId === "thread-native-log"),
|
||||
true,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the event pump alive when native event logging fails", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.subscribedEvents = [
|
||||
{
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "msg-native-log-failure",
|
||||
role: "assistant",
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const nativeEventLogger = {
|
||||
filePath: "memory://opencode-native-events",
|
||||
write: () => Effect.die(new Error("native log write failed")),
|
||||
close: () => Effect.void,
|
||||
};
|
||||
|
||||
const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const sessions = yield* Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-native-log-failure"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* sleep(10);
|
||||
return yield* adapter.listSessions();
|
||||
}).pipe(Effect.provide(adapterLayer));
|
||||
|
||||
assert.equal(sessions.length, 1);
|
||||
assert.equal(sessions[0]?.threadId, "thread-native-log-failure");
|
||||
assert.deepEqual(runtimeMock.state.closeCalls, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,138 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { beforeEach, vi } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import { makeOpenCodeProviderLive } from "./OpenCodeProvider.ts";
|
||||
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
const state = {
|
||||
runVersionError: null as Error | null,
|
||||
inventoryError: null as Error | null,
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.runVersionError = null;
|
||||
state.inventoryError = null;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../opencodeRuntime.ts", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("../opencodeRuntime.ts")>("../opencodeRuntime.ts");
|
||||
|
||||
return {
|
||||
...actual,
|
||||
runOpenCodeCommand: vi.fn(async () => {
|
||||
if (runtimeMock.state.runVersionError) {
|
||||
throw runtimeMock.state.runVersionError;
|
||||
}
|
||||
return { stdout: "opencode 1.0.0\n", stderr: "", code: 0 };
|
||||
}),
|
||||
connectToOpenCodeServer: vi.fn(async ({ serverUrl }: { serverUrl?: string }) => ({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
process: null,
|
||||
external: Boolean(serverUrl),
|
||||
close() {},
|
||||
})),
|
||||
createOpenCodeSdkClient: vi.fn(() => ({})),
|
||||
loadOpenCodeInventory: vi.fn(async () => {
|
||||
if (runtimeMock.state.inventoryError) {
|
||||
throw runtimeMock.state.inventoryError;
|
||||
}
|
||||
return {
|
||||
providerList: { connected: [], all: [] },
|
||||
agents: [],
|
||||
};
|
||||
}),
|
||||
flattenOpenCodeModels: vi.fn(() => []),
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMock.reset();
|
||||
});
|
||||
|
||||
const makeTestLayer = (settingsOverrides?: Parameters<typeof ServerSettingsService.layerTest>[0]) =>
|
||||
makeOpenCodeProviderLive().pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
|
||||
it.effect("shows a codex-style missing binary message", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.runVersionError = new Error("spawn opencode ENOENT");
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
|
||||
assert.equal(snapshot.status, "error");
|
||||
assert.equal(snapshot.installed, false);
|
||||
assert.equal(snapshot.message, "OpenCode CLI (`opencode`) is not installed or not on PATH.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("hides generic Effect.tryPromise text for local CLI probe failures", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.runVersionError = new Error("An error occurred in Effect.tryPromise");
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
|
||||
assert.equal(snapshot.status, "error");
|
||||
assert.equal(snapshot.installed, true);
|
||||
assert.equal(snapshot.message, "Failed to execute OpenCode CLI health check.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(
|
||||
makeTestLayer({
|
||||
providers: {
|
||||
opencode: {
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
}),
|
||||
)("OpenCodeProviderLive with configured server URL", (it) => {
|
||||
it.effect("surfaces a friendly auth error for configured servers", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventoryError = new Error("401 Unauthorized");
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
|
||||
assert.equal(snapshot.status, "error");
|
||||
assert.equal(snapshot.installed, true);
|
||||
assert.equal(
|
||||
snapshot.message,
|
||||
"OpenCode server rejected authentication. Check the server URL and password.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly connection error for configured servers", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventoryError = new Error(
|
||||
"fetch failed: connect ECONNREFUSED 127.0.0.1:9999",
|
||||
);
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
|
||||
assert.equal(snapshot.status, "error");
|
||||
assert.equal(snapshot.installed, true);
|
||||
assert.equal(
|
||||
snapshot.message,
|
||||
"Couldn't reach the configured OpenCode server at http://127.0.0.1:9999. Check that the server is running and the URL is correct.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
Loaded 100 of 300 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user