Compare commits

..
Author SHA1 Message Date
Julius Marminge b3291cf83e Respect installed version update channel
- Derive desktop updater channel from the running app version
- Keep stable builds on latest and prereleases on their own track
- Add tests and release docs for channel matching
2026-04-15 16:40:51 -07:00
282 changed files with 3451 additions and 15901 deletions

No files matched your search

+4 -7
View File
@@ -9,7 +9,7 @@ on:
jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -71,12 +71,12 @@ jobs:
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
release_smoke:
name: Release Smoke
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
@@ -92,8 +92,5 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+47 -176
View File
@@ -1,24 +1,14 @@
name: Release
name: Release Desktop
on:
push:
tags:
- "v*.*.*"
schedule:
- cron: "0 9 * * *"
workflow_dispatch:
inputs:
channel:
description: "Release channel"
required: false
default: stable
type: choice
options:
- stable
- nightly
version:
description: "Release version (for example 1.2.3 or v1.2.3)"
required: false
required: true
type: string
permissions:
@@ -28,24 +18,43 @@ permissions:
jobs:
preflight:
name: Preflight
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
outputs:
release_channel: ${{ steps.release_meta.outputs.release_channel }}
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
release_name: ${{ steps.release_meta.outputs.name }}
short_sha: ${{ steps.release_meta.outputs.short_sha }}
previous_tag: ${{ steps.previous_tag.outputs.previous_tag }}
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
make_latest: ${{ steps.release_meta.outputs.make_latest }}
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- id: release_meta
name: Resolve release version
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -60,60 +69,6 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- id: release_meta
name: Resolve release version
shell: bash
env:
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
DISPATCH_VERSION: ${{ github.event.inputs.version }}
NIGHTLY_DATE: ${{ github.run_started_at }}
NIGHTLY_SHA: ${{ github.sha }}
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
run: |
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
nightly_date="$(date -u -d "$NIGHTLY_DATE" +%Y%m%d)"
node scripts/resolve-nightly-release.ts \
--date "$nightly_date" \
--run-number "$NIGHTLY_RUN_NUMBER" \
--sha "$NIGHTLY_SHA" \
--github-output
echo "release_channel=nightly" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=nightly" >> "$GITHUB_OUTPUT"
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
else
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${DISPATCH_VERSION}"
if [[ -z "$raw" ]]; then
echo "workflow_dispatch stable releases require the version input." >&2
exit 1
fi
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "release_channel=stable" >> "$GITHUB_OUTPUT"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
echo "name=T3 Code v$version" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=latest" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
fi
- name: Lint
run: bun run lint
@@ -123,14 +78,6 @@ jobs:
- name: Test
run: bun run test
- id: previous_tag
name: Resolve previous release tag
run: |
node scripts/resolve-previous-release-tag.ts \
--channel "${{ steps.release_meta.outputs.release_channel }}" \
--current-tag "${{ steps.release_meta.outputs.tag }}" \
--github-output
build:
name: Build ${{ matrix.label }}
needs: preflight
@@ -141,30 +88,25 @@ jobs:
matrix:
include:
- label: macOS arm64
runner: blacksmith-12vcpu-macos-26
runner: macos-14
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: blacksmith-12vcpu-macos-26
runner: macos-15-intel
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: blacksmith-32vcpu-ubuntu-2404
runner: ubuntu-24.04
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: windows-2022 # blacksmith-32vcpu-windows-2025
runner: windows-2022
platform: win
target: nsis
arch: x64
# - label: Windows arm64
# runner: windows-11-arm
# platform: win
# target: nsis
# arch: arm64
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -264,31 +206,18 @@ jobs:
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/*.yml"; do
"release/latest*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
shopt -s nullglob
for manifest in release-publish/*-mac.yml; do
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
done
if [[ -f release-publish/latest-mac.yml ]]; then
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
fi
fi
# Enable if Windows arm64 builds are enabled.
# Windows updater metadata is channel-specific (for example
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
# release job can merge matching arm64/x64 manifests back into one
# canonical manifest per channel.
# if [[ "${{ matrix.platform }}" == "win" ]]; then
# shopt -s nullglob
# for manifest in release-publish/*.yml; do
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
# done
# fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
@@ -299,7 +228,7 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
@@ -328,12 +257,12 @@ jobs:
run: bun run build --filter=@t3tools/web --filter=t3
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
release:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
@@ -355,71 +284,17 @@ jobs:
- name: Merge macOS updater manifests
run: |
shopt -s nullglob
for x64_manifest in release-assets/*-mac-x64.yml; do
arm64_manifest="${x64_manifest%-x64.yml}.yml"
if [[ -f "$arm64_manifest" ]]; then
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
rm -f "$x64_manifest"
fi
done
# - name: Merge Windows updater manifests
# run: |
# shopt -s nullglob
# found_windows_manifest=false
# for x64_manifest in release-assets/*-win-x64.yml; do
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
# continue
# fi
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
# if [[ ! -f "$arm64_manifest" ]]; then
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
# exit 1
# fi
# found_windows_manifest=true
# node scripts/merge-update-manifests.ts --platform win \
# "$arm64_manifest" \
# "$x64_manifest" \
# "$output_manifest"
# rm -f "$arm64_manifest" "$x64_manifest"
# done
# if [[ "$found_windows_manifest" != true ]]; then
# echo "No Windows updater manifests found to merge." >&2
# exit 1
# fi
node scripts/merge-mac-update-manifests.ts \
release-assets/latest-mac.yml \
release-assets/latest-mac-x64.yml
rm -f release-assets/latest-mac-x64.yml
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
previous_tag: ${{ needs.preflight.outputs.previous_tag }}
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
files: |
release-assets/*.dmg
release-assets/*.zip
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
name: T3 Code v${{ needs.preflight.outputs.version }}
generate_release_notes: true
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
@@ -429,14 +304,13 @@ jobs:
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
release-assets/latest*.yml
fail_on_unmatched_files: true
finalize:
name: Finalize release
if: needs.preflight.outputs.release_channel == 'stable'
needs: [preflight, release]
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- id: app_token
@@ -475,9 +349,6 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- id: update_versions
name: Update version strings
env:
+1 -2
View File
@@ -10,8 +10,7 @@
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts",
"*.icon/**"
"apps/web/src/lib/vendor/qrcodegen.ts"
],
"sortPackageJson": {}
}
+4 -5
View File
@@ -1,15 +1,14 @@
{
"name": "@t3tools/desktop",
"version": "0.0.20",
"version": "0.0.17",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
"main": "dist-electron/main.js",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "node scripts/dev-electron.mjs",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "tsdown",
"start": "node scripts/start-electron.mjs",
"start": "bun run scripts/start-electron.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
+4 -4
View File
@@ -17,12 +17,12 @@ if (!Number.isInteger(port) || port <= 0) {
}
const requiredFiles = [
"dist-electron/main.cjs",
"dist-electron/preload.cjs",
"dist-electron/main.js",
"dist-electron/preload.js",
"../server/dist/bin.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
@@ -69,7 +69,7 @@ function startApp() {
const app = spawn(
resolveElectronPath(),
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
{
cwd: desktopDir,
env: childEnv,
+38 -74
View File
@@ -6,8 +6,8 @@ import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
statSync,
writeFileSync,
@@ -19,13 +19,10 @@ import { fileURLToPath } from "node:url";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LAUNCHER_VERSION = 2;
const LAUNCHER_VERSION = 1;
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
const repoRoot = resolve(desktopDir, "..", "..");
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
@@ -46,68 +43,6 @@ function setPlistString(plistPath, key, value) {
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
}
function runChecked(command, args) {
const result = spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
return;
}
const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
if (!existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
}
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
return generatedIconPath;
}
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = join(iconsetRoot, "icon.iconset");
mkdirSync(iconsetDir, { recursive: true });
try {
for (const size of [16, 32, 128, 256, 512]) {
runChecked("sips", [
"-z",
String(size),
String(size),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}.png`),
]);
const retinaSize = size * 2;
runChecked("sips", [
"-z",
String(retinaSize),
String(retinaSize),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
}
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
return generatedIconPath;
} catch (error) {
console.warn(
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
error,
);
return defaultIconPath;
} finally {
rmSync(iconsetRoot, { recursive: true, force: true });
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
@@ -120,6 +55,40 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
if (!existsSync(frameworksDir)) {
return;
}
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
continue;
}
if (!entry.name.startsWith("Electron Helper")) {
continue;
}
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
if (!existsSync(helperPlistPath)) {
continue;
}
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
const helperName = suffix
? `${APP_DISPLAY_NAME} Helper ${suffix}`
: `${APP_DISPLAY_NAME} Helper`;
const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");
const helperBundleId = helperIdSuffix
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
: `${APP_BUNDLE_ID}.helper`;
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
setPlistString(helperPlistPath, "CFBundleName", helperName);
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
}
}
function readJson(path) {
try {
return JSON.parse(readFileSync(path, "utf8"));
@@ -133,7 +102,7 @@ function buildMacLauncher(electronBinaryPath) {
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const iconPath = join(desktopDir, "resources", "icon.icns");
const metadataPath = join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
@@ -157,6 +126,7 @@ function buildMacLauncher(electronBinaryPath) {
rmSync(targetAppBundlePath, { recursive: true, force: true });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
return targetBinaryPath;
@@ -170,11 +140,5 @@ export function resolveElectronPath() {
return electronBinaryPath;
}
// Dev launches do not need a renamed app bundle badly enough to risk breaking
// Electron helper resource lookup on macOS.
if (isDevelopment) {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
const mainJs = resolve(desktopDir, "dist-electron/main.js");
console.log("\nLaunching Electron smoke test...");
+1 -1
View File
@@ -5,7 +5,7 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
-47
View File
@@ -1,47 +0,0 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding.ts";
describe("resolveDesktopAppStageLabel", () => {
it("uses Dev in desktop development", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: true,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toBe("Dev");
});
it("uses Nightly for packaged nightly builds", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: false,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toBe("Nightly");
});
it("uses Alpha for packaged stable builds", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: false,
appVersion: "0.0.17",
}),
).toBe("Alpha");
});
});
describe("resolveDesktopAppBranding", () => {
it("returns a complete desktop branding payload", () => {
expect(
resolveDesktopAppBranding({
isDevelopment: false,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toEqual({
baseName: "T3 Code",
stageLabel: "Nightly",
displayName: "T3 Code (Nightly)",
});
});
});
-28
View File
@@ -1,28 +0,0 @@
import type { DesktopAppBranding, DesktopAppStageLabel } from "@t3tools/contracts";
import { isNightlyDesktopVersion } from "./updateChannels.ts";
const APP_BASE_NAME = "T3 Code";
export function resolveDesktopAppStageLabel(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppStageLabel {
if (input.isDevelopment) {
return "Dev";
}
return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Alpha";
}
export function resolveDesktopAppBranding(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppBranding {
const stageLabel = resolveDesktopAppStageLabel(input);
return {
baseName: APP_BASE_NAME,
stageLabel,
displayName: `${APP_BASE_NAME} (${stageLabel})`,
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { resolveDesktopBackendPort } from "./backendPort.ts";
import { resolveDesktopBackendPort } from "./backendPort";
describe("resolveDesktopBackendPort", () => {
it("returns the starting port when it is available", async () => {
+1 -1
View File
@@ -4,7 +4,7 @@ import {
BackendReadinessAbortedError,
isBackendReadinessAborted,
waitForHttpReady,
} from "./backendReadiness.ts";
} from "./backendReadiness";
describe("waitForHttpReady", () => {
it("returns once the backend serves the requested readiness path", async () => {
+1 -5
View File
@@ -18,7 +18,7 @@ import {
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
type DesktopSecretStorage,
} from "./clientPersistence.ts";
} from "./clientPersistence";
const tempDirectories: string[] = [];
@@ -52,10 +52,6 @@ const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
},
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
+2 -15
View File
@@ -1,13 +1,8 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import {
ClientSettingsSchema,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { Predicate } from "effect";
import * as Schema from "effect/Schema";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
@@ -88,15 +83,7 @@ function toPersistedSavedEnvironmentRecord(
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
if (!raw) {
return null;
}
try {
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
} catch {
return null;
}
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
+1 -1
View File
@@ -11,7 +11,7 @@ vi.mock("electron", () => ({
},
}));
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
import { showDesktopConfirmDialog } from "./confirmDialog";
describe("showDesktopConfirmDialog", () => {
beforeEach(() => {
+4 -87
View File
@@ -7,11 +7,9 @@ import { afterEach, describe, expect, it } from "vitest";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
resolveDefaultDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
} from "./desktopSettings";
const tempDirectories: string[] = [];
@@ -29,15 +27,7 @@ function makeSettingsPath() {
describe("desktopSettings", () => {
it("returns defaults when no settings file exists", () => {
expect(readDesktopSettings(makeSettingsPath(), "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("defaults packaged nightly builds to the nightly update channel", () => {
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("persists and reloads the configured server exposure mode", () => {
@@ -45,14 +35,10 @@ describe("desktopSettings", () => {
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
expect(readDesktopSettings(settingsPath)).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
@@ -61,32 +47,11 @@ describe("desktopSettings", () => {
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
"network-accessible",
),
).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("persists the requested nightly update channel", () => {
expect(
setDesktopUpdateChannelPreference(
{
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
"nightly",
),
).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
});
});
@@ -94,54 +59,6 @@ describe("desktopSettings", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, "{not-json", "utf8");
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("falls back to the nightly channel for legacy nightly settings without an update track", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, JSON.stringify({ serverExposureMode: "local-only" }), "utf8");
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("migrates legacy implicit stable settings to nightly when running a nightly build", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
serverExposureMode: "local-only",
updateChannel: "latest",
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("preserves an explicit stable choice on nightly builds", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
});
+4 -45
View File
@@ -1,28 +1,15 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
}
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
};
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
return {
...DEFAULT_DESKTOP_SETTINGS,
updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
};
}
export function setDesktopServerExposurePreference(
settings: DesktopSettings,
requestedMode: DesktopServerExposureMode,
@@ -35,51 +22,23 @@ export function setDesktopServerExposurePreference(
};
}
export function setDesktopUpdateChannelPreference(
settings: DesktopSettings,
requestedChannel: DesktopUpdateChannel,
): DesktopSettings {
return {
...settings,
updateChannel: requestedChannel,
updateChannelConfiguredByUser: true,
};
}
export function readDesktopSettings(settingsPath: string, appVersion: string): DesktopSettings {
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
export function readDesktopSettings(settingsPath: string): DesktopSettings {
try {
if (!FS.existsSync(settingsPath)) {
return defaultSettings;
return DEFAULT_DESKTOP_SETTINGS;
}
const raw = FS.readFileSync(settingsPath, "utf8");
const parsed = JSON.parse(raw) as {
readonly serverExposureMode?: unknown;
readonly updateChannel?: unknown;
readonly updateChannelConfiguredByUser?: unknown;
};
const parsedUpdateChannel =
parsed.updateChannel === "nightly" || parsed.updateChannel === "latest"
? parsed.updateChannel
: null;
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
const updateChannelConfiguredByUser =
parsed.updateChannelConfiguredByUser === true ||
(isLegacySettings && parsedUpdateChannel === "nightly");
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
updateChannel:
updateChannelConfiguredByUser && parsedUpdateChannel !== null
? parsedUpdateChannel
: defaultSettings.updateChannel,
updateChannelConfiguredByUser,
};
} catch {
return defaultSettings;
return DEFAULT_DESKTOP_SETTINGS;
}
}
+74 -204
View File
@@ -18,14 +18,12 @@ import {
safeStorage,
shell,
} from "electron";
import type { MenuItemConstructorOptions, OpenDialogOptions } from "electron";
import type { MenuItemConstructorOptions } from "electron";
import type {
ClientSettings,
DesktopTheme,
DesktopAppBranding,
DesktopServerExposureMode,
DesktopServerExposureState,
DesktopUpdateChannel,
PersistedSavedEnvironmentRecord,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
@@ -36,14 +34,13 @@ import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
} from "./desktopSettings";
import {
readClientSettings,
readSavedEnvironmentRegistry,
@@ -52,14 +49,18 @@ import {
writeClientSettings,
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
} from "./clientPersistence.ts";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
import { resolveDesktopServerExposure } from "./serverExposure.ts";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels.ts";
import { ServerListeningDetector } from "./serverListeningDetector.ts";
} from "./clientPersistence";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { resolveDesktopServerExposure } from "./serverExposure";
import { syncShellEnvironment } from "./syncShellEnvironment";
import {
resolveDesktopUpdateChannel,
shouldAcceptDesktopUpdateForCurrentVersion,
shouldAllowDesktopPrereleaseUpdates,
} from "./updateChannel";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import { ServerListeningDetector } from "./serverListeningDetector";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
@@ -71,9 +72,8 @@ import {
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine.ts";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
import { resolveDesktopAppBranding } from "./appBranding.ts";
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
syncShellEnvironment();
@@ -85,11 +85,9 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -108,11 +106,7 @@ const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
isDevelopment,
appVersion: app.getVersion(),
});
const APP_DISPLAY_NAME = desktopAppBranding.displayName;
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
@@ -127,32 +121,6 @@ const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
function resolvePickFolderDefaultPath(rawOptions: unknown): string | undefined {
if (typeof rawOptions !== "object" || rawOptions === null) {
return undefined;
}
const { initialPath } = rawOptions as { initialPath?: unknown };
if (typeof initialPath !== "string") {
return undefined;
}
const trimmedPath = initialPath.trim();
if (trimmedPath.length === 0) {
return undefined;
}
if (trimmedPath === "~") {
return OS.homedir();
}
if (trimmedPath.startsWith("~/") || trimmedPath.startsWith("~\\")) {
return Path.join(OS.homedir(), trimmedPath.slice(2));
}
return Path.resolve(trimmedPath);
}
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
const TITLEBAR_HEIGHT = 40;
@@ -160,35 +128,6 @@ const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linu
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
for (const sourceItem of source) {
if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
destructive: sourceItem.destructive === true,
disabled: sourceItem.disabled === true,
};
if (sourceItem.children) {
const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
if (normalizedChildren.length === 0) {
continue;
}
normalizedItem.children = normalizedChildren;
}
normalizedItems.push(normalizedItem);
}
return normalizedItems;
}
type WindowTitleBarOptions = Pick<
BrowserWindowConstructorOptions,
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
@@ -220,7 +159,7 @@ let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH, app.getVersion());
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
@@ -231,11 +170,7 @@ const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(
app.getVersion(),
desktopRuntimeInfo,
desktopSettings.updateChannel,
);
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
function logTimestamp(): string {
return new Date().toISOString();
@@ -1043,18 +978,6 @@ function resolveResourcePath(fileName: string): string | null {
}
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
if (isDevelopment && process.platform === "darwin" && ext === "png") {
const developmentDockIconPath = Path.join(
ROOT_DIR,
"assets",
"dev",
"blueprint-macos-1024.png",
);
if (FS.existsSync(developmentDockIconPath)) {
return developmentDockIconPath;
}
}
return resolveResourcePath(`icon.${ext}`);
}
@@ -1154,26 +1077,6 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
emitUpdateState();
}
function createBaseUpdateState(
channel: DesktopUpdateChannel,
enabled: boolean,
): DesktopUpdateState {
return {
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo, channel),
enabled,
status: enabled ? "idle" : "disabled",
};
}
function applyAutoUpdaterChannel(channel: DesktopUpdateChannel): void {
autoUpdater.channel = channel;
autoUpdater.allowPrerelease = channel === "nightly";
autoUpdater.allowDowngrade = channel === "nightly";
console.info(
`[desktop-updater] Using update channel '${channel}' (allowPrerelease=${channel === "nightly"}, allowDowngrade=${channel === "nightly"}).`,
);
}
function shouldEnableAutoUpdates(): boolean {
const hasUpdateFeedConfig =
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
@@ -1268,6 +1171,9 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
}
function configureAutoUpdater(): void {
const currentVersion = app.getVersion();
const updateChannel = resolveDesktopUpdateChannel(currentVersion);
const allowPrerelease = shouldAllowDesktopPrereleaseUpdates(currentVersion);
const githubToken =
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
if (githubToken) {
@@ -1293,7 +1199,11 @@ function configureAutoUpdater(): void {
}
const enabled = shouldEnableAutoUpdates();
setUpdateState(createBaseUpdateState(desktopSettings.updateChannel, enabled));
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
if (!enabled) {
return;
}
@@ -1301,9 +1211,14 @@ function configureAutoUpdater(): void {
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
applyAutoUpdaterChannel(desktopSettings.updateChannel);
autoUpdater.channel = updateChannel;
autoUpdater.allowPrerelease = allowPrerelease;
autoUpdater.allowDowngrade = false;
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
let lastLoggedDownloadMilestone = -1;
console.info(
`[desktop-updater] Configured update channel=${updateChannel} currentVersion=${currentVersion} allowPrerelease=${allowPrerelease}.`,
);
if (isArm64HostRunningIntelBuild(desktopRuntimeInfo)) {
console.info(
@@ -1315,12 +1230,12 @@ function configureAutoUpdater(): void {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
if (!doesVersionMatchDesktopUpdateChannel(info.version, updateState.channel)) {
console.info(
`[desktop-updater] Ignoring ${info.version} because it does not match the selected '${updateState.channel}' channel.`,
);
if (!shouldAcceptDesktopUpdateForCurrentVersion(currentVersion, info.version)) {
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
lastLoggedDownloadMilestone = -1;
console.info(
`[desktop-updater] Ignoring update ${info.version} on channel=${resolveDesktopUpdateChannel(info.version)} while currentVersion=${currentVersion} is on channel=${updateChannel}.`,
);
return;
}
@@ -1588,11 +1503,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
}
function registerIpcHandlers(): void {
ipcMain.removeAllListeners(GET_APP_BRANDING_CHANNEL);
ipcMain.on(GET_APP_BRANDING_CHANNEL, (event) => {
event.returnValue = desktopAppBranding;
});
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
event.returnValue = {
@@ -1706,16 +1616,15 @@ function registerIpcHandlers(): void {
});
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
const defaultPath = resolvePickFolderDefaultPath(rawOptions);
const openDialogOptions: OpenDialogOptions = {
properties: ["openDirectory", "createDirectory"],
...(defaultPath ? { defaultPath } : {}),
};
const result = owner
? await dialog.showOpenDialog(owner, openDialogOptions)
: await dialog.showOpenDialog(openDialogOptions);
? await dialog.showOpenDialog(owner, {
properties: ["openDirectory", "createDirectory"],
})
: await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
});
if (result.canceled) return null;
return result.filePaths[0] ?? null;
});
@@ -1744,7 +1653,14 @@ function registerIpcHandlers(): void {
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
const normalizedItems = normalizeContextMenuItems(items);
const normalizedItems = items
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
.map((item) => ({
id: item.id,
label: item.label,
destructive: item.destructive === true,
disabled: item.disabled === true,
}));
if (normalizedItems.length === 0) {
return null;
}
@@ -1765,37 +1681,28 @@ function registerIpcHandlers(): void {
if (!window) return null;
return new Promise<string | null>((resolve) => {
const buildTemplate = (
entries: readonly ContextMenuItem[],
): MenuItemConstructorOptions[] => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children);
} else {
itemOption.click = () => resolve(item.id);
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
}
}
template.push(itemOption);
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of normalizedItems) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
return template;
};
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
click: () => resolve(item.id),
};
if (item.destructive) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
}
}
template.push(itemOption);
}
const menu = Menu.buildFromTemplate(buildTemplate(normalizedItems));
const menu = Menu.buildFromTemplate(template);
menu.popup({
window,
...popupPosition,
@@ -1823,43 +1730,6 @@ function registerIpcHandlers(): void {
ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
ipcMain.removeHandler(UPDATE_SET_CHANNEL_CHANNEL);
ipcMain.handle(UPDATE_SET_CHANNEL_CHANNEL, async (_event, rawChannel: unknown) => {
if (rawChannel !== "latest" && rawChannel !== "nightly") {
throw new Error("Invalid desktop update channel input.");
}
if (updateCheckInFlight || updateDownloadInFlight || updateInstallInFlight) {
throw new Error("Cannot change update tracks while an update action is in progress.");
}
const nextChannel = rawChannel as DesktopUpdateChannel;
desktopSettings = setDesktopUpdateChannelPreference(desktopSettings, nextChannel);
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
if (nextChannel === updateState.channel) {
return updateState;
}
const enabled = shouldEnableAutoUpdates();
setUpdateState(createBaseUpdateState(nextChannel, enabled));
if (!enabled || !updaterConfigured) {
return updateState;
}
applyAutoUpdaterChannel(nextChannel);
const allowDowngrade = autoUpdater.allowDowngrade;
// An explicit channel switch should allow the immediate nightly->stable rollback path.
autoUpdater.allowDowngrade = true;
try {
await checkForUpdates("channel-change");
} finally {
autoUpdater.allowDowngrade = allowDowngrade;
}
return updateState;
});
ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
const result = await downloadAvailableUpdate();
@@ -1967,7 +1837,7 @@ function createWindow(): BrowserWindow {
title: APP_DISPLAY_NAME,
...getWindowTitleBarOptions(),
webPreferences: {
preload: Path.join(__dirname, "preload.cjs"),
preload: Path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
+1 -11
View File
@@ -9,11 +9,9 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -26,13 +24,6 @@ const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
const result = ipcRenderer.sendSync(GET_APP_BRANDING_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
@@ -53,7 +44,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
@@ -70,7 +61,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) => ipcRenderer.invoke(UPDATE_SET_CHANNEL_CHANNEL, channel),
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
describe("resolveDesktopRuntimeInfo", () => {
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
describe("resolveLanAdvertisedHost", () => {
it("prefers an explicit host override", () => {
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { ServerListeningDetector } from "./serverListeningDetector.ts";
import { ServerListeningDetector } from "./serverListeningDetector";
describe("ServerListeningDetector", () => {
it("resolves when the server logs the listening line", async () => {
+3 -121
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
import { syncShellEnvironment } from "./syncShellEnvironment";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
@@ -148,7 +148,7 @@ describe("syncShellEnvironment", () => {
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
});
it("does nothing on unsupported platforms", () => {
it("does nothing outside macOS and linux", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
@@ -160,7 +160,7 @@ describe("syncShellEnvironment", () => {
}));
syncShellEnvironment(env, {
platform: "freebsd",
platform: "win32",
readEnvironment,
});
@@ -168,122 +168,4 @@ describe("syncShellEnvironment", () => {
expect(env.PATH).toBe("C:\\Windows\\System32");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("hydrates PATH on Windows by merging PowerShell PATH with inherited PATH", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(() => ({
PATH: "C:\\Custom\\Bin;C:\\Windows\\System32",
}));
const isWindowsCommandAvailable = vi.fn(() => true);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(readWindowsEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
expect(env.PATH).toBe(
[
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
expect(isWindowsCommandAvailable).toHaveBeenCalledTimes(1);
});
it("loads the PowerShell profile on Windows when node is not available", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
options?.loadProfile
? {
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
}
: { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" },
);
const isWindowsCommandAvailable = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(env.PATH).toBe(
[
"C:\\Profile\\Node",
"C:\\Windows\\System32",
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
].join(";"),
);
expect(env.FNM_DIR).toBe("C:\\Users\\testuser\\AppData\\Roaming\\fnm");
expect(env.FNM_MULTISHELL_PATH).toBe(
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
);
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(
2,
["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
{ loadProfile: true },
);
});
it("preserves baseline Windows env when the profile probe fails", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => {
if (options?.loadProfile) {
throw new Error("profile load failed");
}
return { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" };
},
);
const isWindowsCommandAvailable = vi.fn(() => false);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(env.PATH).toBe(
[
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
expect(env.SSH_AUTH_SOCK).toBeUndefined();
});
});
+1 -31
View File
@@ -3,19 +3,9 @@ import {
mergePathEntries,
readPathFromLaunchctl,
readEnvironmentFromLoginShell,
resolveWindowsEnvironment,
} from "@t3tools/shared/shell";
import type {
CommandAvailabilityOptions,
ShellEnvironmentReader,
WindowsShellEnvironmentReader,
} from "@t3tools/shared/shell";
type WindowsCommandAvailabilityChecker = (
command: string,
options?: CommandAvailabilityOptions,
) => boolean;
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
"SSH_AUTH_SOCK",
@@ -35,39 +25,19 @@ export function syncShellEnvironment(
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
readWindowsEnvironment?: WindowsShellEnvironmentReader;
isWindowsCommandAvailable?: WindowsCommandAvailabilityChecker;
readLaunchctlPath?: typeof readPathFromLaunchctl;
userShell?: string;
logWarning?: (message: string, error?: unknown) => void;
} = {},
): void {
const platform = options.platform ?? process.platform;
if (platform !== "darwin" && platform !== "linux") return;
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
const shellEnvironment: Partial<Record<string, string>> = {};
try {
if (platform === "win32") {
const repairedEnvironment = resolveWindowsEnvironment(env, {
...(options.readWindowsEnvironment
? { readEnvironment: options.readWindowsEnvironment }
: {}),
...(options.isWindowsCommandAvailable
? { commandAvailable: options.isWindowsCommandAvailable }
: {}),
});
for (const [key, value] of Object.entries(repairedEnvironment)) {
if (value !== undefined) {
env[key] = value;
}
}
return;
}
if (platform !== "darwin" && platform !== "linux") return;
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
try {
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import {
resolveDesktopUpdateChannel,
shouldAcceptDesktopUpdateForCurrentVersion,
shouldAllowDesktopPrereleaseUpdates,
} from "./updateChannel";
describe("updateChannel", () => {
it("uses the stable latest channel for plain versions", () => {
expect(resolveDesktopUpdateChannel("0.0.17")).toBe("latest");
expect(shouldAllowDesktopPrereleaseUpdates("0.0.17")).toBe(false);
});
it("derives the prerelease channel from the installed version", () => {
expect(resolveDesktopUpdateChannel("0.0.18-nightly.20260415")).toBe("nightly");
expect(shouldAllowDesktopPrereleaseUpdates("0.0.18-nightly.20260415")).toBe(true);
});
it("accepts updates that stay on the same prerelease track", () => {
expect(
shouldAcceptDesktopUpdateForCurrentVersion(
"0.0.18-nightly.20260415",
"0.0.18-nightly.20260416",
),
).toBe(true);
});
it("rejects stable releases while running a nightly build", () => {
expect(shouldAcceptDesktopUpdateForCurrentVersion("0.0.18-nightly.20260415", "0.0.17")).toBe(
false,
);
});
it("rejects updates from a different prerelease track", () => {
expect(
shouldAcceptDesktopUpdateForCurrentVersion("0.0.18-nightly.20260415", "0.0.18-beta.1"),
).toBe(false);
});
});
+26
View File
@@ -0,0 +1,26 @@
const VERSION_PRERELEASE_CHANNEL_PATTERN =
/^\d+\.\d+\.\d+(?:-([0-9A-Za-z-]+)(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z.-]+)?$/;
function resolvePrereleaseChannel(version: string): string | null {
const normalizedVersion = version.trim();
const match = VERSION_PRERELEASE_CHANNEL_PATTERN.exec(normalizedVersion);
const channel = match?.[1]?.trim().toLowerCase();
return channel && channel.length > 0 ? channel : null;
}
export function resolveDesktopUpdateChannel(version: string): string {
return resolvePrereleaseChannel(version) ?? "latest";
}
export function shouldAllowDesktopPrereleaseUpdates(version: string): boolean {
return resolvePrereleaseChannel(version) !== null;
}
export function shouldAcceptDesktopUpdateForCurrentVersion(
currentVersion: string,
candidateVersion: string,
): boolean {
return (
resolveDesktopUpdateChannel(currentVersion) === resolveDesktopUpdateChannel(candidateVersion)
);
}
-41
View File
@@ -1,41 +0,0 @@
import { describe, expect, it } from "vitest";
import {
doesVersionMatchDesktopUpdateChannel,
isNightlyDesktopVersion,
resolveDefaultDesktopUpdateChannel,
} from "./updateChannels.ts";
describe("isNightlyDesktopVersion", () => {
it("detects packaged nightly versions", () => {
expect(isNightlyDesktopVersion("0.0.17-nightly.20260415.1")).toBe(true);
});
it("does not flag stable versions as nightly", () => {
expect(isNightlyDesktopVersion("0.0.17")).toBe(false);
});
});
describe("resolveDefaultDesktopUpdateChannel", () => {
it("defaults stable builds to latest", () => {
expect(resolveDefaultDesktopUpdateChannel("0.0.17")).toBe("latest");
});
it("defaults nightly builds to nightly", () => {
expect(resolveDefaultDesktopUpdateChannel("0.0.17-nightly.20260415.1")).toBe("nightly");
});
});
describe("doesVersionMatchDesktopUpdateChannel", () => {
it("accepts nightly releases on the nightly channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "nightly")).toBe(true);
});
it("rejects stable releases on the nightly channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17", "nightly")).toBe(false);
});
it("rejects nightly releases on the stable channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "latest")).toBe(false);
});
});
-18
View File
@@ -1,18 +0,0 @@
import type { DesktopUpdateChannel } from "@t3tools/contracts";
const NIGHTLY_VERSION_PATTERN = /-nightly\.\d{8}\.\d+$/;
export function isNightlyDesktopVersion(version: string): boolean {
return NIGHTLY_VERSION_PATTERN.test(version);
}
export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
return isNightlyDesktopVersion(appVersion) ? "nightly" : "latest";
}
export function doesVersionMatchDesktopUpdateChannel(
version: string,
channel: DesktopUpdateChannel,
): boolean {
return resolveDefaultDesktopUpdateChannel(version) === channel;
}
+7 -8
View File
@@ -11,7 +11,7 @@ import {
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine.ts";
} from "./updateMachine";
const runtimeInfo = {
hostArch: "x64",
@@ -23,7 +23,7 @@ describe("updateMachine", () => {
it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "error",
message: "network",
@@ -42,7 +42,7 @@ describe("updateMachine", () => {
it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "checking",
},
@@ -58,7 +58,7 @@ describe("updateMachine", () => {
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -76,7 +76,7 @@ describe("updateMachine", () => {
it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -98,7 +98,7 @@ describe("updateMachine", () => {
it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "error",
availableVersion: "1.1.0",
@@ -120,7 +120,7 @@ describe("updateMachine", () => {
it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "checking",
},
@@ -131,7 +131,6 @@ describe("updateMachine", () => {
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
expect(available.status).toBe("available");
expect(available.channel).toBe("latest");
expect(downloading.status).toBe("downloading");
expect(downloading.downloadPercent).toBe(0);
expect(progress.downloadPercent).toBe(55.5);
+2 -8
View File
@@ -1,20 +1,14 @@
import type {
DesktopRuntimeInfo,
DesktopUpdateChannel,
DesktopUpdateState,
} from "@t3tools/contracts";
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState.ts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
export function createInitialDesktopUpdateState(
currentVersion: string,
runtimeInfo: DesktopRuntimeInfo,
channel: DesktopUpdateChannel,
): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
channel,
currentVersion,
hostArch: runtimeInfo.hostArch,
appArch: runtimeInfo.appArch,
+1 -2
View File
@@ -6,12 +6,11 @@ import {
getAutoUpdateDisabledReason,
nextStatusAfterDownloadFailure,
shouldBroadcastDownloadProgress,
} from "./updateState.ts";
} from "./updateState";
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
+1 -1
View File
@@ -3,7 +3,7 @@
"compilerOptions": {
"composite": true,
"types": ["node", "electron"],
"lib": ["ESNext", "DOM", "esnext.disposable"]
"lib": ["ES2023", "DOM", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
}
+1 -1
View File
@@ -4,7 +4,7 @@ const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
outExtensions: () => ({ js: ".js" }),
};
export default defineConfig([
+4 -6
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.20",
"version": "0.0.17",
"license": "MIT",
"repository": {
"type": "git",
@@ -15,17 +15,15 @@
],
"type": "module",
"scripts": {
"dev": "node --watch src/bin.ts",
"dev": "bun run src/bin.ts",
"build": "node scripts/cli.ts build",
"build:bundle": "tsdown",
"start": "node dist/bin.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
+20 -15
View File
@@ -147,13 +147,13 @@ const buildCmd = Command.make(
yield* Effect.log("[cli] Running tsdown...");
yield* runCommand(
ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
ChildProcess.make({
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve `.cmd` shims on PATH.
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
}),
})`bun tsdown`,
);
const webDist = path.join(repoRoot, "apps/web/dist");
@@ -203,8 +203,10 @@ const publishCmd = Command.make(
}
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.gen(function* () {
// Resolve catalog dependencies before any file mutations. If this throws,
// acquire fails and no release hook runs, so filesystem must still be untouched.
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg: PackageJson = {
name: serverPackageJson.name,
@@ -214,22 +216,25 @@ const publishCmd = Command.make(
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
dependencies: resolveCatalogDependencies(
serverPackageJson.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server",
),
overrides: resolveCatalogDependencies(
rootPackageJson.overrides,
rootPackageJson.workspaces.catalog,
"apps/server",
),
dependencies: serverPackageJson.dependencies,
overrides: rootPackageJson.overrides,
};
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
pkg.overrides = resolveCatalogDependencies(
pkg.overrides,
rootPackageJson.workspaces.catalog,
"root overrides",
);
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Prepared package.json for publish");
yield* Effect.log("[cli] Resolved package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
@@ -2,7 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
@@ -10,10 +10,8 @@ import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Lay
import {
AuthControlPlane,
AuthControlPlaneError,
DEFAULT_SESSION_SUBJECT,
} from "../Services/AuthControlPlane.ts";
import type {
AuthControlPlaneShape,
DEFAULT_SESSION_SUBJECT,
IssuedBearerSession,
IssuedPairingLink,
} from "../Services/AuthControlPlane.ts";
@@ -5,7 +5,7 @@ import type {
AuthSessionId,
} from "@t3tools/contracts";
import { Data, DateTime, Duration, Effect, Context } from "effect";
import type { SessionRole } from "./SessionCredentialService.ts";
import { SessionRole } from "./SessionCredentialService";
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { deriveAuthClientMetadata } from "./utils.ts";
import { deriveAuthClientMetadata } from "./utils";
describe("deriveAuthClientMetadata", () => {
it("labels Electron user agents as Electron instead of Chrome", () => {
+3 -3
View File
@@ -5,12 +5,12 @@ import * as Layer from "effect/Layer";
import { Command } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import { cli } from "./cli.ts";
import packageJson from "../package.json" with { type: "json" };
import { cli } from "./cli";
import { version } from "../package.json" with { type: "json" };
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
Command.run(cli, { version: packageJson.version }).pipe(
Command.run(cli, { version }).pipe(
Effect.scoped,
Effect.provide(CliRuntimeLayer),
NodeRuntime.runMain,
+1 -1
View File
@@ -10,7 +10,7 @@ import * as Fiber from "effect/Fiber";
import { TestClock } from "effect/testing";
import { vi } from "vitest";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap.ts";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
import { assertNone, assertSome } from "@effect/vitest/utils";
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
+2 -2
View File
@@ -5,8 +5,8 @@ import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect"
import { NetService } from "@t3tools/shared/Net";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { deriveServerPaths } from "./config.ts";
import { resolveServerConfig } from "./cli.ts";
import { deriveServerPaths } from "./config";
import { resolveServerConfig } from "./cli";
it.layer(NodeServices.layer)("cli config resolution", (it) => {
const defaultObservabilityConfig = {
+11 -12
View File
@@ -40,31 +40,30 @@ import {
RuntimeMode,
type ServerConfigShape,
type StartupPresentation,
} from "./config.ts";
import { readBootstrapEnvelope } from "./bootstrap.ts";
import { expandHomePath, resolveBaseDir } from "./os-jank.ts";
import { runServer } from "./server.ts";
} from "./config";
import { readBootstrapEnvelope } from "./bootstrap";
import { expandHomePath, resolveBaseDir } from "./os-jank";
import { runServer } from "./server";
import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";
import {
formatIssuedPairingCredential,
formatIssuedSession,
formatPairingCredentialList,
formatSessionList,
} from "./cliAuthFormat.ts";
import { AuthControlPlane } from "./auth/Services/AuthControlPlane.ts";
import type { AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
} from "./cliAuthFormat";
import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup.ts";
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup";
import {
clearPersistedServerRuntimeState,
readPersistedServerRuntimeState,
} from "./serverRuntimeState.ts";
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
} from "./serverRuntimeState";
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
+1 -149
View File
@@ -15,7 +15,7 @@ import {
normalizeCodexModelSlug,
readCodexAccountSnapshot,
resolveCodexModelForAccount,
} from "./codexAppServerManager.ts";
} from "./codexAppServerManager";
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
@@ -470,154 +470,6 @@ describe("startSession", () => {
manager.stopAll();
}
});
it("disposes an existing session before starting a replacement for the same thread", async () => {
const manager = new CodexAppServerManager();
const existingContext = {
session: {
provider: "codex",
status: "ready",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.set(asThreadId("thread-1"), existingContext);
const disposeSession = vi
.spyOn(
manager as unknown as {
disposeSession: (
context: typeof existingContext,
options?: { readonly emitLifecycleEvent?: boolean },
) => void;
},
"disposeSession",
)
.mockImplementation(() => {});
const assertSupportedCodexCliVersion = vi
.spyOn(
manager as unknown as {
assertSupportedCodexCliVersion: (input: {
binaryPath: string;
cwd: string;
homePath?: string;
}) => void;
},
"assertSupportedCodexCliVersion",
)
.mockImplementation(() => {});
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("cwd missing");
});
try {
await expect(
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow("cwd missing");
expect(disposeSession).toHaveBeenCalledWith(existingContext, {
emitLifecycleEvent: false,
});
expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
} finally {
disposeSession.mockRestore();
assertSupportedCodexCliVersion.mockRestore();
processCwd.mockRestore();
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.clear();
manager.stopAll();
}
});
it("continues replacement start when existing session disposal fails", async () => {
const manager = new CodexAppServerManager();
const existingContext = {
session: {
provider: "codex",
status: "ready",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.set(asThreadId("thread-1"), existingContext);
const disposeSession = vi
.spyOn(
manager as unknown as {
disposeSession: (
context: typeof existingContext,
options?: { readonly emitLifecycleEvent?: boolean },
) => void;
},
"disposeSession",
)
.mockImplementation(() => {
throw new Error("dispose failed");
});
const assertSupportedCodexCliVersion = vi
.spyOn(
manager as unknown as {
assertSupportedCodexCliVersion: (input: {
binaryPath: string;
cwd: string;
homePath?: string;
}) => void;
},
"assertSupportedCodexCliVersion",
)
.mockImplementation(() => {});
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("cwd missing");
});
try {
await expect(
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow("cwd missing");
expect(disposeSession).toHaveBeenCalledWith(existingContext, {
emitLifecycleEvent: false,
});
expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
} finally {
disposeSession.mockRestore();
assertSupportedCodexCliVersion.mockRestore();
processCwd.mockRestore();
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.clear();
manager.stopAll();
}
});
});
describe("sendTurn", () => {
+7 -41
View File
@@ -25,16 +25,16 @@ import {
formatCodexCliUpgradeMessage,
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "./provider/codexCliVersion.ts";
} from "./provider/codexCliVersion";
import {
readCodexAccountSnapshot,
resolveCodexModelForAccount,
type CodexAccountSnapshot,
} from "./provider/codexAccount.ts";
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer.ts";
} from "./provider/codexAccount";
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
export { buildCodexInitializeParams } from "./provider/codexAppServer.ts";
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount.ts";
export { buildCodexInitializeParams } from "./provider/codexAppServer";
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
type PendingRequestKey = string;
@@ -450,25 +450,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
let context: CodexSessionContext | undefined;
try {
const existingContext = this.sessions.get(threadId);
if (existingContext) {
await Effect.logWarning("codex app-server replacing existing session", {
threadId,
existingStatus: existingContext.session.status,
}).pipe(this.runPromise);
try {
this.disposeSession(existingContext, {
emitLifecycleEvent: false,
});
} catch (error) {
await Effect.logWarning("codex app-server failed to dispose existing session", {
threadId,
existingStatus: existingContext.session.status,
cause: error instanceof Error ? error.message : String(error),
}).pipe(this.runPromise);
}
}
const resolvedCwd = input.cwd ?? process.cwd();
const session: ProviderSession = {
@@ -920,19 +901,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return;
}
this.disposeSession(context, {
emitLifecycleEvent: true,
});
}
private disposeSession(
context: CodexSessionContext,
options?: { readonly emitLifecycleEvent?: boolean },
): void {
if (context.stopping) {
return;
}
context.stopping = true;
for (const pending of context.pending.values()) {
@@ -953,10 +921,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
status: "closed",
activeTurnId: undefined,
});
if (options?.emitLifecycleEvent !== false) {
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
}
this.sessions.delete(context.session.threadId);
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
this.sessions.delete(threadId);
}
listSessions(): ProviderSession[] {
@@ -3,7 +3,7 @@ import { Effect, FileSystem, Layer, Path, Random } from "effect";
import { ServerConfig } from "../../config.ts";
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
import packageJson from "../../../package.json" with { type: "json" };
import { version } from "../../../package.json" with { type: "json" };
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
@@ -77,7 +77,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
os: platformOs(),
arch: platformArch(),
},
serverVersion: packageJson.version,
serverVersion: version,
capabilities: {
repositoryIdentity: true,
},
@@ -166,7 +166,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
[
"exec",
"--ephemeral",
"--skip-git-repo-check",
"-s",
"read-only",
"--model",
+1 -1
View File
@@ -6,7 +6,7 @@ vi.mock("../../processRunner", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner.ts";
import { runProcess } from "../../processRunner";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { GitHubCliLive } from "./GitHubCli.ts";
+1 -1
View File
@@ -1,7 +1,7 @@
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import { runProcess } from "../../processRunner.ts";
import { runProcess } from "../../processRunner";
import { GitHubCliError } from "@t3tools/contracts";
import {
GitHubCli,
+1 -2
View File
@@ -38,8 +38,7 @@ import {
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
import type { GitStatusDetails } from "../Services/GitCore.ts";
import { GitCore, GitStatusDetails } from "../Services/GitCore.ts";
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
+1 -1
View File
@@ -8,7 +8,7 @@
import { Context } from "effect";
import type { Effect } from "effect";
import type { ProcessRunResult } from "../../processRunner.ts";
import type { ProcessRunResult } from "../../processRunner";
import type { GitHubCliError } from "@t3tools/contracts";
export interface GitHubPullRequestSummary {
+4 -4
View File
@@ -15,12 +15,12 @@ import {
ATTACHMENTS_ROUTE_PREFIX,
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import { resolveAttachmentPathById } from "./attachmentStore.ts";
import { resolveStaticDir, ServerConfig } from "./config.ts";
} from "./attachmentPaths";
import { resolveAttachmentPathById } from "./attachmentStore";
import { resolveStaticDir, ServerConfig } from "./config";
import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
import { respondToAuthError } from "./auth/http.ts";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
+2 -2
View File
@@ -3,7 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import { ServerConfig } from "./config.ts";
import { ServerConfig } from "./config";
import {
DEFAULT_KEYBINDINGS,
@@ -13,7 +13,7 @@ import {
compileResolvedKeybindingRule,
compileResolvedKeybindingsConfig,
parseKeybindingShortcut,
} from "./keybindings.ts";
} from "./keybindings";
import { KeybindingsConfigError } from "@t3tools/contracts";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
+2 -2
View File
@@ -19,7 +19,7 @@ import {
THREAD_JUMP_KEYBINDING_COMMANDS,
type ServerConfigIssue,
} from "@t3tools/contracts";
import type { Mutable } from "effect/Types";
import { Mutable } from "effect/Types";
import {
Array,
Cache,
@@ -44,7 +44,7 @@ import {
Stream,
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config.ts";
import { ServerConfig } from "./config";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
type WhenToken =
@@ -1,8 +1,7 @@
import type * as Exit from "effect/Exit";
import { Effect, Option, Tracer } from "effect";
import { spanToTraceRecord } from "./TraceRecord.ts";
import type { EffectTraceRecord } from "./TraceRecord.ts";
import { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts";
import { makeTraceSink, type TraceSink } from "./TraceSink.ts";
export interface LocalFileTracerOptions {
@@ -28,16 +27,12 @@ class LocalFileSpan implements Tracer.Span {
status: Tracer.SpanStatus;
attributes: Map<string, unknown>;
events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
private readonly delegate: Tracer.Span;
private readonly push: (record: EffectTraceRecord) => void;
constructor(
options: Parameters<Tracer.Tracer["span"]>[0],
delegate: Tracer.Span,
push: (record: EffectTraceRecord) => void,
private readonly delegate: Tracer.Span,
private readonly push: (record: EffectTraceRecord) => void,
) {
this.delegate = delegate;
this.push = push;
this.name = delegate.name;
this.spanId = delegate.spanId;
this.traceId = delegate.traceId;
+1 -1
View File
@@ -8,7 +8,7 @@ import {
launchDetached,
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open.ts";
} from "./open";
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
+112 -2
View File
@@ -7,9 +7,10 @@
* @module Open
*/
import { spawn } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
import { Context, Effect, Layer } from "effect";
// ==============================
@@ -17,7 +18,6 @@ import { Context, Effect, Layer } from "effect";
// ==============================
export { OpenError };
export { isCommandAvailable } from "@t3tools/shared/shell";
export interface OpenInEditorInput {
readonly cwd: string;
@@ -29,6 +29,11 @@ interface EditorLaunch {
readonly args: ReadonlyArray<string>;
}
interface CommandAvailabilityOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
}
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
function parseTargetPathAndPosition(target: string): {
@@ -101,6 +106,111 @@ function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [];
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
export function isCommandAvailable(
command: string,
options: CommandAvailabilityOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
);
}
const pathValue = resolvePathEnvironmentVariable(env);
if (pathValue.length === 0) return false;
const pathEntries = pathValue
.split(resolvePathDelimiter(platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
return true;
}
}
}
return false;
}
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
@@ -21,8 +21,8 @@ import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import type { OrchestrationDispatchError } from "../Errors.ts";
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import { OrchestrationDispatchError } from "../Errors.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
@@ -1284,14 +1284,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
return;
}
// Only approval-requested activities should create pending-approval
// rows. Other activity kinds that happen to carry a requestId
// (e.g. user-input.requested / user-input.resolved) must not
// pollute this projection — they have their own accounting via
// derivePendingUserInputCountFromActivities.
if (event.payload.activity.kind !== "approval.requested") {
return;
}
if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
return;
}
@@ -19,8 +19,7 @@ import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -465,7 +465,6 @@ function runtimeEventToActivities(
payload: {
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
+5 -26
View File
@@ -6,10 +6,10 @@ import {
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { parseBase64DataUrl } from "../imageMime.ts";
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore";
import { ServerConfig } from "../config";
import { parseBase64DataUrl } from "../imageMime";
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths";
export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
Effect.gen(function* () {
@@ -28,31 +28,10 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
),
);
const normalizeProjectWorkspaceRootForCreate = (
workspaceRoot: string,
createIfMissing: boolean | undefined,
) =>
workspacePaths
.normalizeWorkspaceRoot(workspaceRoot, {
createIfMissing: createIfMissing === true,
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationDispatchCommandError({
message: cause.message,
}),
),
);
if (command.type === "project.create") {
return {
...command,
workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(
command.workspaceRoot,
command.createWorkspaceRootIfMissing,
),
createWorkspaceRootIfMissing: command.createWorkspaceRootIfMissing === true,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
} satisfies OrchestrationCommand;
}
+3 -116
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { fixPath } from "./os-jank.ts";
import { fixPath } from "./os-jank";
describe("fixPath", () => {
it("hydrates PATH on linux using the resolved login shell", () => {
@@ -53,120 +53,7 @@ describe("fixPath", () => {
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
});
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", () => {
it("does nothing outside macOS and linux even when SHELL is set", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
@@ -175,7 +62,7 @@ describe("fixPath", () => {
fixPath({
env,
platform: "freebsd",
platform: "win32",
readPath,
});
+3 -29
View File
@@ -1,21 +1,12 @@
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 ?? ""));
}
@@ -25,36 +16,19 @@ 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 {
@@ -37,7 +37,6 @@ 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.
@@ -74,7 +73,6 @@ export const migrationEntries = [
[22, "AuthSessionLastConnectedAt", Migration0022],
[23, "ProjectionThreadShellSummary", Migration0023],
[24, "BackfillProjectionThreadShellSummary", Migration0024],
[25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -1,196 +0,0 @@
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,
},
]);
}),
);
});
@@ -1,27 +0,0 @@
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,162 +0,0 @@
import { spawn, type ChildProcess, type ChildProcessByStdio } from "node:child_process";
import type { Readable } from "node:stream";
import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { TerminalProcessInspector } from "../Services/TerminalProcessInspector.ts";
import { TerminalProcessInspectorLive } from "./TerminalProcessInspector.ts";
type ListenerProcess = ChildProcessByStdio<null, Readable, Readable>;
interface StartedProcess {
readonly process: ListenerProcess;
readonly port: number;
}
const stopProcess = (child: ChildProcess) =>
Effect.callback<void>((resume) => {
if (child.exitCode !== null || child.signalCode !== null) {
resume(Effect.void);
return;
}
child.kill("SIGTERM");
const timeout = setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) {
child.kill("SIGKILL");
}
}, 1_000);
child.once("exit", () => {
clearTimeout(timeout);
resume(Effect.void);
});
});
const waitForPort = (child: ListenerProcess) =>
Effect.callback<number, Error>((resume) => {
const timeout = setTimeout(() => {
cleanup();
resume(Effect.fail(new Error("Timed out waiting for listener port")));
}, 3_000);
let stdout = "";
let stderr = "";
const cleanup = () => {
clearTimeout(timeout);
child.stdout.off("data", onStdout);
child.stderr.off("data", onStderr);
child.off("exit", onExit);
};
const onStdout = (chunk: Buffer) => {
stdout += chunk.toString("utf8");
const match = stdout.match(/PORT:(\d+)/);
if (!match?.[1]) return;
const port = Number(match[1]);
if (!Number.isInteger(port) || port <= 0) return;
cleanup();
resume(Effect.succeed(port));
};
const onStderr = (chunk: Buffer) => {
stderr += chunk.toString("utf8");
};
const onExit = (code: number | null) => {
cleanup();
resume(
Effect.fail(
new Error(
`Listener process exited before reporting port (code=${String(code)}): ${stderr.trim()}`,
),
),
);
};
child.stdout.on("data", onStdout);
child.stderr.on("data", onStderr);
child.on("exit", onExit);
return Effect.sync(cleanup);
});
const startListenerProcess = Effect.gen(function* () {
const script = [
"const { createServer } = require('node:http');",
"const server = createServer((_req, res) => {",
" res.statusCode = 200;",
" res.end('ok');",
"});",
"server.listen(0, '127.0.0.1', () => {",
" const address = server.address();",
" if (typeof address !== 'object' || !address) process.exit(1);",
" console.log(`PORT:${address.port}`);",
"});",
"const shutdown = () => server.close(() => process.exit(0));",
"process.on('SIGTERM', shutdown);",
"process.on('SIGINT', shutdown);",
"setInterval(() => {}, 10_000);",
].join("");
const process = spawn("node", ["-e", script], {
stdio: ["ignore", "pipe", "pipe"],
});
const port = yield* waitForPort(process);
return { process, port } satisfies StartedProcess;
});
const nodeChildProcessLayer = NodeChildProcessSpawner.layer.pipe(Layer.provide(NodeServices.layer));
const testLayer = TerminalProcessInspectorLive.pipe(Layer.provide(nodeChildProcessLayer));
it.layer(testLayer)("TerminalProcessInspectorLive", (it) => {
it.effect("detects listening ports when the terminal root pid is the listener", () =>
Effect.acquireUseRelease(
startListenerProcess,
({ process, port }) =>
Effect.gen(function* () {
const listenerPid = process.pid;
if (!listenerPid) {
return yield* Effect.fail(new Error("Listener process pid missing"));
}
const inspector = yield* TerminalProcessInspector;
const activity = yield* inspector.inspect(listenerPid);
assert.equal(activity.hasRunningSubprocess, true);
assert.deepStrictEqual(activity.runningPorts.includes(port), true);
}),
({ process }) => stopProcess(process),
),
);
it.effect("returns idle activity when root process has no children and no listening ports", () =>
Effect.acquireUseRelease(
Effect.sync(() =>
spawn("node", ["-e", "setInterval(() => {}, 10_000)"], {
stdio: ["ignore", "ignore", "ignore"],
}),
),
(process) =>
Effect.gen(function* () {
const idlePid = process.pid;
if (!idlePid) {
return yield* Effect.fail(new Error("Idle process pid missing"));
}
const inspector = yield* TerminalProcessInspector;
const activity = yield* inspector.inspect(idlePid);
assert.equal(activity.hasRunningSubprocess, false);
assert.deepStrictEqual(activity.runningPorts, []);
}),
stopProcess,
),
);
});
@@ -1,232 +0,0 @@
import { Buffer } from "node:buffer";
import { Effect, Layer, Option, PlatformError, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { collectPosixProcessFamilyPids, checkPosixListeningPorts } from "../posix.ts";
import type {
TerminalProcessInspectorShape,
TerminalSubprocessActivity,
} from "../Services/TerminalProcessInspector.ts";
import {
TerminalProcessInspector,
TerminalProcessInspectionError,
} from "../Services/TerminalProcessInspector.ts";
import { checkWindowsListeningPorts, collectWindowsChildPids } from "../win32.ts";
const DEFAULT_COMMAND_KILL_GRACE_MS = 1_000;
interface InspectorCommandResult {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: number;
}
interface CollectOutputResult {
readonly text: string;
readonly truncated: boolean;
}
interface RunInspectorCommandInput {
readonly operation: string;
readonly terminalPid: number;
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs: number;
readonly maxOutputBytes: number;
}
function commandLabel(command: string, args: ReadonlyArray<string>): string {
return [command, ...args].join(" ");
}
const collectOutput = Effect.fn("process.collectOutput")(function* (
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
maxOutputBytes: number,
): Effect.fn.Return<CollectOutputResult, PlatformError.PlatformError> {
return yield* stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => ({
text: "",
bytes: 0,
truncated: false,
}),
(state, chunk) => {
if (state.bytes >= maxOutputBytes) {
return {
...state,
truncated: true,
};
}
const chunkBytes = Buffer.byteLength(chunk);
const remainingBytes = maxOutputBytes - state.bytes;
if (chunkBytes <= remainingBytes) {
return {
text: `${state.text}${chunk}`,
bytes: state.bytes + chunkBytes,
truncated: state.truncated,
};
}
const truncatedChunk = Buffer.from(chunk).subarray(0, remainingBytes).toString("utf8");
return {
text: `${state.text}${truncatedChunk}`,
bytes: state.bytes + remainingBytes,
truncated: true,
};
},
),
Effect.map(({ text, truncated }) => ({ text, truncated })),
);
});
const makeTerminalProcessInspector = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runInspectorCommand = Effect.fn("process.runInspectorCommand")(function* (
input: RunInspectorCommandInput,
) {
const command = ChildProcess.make(input.command, [...input.args], {
killSignal: "SIGTERM",
forceKillAfter: DEFAULT_COMMAND_KILL_GRACE_MS,
});
return yield* Effect.gen(function* () {
const child = yield* spawner.spawn(command).pipe(
Effect.mapError(
(cause) =>
new TerminalProcessInspectionError({
operation: input.operation,
terminalPid: input.terminalPid,
command: commandLabel(input.command, input.args),
detail: "Failed to spawn inspector command.",
cause,
}),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectOutput(child.stdout, input.maxOutputBytes).pipe(
Effect.mapError(
(cause) =>
new TerminalProcessInspectionError({
operation: input.operation,
terminalPid: input.terminalPid,
command: commandLabel(input.command, input.args),
detail: "Failed to read stdout from inspector command.",
cause,
}),
),
),
collectOutput(child.stderr, input.maxOutputBytes).pipe(
Effect.mapError(
(cause) =>
new TerminalProcessInspectionError({
operation: input.operation,
terminalPid: input.terminalPid,
command: commandLabel(input.command, input.args),
detail: "Failed to read stderr from inspector command.",
cause,
}),
),
),
child.exitCode.pipe(
Effect.map(Number),
Effect.mapError(
(cause) =>
new TerminalProcessInspectionError({
operation: input.operation,
terminalPid: input.terminalPid,
command: commandLabel(input.command, input.args),
detail: "Failed to read inspector command exit code.",
cause,
}),
),
),
],
{ concurrency: "unbounded" },
);
return {
stdout: stdout.text,
stderr: stderr.text,
exitCode,
} satisfies InspectorCommandResult;
}).pipe(
Effect.scoped,
Effect.timeoutOption(input.timeoutMs),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TerminalProcessInspectionError({
operation: input.operation,
terminalPid: input.terminalPid,
command: commandLabel(input.command, input.args),
detail: "Inspector command timed out.",
}),
),
onSome: Effect.succeed,
}),
),
);
});
const inspect: TerminalProcessInspectorShape["inspect"] = Effect.fn("process.inspect")(function* (
terminalPid: number,
) {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return {
hasRunningSubprocess: false,
runningPorts: [],
} satisfies TerminalSubprocessActivity;
}
if (process.platform === "win32") {
const childPids = yield* collectWindowsChildPids(terminalPid, runInspectorCommand);
const processPidsForPortScan = [terminalPid, ...childPids];
const runningPorts = yield* checkWindowsListeningPorts(processPidsForPortScan, {
terminalPid,
runCommand: runInspectorCommand,
});
return {
hasRunningSubprocess: childPids.length > 0 || runningPorts.length > 0,
runningPorts,
} satisfies TerminalSubprocessActivity;
}
const processFamilyPids = yield* collectPosixProcessFamilyPids(
terminalPid,
runInspectorCommand,
);
if (processFamilyPids.length === 0) {
return {
hasRunningSubprocess: false,
runningPorts: [],
} satisfies TerminalSubprocessActivity;
}
const subprocessPids = processFamilyPids.filter((pid: number) => pid !== terminalPid);
const runningPorts = yield* checkPosixListeningPorts(processFamilyPids, {
terminalPid,
runCommand: runInspectorCommand,
platform: process.platform,
});
return {
hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0,
runningPorts,
} satisfies TerminalSubprocessActivity;
});
return {
inspect,
} satisfies TerminalProcessInspectorShape;
});
export const TerminalProcessInspectorLive = Layer.effect(
TerminalProcessInspector,
makeTerminalProcessInspector,
);
@@ -1,153 +0,0 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { WebPortInspectionError, WebPortInspector } from "../Services/WebPortInspector.ts";
import { WebPortInspectorLive } from "./WebPortInspector.ts";
const closeServer = (server: Server) =>
Effect.callback<void>((resume) => {
server.closeAllConnections?.();
server.closeIdleConnections?.();
server.close(() => {
resume(Effect.void);
});
return Effect.sync(() => {
try {
server.closeAllConnections?.();
server.closeIdleConnections?.();
server.close();
} catch {
// Ignore cleanup failures in tests.
}
});
});
const listenServer = (server: Server) =>
Effect.callback<number, Error>((resume) => {
const onError = (error: Error) => {
cleanup();
resume(Effect.fail(error));
};
const cleanup = () => {
server.off("error", onError);
};
server.once("error", onError);
server.listen(0, "127.0.0.1", () => {
cleanup();
const address = server.address();
if (!address || typeof address !== "object") {
resume(Effect.fail(new Error("Server did not provide a valid listening address.")));
return;
}
resume(Effect.succeed(address.port));
});
return Effect.gen(function* () {
cleanup();
yield* closeServer(server);
});
});
const startServer = (
handler: (request: IncomingMessage, response: ServerResponse) => void,
): Effect.Effect<{ server: Server; port: number }, Error> =>
Effect.gen(function* () {
const server = createServer(handler);
const port = yield* listenServer(server);
return { server, port };
});
it.layer(WebPortInspectorLive.pipe(Layer.provide(FetchHttpClient.layer)))(
"WebPortInspectorLive",
(it) => {
it.effect("treats slow HTML responses as web ports", () =>
Effect.acquireUseRelease(
startServer((_request, response) => {
setTimeout(() => {
response.statusCode = 200;
response.setHeader("content-type", "text/html; charset=utf-8");
response.end(
"<!DOCTYPE html><html><head><title>ok</title></head><body>hello</body></html>",
);
}, 800);
}),
({ port }) =>
Effect.gen(function* () {
const inspector = yield* WebPortInspector;
const isWeb = yield* inspector.inspect(port);
assert.equal(isWeb, true);
}),
({ server }) => closeServer(server),
),
);
it.effect("treats HTML responses with large bodies as web ports", () =>
Effect.acquireUseRelease(
startServer((_request, response) => {
response.statusCode = 200;
response.setHeader("content-type", "text/html; charset=utf-8");
response.end(
`<!DOCTYPE html><html><head><title>x</title></head><body>${"x".repeat(20_000)}</body></html>`,
);
}),
({ port }) =>
Effect.gen(function* () {
const inspector = yield* WebPortInspector;
const isWeb = yield* inspector.inspect(port);
assert.equal(isWeb, true);
}),
({ server }) => closeServer(server),
),
);
it.effect("ignores HTTP 404 responses", () =>
Effect.acquireUseRelease(
startServer((_request, response) => {
response.statusCode = 404;
response.end();
}),
({ port }) =>
Effect.gen(function* () {
const inspector = yield* WebPortInspector;
const isWeb = yield* inspector.inspect(port);
assert.equal(isWeb, false);
}),
({ server }) => closeServer(server),
),
);
},
);
it.effect("WebPortInspectorLive preserves typed timeout errors", () =>
Effect.gen(function* () {
const inspector = yield* WebPortInspector;
const error = yield* inspector.inspect(3000).pipe(Effect.flip);
assert.equal(Schema.is(WebPortInspectionError)(error), true);
assert.equal(error.detail, "HTTP probe timed out.");
}).pipe(
Effect.provide(
WebPortInspectorLive.pipe(
Layer.provide(
Layer.succeed(HttpClient.HttpClient, {
execute: () =>
Effect.fail(
new WebPortInspectionError({
port: 3000,
host: "127.0.0.1",
detail: "HTTP probe timed out.",
}),
),
} as never),
),
),
),
),
);
@@ -1,179 +0,0 @@
import { Buffer } from "node:buffer";
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
import type { WebPortInspectorShape } from "../Services/WebPortInspector.ts";
import { WebPortInspector, WebPortInspectionError } from "../Services/WebPortInspector.ts";
const DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 2_000;
const WEB_PORT_PROBE_MAX_BODY_BYTES = 8_192;
interface WebProbeResult {
readonly status: number;
readonly contentType: string;
readonly body: string;
readonly location: string;
}
function normalizeHeaderValue(value: string | string[] | undefined): string {
if (typeof value === "string") return value;
if (Array.isArray(value)) return value[0] ?? "";
return "";
}
function isLikelyWebProbe(result: WebProbeResult | null): boolean {
if (!result) return false;
if (result.status === 404) return false;
if (result.status >= 300 && result.status < 400 && result.location.length > 0) {
return true;
}
const contentType = result.contentType.toLowerCase();
if (contentType.includes("text/html") || contentType.includes("application/xhtml+xml")) {
return true;
}
const body = result.body.toLowerCase();
return body.includes("<!doctype") || body.includes("<html") || body.includes("<head");
}
const collectBodyPreview = <E>(
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, never> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => ({
text: "",
bytes: 0,
}),
(state, chunk) => {
if (state.bytes >= WEB_PORT_PROBE_MAX_BODY_BYTES) {
return state;
}
const chunkBytes = Buffer.byteLength(chunk);
const remainingBytes = WEB_PORT_PROBE_MAX_BODY_BYTES - state.bytes;
if (chunkBytes <= remainingBytes) {
return {
text: `${state.text}${chunk}`,
bytes: state.bytes + chunkBytes,
};
}
return {
text: `${state.text}${Buffer.from(chunk).subarray(0, remainingBytes).toString("utf8")}`,
bytes: state.bytes + remainingBytes,
};
},
),
Effect.map((preview) => preview.text),
Effect.orElseSucceed(() => ""),
);
const makeWebPortInspector = Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
const probeWebPortOnHost = Effect.fn("process.probeWebPortOnHost")(function* (
port: number,
host: string,
): Effect.fn.Return<WebProbeResult | null, WebPortInspectionError> {
const request = HttpClientRequest.get(`http://${host}:${port}/`).pipe(
HttpClientRequest.setHeaders({
accept: "text/html,application/xhtml+xml;q=1,*/*;q=0.1",
}),
);
return yield* httpClient.execute(request).pipe(
Effect.flatMap((response) =>
Effect.gen(function* () {
const status = response.status;
const contentType = normalizeHeaderValue(response.headers["content-type"]);
const location = normalizeHeaderValue(response.headers.location);
if (
(status >= 300 && status < 400 && location.length > 0) ||
contentType.toLowerCase().includes("text/html") ||
contentType.toLowerCase().includes("application/xhtml+xml")
) {
return {
status,
contentType,
location,
body: "",
} satisfies WebProbeResult;
}
const body = yield* collectBodyPreview(response.stream);
return {
status,
contentType,
location,
body,
} satisfies WebProbeResult;
}),
),
Effect.timeoutOption(DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new WebPortInspectionError({
port,
host,
detail: "HTTP probe timed out.",
}),
),
onSome: Effect.succeed,
}),
),
Effect.mapError((error) =>
Schema.is(WebPortInspectionError)(error)
? error
: new WebPortInspectionError({
port,
host,
detail: "Failed to execute HTTP probe request.",
cause: error,
}),
),
);
});
const inspect: WebPortInspectorShape["inspect"] = Effect.fn("process.inspectWebPort")(function* (
port: number,
) {
if (!Number.isInteger(port) || port <= 0 || port > 65_535) {
return yield* new WebPortInspectionError({
port,
host: "127.0.0.1",
detail: "Port must be an integer between 1 and 65535.",
});
}
const ipv4Result = yield* probeWebPortOnHost(port, "127.0.0.1").pipe(Effect.exit);
if (ipv4Result._tag === "Success" && isLikelyWebProbe(ipv4Result.value)) {
return true;
}
const ipv6Result = yield* probeWebPortOnHost(port, "::1").pipe(Effect.exit);
if (ipv6Result._tag === "Success" && isLikelyWebProbe(ipv6Result.value)) {
return true;
}
if (ipv4Result._tag === "Success" || ipv6Result._tag === "Success") {
return false;
}
if (ipv6Result._tag === "Failure") {
return yield* Effect.failCause(ipv6Result.cause);
}
return yield* Effect.failCause(ipv4Result.cause);
});
return {
inspect,
} satisfies WebPortInspectorShape;
});
export const WebPortInspectorLive = Layer.effect(WebPortInspector, makeWebPortInspector);
@@ -1,53 +0,0 @@
import { Context, Schema } from "effect";
import type { Effect } from "effect";
function describeTerminalInspectorCause(cause: unknown): string | null {
if (cause instanceof Error && cause.message.length > 0) {
return cause.message;
}
if (typeof cause === "string" && cause.length > 0) {
return cause;
}
if (cause === undefined || cause === null) {
return null;
}
return String(cause);
}
export class TerminalProcessInspectionError extends Schema.TaggedErrorClass<TerminalProcessInspectionError>()(
"TerminalProcessInspectionError",
{
operation: Schema.String,
terminalPid: Schema.Int,
command: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
const cause = describeTerminalInspectorCause(this.cause);
return `${this.operation} failed for terminal pid ${this.terminalPid} (${this.command}): ${this.detail}${
cause ? ` Cause: ${cause}` : ""
}`;
}
}
export interface TerminalSubprocessActivity {
hasRunningSubprocess: boolean;
runningPorts: number[];
}
export type TerminalSubprocessInspector = (
terminalPid: number,
) => Effect.Effect<TerminalSubprocessActivity, TerminalProcessInspectionError>;
export interface TerminalProcessInspectorShape {
readonly inspect: (
terminalPid: number,
) => Effect.Effect<TerminalSubprocessActivity, TerminalProcessInspectionError>;
}
export class TerminalProcessInspector extends Context.Service<
TerminalProcessInspector,
TerminalProcessInspectorShape
>()("t3/process/Services/TerminalProcessInspector") {}
@@ -1,30 +0,0 @@
import { Context, Schema } from "effect";
import type { Effect } from "effect";
export const DEFAULT_WEB_PORT_PROBE_TTL_MS = 10_000;
export type TerminalWebPortInspector = (
port: number,
) => Effect.Effect<boolean, WebPortInspectionError>;
export class WebPortInspectionError extends Schema.TaggedErrorClass<WebPortInspectionError>()(
"WebPortInspectionError",
{
port: Schema.Int,
host: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Web port probe failed for ${this.host}:${this.port}: ${this.detail}`;
}
}
export interface WebPortInspectorShape {
readonly inspect: (port: number) => Effect.Effect<boolean, WebPortInspectionError>;
}
export class WebPortInspector extends Context.Service<WebPortInspector, WebPortInspectorShape>()(
"t3/process/Services/WebPortInspector",
) {}
-60
View File
@@ -1,60 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { checkPosixListeningPorts } from "./posix.ts";
describe("process.checkPosixListeningPorts", () => {
it.effect("falls back to ss when lsof exits with code 1", () =>
Effect.gen(function* () {
const commands: string[] = [];
const ports = yield* checkPosixListeningPorts([123], {
terminalPid: 123,
platform: "linux",
runCommand: (input) => {
commands.push(input.command);
if (input.command === "lsof") {
return Effect.succeed({
stdout: "",
stderr: "",
exitCode: 1,
});
}
return Effect.succeed({
stdout:
"State Recv-Q Send-Q Local Address:Port Peer Address:Port Process\n" +
'LISTEN 0 511 127.0.0.1:3773 0.0.0.0:* users:(("node",pid=123,fd=18))\n',
stderr: "",
exitCode: 0,
});
},
});
assert.deepStrictEqual(ports, [3773]);
assert.deepStrictEqual(commands, ["lsof", "ss"]);
}),
);
it.effect("does not try ss on darwin when lsof reports no listening ports", () =>
Effect.gen(function* () {
const commands: string[] = [];
const ports = yield* checkPosixListeningPorts([123], {
terminalPid: 123,
platform: "darwin",
runCommand: (input) => {
commands.push(input.command);
return Effect.succeed({
stdout: "",
stderr: "",
exitCode: 1,
});
},
});
assert.deepStrictEqual(ports, []);
assert.deepStrictEqual(commands, ["lsof"]);
}),
);
});
-147
View File
@@ -1,147 +0,0 @@
import { Effect } from "effect";
import type { TerminalProcessInspectionError } from "./Services/TerminalProcessInspector.ts";
import { MAX_PORT_NUMBER, portFromAddress } from "./utils.ts";
interface InspectorCommandResult {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: number;
}
interface PosixRunCommand {
(
input: Readonly<{
operation: string;
terminalPid: number;
command: string;
args: ReadonlyArray<string>;
timeoutMs: number;
maxOutputBytes: number;
}>,
): Effect.Effect<InspectorCommandResult, TerminalProcessInspectionError>;
}
export const collectPosixProcessFamilyPids = Effect.fn("process.collectPosixProcessFamilyPids")(
function* (
terminalPid: number,
runCommand: PosixRunCommand,
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
const psResult = yield* runCommand({
operation: "TerminalProcessInspector.collectPosixProcessFamilyPids",
terminalPid,
command: "ps",
args: ["-eo", "pid=,ppid="],
timeoutMs: 1_000,
maxOutputBytes: 262_144,
});
if (psResult.exitCode !== 0) {
return [];
}
const childrenByParentPid = new Map<number, number[]>();
for (const line of psResult.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
const children = childrenByParentPid.get(ppid);
if (children) {
children.push(pid);
} else {
childrenByParentPid.set(ppid, [pid]);
}
}
const processFamily = new Set<number>([terminalPid]);
const pendingParents = [terminalPid];
while (pendingParents.length > 0) {
const parentPid = pendingParents.shift();
if (!parentPid) continue;
const childPids = childrenByParentPid.get(parentPid);
if (!childPids || childPids.length === 0) continue;
for (const childPid of childPids) {
if (processFamily.has(childPid)) continue;
processFamily.add(childPid);
pendingParents.push(childPid);
}
}
return [...processFamily];
},
);
export const checkPosixListeningPorts = Effect.fn("process.checkPosixListeningPorts")(function* (
processIds: number[],
input: {
terminalPid: number;
runCommand: PosixRunCommand;
platform?: NodeJS.Platform;
},
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
if (processIds.length === 0) return [];
const ports = new Set<number>();
const pidFilter = new Set(processIds);
const platform = input.platform ?? process.platform;
const lsofResult = yield* input
.runCommand({
operation: "TerminalProcessInspector.checkPosixListeningPorts.lsof",
terminalPid: input.terminalPid,
command: "lsof",
args: ["-nP", "-a", "-iTCP", "-sTCP:LISTEN", "-p", processIds.join(",")],
timeoutMs: 1_500,
maxOutputBytes: 262_144,
})
.pipe(Effect.exit);
if (lsofResult._tag === "Success") {
if (lsofResult.value.exitCode === 0) {
for (const line of lsofResult.value.stdout.split(/\r?\n/g)) {
const match = line.match(/:(\d+)\s+\(LISTEN\)$/);
if (!match?.[1]) continue;
const port = Number(match[1]);
if (Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER) {
ports.add(port);
}
}
return [...ports].toSorted((left, right) => left - right);
}
if (lsofResult.value.exitCode === 1 && platform === "darwin") {
return [];
}
}
const ssResult = yield* input.runCommand({
operation: "TerminalProcessInspector.checkPosixListeningPorts.ss",
terminalPid: input.terminalPid,
command: "ss",
args: ["-ltnp"],
timeoutMs: 1_500,
maxOutputBytes: 524_288,
});
if (ssResult.exitCode !== 0) {
return [];
}
for (const line of ssResult.stdout.split(/\r?\n/g)) {
if (!line.includes("pid=")) continue;
const localAddress = line.trim().split(/\s+/g)[3];
if (!localAddress) continue;
const port = portFromAddress(localAddress);
if (port === null) continue;
const pidMatches = [...line.matchAll(/pid=(\d+)/g)];
if (pidMatches.length === 0) continue;
if (
pidMatches.some((match) => {
const pid = Number(match[1]);
return Number.isInteger(pid) && pidFilter.has(pid);
})
) {
ports.add(port);
}
}
return [...ports].toSorted((left, right) => left - right);
});
-52
View File
@@ -1,52 +0,0 @@
export const MAX_PORT_NUMBER = 65_535;
export function normalizeRunningPorts(ports: number[]): number[] {
if (ports.length === 0) return [];
return [...new Set(ports)]
.filter((port) => Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER)
.toSorted((left, right) => left - right);
}
export function parsePidList(stdout: string): number[] {
const pids: number[] = [];
for (const line of stdout.split(/\r?\n/g)) {
const pid = Number(line.trim());
if (!Number.isInteger(pid) || pid <= 0) {
continue;
}
pids.push(pid);
}
return [...new Set(pids)];
}
export function parsePortList(stdout: string): number[] {
const ports: number[] = [];
for (const line of stdout.split(/\r?\n/g)) {
const port = Number(line.trim());
if (!Number.isInteger(port)) {
continue;
}
ports.push(port);
}
return normalizeRunningPorts(ports);
}
export function portFromAddress(address: string): number | null {
const match = address.match(/:(\d+)$/);
if (!match?.[1]) return null;
const port = Number(match[1]);
if (!Number.isInteger(port) || port <= 0 || port > MAX_PORT_NUMBER) {
return null;
}
return port;
}
export function arePortListsEqual(left: number[], right: number[]): boolean {
if (left.length !== right.length) return false;
for (let index = 0; index < left.length; index += 1) {
if (left[index] !== right[index]) {
return false;
}
}
return true;
}
-57
View File
@@ -1,57 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { collectWindowsChildPids } from "./win32.ts";
function parentPidFromCommand(command: string | undefined): number {
return Number(/ParentProcessId = (\d+)/.exec(command ?? "")?.[1] ?? "0");
}
describe("process.collectWindowsChildPids", () => {
it.effect("walks the full descendant tree breadth-first", () =>
Effect.gen(function* () {
const commands: string[] = [];
const childMap = new Map<number, string>([
[100, "200\n300\n"],
[200, "400\n"],
[300, ""],
[400, ""],
]);
const childPids = yield* collectWindowsChildPids(100, (input) => {
const command = input.args[3] ?? "";
commands.push(command);
return Effect.succeed({
stdout: childMap.get(parentPidFromCommand(command)) ?? "",
stderr: "",
exitCode: 0,
});
});
assert.deepStrictEqual(childPids, [200, 300, 400]);
assert.equal(commands.length, 4);
}),
);
it.effect("deduplicates repeated descendants to avoid traversal loops", () =>
Effect.gen(function* () {
const childMap = new Map<number, string>([
[100, "200\n300\n"],
[200, "300\n400\n"],
[300, "200\n"],
[400, ""],
]);
const childPids = yield* collectWindowsChildPids(100, (input) => {
const parentPid = parentPidFromCommand(input.args[3]);
return Effect.succeed({
stdout: childMap.get(parentPid) ?? "",
stderr: "",
exitCode: 0,
});
});
assert.deepStrictEqual(childPids, [200, 300, 400]);
}),
);
});
-98
View File
@@ -1,98 +0,0 @@
import { Effect } from "effect";
import type { TerminalProcessInspectionError } from "./Services/TerminalProcessInspector.ts";
import { parsePidList, parsePortList } from "./utils.ts";
interface InspectorCommandResult {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: number;
}
interface WindowsRunCommand {
(
input: Readonly<{
operation: string;
terminalPid: number;
command: string;
args: ReadonlyArray<string>;
timeoutMs: number;
maxOutputBytes: number;
}>,
): Effect.Effect<InspectorCommandResult, TerminalProcessInspectionError>;
}
export const collectWindowsChildPids = Effect.fn("process.collectWindowsChildPids")(function* (
terminalPid: number,
runCommand: WindowsRunCommand,
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
const seenPids = new Set<number>([terminalPid]);
const childPids: number[] = [];
const pendingParentPids = [terminalPid];
while (pendingParentPids.length > 0) {
const parentPid = pendingParentPids.shift();
if (parentPid === undefined) {
break;
}
const command = [
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${parentPid}" -ErrorAction SilentlyContinue`,
"if (-not $children) { exit 0 }",
"$children | Select-Object -ExpandProperty ProcessId",
].join("; ");
const result = yield* runCommand({
operation: "TerminalProcessInspector.collectWindowsChildPids",
terminalPid,
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeoutMs: 1_500,
maxOutputBytes: 32_768,
});
if (result.exitCode !== 0) {
continue;
}
for (const childPid of parsePidList(result.stdout)) {
if (seenPids.has(childPid)) {
continue;
}
seenPids.add(childPid);
childPids.push(childPid);
pendingParentPids.push(childPid);
}
}
return childPids;
});
export const checkWindowsListeningPorts = Effect.fn("process.checkWindowsListeningPorts")(
function* (
processIds: number[],
input: {
terminalPid: number;
runCommand: WindowsRunCommand;
},
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
if (processIds.length === 0) return [];
const processFilter = processIds.map((pid) => `$_.OwningProcess -eq ${pid}`).join(" -or ");
const command = [
"$connections = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue",
`$matching = $connections | Where-Object { ${processFilter} }`,
"if (-not $matching) { exit 0 }",
"$matching | Select-Object -ExpandProperty LocalPort -Unique",
].join("; ");
const result = yield* input.runCommand({
operation: "TerminalProcessInspector.checkWindowsListeningPorts",
terminalPid: input.terminalPid,
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeoutMs: 1_500,
maxOutputBytes: 65_536,
});
if (result.exitCode !== 0) {
return [];
}
return parsePortList(result.stdout);
},
);
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { runProcess } from "./processRunner.ts";
import { runProcess } from "./processRunner";
describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => {
@@ -1,5 +1,3 @@
import { realpathSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Duration, Effect, FileSystem, Layer } from "effect";
@@ -12,10 +10,6 @@ import {
RepositoryIdentityResolverLive,
} from "./RepositoryIdentityResolver.ts";
const normalizePathSeparators = (value: string) => value.replaceAll("\\", "/");
const normalizeResolvedPath = (value: string) =>
normalizePathSeparators(realpathSync.native(value));
const git = (cwd: string, args: ReadonlyArray<string>) =>
Effect.promise(() => runProcess("git", ["-C", cwd, ...args]));
@@ -47,7 +41,6 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(cwd));
expect(identity?.displayName).toBe("t3tools/t3code");
expect(identity?.provider).toBe("github");
expect(identity?.owner).toBe("t3tools");
@@ -55,27 +48,6 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
);
it.effect("returns the git top-level root path when resolving from a nested workspace", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const repoRoot = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-repository-identity-nested-root-test-",
});
const nestedWorkspace = `${repoRoot}/packages/web`;
yield* fileSystem.makeDirectory(nestedWorkspace, { recursive: true });
yield* git(repoRoot, ["init"]);
yield* git(repoRoot, ["remote", "add", "origin", "[email protected]:T3Tools/t3code.git"]);
const resolver = yield* RepositoryIdentityResolver;
const identity = yield* resolver.resolve(nestedWorkspace);
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(repoRoot));
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
);
it.effect("returns null for non-git folders and repos without remotes", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -140,7 +112,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
);
it.effect(
"keeps null identities cached across repeated resolves until the negative TTL expires",
"refreshes cached null identities after the negative TTL when a remote is configured later",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -156,10 +128,8 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
yield* git(cwd, ["remote", "add", "origin", "[email protected]:T3Tools/t3code.git"]);
for (const _attempt of [1, 2, 3]) {
const cachedIdentity = yield* resolver.resolve(cwd);
expect(cachedIdentity).toBeNull();
}
const cachedIdentity = yield* resolver.resolve(cwd);
expect(cachedIdentity).toBeNull();
yield* TestClock.adjust(Duration.millis(120));
@@ -42,7 +42,6 @@ function pickPrimaryRemote(
function buildRepositoryIdentity(input: {
readonly remoteName: string;
readonly remoteUrl: string;
readonly rootPath: string;
}): RepositoryIdentity {
const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
const hostingProvider = detectGitHostingProviderFromRemoteUrl(input.remoteUrl);
@@ -58,7 +57,6 @@ function buildRepositoryIdentity(input: {
remoteName: input.remoteName,
remoteUrl: input.remoteUrl,
},
rootPath: input.rootPath,
...(repositoryPath ? { displayName: repositoryPath } : {}),
...(hostingProvider ? { provider: hostingProvider.kind } : {}),
...(owner ? { owner } : {}),
@@ -68,7 +66,7 @@ function buildRepositoryIdentity(input: {
const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(1);
const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
const DEFAULT_NEGATIVE_CACHE_TTL = Duration.seconds(10);
interface RepositoryIdentityResolverOptions {
readonly cacheCapacity?: number;
@@ -110,7 +108,7 @@ async function resolveRepositoryIdentityFromCacheKey(
}
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.stdout));
return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
return remote ? buildRepositoryIdentity(remote) : null;
} catch {
return null;
}
@@ -351,53 +351,6 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("maps the Claude Opus 4.7 default effort to the SDK-supported max value", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-7",
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "max");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("maps xhigh effort for Claude Opus 4.7 to the SDK-supported max value", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-7",
options: {
effort: "xhigh",
},
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "max");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -1013,97 +966,6 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("falls back to a default plan step label for blank TodoWrite content", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 10).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-todo-plan",
uuid: "stream-todo-start",
parent_tool_use_id: null,
event: {
type: "content_block_start",
index: 1,
content_block: {
type: "tool_use",
id: "tool-todo-1",
name: "TodoWrite",
input: {},
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-todo-plan",
uuid: "stream-todo-input",
parent_tool_use_id: null,
event: {
type: "content_block_delta",
index: 1,
delta: {
type: "input_json_delta",
partial_json:
'{"todos":[{"content":" ","status":"in_progress"},{"content":"Ship it","status":"completed"}]}',
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-todo-plan",
uuid: "stream-todo-stop",
parent_tool_use_id: null,
event: {
type: "content_block_stop",
index: 1,
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-todo-plan",
uuid: "result-todo-plan",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const planUpdated = runtimeEvents.find((event) => event.type === "turn.plan.updated");
assert.equal(planUpdated?.type, "turn.plan.updated");
if (planUpdated?.type === "turn.plan.updated") {
assert.equal(String(planUpdated.turnId), String(turn.turnId));
assert.deepEqual(planUpdated.payload.plan, [
{ step: "Task", status: "inProgress" },
{ step: "Ship it", status: "completed" },
]);
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("classifies Claude Task tool invocations as collaboration agent work", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -1307,71 +1169,6 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("closes the previous session before replacing an existing thread session", () => {
const queries: FakeClaudeQuery[] = [];
const layer = makeClaudeAdapterLive({
createQuery: () => {
const query = new FakeClaudeQuery();
queries.push(query);
return query;
},
}).pipe(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
Stream.runCollect,
Effect.forkChild,
);
const firstSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
const secondSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
resumeCursor: firstSession.resumeCursor,
});
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const activeSessions = yield* adapter.listSessions();
assert.equal(queries.length, 2);
assert.equal(queries[0]?.closeCalls, 1);
assert.equal(queries[1]?.closeCalls, 0);
assert.equal(yield* adapter.hasSession(THREAD_ID), true);
assert.equal(activeSessions.length, 1);
assert.deepEqual(activeSessions[0]?.resumeCursor, secondSession.resumeCursor);
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"session.started",
"session.configured",
"session.state.changed",
],
);
assert.equal(
runtimeEvents.some((event) => event.type === "session.exited"),
false,
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(layer),
);
});
it.effect("stopSession does not throw into the SDK prompt consumer", () => {
// The SDK consumes user messages via `for await (... of prompt)`.
// Stopping a session must end that loop cleanly — not throw an error.
+28 -175
View File
@@ -17,9 +17,9 @@ import {
type SDKResultMessage,
type SettingSource,
type SDKUserMessage,
type ModelUsage,
ModelUsage,
NonNullableUsage,
} from "@anthropic-ai/claude-agent-sdk";
import { parseCliArgs } from "@t3tools/shared/cliArgs";
import {
ApprovalRequestId,
type CanonicalItemType,
@@ -40,7 +40,7 @@ import {
ThreadId,
TurnId,
type UserInputQuestion,
ClaudeAgentEffort,
ClaudeCodeEffort,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
@@ -84,7 +84,6 @@ type ClaudeToolResultStreamKind = Extract<
RuntimeContentStreamKind,
"command_output" | "file_change_output"
>;
type ClaudeSdkEffort = NonNullable<ClaudeQueryOptions["effort"]>;
type PromptQueueItem =
| {
@@ -216,19 +215,13 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray
return squashed.length > 0 ? [squashed] : [];
}
function getEffectiveClaudeAgentEffort(
effort: ClaudeAgentEffort | null | undefined,
): ClaudeSdkEffort | null {
function getEffectiveClaudeCodeEffort(
effort: ClaudeCodeEffort | null | undefined,
): Exclude<ClaudeCodeEffort, "ultrathink"> | null {
if (!effort) {
return null;
}
if (effort === "ultrathink") {
return null;
}
if (effort === "xhigh") {
return "max";
}
return effort;
return effort === "ultrathink" ? null : effort;
}
function isClaudeInterruptedMessage(message: string): boolean {
@@ -296,7 +289,7 @@ function maxClaudeContextWindowFromModelUsage(
}
function normalizeClaudeTokenUsage(
value: unknown,
value: NonNullableUsage | undefined,
contextWindow?: number,
): ThreadTokenUsageSnapshot | undefined {
if (!value || typeof value !== "object") {
@@ -466,37 +459,6 @@ function classifyRequestType(toolName: string): CanonicalRequestType {
: "dynamic_tool_call";
}
function isTodoTool(toolName: string): boolean {
return toolName.toLowerCase().includes("todowrite");
}
type PlanStep = {
step: string;
status: "pending" | "inProgress" | "completed";
};
function extractPlanStepsFromTodoInput(input: Record<string, unknown>): PlanStep[] | null {
// TodoWrite format: { todos: [{ content, status, activeForm? }] }
const todos = input.todos;
if (!Array.isArray(todos) || todos.length === 0) {
return null;
}
return todos
.filter((t): t is Record<string, unknown> => t !== null && typeof t === "object")
.map((todo) => ({
step:
typeof todo.content === "string" && todo.content.trim().length > 0
? todo.content.trim()
: "Task",
status:
todo.status === "completed"
? "completed"
: todo.status === "in_progress"
? "inProgress"
: "pending",
}));
}
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
const commandValue = input.command ?? input.cmd;
const command = typeof commandValue === "string" ? commandValue : undefined;
@@ -504,20 +466,6 @@ function summarizeToolRequest(toolName: string, input: Record<string, unknown>):
return `${toolName}: ${command.trim().slice(0, 400)}`;
}
// For agent/subagent tools, prefer human-readable description or prompt over raw JSON
const itemType = classifyToolItemType(toolName);
if (itemType === "collab_agent_tool_call") {
const description =
typeof input.description === "string" ? input.description.trim() : undefined;
const prompt = typeof input.prompt === "string" ? input.prompt.trim() : undefined;
const subagentType =
typeof input.subagent_type === "string" ? input.subagent_type.trim() : undefined;
const label = description || (prompt ? prompt.slice(0, 200) : undefined);
if (label) {
return subagentType ? `${subagentType}: ${label}` : label;
}
}
const serialized = JSON.stringify(input);
if (serialized.length <= 400) {
return `${toolName}: ${serialized}`;
@@ -976,11 +924,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
((input: {
readonly prompt: AsyncIterable<SDKUserMessage>;
readonly options: ClaudeQueryOptions;
}) =>
query({
prompt: input.prompt,
options: input.options,
}) as ClaudeQueryRuntime);
}) => query({ prompt: input.prompt, options: input.options }) as ClaudeQueryRuntime);
const sessions = new Map<ThreadId, ClaudeSessionContext>();
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
@@ -1019,11 +963,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(typeof message.session_id === "string"
? { providerThreadId: message.session_id }
: {}),
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
...(itemId ? { itemId: ProviderItemId.make(itemId) } : {}),
payload: message,
},
@@ -1412,9 +1352,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(typeof accumulatedTotalProcessedTokens === "number" &&
Number.isFinite(accumulatedTotalProcessedTokens) &&
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
? {
totalProcessedTokens: accumulatedTotalProcessedTokens,
}
? { totalProcessedTokens: accumulatedTotalProcessedTokens }
: {}),
}
: accumulatedSnapshot;
@@ -1478,9 +1416,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
input: tool.input,
},
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/result",
@@ -1602,9 +1538,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
threadId: context.session.threadId,
turnId: context.turnState.turnId,
...(assistantBlockEntry?.block
? {
itemId: asRuntimeItemId(assistantBlockEntry.block.itemId),
}
? { itemId: asRuntimeItemId(assistantBlockEntry.block.itemId) }
: {}),
payload: {
streamKind,
@@ -1663,11 +1597,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
itemId: asRuntimeItemId(nextTool.itemId),
payload: {
itemType: nextTool.itemType,
@@ -1679,39 +1609,13 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
input: nextTool.input,
},
},
providerRefs: nativeProviderRefs(context, {
providerItemId: nextTool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: nextTool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/stream_event/content_block_delta/input_json_delta",
payload: message,
},
});
// Emit plan update when TodoWrite input is parsed
if (parsedInput && isTodoTool(nextTool.toolName)) {
const planSteps = extractPlanStepsFromTodoInput(parsedInput);
if (planSteps && planSteps.length > 0) {
const planStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.plan.updated",
eventId: planStamp.eventId,
provider: PROVIDER,
createdAt: planStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
payload: {
plan: planSteps,
},
providerRefs: nativeProviderRefs(context),
});
}
}
}
return;
}
@@ -1774,9 +1678,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
input: toolInput,
},
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/stream_event/content_block_start",
@@ -1848,9 +1750,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(tool.detail ? { detail: tool.detail } : {}),
data: toolData,
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/user",
@@ -1873,9 +1773,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
streamKind,
delta: toolResult.text,
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/user",
@@ -1900,9 +1798,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(tool.detail ? { detail: tool.detail } : {}),
data: toolData,
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/user",
@@ -2258,9 +2154,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
payload: {
summary: message.summary,
...(message.preceding_tool_use_ids.length > 0
? {
precedingToolUseIds: message.preceding_tool_use_ids,
}
? { precedingToolUseIds: message.preceding_tool_use_ids }
: {}),
},
});
@@ -2477,27 +2371,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
const existingContext = sessions.get(input.threadId);
if (existingContext) {
yield* Effect.logWarning("claude.session.replacing", {
threadId: input.threadId,
existingSessionStatus: existingContext.session.status,
reason: "startSession called with existing active session",
});
yield* stopSessionInternal(existingContext, {
emitExitEvent: false,
}).pipe(
// Replacement cleanup is best-effort: never block the new session on
// either typed failures or unexpected defects from tearing down the old one.
Effect.catchCause((cause) =>
Effect.logWarning("claude.session.replace.stop-failed", {
threadId: input.threadId,
cause,
}),
),
);
}
const startedAt = yield* nowIso;
const resumeState = readClaudeResumeState(input.resumeCursor);
const threadId = input.threadId;
@@ -2533,10 +2406,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const handleAskUserQuestion = Effect.fn("handleAskUserQuestion")(function* (
context: ClaudeSessionContext,
toolInput: Record<string, unknown>,
callbackOptions: {
readonly signal: AbortSignal;
readonly toolUseID?: string;
},
callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string },
) {
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
@@ -2572,11 +2442,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
provider: PROVIDER,
createdAt: requestedStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
requestId: asRuntimeRequestId(requestId),
payload: { questions },
providerRefs: nativeProviderRefs(context, {
@@ -2585,10 +2451,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
raw: {
source: "claude.sdk.permission",
method: "canUseTool/AskUserQuestion",
payload: {
toolName: "AskUserQuestion",
input: toolInput,
},
payload: { toolName: "AskUserQuestion", input: toolInput },
},
});
@@ -2603,9 +2466,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
pendingUserInputs.delete(requestId);
runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers));
};
callbackOptions.signal.addEventListener("abort", onAbort, {
once: true,
});
callbackOptions.signal.addEventListener("abort", onAbort, { once: true });
// Block until the user provides answers.
const answers = yield* Deferred.await(answersDeferred);
@@ -2619,11 +2480,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
provider: PROVIDER,
createdAt: resolvedStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
requestId: asRuntimeRequestId(requestId),
payload: { answers },
providerRefs: nativeProviderRefs(context, {
@@ -2793,9 +2650,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
behavior: "allow",
updatedInput: toolInput,
...(decision === "acceptForSession" && pendingApproval.suggestions
? {
updatedPermissions: [...pendingApproval.suggestions],
}
? { updatedPermissions: [...pendingApproval.suggestions] }
: {}),
} satisfies PermissionResult;
}
@@ -2825,19 +2680,18 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
),
);
const claudeBinaryPath = claudeSettings.binaryPath;
const extraArgs = parseCliArgs(claudeSettings.launchArgs).flags;
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
const caps = getClaudeModelCapabilities(modelSelection?.model);
const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
null) as ClaudeAgentEffort | null;
null) as ClaudeCodeEffort | null;
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
const thinking =
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
? modelSelection.options.thinking
: undefined;
const effectiveEffort = getEffectiveClaudeAgentEffort(effort);
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
const runtimeModeToPermission: Record<string, PermissionMode> = {
"auto-accept-edits": "acceptEdits",
"full-access": "bypassPermissions",
@@ -2865,7 +2719,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
canUseTool,
env: process.env,
...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
};
const queryRuntime = yield* Effect.try({
@@ -25,11 +25,10 @@ import {
providerModelsFromSettings,
spawnAndCollect,
type CommandResult,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
} from "../providerSnapshot";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import { ClaudeProvider } from "../Services/ClaudeProvider";
import { ServerSettingsService } from "../../serverSettings";
import { ServerSettingsError } from "@t3tools/contracts";
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = {
@@ -41,30 +40,7 @@ const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = {
};
const PROVIDER = "claudeAgent" as const;
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-7",
name: "Claude Opus 4.7",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
},
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
@@ -120,24 +96,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
function supportsClaudeOpus47(version: string | null | undefined): boolean {
return version ? compareCliVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
}
function getBuiltInClaudeModelsForVersion(
version: string | null | undefined,
): ReadonlyArray<ServerProviderModel> {
if (supportsClaudeOpus47(version)) {
return BUILT_IN_MODELS;
}
return BUILT_IN_MODELS.filter((model) => model.slug !== "claude-opus-4-7");
}
function formatClaudeOpus47UpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Claude Code ${versionLabel} is too old for Claude Opus 4.7. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_7_VERSION} or newer to access it.`;
}
export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {
const slug = model?.trim();
return (
@@ -526,7 +484,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const allModels = providerModelsFromSettings(
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
@@ -538,7 +496,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: false,
checkedAt,
models: allModels,
models,
probe: {
installed: false,
version: null,
@@ -560,7 +518,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: allModels,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
@@ -578,7 +536,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: allModels,
models,
probe: {
installed: true,
version: null,
@@ -598,7 +556,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: allModels,
models,
probe: {
installed: true,
version: parsedVersion,
@@ -611,16 +569,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
});
}
const models = providerModelsFromSettings(
getBuiltInClaudeModelsForVersion(parsedVersion),
PROVIDER,
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
const opus47UpgradeMessage = supportsClaudeOpus47(parsedVersion)
? undefined
: formatClaudeOpus47UpgradeMessage(parsedVersion);
const slashCommands =
(resolveSlashCommands
? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe(
@@ -710,11 +658,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
...parsed.auth,
...(authMetadata ? authMetadata : {}),
},
...(parsed.message
? { message: parsed.message }
: opus47UpgradeMessage
? { message: opus47UpgradeMessage }
: {}),
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
@@ -146,7 +146,6 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
getBinding: () => Effect.succeed(Option.none()),
remove: () => Effect.void,
listThreadIds: () => Effect.succeed([]),
listBindings: () => Effect.succeed([]),
});
const validationManager = new FakeCodexManager();
@@ -32,22 +32,22 @@ import {
providerModelsFromSettings,
spawnAndCollect,
type CommandResult,
} from "../providerSnapshot.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
} from "../providerSnapshot";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import {
formatCodexCliUpgradeMessage,
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "../codexCliVersion.ts";
} from "../codexCliVersion";
import {
adjustCodexModelsForAccount,
codexAuthSubLabel,
codexAuthSubType,
type CodexAccountSnapshot,
} from "../codexAccount.ts";
import { probeCodexDiscovery } from "../codexAppServer.ts";
import { CodexProvider } from "../Services/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
} from "../codexAccount";
import { probeCodexDiscovery } from "../codexAppServer";
import { CodexProvider } from "../Services/CodexProvider";
import { ServerSettingsService } from "../../serverSettings";
import { ServerSettingsError } from "@t3tools/contracts";
const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = {
@@ -4,10 +4,8 @@ import { assertFailure } from "@effect/vitest/utils";
import { Effect, Layer, Stream } from "effect";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { ClaudeAdapter, ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
import { ProviderUnsupportedError } from "../Errors.ts";
@@ -28,12 +28,12 @@ import {
hasCustomModelProvider,
parseAuthStatusFromOutput,
readCodexConfigModelProvider,
} from "./CodexProvider.ts";
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts";
import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
} from "./CodexProvider";
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider";
import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry";
import { ServerConfig } from "../../config";
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings";
import { ProviderRegistry } from "../Services/ProviderRegistry";
// ── Test helpers ────────────────────────────────────────────────────
@@ -973,69 +973,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
),
);
it.effect(
"includes Claude Opus 4.7 with xhigh as the default effort on supported versions",
() =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
const opus47 = status.models.find((model) => model.slug === "claude-opus-4-7");
if (!opus47) {
assert.fail("Expected Claude Opus 4.7 to be present for Claude Code v2.1.111.");
}
if (!opus47.capabilities) {
assert.fail(
"Expected Claude Opus 4.7 capabilities to be present for Claude Code v2.1.111.",
);
}
assert.deepStrictEqual(
opus47.capabilities.reasoningEffortLevels.find((level) => level.isDefault),
{ value: "xhigh", label: "Extra High", isDefault: true },
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.111\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides Claude Opus 4.7 on older Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(
status.models.some((model) => model.slug === "claude-opus-4-7"),
false,
);
assert.strictEqual(
status.message,
"Claude Code v2.1.110 is too old for Claude Opus 4.7. Upgrade to v2.1.111 or newer to access it.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.110\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns a display label for claude subscription types", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
@@ -6,14 +6,14 @@
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
import { ServerConfig } from "../../config.ts";
import { ClaudeProviderLive } from "./ClaudeProvider.ts";
import { CodexProviderLive } from "./CodexProvider.ts";
import type { ClaudeProviderShape } from "../Services/ClaudeProvider.ts";
import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
import type { CodexProviderShape } from "../Services/CodexProvider.ts";
import { CodexProvider } from "../Services/CodexProvider.ts";
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
import { ServerConfig } from "../../config";
import { ClaudeProviderLive } from "./ClaudeProvider";
import { CodexProviderLive } from "./CodexProvider";
import type { ClaudeProviderShape } from "../Services/ClaudeProvider";
import { ClaudeProvider } from "../Services/ClaudeProvider";
import type { CodexProviderShape } from "../Services/CodexProvider";
import { CodexProvider } from "../Services/CodexProvider";
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry";
import {
hydrateCachedProvider,
PROVIDER_CACHE_IDS,
@@ -21,7 +21,7 @@ import {
readProviderStatusCache,
resolveProviderStatusCachePath,
writeProviderStatusCache,
} from "../providerStatusCache.ts";
} from "../providerStatusCache";
const loadProviders = (
codexProvider: CodexProviderShape,
@@ -654,43 +654,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("stops stale sessions in other providers after a successful replacement start", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const threadId = asThreadId("thread-provider-replacement");
const codexSession = yield* provider.startSession(threadId, {
provider: "codex",
threadId,
cwd: "/tmp/project-provider-replacement",
runtimeMode: "full-access",
});
routing.codex.stopSession.mockClear();
routing.claude.stopSession.mockClear();
const claudeSession = yield* provider.startSession(threadId, {
provider: "claudeAgent",
threadId,
cwd: "/tmp/project-provider-replacement",
runtimeMode: "full-access",
});
assert.equal(codexSession.provider, "codex");
assert.equal(claudeSession.provider, "claudeAgent");
assert.deepEqual(routing.codex.stopSession.mock.calls, [[threadId]]);
assert.equal(routing.claude.stopSession.mock.calls.length, 0);
const sessions = yield* provider.listSessions();
assert.deepEqual(
sessions
.filter((session) => session.threadId === threadId)
.map((session) => session.provider),
["claudeAgent"],
);
}),
);
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -297,40 +297,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
});
const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: {
readonly threadId: ThreadId;
readonly currentProvider: ProviderSession["provider"];
}) {
yield* Effect.forEach(
adapters,
(adapter) =>
adapter.provider === input.currentProvider
? Effect.void
: Effect.gen(function* () {
const hasSession = yield* adapter.hasSession(input.threadId);
if (!hasSession) {
return;
}
yield* adapter.stopSession(input.threadId).pipe(
Effect.tap(() =>
analytics.record("provider.session.stopped", {
provider: adapter.provider,
}),
),
Effect.catchCause((cause) =>
Effect.logWarning("provider.session.stop-stale-failed", {
threadId: input.threadId,
provider: adapter.provider,
cause,
}),
),
);
}),
{ discard: true },
);
});
const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")(
function* (threadId, rawInput) {
const parsed = yield* decodeInputOrValidationError({
@@ -385,10 +351,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
);
}
yield* stopStaleSessionsForThread({
threadId,
currentProvider: adapter.provider,
});
yield* upsertSessionBinding(session, threadId, {
modelSelection: input.modelSelection,
});
@@ -133,78 +133,6 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
}
}));
it("lists persisted bindings with metadata in oldest-first order", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
const olderThreadId = ThreadId.make("thread-runtime-older");
const newerThreadId = ThreadId.make("thread-runtime-newer");
yield* runtimeRepository.upsert({
threadId: newerThreadId,
providerName: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T12:05:00.000Z",
resumeCursor: {
opaque: "resume-newer",
},
runtimePayload: {
cwd: "/tmp/newer",
},
});
yield* runtimeRepository.upsert({
threadId: olderThreadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "approval-required",
status: "starting",
lastSeenAt: "2026-04-14T12:00:00.000Z",
resumeCursor: {
opaque: "resume-older",
},
runtimePayload: {
cwd: "/tmp/older",
},
});
const bindings = yield* directory.listBindings();
assert.deepEqual(bindings, [
{
threadId: olderThreadId,
provider: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "approval-required",
status: "starting",
lastSeenAt: "2026-04-14T12:00:00.000Z",
resumeCursor: {
opaque: "resume-older",
},
runtimePayload: {
cwd: "/tmp/older",
},
},
{
threadId: newerThreadId,
provider: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T12:05:00.000Z",
resumeCursor: {
opaque: "resume-newer",
},
runtimePayload: {
cwd: "/tmp/newer",
},
},
]);
}));
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
@@ -1,13 +1,11 @@
import { type ProviderKind, type ThreadId } from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";
import {
ProviderSessionDirectory,
type ProviderRuntimeBinding,
type ProviderRuntimeBindingWithMetadata,
type ProviderSessionDirectoryShape,
} from "../Services/ProviderSessionDirectory.ts";
@@ -52,27 +50,6 @@ function mergeRuntimePayload(
return next;
}
function toRuntimeBinding(
runtime: ProviderSessionRuntime,
operation: string,
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
return decodeProviderKind(runtime.providerName, operation).pipe(
Effect.map(
(provider) =>
({
threadId: runtime.threadId,
provider,
adapterKey: runtime.adapterKey,
runtimeMode: runtime.runtimeMode,
status: runtime.status,
resumeCursor: runtime.resumeCursor,
runtimePayload: runtime.runtimePayload,
lastSeenAt: runtime.lastSeenAt,
}) satisfies ProviderRuntimeBindingWithMetadata,
),
);
}
const makeProviderSessionDirectory = Effect.gen(function* () {
const repository = yield* ProviderSessionRuntimeRepository;
@@ -83,8 +60,18 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
Option.match(runtime, {
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
onSome: (value) =>
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
Effect.map((binding) => Option.some(binding)),
decodeProviderKind(value.providerName, "ProviderSessionDirectory.getBinding").pipe(
Effect.map((provider) =>
Option.some({
threadId: value.threadId,
provider,
adapterKey: value.adapterKey,
runtimeMode: value.runtimeMode,
status: value.status,
resumeCursor: value.resumeCursor,
runtimePayload: value.runtimePayload,
}),
),
),
}),
),
@@ -158,25 +145,12 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
Effect.map((rows) => rows.map((row) => row.threadId)),
);
const listBindings: ProviderSessionDirectoryShape["listBindings"] = () =>
repository.list().pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listBindings:list")),
Effect.flatMap((rows) =>
Effect.forEach(
rows,
(row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
{ concurrency: "unbounded" },
),
),
);
return {
upsert,
getProvider,
getBinding,
remove,
listThreadIds,
listBindings,
} satisfies ProviderSessionDirectoryShape;
});
@@ -1,522 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../../orchestration/Services/OrchestrationEngine.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderValidationError } from "../Errors.ts";
import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
const defaultModelSelection = {
provider: "codex",
model: "gpt-5-codex",
} as const;
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2_000,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (await predicate()) {
return;
}
if (Date.now() >= deadline) {
throw new Error("Timed out waiting for expectation.");
}
await new Promise((resolve) => setTimeout(resolve, 10));
return poll();
};
return poll();
}
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
function makeReadModel(
threads: ReadonlyArray<{
readonly id: ThreadId;
readonly session: {
readonly threadId: ThreadId;
readonly status: "starting" | "running" | "ready" | "interrupted" | "stopped" | "error";
readonly providerName: "codex" | "claudeAgent";
readonly runtimeMode: "approval-required" | "full-access" | "auto-accept-edits";
readonly activeTurnId: TurnId | null;
readonly lastError: string | null;
readonly updatedAt: string;
} | null;
}>,
) {
const now = new Date().toISOString();
const projectId = ProjectId.make("project-provider-session-reaper");
return {
snapshotSequence: 0,
updatedAt: now,
projects: [
{
id: projectId,
title: "Provider Reaper Project",
workspaceRoot: "/tmp/provider-reaper-project",
defaultModelSelection,
scripts: [],
createdAt: now,
updatedAt: now,
deletedAt: null,
},
],
threads: threads.map((thread) => ({
id: thread.id,
projectId,
title: `Thread ${thread.id}`,
modelSelection: defaultModelSelection,
interactionMode: "default" as const,
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
latestTurn: null,
messages: [],
session: thread.session,
activities: [],
proposedPlans: [],
checkpoints: [],
deletedAt: null,
})),
};
}
describe("ProviderSessionReaper", () => {
let runtime: ManagedRuntime.ManagedRuntime<
ProviderSessionReaper | ProviderSessionRuntimeRepository,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
afterEach(async () => {
if (scope) {
await Effect.runPromise(Scope.close(scope, Exit.void));
}
scope = null;
if (runtime) {
await runtime.dispose();
}
runtime = null;
});
async function createHarness(input: {
readonly readModel: ReturnType<typeof makeReadModel>;
readonly stopSessionImplementation?: (input: {
readonly threadId: ThreadId;
}) => ReturnType<ProviderServiceShape["stopSession"]>;
}) {
const stoppedThreadIds = new Set<ThreadId>();
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
(request) =>
(input.stopSessionImplementation
? input.stopSessionImplementation(request)
: Effect.sync(() => {
stoppedThreadIds.add(request.threadId);
})) as ReturnType<ProviderServiceShape["stopSession"]>,
);
const providerService: ProviderServiceShape = {
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession,
listSessions: () => Effect.succeed([]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
streamEvents: Stream.empty,
};
const orchestrationEngine: OrchestrationEngineShape = {
getReadModel: () => Effect.succeed(input.readModel),
readEvents: () => Stream.empty,
dispatch: () => unsupported(),
streamDomainEvents: Stream.empty,
};
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const layer = makeProviderSessionReaperLive({
inactivityThresholdMs: 1_000,
sweepIntervalMs: 60_000,
}).pipe(
Layer.provideMerge(providerSessionDirectoryLayer),
Layer.provideMerge(runtimeRepositoryLayer),
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)),
Layer.provideMerge(NodeServices.layer),
);
runtime = ManagedRuntime.make(layer);
return { stopSession, stoppedThreadIds };
}
it("reaps stale persisted sessions without active turns", async () => {
const threadId = ThreadId.make("thread-reaper-stale");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-stale",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await waitFor(() => harness.stopSession.mock.calls.length === 1);
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId });
expect(harness.stoppedThreadIds.has(threadId)).toBe(true);
});
it("skips stale sessions when the thread still has an active turn", async () => {
const threadId = ThreadId.make("thread-reaper-active-turn");
const turnId = TurnId.make("turn-reaper-active");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "running",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-active-turn",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await new Promise((resolve) => setTimeout(resolve, 50));
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("does not reap sessions that are still within the inactivity threshold", async () => {
const threadId = ThreadId.make("thread-reaper-fresh");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: now,
resumeCursor: {
opaque: "resume-fresh",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await new Promise((resolve) => setTimeout(resolve, 50));
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("skips persisted sessions that are already marked stopped", async () => {
const threadId = ThreadId.make("thread-reaper-stopped");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "stopped",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "stopped",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-stopped",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await new Promise((resolve) => setTimeout(resolve, 50));
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("continues reaping other sessions when one stop attempt fails", async () => {
const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: failedThreadId,
session: {
threadId: failedThreadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
{
id: reapedThreadId,
session: {
threadId: reapedThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
stopSessionImplementation: (request) =>
request.threadId === failedThreadId
? Effect.fail(
new ProviderValidationError({
operation: "ProviderSessionReaper.test",
issue: "simulated stop failure",
}),
)
: Effect.void,
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId: failedThreadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-failure",
},
runtimePayload: null,
}),
);
await runtime!.runPromise(
repository.upsert({
threadId: reapedThreadId,
providerName: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:01:00.000Z",
resumeCursor: {
opaque: "resume-success",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await waitFor(() => harness.stopSession.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
failedThreadId,
reapedThreadId,
]);
});
it("continues reaping other sessions when one stop attempt defects", async () => {
const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: defectThreadId,
session: {
threadId: defectThreadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
{
id: reapedThreadId,
session: {
threadId: reapedThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
stopSessionImplementation: (request) =>
request.threadId === defectThreadId
? Effect.die(new Error("simulated stop defect"))
: Effect.void,
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId: defectThreadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-defect",
},
runtimePayload: null,
}),
);
await runtime!.runPromise(
repository.upsert({
threadId: reapedThreadId,
providerName: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:01:00.000Z",
resumeCursor: {
opaque: "resume-after-defect",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await waitFor(() => harness.stopSession.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
defectThreadId,
reapedThreadId,
]);
});
});
@@ -1,133 +0,0 @@
import { Duration, Effect, Layer, Schedule } from "effect";
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
ProviderSessionReaper,
type ProviderSessionReaperShape,
} from "../Services/ProviderSessionReaper.ts";
import { ProviderService } from "../Services/ProviderService.ts";
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
export interface ProviderSessionReaperLiveOptions {
readonly inactivityThresholdMs?: number;
readonly sweepIntervalMs?: number;
}
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
Effect.gen(function* () {
const providerService = yield* ProviderService;
const directory = yield* ProviderSessionDirectory;
const orchestrationEngine = yield* OrchestrationEngineService;
const inactivityThresholdMs = Math.max(
1,
options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,
);
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
const sweep = Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
const threadsById = new Map(readModel.threads.map((thread) => [thread.id, thread] as const));
const bindings = yield* directory.listBindings();
const now = Date.now();
let reapedCount = 0;
for (const binding of bindings) {
if (binding.status === "stopped") {
continue;
}
const lastSeenMs = Date.parse(binding.lastSeenAt);
if (Number.isNaN(lastSeenMs)) {
yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
threadId: binding.threadId,
provider: binding.provider,
lastSeenAt: binding.lastSeenAt,
});
continue;
}
const idleDurationMs = now - lastSeenMs;
if (idleDurationMs < inactivityThresholdMs) {
continue;
}
const thread = threadsById.get(binding.threadId);
if (thread?.session?.activeTurnId != null) {
yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
threadId: binding.threadId,
activeTurnId: thread.session.activeTurnId,
idleDurationMs,
});
continue;
}
const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
Effect.tap(() =>
Effect.logInfo("provider.session.reaped", {
threadId: binding.threadId,
provider: binding.provider,
idleDurationMs,
reason: "inactivity_threshold",
}),
),
Effect.as(true),
Effect.catchCause((cause) =>
Effect.logWarning("provider.session.reaper.stop-failed", {
threadId: binding.threadId,
provider: binding.provider,
idleDurationMs,
cause,
}).pipe(Effect.as(false)),
),
);
if (reaped) {
reapedCount += 1;
}
}
if (reapedCount > 0) {
yield* Effect.logInfo("provider.session.reaper.sweep-complete", {
reapedCount,
totalBindings: bindings.length,
});
}
});
const start: ProviderSessionReaperShape["start"] = () =>
Effect.gen(function* () {
yield* Effect.forkScoped(
sweep.pipe(
Effect.catch((error: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-failed", {
error,
}),
),
Effect.catchDefect((defect: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-defect", {
defect,
}),
),
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
),
);
yield* Effect.logInfo("provider.session.reaper.started", {
inactivityThresholdMs,
sweepIntervalMs,
});
});
return {
start,
} satisfies ProviderSessionReaperShape;
});
export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
export const ProviderSessionReaperLive = makeProviderSessionReaperLive();
@@ -1,6 +1,6 @@
import { Context } from "effect";
import type { ServerProviderShape } from "./ServerProvider.ts";
import type { ServerProviderShape } from "./ServerProvider";
export interface ClaudeProviderShape extends ServerProviderShape {}
@@ -1,6 +1,6 @@
import { Context } from "effect";
import type { ServerProviderShape } from "./ServerProvider.ts";
import type { ServerProviderShape } from "./ServerProvider";
export interface CodexProviderShape extends ServerProviderShape {}
@@ -22,10 +22,6 @@ export interface ProviderRuntimeBinding {
readonly runtimeMode?: RuntimeMode;
}
export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {
readonly lastSeenAt: string;
}
export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;
export type ProviderSessionDirectoryWriteError =
@@ -53,11 +49,6 @@ export interface ProviderSessionDirectoryShape {
ReadonlyArray<ThreadId>,
ProviderSessionDirectoryPersistenceError
>;
readonly listBindings: () => Effect.Effect<
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
ProviderSessionDirectoryPersistenceError
>;
}
export class ProviderSessionDirectory extends Context.Service<
@@ -1,14 +0,0 @@
import { Context } from "effect";
import type { Effect, Scope } from "effect";
export interface ProviderSessionReaperShape {
/**
* Start the background provider session reaper within the provided scope.
*/
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
}
export class ProviderSessionReaper extends Context.Service<
ProviderSessionReaper,
ProviderSessionReaperShape
>()("t3/provider/Services/ProviderSessionReaper") {}
@@ -1,17 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts";
describe("cliVersion", () => {
it("normalizes versions with a missing patch segment", () => {
assert.strictEqual(normalizeCliVersion("2.1"), "2.1.0");
});
it("compares prerelease versions before stable versions", () => {
assert.isTrue(compareCliVersions("2.1.111-beta.1", "2.1.111") < 0);
});
it("rejects malformed numeric segments", () => {
assert.isTrue(compareCliVersions("1.2.3abc", "1.2.10") > 0);
});
});
Loaded 100 of 282 files, more files were not shown because too many files have changed in this diff. Show more