Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3631d0a8ee | ||
|
|
505db9f696 | ||
|
|
2d87574e62 | ||
|
|
b2cca674df | ||
|
|
549043863a | ||
|
|
b7df3dfca0 | ||
|
|
6891c77d3e | ||
|
|
d90e15d1d7 | ||
|
|
e0117b271a | ||
|
|
188a40c315 | ||
|
|
7a08fcf2e8 | ||
|
|
19d47408a5 | ||
|
|
3e07f5a6a4 | ||
|
|
d22c6f5280 | ||
|
|
5e13f53571 | ||
|
|
f9580ff088 | ||
|
|
5e1dd56d2c | ||
|
|
68061af042 | ||
|
|
28cb9db20b | ||
|
|
7968f278ee | ||
|
|
44afe784a3 | ||
|
|
9ff31f8c35 | ||
|
|
409ff90a14 | ||
|
|
0d280262f6 | ||
|
|
c9b07d665d | ||
|
|
2e42f3fdf6 | ||
|
|
008ac5c3e5 | ||
|
|
9dcea68bce | ||
|
|
5f7ec73a22 | ||
|
|
569fea87a9 | ||
|
|
33dadb5aec | ||
|
|
d18e43b674 | ||
|
|
6f699346e4 | ||
|
|
f5ecca4480 | ||
|
|
cadd708646 | ||
|
|
5f7becf386 | ||
|
|
9b29be916b | ||
|
|
047a0a697c | ||
|
|
77fcad3586 | ||
|
|
801b83e937 | ||
|
|
f2205bdc42 |
No files matched your search
@@ -9,7 +9,7 @@ on:
|
||||
jobs:
|
||||
quality:
|
||||
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
|
||||
release_smoke:
|
||||
name: Release Smoke
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -92,5 +92,8 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Exercise release-only workflow steps
|
||||
run: node scripts/release-smoke.ts
|
||||
+230
-47
@@ -1,14 +1,24 @@
|
||||
name: Release Desktop
|
||||
name: Release
|
||||
|
||||
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: true
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
@@ -18,43 +28,24 @@ permissions:
|
||||
jobs:
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
release_channel: ${{ steps.release_meta.outputs.release_channel }}
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
release_name: ${{ steps.release_meta.outputs.name }}
|
||||
short_sha: ${{ steps.release_meta.outputs.short_sha }}
|
||||
previous_tag: ${{ steps.previous_tag.outputs.previous_tag }}
|
||||
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
|
||||
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
|
||||
make_latest: ${{ steps.release_meta.outputs.make_latest }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
raw="${{ github.event.inputs.version }}"
|
||||
else
|
||||
raw="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
|
||||
version="${raw#v}"
|
||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "Invalid release version: $raw" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -69,6 +60,60 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
shell: bash
|
||||
env:
|
||||
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
|
||||
DISPATCH_VERSION: ${{ github.event.inputs.version }}
|
||||
NIGHTLY_DATE: ${{ github.run_started_at }}
|
||||
NIGHTLY_SHA: ${{ github.sha }}
|
||||
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
|
||||
nightly_date="$(date -u -d "$NIGHTLY_DATE" +%Y%m%d)"
|
||||
|
||||
node scripts/resolve-nightly-release.ts \
|
||||
--date "$nightly_date" \
|
||||
--run-number "$NIGHTLY_RUN_NUMBER" \
|
||||
--sha "$NIGHTLY_SHA" \
|
||||
--github-output
|
||||
|
||||
echo "release_channel=nightly" >> "$GITHUB_OUTPUT"
|
||||
echo "cli_dist_tag=nightly" >> "$GITHUB_OUTPUT"
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
raw="${DISPATCH_VERSION}"
|
||||
if [[ -z "$raw" ]]; then
|
||||
echo "workflow_dispatch stable releases require the version input." >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
raw="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
|
||||
version="${raw#v}"
|
||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "Invalid release version: $raw" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "release_channel=stable" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
echo "name=T3 Code v$version" >> "$GITHUB_OUTPUT"
|
||||
echo "cli_dist_tag=latest" >> "$GITHUB_OUTPUT"
|
||||
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
@@ -78,6 +123,14 @@ 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
|
||||
@@ -88,25 +141,30 @@ jobs:
|
||||
matrix:
|
||||
include:
|
||||
- label: macOS arm64
|
||||
runner: macos-14
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
- label: macOS x64
|
||||
runner: macos-15-intel
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
- label: Linux x64
|
||||
runner: ubuntu-24.04
|
||||
runner: blacksmith-32vcpu-ubuntu-2404
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
- label: Windows x64
|
||||
runner: windows-2022
|
||||
runner: blacksmith-32vcpu-windows-2025
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
# - label: Windows arm64
|
||||
# runner: windows-11-arm
|
||||
# platform: win
|
||||
# target: nsis
|
||||
# arch: arm64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -130,6 +188,60 @@ jobs:
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Install VS 2022 Spectre-mitigated MSVC libraries
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
$setup = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
|
||||
$spectreComponent = "Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre"
|
||||
|
||||
if (-not (Test-Path $vswhere)) {
|
||||
throw "vswhere.exe not found at $vswhere"
|
||||
}
|
||||
|
||||
if (-not (Test-Path $setup)) {
|
||||
throw "Visual Studio installer setup.exe not found at $setup"
|
||||
}
|
||||
|
||||
$existingSpectreInstall = & $vswhere -products * -requires $spectreComponent -property installationPath
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "vswhere failed while checking for $spectreComponent"
|
||||
}
|
||||
|
||||
if ($existingSpectreInstall) {
|
||||
Write-Host "Spectre-mitigated MSVC libraries already installed at $existingSpectreInstall"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$installPath = & $vswhere -products * -requires Microsoft.Component.MSBuild -property installationPath
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "vswhere failed while locating the Visual Studio Build Tools installation"
|
||||
}
|
||||
|
||||
if (-not $installPath) {
|
||||
throw "Could not find a Visual Studio Build Tools installation to modify"
|
||||
}
|
||||
|
||||
Write-Host "Installing $spectreComponent into $installPath"
|
||||
& $setup modify `
|
||||
--installPath $installPath `
|
||||
--add $spectreComponent `
|
||||
--quiet `
|
||||
--wait `
|
||||
--norestart
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Visual Studio installer failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
|
||||
$verifiedInstall = & $vswhere -products * -requires $spectreComponent -property installationPath
|
||||
if (-not $verifiedInstall) {
|
||||
throw "$spectreComponent was not detected after installation"
|
||||
}
|
||||
|
||||
Write-Host "Installed Spectre-mitigated MSVC libraries at $verifiedInstall"
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
@@ -206,18 +318,31 @@ jobs:
|
||||
"release/*.AppImage" \
|
||||
"release/*.exe" \
|
||||
"release/*.blockmap" \
|
||||
"release/latest*.yml"; do
|
||||
"release/*.yml"; do
|
||||
for file in $pattern; do
|
||||
cp "$file" release-publish/
|
||||
done
|
||||
done
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
|
||||
if [[ -f release-publish/latest-mac.yml ]]; then
|
||||
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
|
||||
fi
|
||||
shopt -s nullglob
|
||||
for manifest in release-publish/*-mac.yml; do
|
||||
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
|
||||
done
|
||||
fi
|
||||
|
||||
# Enable if Windows arm64 builds are enabled.
|
||||
# Windows updater metadata is channel-specific (for example
|
||||
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
|
||||
# release job can merge matching arm64/x64 manifests back into one
|
||||
# canonical manifest per channel.
|
||||
# if [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
# shopt -s nullglob
|
||||
# for manifest in release-publish/*.yml; do
|
||||
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
|
||||
# done
|
||||
# fi
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -228,7 +353,7 @@ jobs:
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -257,12 +382,12 @@ jobs:
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -284,17 +409,71 @@ jobs:
|
||||
|
||||
- name: Merge macOS updater manifests
|
||||
run: |
|
||||
node scripts/merge-mac-update-manifests.ts \
|
||||
release-assets/latest-mac.yml \
|
||||
release-assets/latest-mac-x64.yml
|
||||
rm -f release-assets/latest-mac-x64.yml
|
||||
shopt -s nullglob
|
||||
for x64_manifest in release-assets/*-mac-x64.yml; do
|
||||
arm64_manifest="${x64_manifest%-x64.yml}.yml"
|
||||
if [[ -f "$arm64_manifest" ]]; then
|
||||
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
|
||||
rm -f "$x64_manifest"
|
||||
fi
|
||||
done
|
||||
|
||||
# - name: Merge Windows updater manifests
|
||||
# run: |
|
||||
# shopt -s nullglob
|
||||
# found_windows_manifest=false
|
||||
# for x64_manifest in release-assets/*-win-x64.yml; do
|
||||
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
|
||||
# continue
|
||||
# fi
|
||||
|
||||
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
|
||||
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
|
||||
# if [[ ! -f "$arm64_manifest" ]]; then
|
||||
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
|
||||
# exit 1
|
||||
# fi
|
||||
|
||||
# found_windows_manifest=true
|
||||
# node scripts/merge-update-manifests.ts --platform win \
|
||||
# "$arm64_manifest" \
|
||||
# "$x64_manifest" \
|
||||
# "$output_manifest"
|
||||
# rm -f "$arm64_manifest" "$x64_manifest"
|
||||
# done
|
||||
|
||||
# if [[ "$found_windows_manifest" != true ]]; then
|
||||
# echo "No Windows updater manifests found to merge." >&2
|
||||
# exit 1
|
||||
# fi
|
||||
|
||||
- name: Publish release
|
||||
if: needs.preflight.outputs.previous_tag != ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
name: ${{ needs.preflight.outputs.release_name }}
|
||||
generate_release_notes: true
|
||||
previous_tag: ${{ needs.preflight.outputs.previous_tag }}
|
||||
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
|
||||
make_latest: ${{ needs.preflight.outputs.make_latest }}
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
- name: Publish first release
|
||||
if: needs.preflight.outputs.previous_tag == ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: ${{ needs.preflight.outputs.release_name }}
|
||||
generate_release_notes: true
|
||||
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
|
||||
make_latest: ${{ needs.preflight.outputs.make_latest }}
|
||||
@@ -304,13 +483,14 @@ jobs:
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/latest*.yml
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: needs.preflight.outputs.release_channel == 'stable'
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
@@ -349,6 +529,9 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
|
||||
+2
-1
@@ -10,7 +10,8 @@
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js",
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts"
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts",
|
||||
"*.icon/**"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
@@ -49,6 +49,14 @@ Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Before local development, prepare the environment and install dependencies:
|
||||
|
||||
```bash
|
||||
# Optional: only needed if you use mise for dev tool management.
|
||||
mise install
|
||||
bun install .
|
||||
```
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.17",
|
||||
"version": "0.0.20",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
@@ -23,6 +24,9 @@ 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], {
|
||||
@@ -43,6 +47,68 @@ function setPlistString(plistPath, key, value) {
|
||||
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
|
||||
}
|
||||
|
||||
function runChecked(command, args) {
|
||||
const result = spawnSync(command, args, { encoding: "utf8" });
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
|
||||
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
|
||||
}
|
||||
|
||||
function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
if (!existsSync(developmentMacIconPngPath)) {
|
||||
return defaultIconPath;
|
||||
}
|
||||
|
||||
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
|
||||
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
|
||||
return generatedIconPath;
|
||||
}
|
||||
|
||||
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
|
||||
const iconsetDir = join(iconsetRoot, "icon.iconset");
|
||||
mkdirSync(iconsetDir, { recursive: true });
|
||||
|
||||
try {
|
||||
for (const size of [16, 32, 128, 256, 512]) {
|
||||
runChecked("sips", [
|
||||
"-z",
|
||||
String(size),
|
||||
String(size),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
]);
|
||||
|
||||
const retinaSize = size * 2;
|
||||
runChecked("sips", [
|
||||
"-z",
|
||||
String(retinaSize),
|
||||
String(retinaSize),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
]);
|
||||
}
|
||||
|
||||
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
|
||||
return generatedIconPath;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
|
||||
error,
|
||||
);
|
||||
return defaultIconPath;
|
||||
} finally {
|
||||
rmSync(iconsetRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
@@ -102,7 +168,7 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
const runtimeDir = join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const iconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding";
|
||||
|
||||
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)",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { DesktopAppBranding, DesktopAppStageLabel } from "@t3tools/contracts";
|
||||
|
||||
import { isNightlyDesktopVersion } from "./updateChannels";
|
||||
|
||||
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})`,
|
||||
};
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
} from "./backendReadiness";
|
||||
|
||||
describe("waitForHttpReady", () => {
|
||||
it("returns once the backend reports a successful session endpoint", async () => {
|
||||
it("returns once the backend serves the requested readiness path", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
@@ -20,6 +20,11 @@ describe("waitForHttpReady", () => {
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("retries after a readiness request stalls past the per-request timeout", async () => {
|
||||
@@ -80,4 +85,30 @@ describe("waitForHttpReady", () => {
|
||||
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
|
||||
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
|
||||
});
|
||||
|
||||
it("supports custom readiness predicates", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }));
|
||||
|
||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 0,
|
||||
path: "/api/healthz",
|
||||
isReady: (response) => response.status === 204,
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,8 @@ export interface WaitForHttpReadyOptions {
|
||||
readonly requestTimeoutMs?: number;
|
||||
readonly fetchImpl?: typeof fetch;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly path?: string;
|
||||
readonly isReady?: (response: Response) => boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
@@ -57,6 +59,8 @@ export async function waitForHttpReady(
|
||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
|
||||
const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||
const readinessPath = options?.path ?? "/";
|
||||
const isReady = options?.isReady ?? ((response: Response) => response.ok);
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
for (;;) {
|
||||
@@ -74,11 +78,11 @@ export async function waitForHttpReady(
|
||||
signal?.addEventListener("abort", abortRequest, { once: true });
|
||||
|
||||
try {
|
||||
const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
|
||||
const response = await fetchImpl(new URL(readinessPath, baseUrl).toString(), {
|
||||
redirect: "manual",
|
||||
signal: requestController.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
if (isReady(response)) {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -52,6 +52,10 @@ 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",
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
|
||||
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import {
|
||||
ClientSettingsSchema,
|
||||
type ClientSettings,
|
||||
type PersistedSavedEnvironmentRecord,
|
||||
} from "@t3tools/contracts";
|
||||
import { Predicate } from "effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
interface ClientSettingsDocument {
|
||||
readonly settings: ClientSettings;
|
||||
@@ -83,7 +88,15 @@ function toPersistedSavedEnvironmentRecord(
|
||||
}
|
||||
|
||||
export function readClientSettings(settingsPath: string): ClientSettings | null {
|
||||
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
|
||||
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
|
||||
|
||||
@@ -7,7 +7,9 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
resolveDefaultDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings";
|
||||
|
||||
@@ -27,7 +29,15 @@ function makeSettingsPath() {
|
||||
|
||||
describe("desktopSettings", () => {
|
||||
it("returns defaults when no settings file exists", () => {
|
||||
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
expect(readDesktopSettings(makeSettingsPath(), "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
|
||||
it("defaults packaged nightly builds to the nightly update channel", () => {
|
||||
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("persists and reloads the configured server exposure mode", () => {
|
||||
@@ -35,10 +45,14 @@ describe("desktopSettings", () => {
|
||||
|
||||
writeDesktopSettings(settingsPath, {
|
||||
serverExposureMode: "network-accessible",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
|
||||
expect(readDesktopSettings(settingsPath)).toEqual({
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -47,11 +61,32 @@ describe("desktopSettings", () => {
|
||||
setDesktopServerExposurePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
"network-accessible",
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("persists the requested nightly update channel", () => {
|
||||
expect(
|
||||
setDesktopUpdateChannelPreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
"nightly",
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -59,6 +94,54 @@ describe("desktopSettings", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(settingsPath, "{not-json", "utf8");
|
||||
|
||||
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
|
||||
it("falls back to the nightly channel for legacy nightly settings without an update track", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(settingsPath, JSON.stringify({ serverExposureMode: "local-only" }), "utf8");
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("migrates legacy implicit stable settings to nightly when running a nightly build", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(
|
||||
settingsPath,
|
||||
JSON.stringify({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves an explicit stable choice on nightly builds", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(
|
||||
settingsPath,
|
||||
JSON.stringify({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,28 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
||||
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
|
||||
|
||||
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
readonly updateChannel: DesktopUpdateChannel;
|
||||
readonly updateChannelConfiguredByUser: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
};
|
||||
|
||||
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
|
||||
return {
|
||||
...DEFAULT_DESKTOP_SETTINGS,
|
||||
updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
|
||||
};
|
||||
}
|
||||
|
||||
export function setDesktopServerExposurePreference(
|
||||
settings: DesktopSettings,
|
||||
requestedMode: DesktopServerExposureMode,
|
||||
@@ -22,23 +35,51 @@ export function setDesktopServerExposurePreference(
|
||||
};
|
||||
}
|
||||
|
||||
export function readDesktopSettings(settingsPath: string): DesktopSettings {
|
||||
export function setDesktopUpdateChannelPreference(
|
||||
settings: DesktopSettings,
|
||||
requestedChannel: DesktopUpdateChannel,
|
||||
): DesktopSettings {
|
||||
return {
|
||||
...settings,
|
||||
updateChannel: requestedChannel,
|
||||
updateChannelConfiguredByUser: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function readDesktopSettings(settingsPath: string, appVersion: string): DesktopSettings {
|
||||
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
|
||||
|
||||
try {
|
||||
if (!FS.existsSync(settingsPath)) {
|
||||
return DEFAULT_DESKTOP_SETTINGS;
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
const raw = FS.readFileSync(settingsPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
readonly serverExposureMode?: unknown;
|
||||
readonly updateChannel?: unknown;
|
||||
readonly updateChannelConfiguredByUser?: unknown;
|
||||
};
|
||||
const parsedUpdateChannel =
|
||||
parsed.updateChannel === "nightly" || parsed.updateChannel === "latest"
|
||||
? parsed.updateChannel
|
||||
: null;
|
||||
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
|
||||
const updateChannelConfiguredByUser =
|
||||
parsed.updateChannelConfiguredByUser === true ||
|
||||
(isLegacySettings && parsedUpdateChannel === "nightly");
|
||||
|
||||
return {
|
||||
serverExposureMode:
|
||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||
updateChannel:
|
||||
updateChannelConfiguredByUser && parsedUpdateChannel !== null
|
||||
? parsedUpdateChannel
|
||||
: defaultSettings.updateChannel,
|
||||
updateChannelConfiguredByUser,
|
||||
};
|
||||
} catch {
|
||||
return DEFAULT_DESKTOP_SETTINGS;
|
||||
return defaultSettings;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+332
-81
@@ -18,12 +18,14 @@ import {
|
||||
safeStorage,
|
||||
shell,
|
||||
} from "electron";
|
||||
import type { MenuItemConstructorOptions } from "electron";
|
||||
import type { MenuItemConstructorOptions, OpenDialogOptions } from "electron";
|
||||
import type {
|
||||
ClientSettings,
|
||||
DesktopTheme,
|
||||
DesktopAppBranding,
|
||||
DesktopServerExposureMode,
|
||||
DesktopServerExposureState,
|
||||
DesktopUpdateChannel,
|
||||
PersistedSavedEnvironmentRecord,
|
||||
DesktopUpdateActionResult,
|
||||
DesktopUpdateCheckResult,
|
||||
@@ -39,6 +41,7 @@ import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings";
|
||||
import {
|
||||
@@ -55,6 +58,8 @@ import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
@@ -68,6 +73,7 @@ import {
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
import { resolveDesktopAppBranding } from "./appBranding";
|
||||
|
||||
syncShellEnvironment();
|
||||
|
||||
@@ -79,9 +85,11 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
@@ -100,7 +108,11 @@ const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
|
||||
isDevelopment,
|
||||
appVersion: app.getVersion(),
|
||||
});
|
||||
const APP_DISPLAY_NAME = desktopAppBranding.displayName;
|
||||
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
|
||||
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
|
||||
@@ -115,8 +127,32 @@ const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
||||
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
|
||||
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
|
||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
|
||||
function resolvePickFolderDefaultPath(rawOptions: unknown): string | undefined {
|
||||
if (typeof rawOptions !== "object" || rawOptions === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { initialPath } = rawOptions as { initialPath?: unknown };
|
||||
if (typeof initialPath !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const trimmedPath = initialPath.trim();
|
||||
if (trimmedPath.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (trimmedPath === "~") {
|
||||
return OS.homedir();
|
||||
}
|
||||
|
||||
if (trimmedPath.startsWith("~/") || trimmedPath.startsWith("~\\")) {
|
||||
return Path.join(OS.homedir(), trimmedPath.slice(2));
|
||||
}
|
||||
|
||||
return Path.resolve(trimmedPath);
|
||||
}
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
@@ -124,6 +160,35 @@ 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"
|
||||
@@ -144,6 +209,8 @@ let backendWsUrl = "";
|
||||
let backendEndpointUrl: string | null = null;
|
||||
let backendAdvertisedHost: string | null = null;
|
||||
let backendReadinessAbortController: AbortController | null = null;
|
||||
let backendInitialWindowOpenInFlight: Promise<void> | null = null;
|
||||
let backendListeningDetector: ServerListeningDetector | null = null;
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
@@ -153,7 +220,7 @@ let desktopLogSink: RotatingFileSink | null = null;
|
||||
let backendLogSink: RotatingFileSink | null = null;
|
||||
let restoreStdIoCapture: (() => void) | null = null;
|
||||
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
|
||||
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
|
||||
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH, app.getVersion());
|
||||
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
|
||||
|
||||
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
|
||||
@@ -164,7 +231,11 @@ const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
|
||||
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
|
||||
});
|
||||
const initialUpdateState = (): DesktopUpdateState =>
|
||||
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
|
||||
createInitialDesktopUpdateState(
|
||||
app.getVersion(),
|
||||
desktopRuntimeInfo,
|
||||
desktopSettings.updateChannel,
|
||||
);
|
||||
|
||||
function logTimestamp(): string {
|
||||
return new Date().toISOString();
|
||||
@@ -362,13 +433,17 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
|
||||
async function waitForBackendHttpReady(
|
||||
baseUrl: string,
|
||||
options?: Parameters<typeof waitForHttpReady>[1],
|
||||
): Promise<void> {
|
||||
cancelBackendReadinessWait();
|
||||
const controller = new AbortController();
|
||||
backendReadinessAbortController = controller;
|
||||
|
||||
try {
|
||||
await waitForHttpReady(baseUrl, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
@@ -383,6 +458,88 @@ function cancelBackendReadinessWait(): void {
|
||||
backendReadinessAbortController = null;
|
||||
}
|
||||
|
||||
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
});
|
||||
const listeningPromise = backendListeningDetector?.promise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
cancelBackendReadinessWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function ensureInitialBackendWindowOpen(): void {
|
||||
const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0] ?? null;
|
||||
if (isDevelopment || existingWindow !== null || backendInitialWindowOpenInFlight !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextOpen = waitForBackendWindowReady(backendHttpUrl)
|
||||
.then((source) => {
|
||||
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
|
||||
if (mainWindow ?? BrowserWindow.getAllWindows()[0]) {
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap backend readiness warning message=${formatErrorMessage(error)}`,
|
||||
);
|
||||
console.warn("[desktop] backend readiness check timed out during packaged bootstrap", error);
|
||||
})
|
||||
.finally(() => {
|
||||
if (backendInitialWindowOpenInFlight === nextOpen) {
|
||||
backendInitialWindowOpenInFlight = null;
|
||||
}
|
||||
});
|
||||
|
||||
backendInitialWindowOpenInFlight = nextOpen;
|
||||
}
|
||||
|
||||
function writeDesktopStreamChunk(
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: unknown,
|
||||
@@ -460,14 +617,16 @@ function initializePackagedLogging(): void {
|
||||
}
|
||||
|
||||
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
||||
if (!app.isPackaged || backendLogSink === null) return;
|
||||
const writeChunk = (chunk: unknown): void => {
|
||||
if (!backendLogSink) return;
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink.write(buffer);
|
||||
const attachStream = (stream: NodeJS.ReadableStream | null | undefined): void => {
|
||||
stream?.on("data", (chunk: unknown) => {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink?.write(buffer);
|
||||
backendListeningDetector?.push(buffer);
|
||||
});
|
||||
};
|
||||
child.stdout?.on("data", writeChunk);
|
||||
child.stderr?.on("data", writeChunk);
|
||||
|
||||
attachStream(child.stdout);
|
||||
attachStream(child.stderr);
|
||||
}
|
||||
|
||||
initializePackagedLogging();
|
||||
@@ -884,6 +1043,18 @@ function resolveResourcePath(fileName: string): string | null {
|
||||
}
|
||||
|
||||
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
|
||||
if (isDevelopment && process.platform === "darwin" && ext === "png") {
|
||||
const developmentDockIconPath = Path.join(
|
||||
ROOT_DIR,
|
||||
"assets",
|
||||
"dev",
|
||||
"blueprint-macos-1024.png",
|
||||
);
|
||||
if (FS.existsSync(developmentDockIconPath)) {
|
||||
return developmentDockIconPath;
|
||||
}
|
||||
}
|
||||
|
||||
return resolveResourcePath(`icon.${ext}`);
|
||||
}
|
||||
|
||||
@@ -983,6 +1154,26 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
|
||||
emitUpdateState();
|
||||
}
|
||||
|
||||
function createBaseUpdateState(
|
||||
channel: DesktopUpdateChannel,
|
||||
enabled: boolean,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo, channel),
|
||||
enabled,
|
||||
status: enabled ? "idle" : "disabled",
|
||||
};
|
||||
}
|
||||
|
||||
function applyAutoUpdaterChannel(channel: DesktopUpdateChannel): void {
|
||||
autoUpdater.channel = channel;
|
||||
autoUpdater.allowPrerelease = channel === "nightly";
|
||||
autoUpdater.allowDowngrade = channel === "nightly";
|
||||
console.info(
|
||||
`[desktop-updater] Using update channel '${channel}' (allowPrerelease=${channel === "nightly"}, allowDowngrade=${channel === "nightly"}).`,
|
||||
);
|
||||
}
|
||||
|
||||
function shouldEnableAutoUpdates(): boolean {
|
||||
const hasUpdateFeedConfig =
|
||||
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
|
||||
@@ -1102,11 +1293,7 @@ function configureAutoUpdater(): void {
|
||||
}
|
||||
|
||||
const enabled = shouldEnableAutoUpdates();
|
||||
setUpdateState({
|
||||
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
|
||||
enabled,
|
||||
status: enabled ? "idle" : "disabled",
|
||||
});
|
||||
setUpdateState(createBaseUpdateState(desktopSettings.updateChannel, enabled));
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
@@ -1114,10 +1301,7 @@ function configureAutoUpdater(): void {
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
|
||||
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
|
||||
autoUpdater.allowDowngrade = false;
|
||||
applyAutoUpdaterChannel(desktopSettings.updateChannel);
|
||||
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
|
||||
let lastLoggedDownloadMilestone = -1;
|
||||
|
||||
@@ -1131,6 +1315,15 @@ function configureAutoUpdater(): void {
|
||||
console.info("[desktop-updater] Looking for updates...");
|
||||
});
|
||||
autoUpdater.on("update-available", (info) => {
|
||||
if (!doesVersionMatchDesktopUpdateChannel(info.version, updateState.channel)) {
|
||||
console.info(
|
||||
`[desktop-updater] Ignoring ${info.version} because it does not match the selected '${updateState.channel}' channel.`,
|
||||
);
|
||||
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
|
||||
lastLoggedDownloadMilestone = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdateState(
|
||||
reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
updateState,
|
||||
@@ -1222,7 +1415,7 @@ function startBackend(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const captureBackendLogs = !isDevelopment;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
@@ -1259,6 +1452,8 @@ function startBackend(): void {
|
||||
scheduleBackendRestart("missing desktop bootstrap pipe");
|
||||
return;
|
||||
}
|
||||
const listeningDetector = new ServerListeningDetector();
|
||||
backendListeningDetector = listeningDetector;
|
||||
backendProcess = child;
|
||||
let backendSessionClosed = false;
|
||||
const closeBackendSession = (details: string) => {
|
||||
@@ -1277,6 +1472,10 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
if (backendListeningDetector === listeningDetector) {
|
||||
listeningDetector.fail(error);
|
||||
backendListeningDetector = null;
|
||||
}
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
@@ -1289,6 +1488,14 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (backendListeningDetector === listeningDetector) {
|
||||
listeningDetector.fail(
|
||||
new Error(
|
||||
`backend exited before logging readiness (code=${code ?? "null"} signal=${signal ?? "null"})`,
|
||||
),
|
||||
);
|
||||
backendListeningDetector = null;
|
||||
}
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
@@ -1300,10 +1507,13 @@ function startBackend(): void {
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
});
|
||||
|
||||
ensureInitialBackendWindowOpen();
|
||||
}
|
||||
|
||||
function stopBackend(): void {
|
||||
cancelBackendReadinessWait();
|
||||
backendListeningDetector = null;
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1378,6 +1588,11 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
ipcMain.removeAllListeners(GET_APP_BRANDING_CHANNEL);
|
||||
ipcMain.on(GET_APP_BRANDING_CHANNEL, (event) => {
|
||||
event.returnValue = desktopAppBranding;
|
||||
});
|
||||
|
||||
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
|
||||
event.returnValue = {
|
||||
@@ -1491,15 +1706,16 @@ function registerIpcHandlers(): void {
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
|
||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||
const defaultPath = resolvePickFolderDefaultPath(rawOptions);
|
||||
const openDialogOptions: OpenDialogOptions = {
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
...(defaultPath ? { defaultPath } : {}),
|
||||
};
|
||||
const result = owner
|
||||
? await dialog.showOpenDialog(owner, {
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
})
|
||||
: await dialog.showOpenDialog({
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
});
|
||||
? await dialog.showOpenDialog(owner, openDialogOptions)
|
||||
: await dialog.showOpenDialog(openDialogOptions);
|
||||
if (result.canceled) return null;
|
||||
return result.filePaths[0] ?? null;
|
||||
});
|
||||
@@ -1528,14 +1744,7 @@ function registerIpcHandlers(): void {
|
||||
ipcMain.handle(
|
||||
CONTEXT_MENU_CHANNEL,
|
||||
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
|
||||
const normalizedItems = items
|
||||
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
destructive: item.destructive === true,
|
||||
disabled: item.disabled === true,
|
||||
}));
|
||||
const normalizedItems = normalizeContextMenuItems(items);
|
||||
if (normalizedItems.length === 0) {
|
||||
return null;
|
||||
}
|
||||
@@ -1556,28 +1765,37 @@ function registerIpcHandlers(): void {
|
||||
if (!window) return null;
|
||||
|
||||
return new Promise<string | null>((resolve) => {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
for (const item of normalizedItems) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
click: () => resolve(item.id),
|
||||
};
|
||||
if (item.destructive) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (destructiveIcon) {
|
||||
itemOption.icon = destructiveIcon;
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
): MenuItemConstructorOptions[] => {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children);
|
||||
} else {
|
||||
itemOption.click = () => resolve(item.id);
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (destructiveIcon) {
|
||||
itemOption.icon = destructiveIcon;
|
||||
}
|
||||
}
|
||||
template.push(itemOption);
|
||||
}
|
||||
template.push(itemOption);
|
||||
}
|
||||
return template;
|
||||
};
|
||||
|
||||
const menu = Menu.buildFromTemplate(template);
|
||||
const menu = Menu.buildFromTemplate(buildTemplate(normalizedItems));
|
||||
menu.popup({
|
||||
window,
|
||||
...popupPosition,
|
||||
@@ -1605,6 +1823,43 @@ function registerIpcHandlers(): void {
|
||||
ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
|
||||
ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
|
||||
|
||||
ipcMain.removeHandler(UPDATE_SET_CHANNEL_CHANNEL);
|
||||
ipcMain.handle(UPDATE_SET_CHANNEL_CHANNEL, async (_event, rawChannel: unknown) => {
|
||||
if (rawChannel !== "latest" && rawChannel !== "nightly") {
|
||||
throw new Error("Invalid desktop update channel input.");
|
||||
}
|
||||
if (updateCheckInFlight || updateDownloadInFlight || updateInstallInFlight) {
|
||||
throw new Error("Cannot change update tracks while an update action is in progress.");
|
||||
}
|
||||
|
||||
const nextChannel = rawChannel as DesktopUpdateChannel;
|
||||
|
||||
desktopSettings = setDesktopUpdateChannelPreference(desktopSettings, nextChannel);
|
||||
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
|
||||
|
||||
if (nextChannel === updateState.channel) {
|
||||
return updateState;
|
||||
}
|
||||
|
||||
const enabled = shouldEnableAutoUpdates();
|
||||
setUpdateState(createBaseUpdateState(nextChannel, enabled));
|
||||
|
||||
if (!enabled || !updaterConfigured) {
|
||||
return updateState;
|
||||
}
|
||||
|
||||
applyAutoUpdaterChannel(nextChannel);
|
||||
const allowDowngrade = autoUpdater.allowDowngrade;
|
||||
// An explicit channel switch should allow the immediate nightly->stable rollback path.
|
||||
autoUpdater.allowDowngrade = true;
|
||||
try {
|
||||
await checkForUpdates("channel-change");
|
||||
} finally {
|
||||
autoUpdater.allowDowngrade = allowDowngrade;
|
||||
}
|
||||
return updateState;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
|
||||
ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
|
||||
const result = await downloadAvailableUpdate();
|
||||
@@ -1705,7 +1960,7 @@ function createWindow(): BrowserWindow {
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: isDevelopment,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: getInitialWindowBackgroundColor(),
|
||||
...getIconOption(),
|
||||
@@ -1779,20 +2034,23 @@ function createWindow(): BrowserWindow {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
if (!isDevelopment) {
|
||||
window.once("ready-to-show", () => {
|
||||
revealWindow(window);
|
||||
});
|
||||
}
|
||||
|
||||
let initialRevealScheduled = false;
|
||||
const revealInitialWindow = () => {
|
||||
if (initialRevealScheduled) {
|
||||
return;
|
||||
}
|
||||
initialRevealScheduled = true;
|
||||
revealWindow(window);
|
||||
};
|
||||
|
||||
window.once("ready-to-show", revealInitialWindow);
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
setImmediate(() => {
|
||||
revealWindow(window);
|
||||
});
|
||||
} else {
|
||||
void window.loadURL(resolveDesktopWindowUrl());
|
||||
void window.loadURL(backendHttpUrl);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -1804,14 +2062,6 @@ function createWindow(): BrowserWindow {
|
||||
return window;
|
||||
}
|
||||
|
||||
function resolveDesktopWindowUrl(): string {
|
||||
if (backendHttpUrl) {
|
||||
return backendHttpUrl;
|
||||
}
|
||||
|
||||
return `${DESKTOP_SCHEME}://app`;
|
||||
}
|
||||
|
||||
// Override Electron's userData path before the `ready` event so that
|
||||
// Chromium session data uses a filesystem-friendly directory name.
|
||||
// Must be called synchronously at the top level — before `app.whenReady()`.
|
||||
@@ -1885,10 +2135,7 @@ async function bootstrap(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
await waitForBackendHttpReady(backendHttpUrl);
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
ensureInitialBackendWindowOpen();
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
@@ -1922,7 +2169,11 @@ app
|
||||
revealWindow(existingWindow);
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
return;
|
||||
}
|
||||
ensureInitialBackendWindowOpen();
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -9,9 +9,11 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
@@ -24,6 +26,13 @@ const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getAppBranding: () => {
|
||||
const result = ipcRenderer.sendSync(GET_APP_BRANDING_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
return null;
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getAppBranding"]>;
|
||||
},
|
||||
getLocalEnvironmentBootstrap: () => {
|
||||
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
@@ -44,7 +53,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
|
||||
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
@@ -61,6 +70,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||
setUpdateChannel: (channel) => ipcRenderer.invoke(UPDATE_SET_CHANNEL_CHANNEL, channel),
|
||||
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
|
||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
|
||||
describe("ServerListeningDetector", () => {
|
||||
it("resolves when the server logs the listening line", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listening on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves when the listening line arrives across multiple chunks", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listen");
|
||||
detector.push("ing on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects when the server exits before logging readiness", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
const error = new Error("server exited");
|
||||
|
||||
detector.fail(error);
|
||||
|
||||
await expect(detector.promise).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
const LISTENING_LOG_FRAGMENT = "Listening on http://";
|
||||
const MAX_BUFFER_CHARS = 8_192;
|
||||
|
||||
export class ServerListeningDetector {
|
||||
private buffer = "";
|
||||
private settled = false;
|
||||
private readonly resolvePromise: () => void;
|
||||
private readonly rejectPromise: (error: unknown) => void;
|
||||
readonly promise: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
let resolvePromise: (() => void) | null = null;
|
||||
let rejectPromise: ((error: unknown) => void) | null = null;
|
||||
|
||||
this.promise = new Promise<void>((resolve, reject) => {
|
||||
resolvePromise = resolve;
|
||||
rejectPromise = reject;
|
||||
});
|
||||
|
||||
this.resolvePromise = () => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
resolvePromise?.();
|
||||
};
|
||||
this.rejectPromise = (error) => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
rejectPromise?.(error);
|
||||
};
|
||||
}
|
||||
|
||||
push(chunk: unknown): void {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
|
||||
this.buffer = `${this.buffer}${text.replace(/\r/g, "")}`;
|
||||
if (this.buffer.includes(LISTENING_LOG_FRAGMENT)) {
|
||||
this.resolvePromise();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.buffer.length > MAX_BUFFER_CHARS) {
|
||||
this.buffer = this.buffer.slice(-MAX_BUFFER_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
fail(error: unknown): void {
|
||||
this.rejectPromise(error);
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,12 @@ describe("syncShellEnvironment", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
HOMEBREW_PREFIX: "/opt/homebrew",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
@@ -18,9 +19,18 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
expect(env.HOMEBREW_PREFIX).toBe("/opt/homebrew");
|
||||
});
|
||||
|
||||
it("preserves an inherited SSH_AUTH_SOCK value", () => {
|
||||
@@ -77,11 +87,67 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("falls back to launchctl PATH on macOS when shell probing does not return one", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/opt/homebrew/bin/nu",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error("unknown flag");
|
||||
})
|
||||
.mockImplementationOnce(() => ({}));
|
||||
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
const logWarning = vi.fn();
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "darwin",
|
||||
readEnvironment,
|
||||
readLaunchctlPath,
|
||||
userShell: "/bin/zsh",
|
||||
logWarning,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(2, "/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
|
||||
expect(logWarning).toHaveBeenCalledWith(
|
||||
"Failed to read login shell environment from /opt/homebrew/bin/nu.",
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
|
||||
@@ -1,36 +1,79 @@
|
||||
import {
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const;
|
||||
|
||||
function logShellEnvironmentWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[desktop] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
options: {
|
||||
platform?: NodeJS.Platform;
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
|
||||
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
|
||||
const shellEnvironment: Partial<Record<string, string>> = {};
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
|
||||
if (shellEnvironment.PATH) {
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read login shell environment from ${shell}.`, error);
|
||||
}
|
||||
}
|
||||
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
]);
|
||||
|
||||
if (shellEnvironment.PATH) {
|
||||
env.PATH = shellEnvironment.PATH;
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellEnvironment.PATH
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellEnvironment.PATH ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
|
||||
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
|
||||
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
} catch {
|
||||
// Keep inherited environment if shell lookup fails.
|
||||
|
||||
for (const name of [
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const) {
|
||||
if (!env[name] && shellEnvironment[name]) {
|
||||
env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to synchronize the desktop shell environment.", error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
doesVersionMatchDesktopUpdateChannel,
|
||||
isNightlyDesktopVersion,
|
||||
resolveDefaultDesktopUpdateChannel,
|
||||
} from "./updateChannels";
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { DesktopUpdateChannel } from "@t3tools/contracts";
|
||||
|
||||
const NIGHTLY_VERSION_PATTERN = /-nightly\.\d{8}\.\d+$/;
|
||||
|
||||
export function isNightlyDesktopVersion(version: string): boolean {
|
||||
return NIGHTLY_VERSION_PATTERN.test(version);
|
||||
}
|
||||
|
||||
export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
|
||||
return isNightlyDesktopVersion(appVersion) ? "nightly" : "latest";
|
||||
}
|
||||
|
||||
export function doesVersionMatchDesktopUpdateChannel(
|
||||
version: string,
|
||||
channel: DesktopUpdateChannel,
|
||||
): boolean {
|
||||
return resolveDefaultDesktopUpdateChannel(version) === channel;
|
||||
}
|
||||
@@ -23,7 +23,7 @@ describe("updateMachine", () => {
|
||||
it("clears transient errors when a check starts", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
message: "network",
|
||||
@@ -42,7 +42,7 @@ describe("updateMachine", () => {
|
||||
it("records a check failure without exposing an action", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
@@ -58,7 +58,7 @@ describe("updateMachine", () => {
|
||||
it("preserves available version on download failure for retry", () => {
|
||||
const state = reduceDesktopUpdateStateOnDownloadFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
@@ -76,7 +76,7 @@ describe("updateMachine", () => {
|
||||
it("transitions to downloaded and then preserves install retry state", () => {
|
||||
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
@@ -98,7 +98,7 @@ describe("updateMachine", () => {
|
||||
it("clears stale download state when no update is available", () => {
|
||||
const state = reduceDesktopUpdateStateOnNoUpdate(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
availableVersion: "1.1.0",
|
||||
@@ -120,7 +120,7 @@ describe("updateMachine", () => {
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
@@ -131,6 +131,7 @@ describe("updateMachine", () => {
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(available.channel).toBe("latest");
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
|
||||
import type {
|
||||
DesktopRuntimeInfo,
|
||||
DesktopUpdateChannel,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
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,
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
channel: "latest",
|
||||
currentVersion: "1.0.0",
|
||||
hostArch: "x64",
|
||||
appArch: "x64",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.17",
|
||||
"version": "0.0.20",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -20,10 +20,11 @@
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
|
||||
@@ -470,6 +470,154 @@ 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", () => {
|
||||
|
||||
@@ -450,6 +450,25 @@ 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 = {
|
||||
@@ -901,6 +920,19 @@ 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()) {
|
||||
@@ -921,8 +953,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
|
||||
this.sessions.delete(threadId);
|
||||
if (options?.emitLifecycleEvent !== false) {
|
||||
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
|
||||
}
|
||||
this.sessions.delete(context.session.threadId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
|
||||
@@ -24,6 +24,7 @@ export interface ServerDerivedPaths {
|
||||
readonly dbPath: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly settingsPath: string;
|
||||
readonly providerStatusCacheDir: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly logsDir: string;
|
||||
@@ -76,11 +77,13 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
const providerLogsDir = join(logsDir, "provider");
|
||||
const providerStatusCacheDir = join(baseDir, "caches");
|
||||
return {
|
||||
stateDir,
|
||||
dbPath,
|
||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
||||
settingsPath: join(stateDir, "settings.json"),
|
||||
providerStatusCacheDir,
|
||||
worktreesDir: join(baseDir, "worktrees"),
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
@@ -110,6 +113,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
|
||||
],
|
||||
|
||||
@@ -166,6 +166,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"--skip-git-repo-check",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
|
||||
@@ -226,6 +226,7 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
@@ -42,6 +42,16 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const kiroLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLaunch, {
|
||||
command: "kiro",
|
||||
args: ["ide", "/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -122,6 +132,16 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const kiroLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLineAndColumn, {
|
||||
command: "kiro",
|
||||
args: ["ide", "--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -354,6 +374,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "kiro.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
@@ -361,7 +382,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(editors, ["trae", "kiro", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -75,6 +75,14 @@ function resolveCommandEditorArgs(
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
|
||||
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
|
||||
}
|
||||
|
||||
function resolveAvailableCommand(
|
||||
commands: ReadonlyArray<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
@@ -273,7 +281,7 @@ export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
|
||||
return {
|
||||
command,
|
||||
args: resolveCommandEditorArgs(editorDef, input.cwd),
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1505,6 +1505,329 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears stale pending approvals from projected shell summaries", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-stale-approval-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make("project-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:00.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make("project-stale-approval"),
|
||||
title: "Project Stale Approval",
|
||||
workspaceRoot: "/tmp/project-stale-approval",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:30:00.000Z",
|
||||
updatedAt: "2026-02-26T12:30:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-stale-approval-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:01.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-approval"),
|
||||
projectId: ProjectId.make("project-stale-approval"),
|
||||
title: "Thread Stale Approval",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:30:01.000Z",
|
||||
updatedAt: "2026-02-26T12:30:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-stale-approval-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:02.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-stale-approval-requested"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: {
|
||||
requestId: "approval-request-stale-1",
|
||||
requestKind: "command",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:30:02.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-stale-approval-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-approval"),
|
||||
occurredAt: "2026-02-26T12:30:03.000Z",
|
||||
commandId: CommandId.make("cmd-stale-approval-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-approval-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-stale-approval-failed"),
|
||||
tone: "error",
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
payload: {
|
||||
requestId: "approval-request-stale-1",
|
||||
detail: "Unknown pending permission request: approval-request-stale-1",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:30:03.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly requestId: string;
|
||||
readonly status: string;
|
||||
readonly resolvedAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
request_id AS "requestId",
|
||||
status,
|
||||
resolved_at AS "resolvedAt"
|
||||
FROM projection_pending_approvals
|
||||
WHERE request_id = 'approval-request-stale-1'
|
||||
`;
|
||||
assert.deepEqual(approvalRows, [
|
||||
{
|
||||
requestId: "approval-request-stale-1",
|
||||
status: "resolved",
|
||||
resolvedAt: "2026-02-26T12:30:03.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly pendingApprovalCount: number;
|
||||
}>`
|
||||
SELECT pending_approval_count AS "pendingApprovalCount"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-stale-approval'
|
||||
`;
|
||||
assert.deepEqual(threadRows, [{ pendingApprovalCount: 0 }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores non-stale provider approval response failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-nonstale-approval-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make("project-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:00.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make("project-nonstale-approval"),
|
||||
title: "Project Non-Stale Approval",
|
||||
workspaceRoot: "/tmp/project-nonstale-approval",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:45:00.000Z",
|
||||
updatedAt: "2026-02-26T12:45:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-nonstale-approval-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:01.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
projectId: ProjectId.make("project-nonstale-approval"),
|
||||
title: "Thread Non-Stale Approval",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:45:01.000Z",
|
||||
updatedAt: "2026-02-26T12:45:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-nonstale-approval-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:02.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-nonstale-approval-requested"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: {
|
||||
requestId: "approval-request-nonstale-existing",
|
||||
requestKind: "command",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:45:02.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-nonstale-approval-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:03.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-nonstale-approval-failed-existing"),
|
||||
tone: "error",
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
payload: {
|
||||
requestId: "approval-request-nonstale-existing",
|
||||
detail: "Provider timed out while responding to approval request",
|
||||
},
|
||||
turnId: TurnId.make("turn-nonstale-failure"),
|
||||
createdAt: "2026-02-26T12:45:03.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-nonstale-approval-5"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-nonstale-approval"),
|
||||
occurredAt: "2026-02-26T12:45:04.000Z",
|
||||
commandId: CommandId.make("cmd-nonstale-approval-5"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-nonstale-approval-5"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-nonstale-approval"),
|
||||
activity: {
|
||||
id: EventId.make("activity-nonstale-approval-failed-missing"),
|
||||
tone: "error",
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
payload: {
|
||||
requestId: "approval-request-nonstale-missing",
|
||||
detail: "Provider timed out while responding to approval request",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:45:04.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly requestId: string;
|
||||
readonly status: string;
|
||||
readonly turnId: string | null;
|
||||
readonly createdAt: string;
|
||||
readonly resolvedAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
request_id AS "requestId",
|
||||
status,
|
||||
turn_id AS "turnId",
|
||||
created_at AS "createdAt",
|
||||
resolved_at AS "resolvedAt"
|
||||
FROM projection_pending_approvals
|
||||
WHERE request_id IN (
|
||||
'approval-request-nonstale-existing',
|
||||
'approval-request-nonstale-missing'
|
||||
)
|
||||
ORDER BY request_id
|
||||
`;
|
||||
assert.deepEqual(approvalRows, [
|
||||
{
|
||||
requestId: "approval-request-nonstale-existing",
|
||||
status: "pending",
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:45:02.000Z",
|
||||
resolvedAt: null,
|
||||
},
|
||||
]);
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly pendingApprovalCount: number;
|
||||
}>`
|
||||
SELECT pending_approval_count AS "pendingApprovalCount"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-nonstale-approval'
|
||||
`;
|
||||
assert.deepEqual(threadRows, [{ pendingApprovalCount: 1 }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not fallback-retain messages whose turnId is removed by revert", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
|
||||
@@ -90,6 +90,17 @@ function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||
return typeof requestId === "string" ? ApprovalRequestId.make(requestId) : null;
|
||||
}
|
||||
|
||||
function isStalePendingApprovalFailureDetail(detail: string | null): boolean {
|
||||
if (detail === null) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
detail.includes("stale pending approval request") ||
|
||||
detail.includes("unknown pending approval request") ||
|
||||
detail.includes("unknown pending permission request")
|
||||
);
|
||||
}
|
||||
|
||||
function derivePendingUserInputCountFromActivities(
|
||||
activities: ReadonlyArray<ProjectionThreadActivity>,
|
||||
): number {
|
||||
@@ -1245,6 +1256,42 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.payload.activity.kind === "provider.approval.respond.failed") {
|
||||
const payload =
|
||||
typeof event.payload.activity.payload === "object" &&
|
||||
event.payload.activity.payload !== null
|
||||
? (event.payload.activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const detail =
|
||||
typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
if (isStalePendingApprovalFailureDetail(detail)) {
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
if (existingRow.value.status === "resolved") {
|
||||
return;
|
||||
}
|
||||
yield* projectionPendingApprovalRepository.upsert({
|
||||
requestId,
|
||||
threadId: existingRow.value.threadId,
|
||||
turnId: existingRow.value.turnId,
|
||||
status: "resolved",
|
||||
decision: null,
|
||||
createdAt: existingRow.value.createdAt,
|
||||
resolvedAt: event.payload.activity.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,10 @@ import {
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
@@ -177,6 +181,24 @@ describe("ProviderCommandReactor", () => {
|
||||
: "renamed-branch",
|
||||
}),
|
||||
);
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "renamed-branch",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
);
|
||||
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>((_) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
@@ -225,6 +247,15 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(GitStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.die("refreshLocalStatus should not be called in this test"),
|
||||
refreshStatus,
|
||||
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
|
||||
} satisfies GitStatusBroadcasterShape),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(TextGeneration, {
|
||||
generateBranchName,
|
||||
@@ -279,6 +310,7 @@ describe("ProviderCommandReactor", () => {
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
renameBranch,
|
||||
refreshStatus,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
stateDir,
|
||||
@@ -513,9 +545,11 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await waitFor(() => harness.refreshStatus.mock.calls.length === 1);
|
||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({
|
||||
message: "Add a safer reconnect backoff.",
|
||||
});
|
||||
expect(harness.refreshStatus.mock.calls[0]?.[0]).toBe("/tmp/provider-project-worktree");
|
||||
});
|
||||
|
||||
it("forwards codex model options through session start and turn send", async () => {
|
||||
@@ -1241,6 +1275,61 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("starts a fresh session when only projected session state exists", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-stale"),
|
||||
role: "user",
|
||||
text: "resume codex",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
});
|
||||
|
||||
it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -11,11 +11,13 @@ import {
|
||||
type RuntimeMode,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git";
|
||||
import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
|
||||
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
|
||||
@@ -72,8 +74,6 @@ const serverCommandId = (tag: string): CommandId =>
|
||||
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
const DEFAULT_THREAD_TITLE = "New thread";
|
||||
|
||||
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
|
||||
@@ -119,10 +119,6 @@ function stalePendingRequestDetail(
|
||||
return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
|
||||
}
|
||||
|
||||
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||
}
|
||||
|
||||
function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
@@ -150,6 +146,7 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const git = yield* GitCore;
|
||||
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||
@@ -290,14 +287,14 @@ const make = Effect.gen(function* () {
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const activeSession = yield* resolveActiveSession(threadId);
|
||||
const existingSessionThreadId =
|
||||
thread.session && thread.session.status !== "stopped" ? thread.id : null;
|
||||
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
@@ -452,6 +449,7 @@ const make = Effect.gen(function* () {
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
});
|
||||
yield* gitStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
||||
|
||||
@@ -465,6 +465,7 @@ 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,
|
||||
|
||||
@@ -28,10 +28,31 @@ 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* normalizeProjectWorkspaceRoot(command.workspaceRoot),
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(
|
||||
command.workspaceRoot,
|
||||
command.createWorkspaceRootIfMissing,
|
||||
),
|
||||
createWorkspaceRootIfMissing: command.createWorkspaceRootIfMissing === true,
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ describe("fixPath", () => {
|
||||
it("hydrates PATH on linux using the resolved login shell", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
};
|
||||
const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
|
||||
@@ -17,6 +17,39 @@ describe("fixPath", () => {
|
||||
});
|
||||
|
||||
expect(readPath).toHaveBeenCalledWith("/bin/zsh");
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
});
|
||||
|
||||
it("falls back to launchctl PATH on macOS when shell probing fails", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/opt/homebrew/bin/nu",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readPath = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error("unknown flag");
|
||||
})
|
||||
.mockImplementationOnce(() => undefined);
|
||||
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
const logWarning = vi.fn();
|
||||
|
||||
fixPath({
|
||||
env,
|
||||
platform: "darwin",
|
||||
readPath,
|
||||
readLaunchctlPath,
|
||||
userShell: "/bin/zsh",
|
||||
logWarning,
|
||||
});
|
||||
|
||||
expect(readPath).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu");
|
||||
expect(readPath).toHaveBeenNthCalledWith(2, "/bin/zsh");
|
||||
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
|
||||
expect(logWarning).toHaveBeenCalledWith(
|
||||
"Failed to read PATH from login shell /opt/homebrew/bin/nu.",
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
|
||||
@@ -1,28 +1,57 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell";
|
||||
import {
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readPathFromLoginShell,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
function logPathHydrationWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[server] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
|
||||
export function fixPath(
|
||||
options: {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
platform?: NodeJS.Platform;
|
||||
readPath?: typeof readPathFromLoginShell;
|
||||
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 {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
const result = (options.readPath ?? readPathFromLoginShell)(shell);
|
||||
if (result) {
|
||||
env.PATH = result;
|
||||
let shellPath: string | undefined;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
shellPath = readPath(shell);
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read PATH from login shell ${shell}.`, error);
|
||||
}
|
||||
|
||||
if (shellPath) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore — keep default PATH
|
||||
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellPath
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to hydrate PATH from the user environment.", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ import Migration0020 from "./Migrations/020_AuthAccessManagement.ts";
|
||||
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";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -71,6 +72,7 @@ export const migrationEntries = [
|
||||
[21, "AuthSessionClientMetadata", Migration0021],
|
||||
[22, "AuthSessionLastConnectedAt", Migration0022],
|
||||
[23, "ProjectionThreadShellSummary", Migration0023],
|
||||
[24, "BackfillProjectionThreadShellSummary", Migration0024],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
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("024_BackfillProjectionThreadShellSummary", (it) => {
|
||||
it.effect("backfills thread shell summary fields and clears stale projected approvals", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 23 });
|
||||
|
||||
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-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'approval-required',
|
||||
'plan',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'message-user-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'user',
|
||||
'Need help',
|
||||
NULL,
|
||||
0,
|
||||
'2026-02-24T00:01:00.000Z',
|
||||
'2026-02-24T00:01:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
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-1',
|
||||
'turn-1',
|
||||
'approval',
|
||||
'approval.requested',
|
||||
'Command approval requested',
|
||||
'{"requestId":"approval-1","requestKind":"command"}',
|
||||
NULL,
|
||||
'2026-02-24T00:02:00.000Z'
|
||||
),
|
||||
(
|
||||
'activity-approval-stale',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'error',
|
||||
'provider.approval.respond.failed',
|
||||
'Provider approval response failed',
|
||||
'{"requestId":"approval-1","detail":"Unknown pending permission request: approval-1"}',
|
||||
NULL,
|
||||
'2026-02-24T00:03:00.000Z'
|
||||
),
|
||||
(
|
||||
'activity-user-input-requested',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'info',
|
||||
'user-input.requested',
|
||||
'User input requested',
|
||||
'{"requestId":"input-1","questions":[{"id":"area","header":"Area","question":"Which repo area should I inspect next?","options":[{"label":"Server","description":"Server orchestration."}]}]}',
|
||||
NULL,
|
||||
'2026-02-24T00:04:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_proposed_plans (
|
||||
plan_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
plan_markdown,
|
||||
implemented_at,
|
||||
implementation_thread_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'plan-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'# Do the thing',
|
||||
NULL,
|
||||
NULL,
|
||||
'2026-02-24T00:05:00.000Z',
|
||||
'2026-02-24T00:05:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_pending_approvals (
|
||||
request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
status,
|
||||
decision,
|
||||
created_at,
|
||||
resolved_at
|
||||
)
|
||||
VALUES (
|
||||
'approval-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'pending',
|
||||
NULL,
|
||||
'2026-02-24T00:02:00.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 24 });
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly latestUserMessageAt: string | null;
|
||||
readonly pendingApprovalCount: number;
|
||||
readonly pendingUserInputCount: number;
|
||||
readonly hasActionableProposedPlan: number;
|
||||
}>`
|
||||
SELECT
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-1'
|
||||
`;
|
||||
assert.deepStrictEqual(threadRows, [
|
||||
{
|
||||
latestUserMessageAt: "2026-02-24T00:01:00.000Z",
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 1,
|
||||
hasActionableProposedPlan: 1,
|
||||
},
|
||||
]);
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly status: string;
|
||||
readonly resolvedAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
status,
|
||||
resolved_at AS "resolvedAt"
|
||||
FROM projection_pending_approvals
|
||||
WHERE request_id = 'approval-1'
|
||||
`;
|
||||
assert.deepStrictEqual(approvalRows, [
|
||||
{
|
||||
status: "resolved",
|
||||
resolvedAt: "2026-02-24T00:03:00.000Z",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
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`
|
||||
INSERT OR IGNORE INTO projection_pending_approvals (
|
||||
request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
status,
|
||||
decision,
|
||||
created_at,
|
||||
resolved_at
|
||||
)
|
||||
SELECT
|
||||
requested.request_id,
|
||||
requested.thread_id,
|
||||
requested.turn_id,
|
||||
'pending',
|
||||
NULL,
|
||||
requested.created_at,
|
||||
NULL
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
created_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at ASC, activity_id ASC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'approval.requested'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS requested
|
||||
WHERE requested.row_number = 1
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_resolutions AS (
|
||||
SELECT
|
||||
resolved.request_id,
|
||||
resolved.resolved_at,
|
||||
resolved.decision
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
created_at AS resolved_at,
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.decision') IN (
|
||||
'accept',
|
||||
'acceptForSession',
|
||||
'decline',
|
||||
'cancel'
|
||||
)
|
||||
THEN json_extract(payload_json, '$.decision')
|
||||
ELSE NULL
|
||||
END AS decision,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at DESC, activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'approval.resolved'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS resolved
|
||||
WHERE resolved.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = (
|
||||
SELECT latest_resolutions.decision
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
),
|
||||
resolved_at = (
|
||||
SELECT latest_resolutions.resolved_at
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_response_events AS (
|
||||
SELECT
|
||||
response.request_id,
|
||||
response.resolved_at,
|
||||
response.decision
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
occurred_at AS resolved_at,
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.decision') IN (
|
||||
'accept',
|
||||
'acceptForSession',
|
||||
'decline',
|
||||
'cancel'
|
||||
)
|
||||
THEN json_extract(payload_json, '$.decision')
|
||||
ELSE NULL
|
||||
END AS decision,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY occurred_at DESC, sequence DESC
|
||||
) AS row_number
|
||||
FROM orchestration_events
|
||||
WHERE event_type = 'thread.approval-response-requested'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS response
|
||||
WHERE response.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = (
|
||||
SELECT latest_response_events.decision
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
),
|
||||
resolved_at = (
|
||||
SELECT latest_response_events.resolved_at
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_stale_failures AS (
|
||||
SELECT
|
||||
failure.request_id,
|
||||
failure.resolved_at
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
created_at AS resolved_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at DESC, activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'provider.approval.respond.failed'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
AND (
|
||||
lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%stale pending approval request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending approval request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending permission request%'
|
||||
)
|
||||
) AS failure
|
||||
WHERE failure.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = NULL,
|
||||
resolved_at = (
|
||||
SELECT latest_stale_failures.resolved_at
|
||||
FROM latest_stale_failures
|
||||
WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE status = 'pending'
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_stale_failures
|
||||
WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET
|
||||
latest_user_message_at = (
|
||||
SELECT MAX(message.created_at)
|
||||
FROM projection_thread_messages AS message
|
||||
WHERE message.thread_id = projection_threads.thread_id
|
||||
AND message.role = 'user'
|
||||
),
|
||||
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),
|
||||
pending_user_input_count = COALESCE((
|
||||
WITH latest_user_input_states AS (
|
||||
SELECT
|
||||
latest.request_id,
|
||||
latest.kind,
|
||||
latest.detail
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(activity.payload_json, '$.requestId') AS request_id,
|
||||
activity.kind,
|
||||
lower(COALESCE(json_extract(activity.payload_json, '$.detail'), '')) AS detail,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(activity.payload_json, '$.requestId')
|
||||
ORDER BY activity.created_at DESC, activity.activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities AS activity
|
||||
WHERE activity.thread_id = projection_threads.thread_id
|
||||
AND json_extract(activity.payload_json, '$.requestId') IS NOT NULL
|
||||
AND activity.kind IN (
|
||||
'user-input.requested',
|
||||
'user-input.resolved',
|
||||
'provider.user-input.respond.failed'
|
||||
)
|
||||
) AS latest
|
||||
WHERE latest.row_number = 1
|
||||
)
|
||||
SELECT COUNT(*)
|
||||
FROM latest_user_input_states
|
||||
WHERE latest_user_input_states.kind = 'user-input.requested'
|
||||
OR (
|
||||
latest_user_input_states.kind = 'provider.user-input.respond.failed'
|
||||
AND latest_user_input_states.detail NOT LIKE '%stale pending user-input request%'
|
||||
AND latest_user_input_states.detail NOT LIKE '%unknown pending user-input request%'
|
||||
)
|
||||
), 0),
|
||||
has_actionable_proposed_plan = COALESCE((
|
||||
SELECT CASE
|
||||
WHEN projection_threads.latest_turn_id IS NOT NULL
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_proposed_plans AS latest_turn_plan_exists
|
||||
WHERE latest_turn_plan_exists.thread_id = projection_threads.thread_id
|
||||
AND latest_turn_plan_exists.turn_id = projection_threads.latest_turn_id
|
||||
)
|
||||
THEN CASE
|
||||
WHEN (
|
||||
SELECT latest_turn_plan.implemented_at
|
||||
FROM projection_thread_proposed_plans AS latest_turn_plan
|
||||
WHERE latest_turn_plan.thread_id = projection_threads.thread_id
|
||||
AND latest_turn_plan.turn_id = projection_threads.latest_turn_id
|
||||
ORDER BY latest_turn_plan.updated_at DESC, latest_turn_plan.plan_id DESC
|
||||
LIMIT 1
|
||||
) IS NULL
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END
|
||||
WHEN EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_proposed_plans AS any_plan
|
||||
WHERE any_plan.thread_id = projection_threads.thread_id
|
||||
)
|
||||
THEN CASE
|
||||
WHEN (
|
||||
SELECT latest_plan.implemented_at
|
||||
FROM projection_thread_proposed_plans AS latest_plan
|
||||
WHERE latest_plan.thread_id = projection_threads.thread_id
|
||||
ORDER BY latest_plan.updated_at DESC, latest_plan.plan_id DESC
|
||||
LIMIT 1
|
||||
) IS NULL
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END
|
||||
ELSE 0
|
||||
END
|
||||
), 0)
|
||||
`;
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
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";
|
||||
@@ -10,6 +12,10 @@ 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]));
|
||||
|
||||
@@ -41,6 +47,7 @@ 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");
|
||||
@@ -48,6 +55,27 @@ 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;
|
||||
@@ -112,7 +140,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"refreshes cached null identities after the negative TTL when a remote is configured later",
|
||||
"keeps null identities cached across repeated resolves until the negative TTL expires",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -128,8 +156,10 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
|
||||
|
||||
yield* git(cwd, ["remote", "add", "origin", "[email protected]:T3Tools/t3code.git"]);
|
||||
|
||||
const cachedIdentity = yield* resolver.resolve(cwd);
|
||||
expect(cachedIdentity).toBeNull();
|
||||
for (const _attempt of [1, 2, 3]) {
|
||||
const cachedIdentity = yield* resolver.resolve(cwd);
|
||||
expect(cachedIdentity).toBeNull();
|
||||
}
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(120));
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ 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);
|
||||
@@ -57,6 +58,7 @@ function buildRepositoryIdentity(input: {
|
||||
remoteName: input.remoteName,
|
||||
remoteUrl: input.remoteUrl,
|
||||
},
|
||||
rootPath: input.rootPath,
|
||||
...(repositoryPath ? { displayName: repositoryPath } : {}),
|
||||
...(hostingProvider ? { provider: hostingProvider.kind } : {}),
|
||||
...(owner ? { owner } : {}),
|
||||
@@ -66,7 +68,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.seconds(10);
|
||||
const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
|
||||
|
||||
interface RepositoryIdentityResolverOptions {
|
||||
readonly cacheCapacity?: number;
|
||||
@@ -108,7 +110,7 @@ async function resolveRepositoryIdentityFromCacheKey(
|
||||
}
|
||||
|
||||
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.stdout));
|
||||
return remote ? buildRepositoryIdentity(remote) : null;
|
||||
return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -351,6 +351,53 @@ 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* () {
|
||||
@@ -966,6 +1013,97 @@ 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* () {
|
||||
@@ -1169,6 +1307,71 @@ 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.
|
||||
|
||||
@@ -18,8 +18,8 @@ import {
|
||||
type SettingSource,
|
||||
type SDKUserMessage,
|
||||
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,
|
||||
ClaudeCodeEffort,
|
||||
ClaudeAgentEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
@@ -84,6 +84,7 @@ type ClaudeToolResultStreamKind = Extract<
|
||||
RuntimeContentStreamKind,
|
||||
"command_output" | "file_change_output"
|
||||
>;
|
||||
type ClaudeSdkEffort = NonNullable<ClaudeQueryOptions["effort"]>;
|
||||
|
||||
type PromptQueueItem =
|
||||
| {
|
||||
@@ -215,13 +216,19 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray
|
||||
return squashed.length > 0 ? [squashed] : [];
|
||||
}
|
||||
|
||||
function getEffectiveClaudeCodeEffort(
|
||||
effort: ClaudeCodeEffort | null | undefined,
|
||||
): Exclude<ClaudeCodeEffort, "ultrathink"> | null {
|
||||
function getEffectiveClaudeAgentEffort(
|
||||
effort: ClaudeAgentEffort | null | undefined,
|
||||
): ClaudeSdkEffort | null {
|
||||
if (!effort) {
|
||||
return null;
|
||||
}
|
||||
return effort === "ultrathink" ? null : effort;
|
||||
if (effort === "ultrathink") {
|
||||
return null;
|
||||
}
|
||||
if (effort === "xhigh") {
|
||||
return "max";
|
||||
}
|
||||
return effort;
|
||||
}
|
||||
|
||||
function isClaudeInterruptedMessage(message: string): boolean {
|
||||
@@ -289,7 +296,7 @@ function maxClaudeContextWindowFromModelUsage(
|
||||
}
|
||||
|
||||
function normalizeClaudeTokenUsage(
|
||||
value: NonNullableUsage | undefined,
|
||||
value: unknown,
|
||||
contextWindow?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
@@ -459,6 +466,37 @@ 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;
|
||||
@@ -466,6 +504,20 @@ 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}`;
|
||||
@@ -924,7 +976,11 @@ 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>();
|
||||
@@ -963,7 +1019,11 @@ 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,
|
||||
},
|
||||
@@ -1352,7 +1412,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? { totalProcessedTokens: accumulatedTotalProcessedTokens }
|
||||
? {
|
||||
totalProcessedTokens: accumulatedTotalProcessedTokens,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: accumulatedSnapshot;
|
||||
@@ -1416,7 +1478,9 @@ 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",
|
||||
@@ -1538,7 +1602,9 @@ 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,
|
||||
@@ -1597,7 +1663,11 @@ 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,
|
||||
@@ -1609,13 +1679,39 @@ 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;
|
||||
}
|
||||
@@ -1678,7 +1774,9 @@ 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",
|
||||
@@ -1750,7 +1848,9 @@ 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",
|
||||
@@ -1773,7 +1873,9 @@ 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",
|
||||
@@ -1798,7 +1900,9 @@ 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",
|
||||
@@ -2154,7 +2258,9 @@ 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,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
@@ -2371,6 +2477,27 @@ 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;
|
||||
@@ -2406,7 +2533,10 @@ 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);
|
||||
|
||||
@@ -2442,7 +2572,11 @@ 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, {
|
||||
@@ -2451,7 +2585,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
raw: {
|
||||
source: "claude.sdk.permission",
|
||||
method: "canUseTool/AskUserQuestion",
|
||||
payload: { toolName: "AskUserQuestion", input: toolInput },
|
||||
payload: {
|
||||
toolName: "AskUserQuestion",
|
||||
input: toolInput,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2466,7 +2603,9 @@ 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);
|
||||
@@ -2480,7 +2619,11 @@ 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, {
|
||||
@@ -2650,7 +2793,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
behavior: "allow",
|
||||
updatedInput: toolInput,
|
||||
...(decision === "acceptForSession" && pendingApproval.suggestions
|
||||
? { updatedPermissions: [...pendingApproval.suggestions] }
|
||||
? {
|
||||
updatedPermissions: [...pendingApproval.suggestions],
|
||||
}
|
||||
: {}),
|
||||
} satisfies PermissionResult;
|
||||
}
|
||||
@@ -2680,18 +2825,19 @@ 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 ClaudeCodeEffort | null;
|
||||
null) as ClaudeAgentEffort | null;
|
||||
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
|
||||
const thinking =
|
||||
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
|
||||
? modelSelection.options.thinking
|
||||
: undefined;
|
||||
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
|
||||
const effectiveEffort = getEffectiveClaudeAgentEffort(effort);
|
||||
const runtimeModeToPermission: Record<string, PermissionMode> = {
|
||||
"auto-accept-edits": "acceptEdits",
|
||||
"full-access": "bypassPermissions",
|
||||
@@ -2719,6 +2865,7 @@ 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({
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
} from "../providerSnapshot";
|
||||
import { compareCliVersions } from "../cliVersion";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
import { ClaudeProvider } from "../Services/ClaudeProvider";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
@@ -40,7 +41,30 @@ 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",
|
||||
@@ -96,6 +120,24 @@ 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 (
|
||||
@@ -484,7 +526,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
const allModels = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
claudeSettings.customModels,
|
||||
@@ -496,7 +538,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
models: allModels,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
@@ -518,7 +560,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
models: allModels,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
@@ -536,7 +578,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
models: allModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
@@ -556,7 +598,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
models: allModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
@@ -569,6 +611,16 @@ 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(
|
||||
@@ -658,11 +710,55 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
...parsed.auth,
|
||||
...(authMetadata ? authMetadata : {}),
|
||||
},
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
...(parsed.message
|
||||
? { message: parsed.message }
|
||||
: opus47UpgradeMessage
|
||||
? { message: opus47UpgradeMessage }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvider => {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Claude provider status has not been checked in this session yet.",
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const ClaudeProviderLive = Layer.effect(
|
||||
ClaudeProvider,
|
||||
Effect.gen(function* () {
|
||||
@@ -698,6 +794,7 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
Stream.map((settings) => settings.providers.claudeAgent),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingClaudeProvider,
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -146,6 +146,7 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
remove: () => Effect.void,
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
const validationManager = new FakeCodexManager();
|
||||
|
||||
@@ -552,6 +552,46 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
});
|
||||
});
|
||||
|
||||
const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
codexSettings.customModels,
|
||||
DEFAULT_CODEX_MODEL_CAPABILITIES,
|
||||
);
|
||||
|
||||
if (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex provider status has not been checked in this session yet.",
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const CodexProviderLive = Layer.effect(
|
||||
CodexProvider,
|
||||
Effect.gen(function* () {
|
||||
@@ -602,6 +642,7 @@ export const CodexProviderLive = Layer.effect(
|
||||
Stream.map((settings) => settings.providers.codex),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingCodexProvider,
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} 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";
|
||||
|
||||
@@ -562,6 +563,61 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
|
||||
});
|
||||
|
||||
it.effect("does not probe provider health during registry startup", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnCount = 0;
|
||||
const serverSettings = yield* makeMutableServerSettingsService();
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
spawnCount += 1;
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") {
|
||||
if (command === "codex") {
|
||||
return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
}
|
||||
return { stdout: "claude 1.0.0\n", stderr: "", code: 0 };
|
||||
}
|
||||
if (joined === "login status") {
|
||||
return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
}
|
||||
if (joined === "auth status") {
|
||||
return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${command} ${joined}`);
|
||||
}),
|
||||
),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ServerSettingsService, serverSettings),
|
||||
providerRegistryLayer,
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
assert.deepStrictEqual(yield* registry.getProviders, []);
|
||||
assert.strictEqual(spawnCount, 0);
|
||||
|
||||
const refreshed = yield* registry.refresh("codex");
|
||||
assert.strictEqual(spawnCount > 0, true);
|
||||
assert.strictEqual(
|
||||
refreshed.find((provider) => provider.provider === "codex")?.status,
|
||||
"ready",
|
||||
);
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reruns codex health when codex provider settings change", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* makeMutableServerSettingsService();
|
||||
@@ -569,6 +625,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
const joined = args.join(" ");
|
||||
@@ -596,8 +657,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
const registry = yield* ProviderRegistry;
|
||||
|
||||
const initial = yield* registry.getProviders;
|
||||
assert.deepStrictEqual(initial, []);
|
||||
|
||||
const refreshed = yield* registry.refresh("codex");
|
||||
assert.strictEqual(
|
||||
initial.find((status) => status.provider === "codex")?.status,
|
||||
refreshed.find((status) => status.provider === "codex")?.status,
|
||||
"ready",
|
||||
);
|
||||
|
||||
@@ -909,6 +973,69 @@ 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"));
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
* @module ProviderRegistryLive
|
||||
*/
|
||||
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
|
||||
import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config";
|
||||
import { ClaudeProviderLive } from "./ClaudeProvider";
|
||||
import { CodexProviderLive } from "./CodexProvider";
|
||||
import type { ClaudeProviderShape } from "../Services/ClaudeProvider";
|
||||
@@ -13,6 +14,14 @@ 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,
|
||||
orderProviderSnapshots,
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache";
|
||||
|
||||
const loadProviders = (
|
||||
codexProvider: CodexProviderShape,
|
||||
@@ -32,61 +41,152 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
Effect.gen(function* () {
|
||||
const codexProvider = yield* CodexProvider;
|
||||
const claudeProvider = yield* ClaudeProvider;
|
||||
const config = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
yield* loadProviders(codexProvider, claudeProvider),
|
||||
const fallbackProviders = yield* loadProviders(codexProvider, claudeProvider);
|
||||
const cachePathByProvider = new Map(
|
||||
PROVIDER_CACHE_IDS.map(
|
||||
(provider) =>
|
||||
[
|
||||
provider,
|
||||
resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
provider,
|
||||
}),
|
||||
] as const,
|
||||
),
|
||||
);
|
||||
const fallbackByProvider = new Map(
|
||||
fallbackProviders.map((provider) => [provider.provider, provider] as const),
|
||||
);
|
||||
const cachedProviders = yield* Effect.forEach(
|
||||
PROVIDER_CACHE_IDS,
|
||||
(provider) => {
|
||||
const filePath = cachePathByProvider.get(provider)!;
|
||||
const fallbackProvider = fallbackByProvider.get(provider)!;
|
||||
return readProviderStatusCache(filePath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.map((cachedProvider) =>
|
||||
cachedProvider === undefined
|
||||
? undefined
|
||||
: hydrateCachedProvider({
|
||||
cachedProvider,
|
||||
fallbackProvider,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.map((providers) =>
|
||||
orderProviderSnapshots(
|
||||
providers.filter((provider): provider is ServerProvider => provider !== undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
|
||||
const syncProviders = Effect.fn("syncProviders")(function* (options?: {
|
||||
readonly publish?: boolean;
|
||||
}) {
|
||||
const previousProviders = yield* Ref.get(providersRef);
|
||||
const providers = yield* loadProviders(codexProvider, claudeProvider);
|
||||
yield* Ref.set(providersRef, providers);
|
||||
const persistProvider = (provider: ServerProvider) =>
|
||||
writeProviderStatusCache({
|
||||
filePath: cachePathByProvider.get(provider.provider)!,
|
||||
provider,
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.ignore,
|
||||
);
|
||||
|
||||
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [provider.provider, provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(provider.provider, provider);
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* Effect.forEach(nextProviders, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
if (options?.publish !== false) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
const syncProvider = Effect.fn("syncProvider")(function* (
|
||||
provider: ServerProvider,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
|
||||
switch (provider) {
|
||||
case "codex":
|
||||
yield* codexProvider.refresh;
|
||||
break;
|
||||
return yield* codexProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
case "claudeAgent":
|
||||
yield* claudeProvider.refresh;
|
||||
break;
|
||||
return yield* claudeProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
default:
|
||||
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
break;
|
||||
return yield* Effect.all(
|
||||
[
|
||||
codexProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
),
|
||||
claudeProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
),
|
||||
],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.andThen(Ref.get(providersRef)));
|
||||
}
|
||||
return yield* syncProviders();
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, (provider) =>
|
||||
syncProvider(provider),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, (provider) =>
|
||||
syncProvider(provider),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return {
|
||||
getProviders: syncProviders({ publish: false }).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: (provider?: ProviderKind) =>
|
||||
refresh(provider).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
Effect.orElseSucceed(() => [] as ReadonlyArray<ServerProvider>),
|
||||
),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
|
||||
@@ -654,6 +654,43 @@ 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,6 +297,40 @@ 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({
|
||||
@@ -351,6 +385,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
);
|
||||
}
|
||||
|
||||
yield* stopStaleSessionsForThread({
|
||||
threadId,
|
||||
currentProvider: adapter.provider,
|
||||
});
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
@@ -133,6 +133,78 @@ 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,11 +1,13 @@
|
||||
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";
|
||||
|
||||
@@ -50,6 +52,27 @@ 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;
|
||||
|
||||
@@ -60,18 +83,8 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
Option.match(runtime, {
|
||||
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
|
||||
onSome: (value) =>
|
||||
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,
|
||||
}),
|
||||
),
|
||||
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
|
||||
Effect.map((binding) => Option.some(binding)),
|
||||
),
|
||||
}),
|
||||
),
|
||||
@@ -145,12 +158,25 @@ 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;
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
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,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
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();
|
||||
@@ -22,6 +22,10 @@ export interface ProviderRuntimeBinding {
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
}
|
||||
|
||||
export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {
|
||||
readonly lastSeenAt: string;
|
||||
}
|
||||
|
||||
export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
export type ProviderSessionDirectoryWriteError =
|
||||
@@ -49,6 +53,11 @@ export interface ProviderSessionDirectoryShape {
|
||||
ReadonlyArray<ThreadId>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
|
||||
readonly listBindings: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
}
|
||||
|
||||
export class ProviderSessionDirectory extends Context.Service<
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
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") {}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import { compareCliVersions, normalizeCliVersion } from "./cliVersion";
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
interface ParsedCliSemver {
|
||||
readonly major: number;
|
||||
readonly minor: number;
|
||||
readonly patch: number;
|
||||
readonly prerelease: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const CLI_VERSION_NUMBER_SEGMENT = /^\d+$/;
|
||||
|
||||
export function normalizeCliVersion(version: string): string {
|
||||
const [main, prerelease] = version.trim().split("-", 2);
|
||||
const segments = (main ?? "")
|
||||
.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0);
|
||||
|
||||
if (segments.length === 2) {
|
||||
segments.push("0");
|
||||
}
|
||||
|
||||
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
|
||||
}
|
||||
|
||||
function parseCliSemver(version: string): ParsedCliSemver | null {
|
||||
const normalized = normalizeCliVersion(version);
|
||||
const [main = "", prerelease] = normalized.split("-", 2);
|
||||
const segments = main.split(".");
|
||||
if (segments.length !== 3) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [majorSegment, minorSegment, patchSegment] = segments;
|
||||
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
!CLI_VERSION_NUMBER_SEGMENT.test(majorSegment) ||
|
||||
!CLI_VERSION_NUMBER_SEGMENT.test(minorSegment) ||
|
||||
!CLI_VERSION_NUMBER_SEGMENT.test(patchSegment)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const major = Number.parseInt(majorSegment, 10);
|
||||
const minor = Number.parseInt(minorSegment, 10);
|
||||
const patch = Number.parseInt(patchSegment, 10);
|
||||
if (![major, minor, patch].every(Number.isInteger)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
prerelease:
|
||||
prerelease
|
||||
?.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0) ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function comparePrereleaseIdentifier(left: string, right: string): number {
|
||||
const leftNumeric = /^\d+$/.test(left);
|
||||
const rightNumeric = /^\d+$/.test(right);
|
||||
|
||||
if (leftNumeric && rightNumeric) {
|
||||
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
|
||||
}
|
||||
if (leftNumeric) {
|
||||
return -1;
|
||||
}
|
||||
if (rightNumeric) {
|
||||
return 1;
|
||||
}
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
export function compareCliVersions(left: string, right: string): number {
|
||||
const parsedLeft = parseCliSemver(left);
|
||||
const parsedRight = parseCliSemver(right);
|
||||
if (!parsedLeft || !parsedRight) {
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
if (parsedLeft.major !== parsedRight.major) {
|
||||
return parsedLeft.major - parsedRight.major;
|
||||
}
|
||||
if (parsedLeft.minor !== parsedRight.minor) {
|
||||
return parsedLeft.minor - parsedRight.minor;
|
||||
}
|
||||
if (parsedLeft.patch !== parsedRight.patch) {
|
||||
return parsedLeft.patch - parsedRight.patch;
|
||||
}
|
||||
|
||||
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
if (parsedLeft.prerelease.length === 0) {
|
||||
return 1;
|
||||
}
|
||||
if (parsedRight.prerelease.length === 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const leftIdentifier = parsedLeft.prerelease[index];
|
||||
const rightIdentifier = parsedRight.prerelease[index];
|
||||
if (leftIdentifier === undefined) {
|
||||
return -1;
|
||||
}
|
||||
if (rightIdentifier === undefined) {
|
||||
return 1;
|
||||
}
|
||||
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
|
||||
if (comparison !== 0) {
|
||||
return comparison;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,121 +1,10 @@
|
||||
import { compareCliVersions, normalizeCliVersion } from "./cliVersion";
|
||||
|
||||
const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/;
|
||||
|
||||
export const MINIMUM_CODEX_CLI_VERSION = "0.37.0";
|
||||
|
||||
interface ParsedSemver {
|
||||
readonly major: number;
|
||||
readonly minor: number;
|
||||
readonly patch: number;
|
||||
readonly prerelease: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
function normalizeCodexVersion(version: string): string {
|
||||
const [main, prerelease] = version.trim().split("-", 2);
|
||||
const segments = (main ?? "")
|
||||
.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0);
|
||||
|
||||
if (segments.length === 2) {
|
||||
segments.push("0");
|
||||
}
|
||||
|
||||
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
|
||||
}
|
||||
|
||||
function parseSemver(version: string): ParsedSemver | null {
|
||||
const normalized = normalizeCodexVersion(version);
|
||||
const [main = "", prerelease] = normalized.split("-", 2);
|
||||
const segments = main.split(".");
|
||||
if (segments.length !== 3) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [majorSegment, minorSegment, patchSegment] = segments;
|
||||
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const major = Number.parseInt(majorSegment, 10);
|
||||
const minor = Number.parseInt(minorSegment, 10);
|
||||
const patch = Number.parseInt(patchSegment, 10);
|
||||
if (![major, minor, patch].every(Number.isInteger)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
prerelease:
|
||||
prerelease
|
||||
?.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0) ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function comparePrereleaseIdentifier(left: string, right: string): number {
|
||||
const leftNumeric = /^\d+$/.test(left);
|
||||
const rightNumeric = /^\d+$/.test(right);
|
||||
|
||||
if (leftNumeric && rightNumeric) {
|
||||
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
|
||||
}
|
||||
if (leftNumeric) {
|
||||
return -1;
|
||||
}
|
||||
if (rightNumeric) {
|
||||
return 1;
|
||||
}
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
export function compareCodexCliVersions(left: string, right: string): number {
|
||||
const parsedLeft = parseSemver(left);
|
||||
const parsedRight = parseSemver(right);
|
||||
if (!parsedLeft || !parsedRight) {
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
if (parsedLeft.major !== parsedRight.major) {
|
||||
return parsedLeft.major - parsedRight.major;
|
||||
}
|
||||
if (parsedLeft.minor !== parsedRight.minor) {
|
||||
return parsedLeft.minor - parsedRight.minor;
|
||||
}
|
||||
if (parsedLeft.patch !== parsedRight.patch) {
|
||||
return parsedLeft.patch - parsedRight.patch;
|
||||
}
|
||||
|
||||
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
if (parsedLeft.prerelease.length === 0) {
|
||||
return 1;
|
||||
}
|
||||
if (parsedRight.prerelease.length === 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const leftIdentifier = parsedLeft.prerelease[index];
|
||||
const rightIdentifier = parsedRight.prerelease[index];
|
||||
if (leftIdentifier === undefined) {
|
||||
return -1;
|
||||
}
|
||||
if (rightIdentifier === undefined) {
|
||||
return 1;
|
||||
}
|
||||
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
|
||||
if (comparison !== 0) {
|
||||
return comparison;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
export const compareCodexCliVersions = compareCliVersions;
|
||||
|
||||
export function parseCodexCliVersion(output: string): string | null {
|
||||
const match = CODEX_VERSION_PATTERN.exec(output);
|
||||
@@ -123,12 +12,7 @@ export function parseCodexCliVersion(output: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = parseSemver(match[1]);
|
||||
if (!parsed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeCodexVersion(match[1]);
|
||||
return normalizeCliVersion(match[1]);
|
||||
}
|
||||
|
||||
export function isCodexCliVersionSupported(version: string): boolean {
|
||||
|
||||
@@ -11,6 +11,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
readonly initialSnapshot: (settings: Settings) => ServerProvider;
|
||||
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
@@ -20,7 +21,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const initialSettings = yield* input.getSettings;
|
||||
const initialSnapshot = yield* input.checkProvider;
|
||||
const initialSnapshot = input.initialSnapshot(initialSettings);
|
||||
const snapshotRef = yield* Ref.make(initialSnapshot);
|
||||
const settingsRef = yield* Ref.make(initialSettings);
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem } from "effect";
|
||||
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "./providerStatusCache";
|
||||
|
||||
const makeProvider = (
|
||||
provider: ServerProvider["provider"],
|
||||
overrides?: Partial<ServerProvider>,
|
||||
): ServerProvider => ({
|
||||
provider,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-11T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
it.effect("writes and reads provider status snapshots", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-cache-" });
|
||||
const codexProvider = makeProvider("codex");
|
||||
const claudeProvider = makeProvider("claudeAgent", {
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
});
|
||||
const codexPath = resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
provider: "codex",
|
||||
});
|
||||
const claudePath = resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
yield* writeProviderStatusCache({
|
||||
filePath: codexPath,
|
||||
provider: codexProvider,
|
||||
});
|
||||
yield* writeProviderStatusCache({
|
||||
filePath: claudePath,
|
||||
provider: claudeProvider,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(codexPath), codexProvider);
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(claudePath), claudeProvider);
|
||||
}),
|
||||
);
|
||||
|
||||
it("hydrates cached provider status onto current settings-derived models", () => {
|
||||
const cachedCodex = makeProvider("codex", {
|
||||
checkedAt: "2026-04-10T12:00:00.000Z",
|
||||
models: [],
|
||||
message: "Cached message",
|
||||
skills: [
|
||||
{
|
||||
name: "github:gh-fix-ci",
|
||||
path: "/tmp/skills/gh-fix-ci/SKILL.md",
|
||||
enabled: true,
|
||||
displayName: "CI Debug",
|
||||
},
|
||||
],
|
||||
});
|
||||
const fallbackCodex = makeProvider("codex", {
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
message: "Pending refresh",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(
|
||||
hydrateCachedProvider({
|
||||
cachedProvider: cachedCodex,
|
||||
fallbackProvider: fallbackCodex,
|
||||
}),
|
||||
{
|
||||
...fallbackCodex,
|
||||
installed: cachedCodex.installed,
|
||||
version: cachedCodex.version,
|
||||
status: cachedCodex.status,
|
||||
auth: cachedCodex.auth,
|
||||
checkedAt: cachedCodex.checkedAt,
|
||||
slashCommands: cachedCodex.slashCommands,
|
||||
skills: cachedCodex.skills,
|
||||
message: cachedCodex.message,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores stale cached enabled state when the provider is now disabled", () => {
|
||||
const cachedCodex = makeProvider("codex", {
|
||||
checkedAt: "2026-04-10T12:00:00.000Z",
|
||||
message: "Cached ready status",
|
||||
});
|
||||
const disabledFallback = makeProvider("codex", {
|
||||
enabled: false,
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "disabled",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(
|
||||
hydrateCachedProvider({
|
||||
cachedProvider: cachedCodex,
|
||||
fallbackProvider: disabledFallback,
|
||||
}),
|
||||
disabledFallback,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import * as nodePath from "node:path";
|
||||
import { type ServerProvider, ServerProvider as ServerProviderSchema } from "@t3tools/contracts";
|
||||
import { Cause, Effect, FileSystem, Path, Schema } from "effect";
|
||||
|
||||
export const PROVIDER_CACHE_IDS = ["codex", "claudeAgent"] as const satisfies ReadonlyArray<
|
||||
ServerProvider["provider"]
|
||||
>;
|
||||
|
||||
const decodeProviderStatusCache = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(ServerProviderSchema),
|
||||
);
|
||||
|
||||
const providerOrderRank = (provider: ServerProvider["provider"]): number => {
|
||||
const rank = PROVIDER_CACHE_IDS.indexOf(provider);
|
||||
return rank === -1 ? Number.MAX_SAFE_INTEGER : rank;
|
||||
};
|
||||
|
||||
export const orderProviderSnapshots = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
[...providers].toSorted(
|
||||
(left, right) => providerOrderRank(left.provider) - providerOrderRank(right.provider),
|
||||
);
|
||||
|
||||
export const hydrateCachedProvider = (input: {
|
||||
readonly cachedProvider: ServerProvider;
|
||||
readonly fallbackProvider: ServerProvider;
|
||||
}): ServerProvider => {
|
||||
if (
|
||||
!input.fallbackProvider.enabled ||
|
||||
input.cachedProvider.enabled !== input.fallbackProvider.enabled
|
||||
) {
|
||||
return input.fallbackProvider;
|
||||
}
|
||||
|
||||
const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
|
||||
const hydratedProvider: ServerProvider = {
|
||||
...fallbackWithoutMessage,
|
||||
installed: input.cachedProvider.installed,
|
||||
version: input.cachedProvider.version,
|
||||
status: input.cachedProvider.status,
|
||||
auth: input.cachedProvider.auth,
|
||||
checkedAt: input.cachedProvider.checkedAt,
|
||||
slashCommands: input.cachedProvider.slashCommands,
|
||||
skills: input.cachedProvider.skills,
|
||||
};
|
||||
|
||||
return input.cachedProvider.message
|
||||
? { ...hydratedProvider, message: input.cachedProvider.message }
|
||||
: hydratedProvider;
|
||||
};
|
||||
|
||||
export const resolveProviderStatusCachePath = (input: {
|
||||
readonly cacheDir: string;
|
||||
readonly provider: ServerProvider["provider"];
|
||||
}) => nodePath.join(input.cacheDir, `${input.provider}.json`);
|
||||
|
||||
export const readProviderStatusCache = (filePath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return yield* decodeProviderStatusCache(trimmed).pipe(
|
||||
Effect.matchCauseEffect({
|
||||
onFailure: (cause) =>
|
||||
Effect.logWarning("failed to parse provider status cache, ignoring", {
|
||||
path: filePath,
|
||||
issues: Cause.pretty(cause),
|
||||
}).pipe(Effect.as(undefined)),
|
||||
onSuccess: Effect.succeed,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const writeProviderStatusCache = (input: {
|
||||
readonly filePath: string;
|
||||
readonly provider: ServerProvider;
|
||||
}) => {
|
||||
const tempPath = `${input.filePath}.${process.pid}.${Date.now()}.tmp`;
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const encoded = `${JSON.stringify(input.provider, null, 2)}\n`;
|
||||
|
||||
yield* fs.makeDirectory(path.dirname(input.filePath), { recursive: true });
|
||||
yield* fs.writeFileString(tempPath, encoded);
|
||||
yield* fs.rename(tempPath, input.filePath);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }));
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
+514
-11
@@ -11,6 +11,7 @@ import {
|
||||
KeybindingRule,
|
||||
MessageId,
|
||||
OpenError,
|
||||
type OrchestrationThreadShell,
|
||||
TerminalNotRunningError,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
@@ -58,6 +59,10 @@ import {
|
||||
import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "./git/Services/GitStatusBroadcaster.ts";
|
||||
import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
|
||||
import { Open, type OpenShape } from "./open.ts";
|
||||
import {
|
||||
@@ -162,6 +167,32 @@ const makeDefaultOrchestrationReadModel = () => {
|
||||
};
|
||||
};
|
||||
|
||||
const makeDefaultOrchestrationThreadShell = (
|
||||
overrides: Partial<OrchestrationThreadShell> = {},
|
||||
): OrchestrationThreadShell => {
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
id: defaultThreadId,
|
||||
projectId: defaultProjectId,
|
||||
title: "Default Thread",
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...overrides,
|
||||
};
|
||||
};
|
||||
|
||||
const workspaceAndProjectServicesLayer = Layer.mergeAll(
|
||||
WorkspacePathsLive,
|
||||
WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)),
|
||||
@@ -293,6 +324,7 @@ const buildAppUnderTest = (options?: {
|
||||
open?: Partial<OpenShape>;
|
||||
gitCore?: Partial<GitCoreShape>;
|
||||
gitManager?: Partial<GitManagerShape>;
|
||||
gitStatusBroadcaster?: Partial<GitStatusBroadcasterShape>;
|
||||
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
|
||||
terminalManager?: Partial<TerminalManagerShape>;
|
||||
orchestrationEngine?: Partial<OrchestrationEngineShape>;
|
||||
@@ -341,7 +373,11 @@ const buildAppUnderTest = (options?: {
|
||||
const gitManagerLayer = Layer.mock(GitManager)({
|
||||
...options?.layers?.gitManager,
|
||||
});
|
||||
const gitStatusBroadcasterLayer = GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
|
||||
const gitStatusBroadcasterLayer = options?.layers?.gitStatusBroadcaster
|
||||
? Layer.mock(GitStatusBroadcaster)({
|
||||
...options.layers.gitStatusBroadcaster,
|
||||
})
|
||||
: GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
|
||||
|
||||
const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
|
||||
disableListenLog: true,
|
||||
@@ -1781,7 +1817,20 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () =>
|
||||
Effect.gen(function* () {
|
||||
const providers = [] as const;
|
||||
const providers = [
|
||||
{
|
||||
provider: "codex" as const,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready" as const,
|
||||
auth: { status: "authenticated" as const },
|
||||
checkedAt: "2026-04-11T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const;
|
||||
const changeEvent = {
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
@@ -1838,7 +1887,20 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const providers = [] as const;
|
||||
const nextProviders = [
|
||||
{
|
||||
provider: "codex" as const,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready" as const,
|
||||
auth: { status: "authenticated" as const },
|
||||
checkedAt: "2026-04-11T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
@@ -1851,7 +1913,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
},
|
||||
providerRegistry: {
|
||||
getProviders: Effect.succeed([]),
|
||||
streamChanges: Stream.succeed(providers),
|
||||
streamChanges: Stream.succeed(nextProviders),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -1865,10 +1927,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
const [first, second] = Array.from(events);
|
||||
assert.equal(first?.type, "snapshot");
|
||||
if (first?.type === "snapshot") {
|
||||
assert.deepEqual(first.config.providers, []);
|
||||
}
|
||||
assert.deepEqual(second, {
|
||||
version: 1,
|
||||
type: "providerStatuses",
|
||||
payload: { providers },
|
||||
payload: { providers: nextProviders },
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
@@ -2001,6 +2066,40 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("creates a missing workspace root during websocket project.create dispatch", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const parentDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-create-" });
|
||||
const missingWorkspaceRoot = path.join(parentDir, "nested", "new-project");
|
||||
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-create-missing-root"),
|
||||
projectId: ProjectId.make("project-create-missing-root"),
|
||||
title: "New Project",
|
||||
workspaceRoot: missingWorkspaceRoot,
|
||||
createWorkspaceRootIfMissing: true,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const stat = yield* fs.stat(missingWorkspaceRoot);
|
||||
|
||||
assert.isAtLeast(response.sequence, 0);
|
||||
assert.equal(stat.type, "Directory");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc projects.writeFile errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -2873,21 +2972,48 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("closes thread terminals after a successful archive command", () =>
|
||||
it.effect("stops the provider session and closes thread terminals after archive", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive");
|
||||
const closeInputs: Array<Parameters<TerminalManagerShape["close"]>[0]> = [];
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
closeInputs.push(input);
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: () => Effect.succeed({ sequence: 8 }),
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.succeed(
|
||||
Option.some(
|
||||
makeDefaultOrchestrationThreadShell({
|
||||
id: threadId,
|
||||
updatedAt: now,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -2903,8 +3029,363 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 8);
|
||||
assert.deepEqual(closeInputs, [{ threadId }]);
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, [
|
||||
"dispatch:thread.archive",
|
||||
"dispatch:thread.session.stop",
|
||||
`terminal.close:${threadId}`,
|
||||
]);
|
||||
const sessionStopCommand = dispatchedCommands[1];
|
||||
assert.equal(sessionStopCommand?.type, "thread.session.stop");
|
||||
if (sessionStopCommand?.type === "thread.session.stop") {
|
||||
assert.equal(sessionStopCommand.threadId, threadId);
|
||||
}
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("checks session status before archiving removes the thread from active lookups", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive-precheck");
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const now = new Date().toISOString();
|
||||
let archived = false;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
if (command.type === "thread.archive") {
|
||||
archived = true;
|
||||
}
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`query:thread-shell:${archived ? "archived" : "active"}`);
|
||||
return archived
|
||||
? Option.none()
|
||||
: Option.some(
|
||||
makeDefaultOrchestrationThreadShell({
|
||||
id: threadId,
|
||||
updatedAt: now,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-precheck"),
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, [
|
||||
"query:thread-shell:active",
|
||||
"dispatch:thread.archive",
|
||||
"dispatch:thread.session.stop",
|
||||
`terminal.close:${threadId}`,
|
||||
]);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.archive", "thread.session.stop"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("archives without dispatching session stop when the thread has no session", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive-no-session");
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.succeed(
|
||||
Option.some(makeDefaultOrchestrationThreadShell({ id: threadId, session: null })),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-no-session"),
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, ["dispatch:thread.archive", `terminal.close:${threadId}`]);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.archive"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"archives without dispatching session stop when the thread session is already stopped",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive-stopped-session");
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.succeed(
|
||||
Option.some(
|
||||
makeDefaultOrchestrationThreadShell({
|
||||
id: threadId,
|
||||
updatedAt: now,
|
||||
session: {
|
||||
threadId,
|
||||
status: "stopped",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-stopped-session"),
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, ["dispatch:thread.archive", `terminal.close:${threadId}`]);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.archive"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("archives and still closes terminals when session stop fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive-stop-failure");
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
if (command.type === "thread.session.stop") {
|
||||
return Effect.fail(
|
||||
new OrchestrationListenerCallbackError({
|
||||
listener: "domain-event",
|
||||
detail: "simulated archive stop failure",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed({ sequence: dispatchedCommands.length });
|
||||
},
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.succeed(
|
||||
Option.some(
|
||||
makeDefaultOrchestrationThreadShell({
|
||||
id: threadId,
|
||||
updatedAt: now,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-stop-failure"),
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, [
|
||||
"dispatch:thread.archive",
|
||||
"dispatch:thread.session.stop",
|
||||
`terminal.close:${threadId}`,
|
||||
]);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.archive", "thread.session.stop"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("archives and still closes terminals when session stop defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive-stop-defect");
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
if (command.type === "thread.session.stop") {
|
||||
return Effect.die(new Error("simulated archive stop defect"));
|
||||
}
|
||||
return Effect.succeed({ sequence: dispatchedCommands.length });
|
||||
},
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.succeed(
|
||||
Option.some(
|
||||
makeDefaultOrchestrationThreadShell({
|
||||
id: threadId,
|
||||
updatedAt: now,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-stop-defect"),
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, [
|
||||
"dispatch:thread.archive",
|
||||
"dispatch:thread.session.stop",
|
||||
`terminal.close:${threadId}`,
|
||||
]);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.archive", "thread.session.stop"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -2913,6 +3394,24 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "t3code/bootstrap-branch",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
);
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
@@ -2937,6 +3436,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
gitStatusBroadcaster: {
|
||||
refreshStatus,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
@@ -3014,6 +3516,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
projectCwd: "/tmp/project",
|
||||
worktreePath: "/tmp/bootstrap-worktree",
|
||||
});
|
||||
assert.deepEqual(refreshStatus.mock.calls[0]?.[0], "/tmp/bootstrap-worktree");
|
||||
|
||||
const setupActivities = dispatchedCommands.filter(
|
||||
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
|
||||
|
||||
@@ -23,6 +23,7 @@ import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper";
|
||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
|
||||
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
|
||||
import { GitCoreLive } from "./git/Layers/GitCore";
|
||||
@@ -134,6 +135,10 @@ const CheckpointingLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
);
|
||||
|
||||
const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
|
||||
const ProviderLayerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
@@ -143,9 +148,6 @@ const ProviderLayerLive = Layer.unwrap(
|
||||
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "canonical",
|
||||
});
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const codexAdapterLayer = makeCodexAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
@@ -155,11 +157,14 @@ const ProviderLayerLive = Layer.unwrap(
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
canonicalEventLogger ? { canonicalEventLogger } : undefined,
|
||||
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
||||
).pipe(
|
||||
Layer.provide(adapterRegistryLayer),
|
||||
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -194,12 +199,16 @@ const AuthLayerLive = ServerAuthLive.pipe(
|
||||
Layer.provide(ServerSecretStoreLive),
|
||||
);
|
||||
|
||||
const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
|
||||
Layer.provideMerge(ProviderLayerLive),
|
||||
Layer.provideMerge(OrchestrationLayerLive),
|
||||
);
|
||||
|
||||
const RuntimeDependenciesLive = ReactorLayerLive.pipe(
|
||||
// Core Services
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
Layer.provideMerge(OrchestrationLayerLive),
|
||||
Layer.provideMerge(ProviderLayerLive),
|
||||
Layer.provideMerge(ProviderRuntimeLayerLive),
|
||||
Layer.provideMerge(TerminalLayerLive),
|
||||
Layer.provideMerge(PersistenceLayerLive),
|
||||
Layer.provideMerge(KeybindingsLive),
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
import { DEFAULT_MODEL_BY_PROVIDER } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { DEFAULT_MODEL_BY_PROVIDER, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Deferred, Effect, Fiber, Option, Ref } from "effect";
|
||||
import { Deferred, Effect, Fiber, Option, Ref, Stream } from "effect";
|
||||
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import {
|
||||
getAutoBootstrapDefaultModelSelection,
|
||||
launchStartupHeartbeat,
|
||||
makeCommandGate,
|
||||
resolveAutoBootstrapWelcomeTargets,
|
||||
resolveWelcomeBase,
|
||||
ServerRuntimeStartupError,
|
||||
} from "./serverRuntimeStartup.ts";
|
||||
|
||||
@@ -93,3 +101,109 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolveWelcomeBase derives cwd and project name from server config", () =>
|
||||
Effect.gen(function* () {
|
||||
const welcome = yield* resolveWelcomeBase.pipe(
|
||||
Effect.provideService(ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
} as never),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(welcome, {
|
||||
cwd: "/tmp/startup-project",
|
||||
projectName: "startup-project",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and thread ids", () => {
|
||||
const bootstrapProjectId = ProjectId.make("project-startup-bootstrap");
|
||||
const bootstrapThreadId = ThreadId.make("thread-startup-bootstrap");
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const targets = yield* resolveAutoBootstrapWelcomeTargets.pipe(
|
||||
Effect.provideService(ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () =>
|
||||
Effect.succeed(
|
||||
Option.some({
|
||||
id: bootstrapProjectId,
|
||||
title: "Startup Project",
|
||||
workspaceRoot: "/tmp/startup-project",
|
||||
defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
}),
|
||||
),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(targets, {
|
||||
bootstrapProjectId,
|
||||
bootstrapThreadId,
|
||||
});
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const targets = yield* resolveAutoBootstrapWelcomeTargets.pipe(
|
||||
Effect.provideService(ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
assert.equal(typeof targets.bootstrapProjectId, "string");
|
||||
assert.equal(typeof targets.bootstrapThreadId, "string");
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), ["project.create", "thread.create"]);
|
||||
}),
|
||||
);
|
||||
@@ -32,6 +32,7 @@ import { ServerSettingsService } from "./serverSettings";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth";
|
||||
import { ProviderSessionReaper } from "./provider/Services/ProviderSessionReaper";
|
||||
import {
|
||||
formatHeadlessServeOutput,
|
||||
formatHostForUrl,
|
||||
@@ -157,7 +158,18 @@ export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
});
|
||||
|
||||
const autoBootstrapWelcome = Effect.gen(function* () {
|
||||
export const resolveWelcomeBase = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
return {
|
||||
cwd: serverConfig.cwd,
|
||||
projectName,
|
||||
} as const;
|
||||
});
|
||||
|
||||
export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
@@ -221,12 +233,7 @@ const autoBootstrapWelcome = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
return {
|
||||
cwd: serverConfig.cwd,
|
||||
projectName,
|
||||
...(bootstrapProjectId ? { bootstrapProjectId } : {}),
|
||||
...(bootstrapThreadId ? { bootstrapThreadId } : {}),
|
||||
} as const;
|
||||
@@ -271,10 +278,11 @@ const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>)
|
||||
Effect.withSpan(`server.startup.${phase}`),
|
||||
);
|
||||
|
||||
const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
export const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const keybindings = yield* Keybindings;
|
||||
const orchestrationReactor = yield* OrchestrationReactor;
|
||||
const providerSessionReaper = yield* ProviderSessionReaper;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const serverEnvironment = yield* ServerEnvironment;
|
||||
@@ -319,18 +327,19 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
yield* Effect.logDebug("startup phase: starting orchestration reactors");
|
||||
yield* runStartupPhase(
|
||||
"reactors.start",
|
||||
orchestrationReactor.start().pipe(Scope.provide(reactorScope)),
|
||||
Effect.gen(function* () {
|
||||
yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
|
||||
yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.logDebug("startup phase: preparing welcome payload");
|
||||
const welcome = yield* runStartupPhase("welcome.prepare", autoBootstrapWelcome);
|
||||
const welcomeBase = yield* resolveWelcomeBase;
|
||||
const environment = yield* serverEnvironment.getDescriptor;
|
||||
yield* Effect.logDebug("startup phase: preparing welcome payload");
|
||||
yield* Effect.logDebug("startup phase: publishing welcome event", {
|
||||
environmentId: environment.environmentId,
|
||||
cwd: welcome.cwd,
|
||||
projectName: welcome.projectName,
|
||||
bootstrapProjectId: welcome.bootstrapProjectId,
|
||||
bootstrapThreadId: welcome.bootstrapThreadId,
|
||||
cwd: welcomeBase.cwd,
|
||||
projectName: welcomeBase.projectName,
|
||||
});
|
||||
yield* runStartupPhase(
|
||||
"welcome.publish",
|
||||
@@ -339,10 +348,47 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
type: "welcome",
|
||||
payload: {
|
||||
environment,
|
||||
...welcome,
|
||||
...welcomeBase,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
if (serverConfig.autoBootstrapProjectFromCwd) {
|
||||
yield* Effect.forkScoped(
|
||||
runStartupPhase(
|
||||
"welcome.autobootstrap",
|
||||
Effect.gen(function* () {
|
||||
const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets;
|
||||
if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Effect.logDebug("startup phase: publishing bootstrapped welcome event", {
|
||||
environmentId: environment.environmentId,
|
||||
cwd: welcomeBase.cwd,
|
||||
projectName: welcomeBase.projectName,
|
||||
bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
|
||||
bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
|
||||
});
|
||||
yield* lifecycleEvents.publish({
|
||||
version: 1,
|
||||
type: "welcome",
|
||||
payload: {
|
||||
environment,
|
||||
...welcomeBase,
|
||||
...bootstrapTargets,
|
||||
},
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("startup auto-bootstrap welcome failed", {
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.annotateSpans({
|
||||
"server.mode": serverConfig.mode,
|
||||
|
||||
@@ -92,6 +92,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
enabled: true,
|
||||
binaryPath: "/usr/local/bin/claude",
|
||||
customModels: ["claude-custom"],
|
||||
launchArgs: "",
|
||||
});
|
||||
assert.deepEqual(next.textGenerationModelSelection, {
|
||||
provider: "codex",
|
||||
@@ -141,6 +142,35 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("drops stale text generation options when resetting model selection", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const next = yield* serverSettings.updateSettings({
|
||||
textGenerationModelSelection: {
|
||||
provider: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.provider,
|
||||
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(next.textGenerationModelSelection, {
|
||||
provider: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.provider,
|
||||
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("trims provider path settings when updates are applied", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
@@ -167,6 +197,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
enabled: true,
|
||||
binaryPath: "/opt/homebrew/bin/claude",
|
||||
customModels: [],
|
||||
launchArgs: "",
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
@@ -176,12 +207,14 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
|
||||
const next = yield* serverSettings.updateSettings({
|
||||
addProjectBaseDirectory: " ~/Development ",
|
||||
observability: {
|
||||
otlpTracesUrl: " http://localhost:4318/v1/traces ",
|
||||
otlpMetricsUrl: " http://localhost:4318/v1/metrics ",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(next.addProjectBaseDirectory, "~/Development");
|
||||
assert.deepEqual(next.observability, {
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
@@ -215,6 +248,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const next = yield* serverSettings.updateSettings({
|
||||
addProjectBaseDirectory: "~/Development",
|
||||
observability: {
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
@@ -230,6 +264,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
|
||||
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
|
||||
assert.deepEqual(JSON.parse(raw), {
|
||||
addProjectBaseDirectory: "~/Development",
|
||||
observability: {
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
|
||||
@@ -42,6 +42,7 @@ import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
|
||||
export interface ServerSettingsShape {
|
||||
/** Start the settings runtime and attach file watching. */
|
||||
@@ -80,7 +81,20 @@ export class ServerSettingsService extends Context.Service<
|
||||
getSettings: Ref.get(currentSettingsRef),
|
||||
updateSettings: (patch) =>
|
||||
Ref.get(currentSettingsRef).pipe(
|
||||
Effect.map((currentSettings) => deepMerge(currentSettings, patch)),
|
||||
Effect.flatMap((currentSettings) =>
|
||||
Schema.decodeEffect(ServerSettings)(
|
||||
applyServerSettingsPatch(currentSettings, patch),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSettingsError({
|
||||
settingsPath: "<memory>",
|
||||
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -314,7 +328,9 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
writeSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* getSettingsFromCache;
|
||||
const next = yield* Schema.decodeEffect(ServerSettings)(deepMerge(current, patch)).pipe(
|
||||
const next = yield* Schema.decodeEffect(ServerSettings)(
|
||||
applyServerSettingsPatch(current, patch),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSettingsError({
|
||||
|
||||
@@ -68,6 +68,11 @@ const searchWorkspaceEntries = (input: { cwd: string; query: string; limit: numb
|
||||
return yield* workspaceEntries.search(input);
|
||||
});
|
||||
|
||||
const appendSeparator = (input: string) =>
|
||||
input.endsWith("/") || input.endsWith("\\")
|
||||
? input
|
||||
: `${input}${process.platform === "win32" ? "\\" : "/"}`;
|
||||
|
||||
it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
@@ -275,4 +280,85 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("browse", () => {
|
||||
it.effect("returns matching directories and excludes files", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const path = yield* Path.Path;
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-prefix-" });
|
||||
yield* writeTextFile(cwd, "alphabet.txt", "ignore me");
|
||||
yield* writeTextFile(cwd, "alpha/index.ts", "export {};\n");
|
||||
yield* writeTextFile(cwd, "alpine/index.ts", "export {};\n");
|
||||
|
||||
const result = yield* workspaceEntries.browse({
|
||||
partialPath: path.join(cwd, "alp"),
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
parentPath: cwd,
|
||||
entries: [
|
||||
{ name: "alpha", fullPath: path.join(cwd, "alpha") },
|
||||
{ name: "alpine", fullPath: path.join(cwd, "alpine") },
|
||||
],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shows dot directories in directory mode and hidden-prefix mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const path = yield* Path.Path;
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-hidden-" });
|
||||
yield* writeTextFile(cwd, ".config/settings.json", "{}");
|
||||
yield* writeTextFile(cwd, "config/settings.json", "{}");
|
||||
|
||||
const directoryResult = yield* workspaceEntries.browse({
|
||||
partialPath: appendSeparator(cwd),
|
||||
});
|
||||
const hiddenPrefixResult = yield* workspaceEntries.browse({
|
||||
partialPath: `${appendSeparator(cwd)}.c`,
|
||||
});
|
||||
|
||||
expect(directoryResult.entries.map((entry) => entry.name)).toEqual([".config", "config"]);
|
||||
expect(hiddenPrefixResult).toEqual({
|
||||
parentPath: cwd,
|
||||
entries: [{ name: ".config", fullPath: path.join(cwd, ".config") }],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("supports relative paths when cwd is provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const path = yield* Path.Path;
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-relative-" });
|
||||
yield* writeTextFile(cwd, "packages/pkg.json", "{}");
|
||||
|
||||
const result = yield* workspaceEntries.browse({
|
||||
cwd,
|
||||
partialPath: "./pack",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
parentPath: cwd,
|
||||
entries: [{ name: "packages", fullPath: path.join(cwd, "packages") }],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects relative paths without cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
|
||||
const error = yield* workspaceEntries
|
||||
.browse({
|
||||
partialPath: "./src",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.detail).toBe("Relative filesystem browse paths require a current project.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import * as OS from "node:os";
|
||||
import fsPromises from "node:fs/promises";
|
||||
import type { Dirent } from "node:fs";
|
||||
|
||||
import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect";
|
||||
|
||||
import { type ProjectEntry } from "@t3tools/contracts";
|
||||
import { type FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
|
||||
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
|
||||
import {
|
||||
insertRankedSearchResult,
|
||||
normalizeSearchQuery,
|
||||
@@ -14,6 +16,7 @@ import {
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
WorkspaceEntries,
|
||||
WorkspaceEntriesBrowseError,
|
||||
WorkspaceEntriesError,
|
||||
type WorkspaceEntriesShape,
|
||||
} from "../Services/WorkspaceEntries.ts";
|
||||
@@ -52,6 +55,16 @@ function toPosixPath(input: string): string {
|
||||
return input.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
function expandHomePath(input: string, path: Path.Path): string {
|
||||
if (input === "~") {
|
||||
return OS.homedir();
|
||||
}
|
||||
if (input.startsWith("~/") || input.startsWith("~\\")) {
|
||||
return path.join(OS.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
function parentPathOf(input: string): string | undefined {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
@@ -129,6 +142,36 @@ function directoryAncestorsOf(relativePath: string): string[] {
|
||||
return directories;
|
||||
}
|
||||
|
||||
const resolveBrowseTarget = (
|
||||
input: FilesystemBrowseInput,
|
||||
pathService: Path.Path,
|
||||
): Effect.Effect<string, WorkspaceEntriesBrowseError> =>
|
||||
Effect.gen(function* () {
|
||||
if (process.platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
|
||||
return yield* new WorkspaceEntriesBrowseError({
|
||||
cwd: input.cwd,
|
||||
partialPath: input.partialPath,
|
||||
operation: "workspaceEntries.resolveBrowseTarget",
|
||||
detail: "Windows-style paths are only supported on Windows.",
|
||||
});
|
||||
}
|
||||
|
||||
if (!isExplicitRelativePath(input.partialPath)) {
|
||||
return pathService.resolve(expandHomePath(input.partialPath, pathService));
|
||||
}
|
||||
|
||||
if (!input.cwd) {
|
||||
return yield* new WorkspaceEntriesBrowseError({
|
||||
cwd: input.cwd,
|
||||
partialPath: input.partialPath,
|
||||
operation: "workspaceEntries.resolveBrowseTarget",
|
||||
detail: "Relative filesystem browse paths require a current project.",
|
||||
});
|
||||
}
|
||||
|
||||
return pathService.resolve(expandHomePath(input.cwd, pathService), input.partialPath);
|
||||
});
|
||||
|
||||
export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const gitOption = yield* Effect.serviceOption(GitCore);
|
||||
@@ -379,6 +422,46 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const browse: WorkspaceEntriesShape["browse"] = Effect.fn("WorkspaceEntries.browse")(
|
||||
function* (input) {
|
||||
const resolvedInputPath = yield* resolveBrowseTarget(input, path);
|
||||
const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
|
||||
const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
|
||||
const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
|
||||
|
||||
const dirents = yield* Effect.tryPromise({
|
||||
try: () => fsPromises.readdir(parentPath, { withFileTypes: true }),
|
||||
catch: (cause) =>
|
||||
new WorkspaceEntriesBrowseError({
|
||||
cwd: input.cwd,
|
||||
partialPath: input.partialPath,
|
||||
operation: "workspaceEntries.browse.readDirectory",
|
||||
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const showHidden = endsWithSeparator || prefix.startsWith(".");
|
||||
const lowerPrefix = prefix.toLowerCase();
|
||||
|
||||
return {
|
||||
parentPath,
|
||||
entries: dirents
|
||||
.filter(
|
||||
(dirent) =>
|
||||
dirent.isDirectory() &&
|
||||
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
|
||||
(showHidden || !dirent.name.startsWith(".")),
|
||||
)
|
||||
.map((dirent) => ({
|
||||
name: dirent.name,
|
||||
fullPath: path.join(parentPath, dirent.name),
|
||||
}))
|
||||
.toSorted((left, right) => left.name.localeCompare(right.name)),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const search: WorkspaceEntriesShape["search"] = Effect.fn("WorkspaceEntries.search")(
|
||||
function* (input) {
|
||||
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
|
||||
@@ -415,6 +498,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
return {
|
||||
browse,
|
||||
invalidate,
|
||||
search,
|
||||
} satisfies WorkspaceEntriesShape;
|
||||
|
||||
@@ -58,6 +58,24 @@ it.layer(TestLayer)("WorkspacePathsLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates missing directories when createIfMissing is enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cwd = yield* makeTempDir();
|
||||
const path = yield* Path.Path;
|
||||
const missingPath = path.join(cwd, "nested", "new-project");
|
||||
|
||||
const resolved = yield* workspacePaths.normalizeWorkspaceRoot(missingPath, {
|
||||
createIfMissing: true,
|
||||
});
|
||||
const stat = yield* fileSystem.stat(resolved);
|
||||
|
||||
expect(resolved).toBe(missingPath);
|
||||
expect(stat.type).toBe("Directory");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects file paths", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import {
|
||||
WorkspacePaths,
|
||||
WorkspacePathOutsideRootError,
|
||||
WorkspaceRootCreateFailedError,
|
||||
WorkspaceRootNotDirectoryError,
|
||||
WorkspaceRootNotExistsError,
|
||||
type WorkspacePathsShape,
|
||||
@@ -29,11 +30,25 @@ export const makeWorkspacePaths = Effect.gen(function* () {
|
||||
|
||||
const normalizeWorkspaceRoot: WorkspacePathsShape["normalizeWorkspaceRoot"] = Effect.fn(
|
||||
"WorkspacePaths.normalizeWorkspaceRoot",
|
||||
)(function* (workspaceRoot) {
|
||||
)(function* (workspaceRoot, options) {
|
||||
const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));
|
||||
const workspaceStat = yield* fileSystem
|
||||
let workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!workspaceStat && options?.createIfMissing) {
|
||||
yield* fileSystem.makeDirectory(normalizedWorkspaceRoot, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new WorkspaceRootCreateFailedError({
|
||||
workspaceRoot,
|
||||
normalizedWorkspaceRoot,
|
||||
}),
|
||||
),
|
||||
);
|
||||
workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
}
|
||||
if (!workspaceStat) {
|
||||
return yield* new WorkspaceRootNotExistsError({
|
||||
workspaceRoot,
|
||||
|
||||
@@ -9,7 +9,12 @@
|
||||
import { Schema, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "@t3tools/contracts";
|
||||
import type {
|
||||
FilesystemBrowseInput,
|
||||
FilesystemBrowseResult,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export class WorkspaceEntriesError extends Schema.TaggedErrorClass<WorkspaceEntriesError>()(
|
||||
"WorkspaceEntriesError",
|
||||
@@ -21,11 +26,29 @@ export class WorkspaceEntriesError extends Schema.TaggedErrorClass<WorkspaceEntr
|
||||
},
|
||||
) {}
|
||||
|
||||
export class WorkspaceEntriesBrowseError extends Schema.TaggedErrorClass<WorkspaceEntriesBrowseError>()(
|
||||
"WorkspaceEntriesBrowseError",
|
||||
{
|
||||
cwd: Schema.optional(Schema.String),
|
||||
partialPath: Schema.String,
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
/**
|
||||
* WorkspaceEntriesShape - Service API for workspace entry search and cache
|
||||
* invalidation.
|
||||
*/
|
||||
export interface WorkspaceEntriesShape {
|
||||
/**
|
||||
* Browse matching directories for the provided partial path.
|
||||
*/
|
||||
readonly browse: (
|
||||
input: FilesystemBrowseInput,
|
||||
) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
|
||||
|
||||
/**
|
||||
* Search indexed workspace entries for files and directories matching the
|
||||
* provided query.
|
||||
|
||||
@@ -21,6 +21,18 @@ export class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass<Workspa
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceRootCreateFailedError extends Schema.TaggedErrorClass<WorkspaceRootCreateFailedError>()(
|
||||
"WorkspaceRootCreateFailedError",
|
||||
{
|
||||
workspaceRoot: Schema.String,
|
||||
normalizedWorkspaceRoot: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create workspace root: ${this.normalizedWorkspaceRoot}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceRootNotDirectoryError extends Schema.TaggedErrorClass<WorkspaceRootNotDirectoryError>()(
|
||||
"WorkspaceRootNotDirectoryError",
|
||||
{
|
||||
@@ -47,6 +59,7 @@ export class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass<Works
|
||||
|
||||
export const WorkspacePathsError = Schema.Union([
|
||||
WorkspaceRootNotExistsError,
|
||||
WorkspaceRootCreateFailedError,
|
||||
WorkspaceRootNotDirectoryError,
|
||||
WorkspacePathOutsideRootError,
|
||||
]);
|
||||
@@ -61,7 +74,11 @@ export interface WorkspacePathsShape {
|
||||
*/
|
||||
readonly normalizeWorkspaceRoot: (
|
||||
workspaceRoot: string,
|
||||
) => Effect.Effect<string, WorkspaceRootNotExistsError | WorkspaceRootNotDirectoryError>;
|
||||
options?: { readonly createIfMissing?: boolean },
|
||||
) => Effect.Effect<
|
||||
string,
|
||||
WorkspaceRootNotExistsError | WorkspaceRootCreateFailedError | WorkspaceRootNotDirectoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Resolve a relative path within a validated workspace root.
|
||||
|
||||
+71
-2
@@ -1,4 +1,4 @@
|
||||
import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
|
||||
import { Cause, Duration, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
|
||||
import {
|
||||
type AuthAccessStreamEvent,
|
||||
AuthSessionId,
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
ProjectSearchEntriesError,
|
||||
ProjectWriteFileError,
|
||||
OrchestrationReplayEventsError,
|
||||
FilesystemBrowseError,
|
||||
ThreadId,
|
||||
type TerminalEvent,
|
||||
WS_METHODS,
|
||||
@@ -85,6 +86,8 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
);
|
||||
}
|
||||
|
||||
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
|
||||
|
||||
function toAuthAccessStreamEvent(
|
||||
change: BootstrapCredentialChange | SessionCredentialChange,
|
||||
revision: number,
|
||||
@@ -464,6 +467,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
branch: worktree.worktree.branch,
|
||||
worktreePath: targetWorktreePath,
|
||||
});
|
||||
yield* refreshGitStatus(targetWorktreePath);
|
||||
}
|
||||
|
||||
yield* runSetupProgram();
|
||||
@@ -546,8 +550,45 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
ORCHESTRATION_WS_METHODS.dispatchCommand,
|
||||
Effect.gen(function* () {
|
||||
const normalizedCommand = yield* normalizeDispatchCommand(command);
|
||||
const shouldStopSessionAfterArchive =
|
||||
normalizedCommand.type === "thread.archive"
|
||||
? yield* projectionSnapshotQuery
|
||||
.getThreadShellById(normalizedCommand.threadId)
|
||||
.pipe(
|
||||
Effect.map(
|
||||
Option.match({
|
||||
onNone: () => false,
|
||||
onSome: (thread) =>
|
||||
thread.session !== null && thread.session.status !== "stopped",
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
)
|
||||
: false;
|
||||
const result = yield* dispatchNormalizedCommand(normalizedCommand);
|
||||
if (normalizedCommand.type === "thread.archive") {
|
||||
if (shouldStopSessionAfterArchive) {
|
||||
yield* Effect.gen(function* () {
|
||||
const stopCommand = yield* normalizeDispatchCommand({
|
||||
type: "thread.session.stop",
|
||||
commandId: CommandId.make(
|
||||
`session-stop-for-archive:${normalizedCommand.commandId}`,
|
||||
),
|
||||
threadId: normalizedCommand.threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
yield* dispatchNormalizedCommand(stopCommand);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("failed to stop provider session during archive", {
|
||||
threadId: normalizedCommand.threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to close thread terminals after archive", {
|
||||
@@ -765,6 +806,20 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
}),
|
||||
[WS_METHODS.filesystemBrowse]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.filesystemBrowse,
|
||||
workspaceEntries.browse(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new FilesystemBrowseError({
|
||||
message: cause.detail,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.subscribeGitStatus]: (input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeGitStatus,
|
||||
@@ -918,6 +973,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
type: "providerStatuses" as const,
|
||||
payload: { providers },
|
||||
})),
|
||||
Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)),
|
||||
);
|
||||
const settingsUpdates = serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => ({
|
||||
@@ -927,13 +983,26 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
})),
|
||||
);
|
||||
|
||||
yield* Effect.all(
|
||||
[providerRegistry.refresh("codex"), providerRegistry.refresh("claudeAgent")],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);
|
||||
|
||||
const liveUpdates = Stream.merge(
|
||||
keybindingsUpdates,
|
||||
Stream.merge(providerStatuses, settingsUpdates),
|
||||
);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
version: 1 as const,
|
||||
type: "snapshot" as const,
|
||||
config: yield* loadServerConfig,
|
||||
}),
|
||||
Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
|
||||
liveUpdates,
|
||||
);
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.17",
|
||||
"version": "0.0.20",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const originalWindow = globalThis.window;
|
||||
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
|
||||
if (originalWindow === undefined) {
|
||||
Reflect.deleteProperty(globalThis, "window");
|
||||
return;
|
||||
}
|
||||
|
||||
globalThis.window = originalWindow;
|
||||
});
|
||||
|
||||
describe("branding", () => {
|
||||
it("uses injected desktop branding when available", async () => {
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: {
|
||||
desktopBridge: {
|
||||
getAppBranding: () => ({
|
||||
baseName: "T3 Code",
|
||||
stageLabel: "Nightly",
|
||||
displayName: "T3 Code (Nightly)",
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const branding = await import("./branding");
|
||||
|
||||
expect(branding.APP_BASE_NAME).toBe("T3 Code");
|
||||
expect(branding.APP_STAGE_LABEL).toBe("Nightly");
|
||||
expect(branding.APP_DISPLAY_NAME).toBe("T3 Code (Nightly)");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,18 @@
|
||||
export const APP_BASE_NAME = "T3 Code";
|
||||
export const APP_STAGE_LABEL = import.meta.env.DEV ? "Dev" : "Alpha";
|
||||
export const APP_DISPLAY_NAME = `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
|
||||
import type { DesktopAppBranding } from "@t3tools/contracts";
|
||||
|
||||
function readInjectedDesktopAppBranding(): DesktopAppBranding | null {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return window.desktopBridge?.getAppBranding?.() ?? null;
|
||||
}
|
||||
|
||||
const injectedDesktopAppBranding = readInjectedDesktopAppBranding();
|
||||
|
||||
export const APP_BASE_NAME = injectedDesktopAppBranding?.baseName ?? "T3 Code";
|
||||
export const APP_STAGE_LABEL =
|
||||
injectedDesktopAppBranding?.stageLabel ?? (import.meta.env.DEV ? "Dev" : "Alpha");
|
||||
export const APP_DISPLAY_NAME =
|
||||
injectedDesktopAppBranding?.displayName ?? `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
|
||||
export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0";
|
||||
@@ -1,13 +1,32 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
interface CommandPaletteOpenIntent {
|
||||
kind: "add-project";
|
||||
requestId: number;
|
||||
}
|
||||
|
||||
interface CommandPaletteStore {
|
||||
open: boolean;
|
||||
openIntent: CommandPaletteOpenIntent | null;
|
||||
setOpen: (open: boolean) => void;
|
||||
toggleOpen: () => void;
|
||||
openAddProject: () => void;
|
||||
clearOpenIntent: () => void;
|
||||
}
|
||||
|
||||
export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
|
||||
open: false,
|
||||
setOpen: (open) => set({ open }),
|
||||
toggleOpen: () => set((state) => ({ open: !state.open })),
|
||||
openIntent: null,
|
||||
setOpen: (open) => set({ open, ...(open ? {} : { openIntent: null }) }),
|
||||
toggleOpen: () =>
|
||||
set((state) => ({ open: !state.open, ...(state.open ? { openIntent: null } : {}) })),
|
||||
openAddProject: () =>
|
||||
set((state) => ({
|
||||
open: true,
|
||||
openIntent: {
|
||||
kind: "add-project",
|
||||
requestId: (state.openIntent?.requestId ?? 0) + 1,
|
||||
},
|
||||
})),
|
||||
clearOpenIntent: () => set({ openIntent: null }),
|
||||
}));
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
resolveEffectiveEnvMode,
|
||||
resolveEnvModeLabel,
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
@@ -157,6 +158,16 @@ describe("resolveCurrentWorkspaceLabel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveLockedWorkspaceLabel", () => {
|
||||
it("uses a shorter label for the main repo checkout", () => {
|
||||
expect(resolveLockedWorkspaceLabel(null)).toBe("Local checkout");
|
||||
});
|
||||
|
||||
it("uses a shorter label for an attached worktree", () => {
|
||||
expect(resolveLockedWorkspaceLabel("/repo/.t3/worktrees/feature-a")).toBe("Worktree");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
it("strips the remote prefix from a remote ref", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
|
||||
|
||||
@@ -50,6 +50,10 @@ export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null):
|
||||
return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");
|
||||
}
|
||||
|
||||
export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null): string {
|
||||
return activeWorktreePath ? "Worktree" : "Local checkout";
|
||||
}
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
activeWorktreePath: string | null;
|
||||
hasServerThread: boolean;
|
||||
|
||||
@@ -20,6 +20,9 @@ interface BranchToolbarProps {
|
||||
threadId: ThreadId;
|
||||
draftId?: DraftId;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
effectiveEnvModeOverride?: EnvMode;
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
envLocked: boolean;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
@@ -32,6 +35,9 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
threadId,
|
||||
draftId,
|
||||
onEnvModeChange,
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
envLocked,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
@@ -59,11 +65,13 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
const activeProject = useStore(activeProjectSelector);
|
||||
const hasActiveThread = serverThread !== undefined || draftThread !== null;
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread: serverThread !== undefined,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const effectiveEnvMode =
|
||||
effectiveEnvModeOverride ??
|
||||
resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread: serverThread !== undefined,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const envModeLocked = envLocked || (serverThread !== undefined && activeWorktreePath !== null);
|
||||
|
||||
const showEnvironmentPicker =
|
||||
@@ -98,6 +106,9 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
threadId={threadId}
|
||||
{...(draftId ? { draftId } : {})}
|
||||
envLocked={envLocked}
|
||||
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
|
||||
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
|
||||
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
|
||||
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
|
||||
@@ -49,6 +49,9 @@ interface BranchToolbarBranchSelectorProps {
|
||||
threadId: ThreadId;
|
||||
draftId?: DraftId;
|
||||
envLocked: boolean;
|
||||
effectiveEnvModeOverride?: "local" | "worktree";
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
@@ -77,6 +80,9 @@ export function BranchToolbarBranchSelector({
|
||||
threadId,
|
||||
draftId,
|
||||
envLocked,
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
@@ -108,16 +114,21 @@ export function BranchToolbarBranchSelector({
|
||||
const activeProject = useStore(activeProjectSelector);
|
||||
|
||||
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
|
||||
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
|
||||
const activeThreadBranch =
|
||||
activeThreadBranchOverride !== undefined
|
||||
? activeThreadBranchOverride
|
||||
: (serverThread?.branch ?? draftThread?.branch ?? null);
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const branchCwd = activeWorktreePath ?? activeProjectCwd;
|
||||
const hasServerThread = serverThread !== undefined;
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const effectiveEnvMode =
|
||||
effectiveEnvModeOverride ??
|
||||
resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread branch mutation (colocated — only this component calls it)
|
||||
@@ -146,6 +157,7 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
onActiveThreadBranchOverrideChange?.(branch);
|
||||
setThreadBranchAction(threadRef, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
@@ -167,6 +179,7 @@ export function BranchToolbarBranchSelector({
|
||||
serverSession,
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
setThreadBranchAction,
|
||||
setDraftThreadContext,
|
||||
draftId,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { memo, useMemo } from "react";
|
||||
import {
|
||||
resolveCurrentWorkspaceLabel,
|
||||
resolveEnvModeLabel,
|
||||
resolveLockedWorkspaceLabel,
|
||||
type EnvMode,
|
||||
} from "./BranchToolbar.logic";
|
||||
import {
|
||||
@@ -43,12 +44,12 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
{activeWorktreePath ? (
|
||||
<>
|
||||
<FolderGitIcon className="size-3" />
|
||||
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FolderIcon className="size-3" />
|
||||
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
|
||||
{resolveLockedWorkspaceLabel(activeWorktreePath)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -63,7 +63,7 @@ describe("ChatMarkdown", () => {
|
||||
);
|
||||
|
||||
try {
|
||||
const link = page.getByRole("link", { name: "PermissionRule.ts:1" });
|
||||
const link = page.getByRole("link", { name: "PermissionRule.ts · L1" });
|
||||
await expect.element(link).toBeInTheDocument();
|
||||
await expect.element(link).toHaveAttribute("href", `${filePath}#L1`);
|
||||
|
||||
@@ -76,4 +76,66 @@ describe("ChatMarkdown", () => {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows column information inline when present", async () => {
|
||||
const filePath =
|
||||
"/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
|
||||
const screen = await render(
|
||||
<ChatMarkdown text={`[PermissionRule.ts](file://${filePath}#L1C7)`} cwd="/repo/project" />,
|
||||
);
|
||||
|
||||
try {
|
||||
const link = page.getByRole("link", { name: "PermissionRule.ts · L1:C7" });
|
||||
await expect.element(link).toBeInTheDocument();
|
||||
await expect.element(link).toHaveAttribute("href", `${filePath}#L1C7`);
|
||||
|
||||
await link.click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(openInPreferredEditorMock).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
`${filePath}:1:7`,
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("disambiguates duplicate file basenames inline", async () => {
|
||||
const firstPath = "/Users/yashsingh/p/t3code/apps/web/src/components/chat/MessagesTimeline.tsx";
|
||||
const secondPath = "/Users/yashsingh/p/t3code/apps/web/src/components/MessagesTimeline.tsx";
|
||||
const screen = await render(
|
||||
<ChatMarkdown
|
||||
text={`See [MessagesTimeline.tsx](file://${firstPath}) and [MessagesTimeline.tsx](file://${secondPath}).`}
|
||||
cwd="/repo/project"
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
await expect
|
||||
.element(page.getByRole("link", { name: "MessagesTimeline.tsx · components/chat" }))
|
||||
.toBeInTheDocument();
|
||||
await expect
|
||||
.element(page.getByRole("link", { name: "MessagesTimeline.tsx · src/components" }))
|
||||
.toBeInTheDocument();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps normal web links unchanged", async () => {
|
||||
const screen = await render(
|
||||
<ChatMarkdown text="[OpenAI](https://openai.com/docs)" cwd="/repo/project" />,
|
||||
);
|
||||
|
||||
try {
|
||||
const link = page.getByRole("link", { name: "OpenAI" });
|
||||
await expect.element(link).toBeInTheDocument();
|
||||
await expect.element(link).toHaveAttribute("href", "https://openai.com/docs");
|
||||
await expect.element(link).toHaveAttribute("target", "_blank");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import React, {
|
||||
Children,
|
||||
Suspense,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
isValidElement,
|
||||
use,
|
||||
useCallback,
|
||||
@@ -17,13 +18,17 @@ import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import { defaultUrlTransform } from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveMarkdownFileLinkTarget, rewriteMarkdownFileUriHref } from "../markdown-links";
|
||||
import { resolveMarkdownFileLinkMeta, rewriteMarkdownFileUriHref } from "../markdown-links";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { cn } from "../lib/utils";
|
||||
|
||||
class CodeHighlightErrorBoundary extends React.Component<
|
||||
{ fallback: ReactNode; children: ReactNode },
|
||||
@@ -236,34 +241,289 @@ function SuspenseShikiCodeBlock({
|
||||
);
|
||||
}
|
||||
|
||||
interface MarkdownFileLinkProps {
|
||||
href: string;
|
||||
targetPath: string;
|
||||
displayPath: string;
|
||||
filePath: string;
|
||||
label: string;
|
||||
theme: "light" | "dark";
|
||||
className?: string | undefined;
|
||||
}
|
||||
|
||||
const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
|
||||
const MARKDOWN_FILE_LINK_CLASS_NAME =
|
||||
"chat-markdown-file-link relative top-[2px] max-w-full no-underline";
|
||||
const MARKDOWN_FILE_LINK_ICON_CLASS_NAME = "chat-markdown-file-link-icon size-3.5 shrink-0";
|
||||
const MARKDOWN_FILE_LINK_LABEL_CLASS_NAME = "chat-markdown-file-link-label truncate";
|
||||
|
||||
function pathParentSegments(path: string): string[] {
|
||||
const normalized = path.replaceAll("\\", "/");
|
||||
const segments = normalized.split("/").filter((segment) => segment.length > 0);
|
||||
return segments.slice(0, -1);
|
||||
}
|
||||
|
||||
function buildFileLinkParentSuffixByPath(filePaths: ReadonlyArray<string>): Map<string, string> {
|
||||
const groups = new Map<string, Set<string>>();
|
||||
for (const filePath of filePaths) {
|
||||
const pathSegments = filePath
|
||||
.replaceAll("\\", "/")
|
||||
.split("/")
|
||||
.filter((segment) => segment.length > 0);
|
||||
const basename = pathSegments[pathSegments.length - 1];
|
||||
if (!basename) continue;
|
||||
const group = groups.get(basename) ?? new Set<string>();
|
||||
group.add(filePath);
|
||||
groups.set(basename, group);
|
||||
}
|
||||
|
||||
const suffixByPath = new Map<string, string>();
|
||||
for (const group of groups.values()) {
|
||||
const uniquePaths = [...group];
|
||||
if (uniquePaths.length < 2) continue;
|
||||
|
||||
const parentSegmentsByPath = new Map(
|
||||
uniquePaths.map((filePath) => [filePath, pathParentSegments(filePath)]),
|
||||
);
|
||||
const minUniqueDepthByPath = new Map<string, number>();
|
||||
|
||||
for (const filePath of uniquePaths) {
|
||||
const segments = parentSegmentsByPath.get(filePath) ?? [];
|
||||
let resolvedDepth = segments.length;
|
||||
for (let depth = 1; depth <= segments.length; depth += 1) {
|
||||
const candidate = segments.slice(-depth).join("/");
|
||||
const collision = uniquePaths.some((otherPath) => {
|
||||
if (otherPath === filePath) return false;
|
||||
const otherSegments = parentSegmentsByPath.get(otherPath) ?? [];
|
||||
return otherSegments.slice(-depth).join("/") === candidate;
|
||||
});
|
||||
if (!collision) {
|
||||
resolvedDepth = depth;
|
||||
break;
|
||||
}
|
||||
}
|
||||
minUniqueDepthByPath.set(filePath, resolvedDepth);
|
||||
}
|
||||
|
||||
for (const filePath of uniquePaths) {
|
||||
const segments = parentSegmentsByPath.get(filePath) ?? [];
|
||||
if (segments.length === 0) continue;
|
||||
const minUniqueDepth = minUniqueDepthByPath.get(filePath) ?? 1;
|
||||
const suffixDepth = Math.min(segments.length, Math.max(minUniqueDepth, 2));
|
||||
suffixByPath.set(filePath, segments.slice(-suffixDepth).join("/"));
|
||||
}
|
||||
}
|
||||
|
||||
return suffixByPath;
|
||||
}
|
||||
|
||||
function extractMarkdownLinkHrefs(text: string): string[] {
|
||||
const hrefs: string[] = [];
|
||||
for (const match of text.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
|
||||
const href = match[1]?.trim();
|
||||
if (!href) continue;
|
||||
hrefs.push(href);
|
||||
}
|
||||
return hrefs;
|
||||
}
|
||||
|
||||
function normalizeMarkdownLinkHrefKey(href: string): string {
|
||||
return rewriteMarkdownFileUriHref(href.trim()) ?? href.trim();
|
||||
}
|
||||
|
||||
const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
href,
|
||||
targetPath,
|
||||
displayPath,
|
||||
filePath,
|
||||
label,
|
||||
theme,
|
||||
className,
|
||||
}: MarkdownFileLinkProps) {
|
||||
const handleOpen = useCallback(() => {
|
||||
const api = readLocalApi();
|
||||
if (!api) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Open in editor is unavailable",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void openInPreferredEditor(api, targetPath).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open file",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, [targetPath]);
|
||||
|
||||
const handleCopy = useCallback((value: string, title: string) => {
|
||||
if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to copy ${title.toLowerCase()}`,
|
||||
description: "Clipboard API unavailable.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void navigator.clipboard.writeText(value).then(
|
||||
() => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: `${title} copied`,
|
||||
description: value,
|
||||
});
|
||||
},
|
||||
(error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to copy ${title.toLowerCase()}`,
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
},
|
||||
);
|
||||
}, []);
|
||||
|
||||
const handleContextMenu = useCallback(
|
||||
async (event: ReactMouseEvent<HTMLAnchorElement>) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const api = readLocalApi();
|
||||
if (!api) return;
|
||||
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "open", label: "Open in editor" },
|
||||
{ id: "copy-relative", label: "Copy relative path" },
|
||||
{ id: "copy-full", label: "Copy full path" },
|
||||
] as const,
|
||||
{ x: event.clientX, y: event.clientY },
|
||||
);
|
||||
|
||||
if (clicked === "open") {
|
||||
handleOpen();
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-relative") {
|
||||
handleCopy(displayPath, "Relative path");
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-full") {
|
||||
handleCopy(targetPath, "Full path");
|
||||
}
|
||||
},
|
||||
[displayPath, handleCopy, handleOpen, targetPath],
|
||||
);
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<a
|
||||
href={href}
|
||||
className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, className)}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleOpen();
|
||||
}}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
<VscodeEntryIcon
|
||||
pathValue={filePath}
|
||||
kind="file"
|
||||
theme={theme}
|
||||
className={cn(MARKDOWN_FILE_LINK_ICON_CLASS_NAME, "text-current")}
|
||||
/>
|
||||
<span className={MARKDOWN_FILE_LINK_LABEL_CLASS_NAME}>{label}</span>
|
||||
</a>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-[min(40rem,calc(100vw-2rem))] font-mono text-[11px] leading-tight"
|
||||
>
|
||||
<div className="markdown-file-link-tooltip-scroll overflow-x-auto whitespace-nowrap">
|
||||
{displayPath}
|
||||
</div>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}, areMarkdownFileLinkPropsEqual);
|
||||
|
||||
function areMarkdownFileLinkPropsEqual(
|
||||
previous: Readonly<MarkdownFileLinkProps>,
|
||||
next: Readonly<MarkdownFileLinkProps>,
|
||||
): boolean {
|
||||
return (
|
||||
previous.href === next.href &&
|
||||
previous.targetPath === next.targetPath &&
|
||||
previous.displayPath === next.displayPath &&
|
||||
previous.filePath === next.filePath &&
|
||||
previous.label === next.label &&
|
||||
previous.theme === next.theme &&
|
||||
previous.className === next.className
|
||||
);
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const markdownFileLinkMetaByHref = useMemo(() => {
|
||||
const metaByHref = new Map<
|
||||
string,
|
||||
NonNullable<ReturnType<typeof resolveMarkdownFileLinkMeta>>
|
||||
>();
|
||||
for (const href of extractMarkdownLinkHrefs(text)) {
|
||||
const normalizedHref = normalizeMarkdownLinkHrefKey(href);
|
||||
if (metaByHref.has(normalizedHref)) continue;
|
||||
const meta = resolveMarkdownFileLinkMeta(normalizedHref, cwd);
|
||||
if (meta) {
|
||||
metaByHref.set(normalizedHref, meta);
|
||||
}
|
||||
}
|
||||
return metaByHref;
|
||||
}, [cwd, text]);
|
||||
const fileLinkParentSuffixByPath = useMemo(() => {
|
||||
const filePaths = [...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath);
|
||||
return buildFileLinkParentSuffixByPath(filePaths);
|
||||
}, [markdownFileLinkMetaByHref]);
|
||||
const markdownUrlTransform = useCallback((href: string) => {
|
||||
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
|
||||
}, []);
|
||||
const markdownComponents = useMemo<Components>(
|
||||
() => ({
|
||||
a({ node: _node, href, ...props }) {
|
||||
const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
|
||||
if (!targetPath) {
|
||||
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
|
||||
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
|
||||
if (!fileLinkMeta) {
|
||||
return <a {...props} href={href} target="_blank" rel="noopener noreferrer" />;
|
||||
}
|
||||
|
||||
const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath);
|
||||
const labelParts = [fileLinkMeta.basename];
|
||||
if (typeof parentSuffix === "string" && parentSuffix.length > 0) {
|
||||
labelParts.push(parentSuffix);
|
||||
}
|
||||
if (fileLinkMeta.line) {
|
||||
labelParts.push(
|
||||
`L${fileLinkMeta.line}${fileLinkMeta.column ? `:C${fileLinkMeta.column}` : ""}`,
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<a
|
||||
{...props}
|
||||
href={href}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const api = readLocalApi();
|
||||
if (api) {
|
||||
void openInPreferredEditor(api, targetPath);
|
||||
} else {
|
||||
console.warn("Native API not found. Unable to open file in editor.");
|
||||
}
|
||||
}}
|
||||
<MarkdownFileLink
|
||||
href={href ?? fileLinkMeta.targetPath}
|
||||
targetPath={fileLinkMeta.targetPath}
|
||||
displayPath={fileLinkMeta.displayPath}
|
||||
filePath={fileLinkMeta.filePath}
|
||||
label={labelParts.join(" · ")}
|
||||
theme={resolvedTheme}
|
||||
className={props.className}
|
||||
/>
|
||||
);
|
||||
},
|
||||
@@ -289,7 +549,13 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
);
|
||||
},
|
||||
}),
|
||||
[cwd, diffThemeName, isStreaming],
|
||||
[
|
||||
diffThemeName,
|
||||
fileLinkParentSuffixByPath,
|
||||
isStreaming,
|
||||
markdownFileLinkMetaByHref,
|
||||
resolvedTheme,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,7 @@ import {
|
||||
deriveComposerSendState,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
resolveSendEnvMode,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
waitForStartedServerThread,
|
||||
} from "./ChatView.logic";
|
||||
@@ -82,6 +83,17 @@ describe("buildExpiredTerminalContextToastCopy", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSendEnvMode", () => {
|
||||
it("keeps worktree mode for git repositories", () => {
|
||||
expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: true })).toBe("worktree");
|
||||
});
|
||||
|
||||
it("forces local mode for non-git repositories", () => {
|
||||
expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: false })).toBe("local");
|
||||
expect(resolveSendEnvMode({ requestedEnvMode: "local", isGitRepo: false })).toBe("local");
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconcileMountedTerminalThreadIds", () => {
|
||||
it("keeps previously mounted open threads and adds the active open thread", () => {
|
||||
expect(
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";
|
||||
import { randomUUID } from "~/lib/utils";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import { Schema } from "effect";
|
||||
import { selectThreadByRef, useStore } from "../store";
|
||||
@@ -17,10 +16,10 @@ import {
|
||||
stripInlineTerminalContextPlaceholders,
|
||||
type TerminalContextDraft,
|
||||
} from "../lib/terminalContext";
|
||||
import type { DraftThreadEnvMode } from "../composerDraftStore";
|
||||
|
||||
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
|
||||
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
|
||||
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
|
||||
|
||||
@@ -157,10 +156,11 @@ export function readFileAsDataUrl(file: File): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
export function buildTemporaryWorktreeBranchName(): string {
|
||||
// Keep the 8-hex suffix shape for backend temporary-branch detection.
|
||||
const token = randomUUID().slice(0, 8).toLowerCase();
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
export function resolveSendEnvMode(input: {
|
||||
requestedEnvMode: DraftThreadEnvMode;
|
||||
isGitRepo: boolean;
|
||||
}): DraftThreadEnvMode {
|
||||
return input.isGitRepo ? input.requestedEnvMode : "local";
|
||||
}
|
||||
|
||||
export function cloneComposerImageForRetry(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
type ApprovalRequestId,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ClaudeCodeEffort,
|
||||
type ClaudeAgentEffort,
|
||||
type EnvironmentId,
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
@@ -91,6 +91,9 @@ import {
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
|
||||
import { BranchToolbar } from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
@@ -110,7 +113,7 @@ import { getProviderModelCapabilities, resolveSelectableProvider } from "../prov
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { resolveAppModelSelection } from "../modelSelection";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { deriveLogicalProjectKey } from "../logicalProject";
|
||||
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
|
||||
import {
|
||||
useSavedEnvironmentRegistryStore,
|
||||
useSavedEnvironmentRuntimeStore,
|
||||
@@ -143,7 +146,6 @@ import {
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildLocalDraftThread,
|
||||
buildTemporaryWorktreeBranchName,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
@@ -156,6 +158,7 @@ import {
|
||||
deriveLockedProvider,
|
||||
readFileAsDataUrl,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
resolveSendEnvMode,
|
||||
revokeBlobPreviewUrl,
|
||||
revokeUserMessagePreviewUrls,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
@@ -170,6 +173,7 @@ import {
|
||||
} from "~/rpc/serverState";
|
||||
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
|
||||
import { retainThreadDetailSubscription } from "../environments/runtime/service";
|
||||
import { RightPanelSheet } from "./RightPanelSheet";
|
||||
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
@@ -302,7 +306,7 @@ function formatOutgoingPrompt(params: {
|
||||
}): string {
|
||||
const caps = getProviderModelCapabilities(params.models, params.model, params.provider);
|
||||
if (params.effort && caps.promptInjectedEffortLevels.includes(params.effort)) {
|
||||
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null);
|
||||
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeAgentEffort | null);
|
||||
}
|
||||
return params.text;
|
||||
}
|
||||
@@ -674,6 +678,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
|
||||
useState<Record<string, number>>({});
|
||||
const [planSidebarOpen, setPlanSidebarOpen] = useState(false);
|
||||
const shouldUsePlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
|
||||
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
|
||||
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
|
||||
// When set, the thread-change reset effect will open the sidebar instead of closing it.
|
||||
@@ -688,6 +693,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
|
||||
Record<string, string[]>
|
||||
>({});
|
||||
const [pendingServerThreadEnvMode, setPendingServerThreadEnvMode] =
|
||||
useState<DraftThreadEnvMode | null>(null);
|
||||
const [pendingServerThreadBranch, setPendingServerThreadBranch] = useState<string | null>();
|
||||
const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage(
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
{},
|
||||
@@ -839,10 +847,16 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId);
|
||||
const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId);
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const logicalProjectEnvironments = useMemo(() => {
|
||||
if (!activeProject) return [];
|
||||
const logicalKey = deriveLogicalProjectKey(activeProject);
|
||||
const memberProjects = allProjects.filter((p) => deriveLogicalProjectKey(p) === logicalKey);
|
||||
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
|
||||
const memberProjects = allProjects.filter(
|
||||
(p) => deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) === logicalKey,
|
||||
);
|
||||
const seen = new Set<string>();
|
||||
const envs: Array<{
|
||||
environmentId: EnvironmentId;
|
||||
@@ -878,6 +892,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}, [
|
||||
activeProject,
|
||||
allProjects,
|
||||
projectGroupingSettings,
|
||||
primaryEnvironmentId,
|
||||
savedEnvironmentRegistry,
|
||||
savedEnvironmentRuntimeById,
|
||||
@@ -907,7 +922,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
throw new Error("No active project is available for this pull request.");
|
||||
}
|
||||
const activeProjectRef = scopeProjectRef(activeProject.environmentId, activeProject.id);
|
||||
const logicalProjectKey = deriveLogicalProjectKey(activeProject);
|
||||
const logicalProjectKey = deriveLogicalProjectKeyFromSettings(
|
||||
activeProject,
|
||||
projectGroupingSettings,
|
||||
);
|
||||
const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey);
|
||||
if (storedDraftSession) {
|
||||
setDraftThreadContext(storedDraftSession.draftId, input);
|
||||
@@ -968,6 +986,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
getDraftSessionByLogicalProjectKey,
|
||||
isServerThread,
|
||||
navigate,
|
||||
projectGroupingSettings,
|
||||
routeKind,
|
||||
setDraftThreadContext,
|
||||
setLogicalProjectDraftThreadId,
|
||||
@@ -1103,6 +1122,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
() => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined),
|
||||
[activeLatestTurn?.turnId, threadActivities],
|
||||
);
|
||||
const planSidebarLabel = sidebarProposedPlan || interactionMode === "plan" ? "Plan" : "Tasks";
|
||||
const showPlanFollowUpPrompt =
|
||||
pendingUserInputs.length === 0 &&
|
||||
interactionMode === "plan" &&
|
||||
@@ -1884,16 +1904,19 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const togglePlanSidebar = useCallback(() => {
|
||||
setPlanSidebarOpen((open) => {
|
||||
if (open) {
|
||||
const turnKey = activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? null;
|
||||
if (turnKey) {
|
||||
planSidebarDismissedForTurnRef.current = turnKey;
|
||||
}
|
||||
planSidebarDismissedForTurnRef.current =
|
||||
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
|
||||
} else {
|
||||
planSidebarDismissedForTurnRef.current = null;
|
||||
}
|
||||
return !open;
|
||||
});
|
||||
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
|
||||
const closePlanSidebar = useCallback(() => {
|
||||
setPlanSidebarOpen(false);
|
||||
planSidebarDismissedForTurnRef.current =
|
||||
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
|
||||
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
|
||||
|
||||
const persistThreadSettingsForNextTurn = useCallback(
|
||||
async (input: {
|
||||
@@ -1985,6 +2008,18 @@ export default function ChatView(props: ChatViewProps) {
|
||||
planSidebarDismissedForTurnRef.current = null;
|
||||
}, [activeThread?.id]);
|
||||
|
||||
// Auto-open the plan sidebar when plan/todo steps arrive for the current turn.
|
||||
// Don't auto-open for plans carried over from a previous turn (the user can open manually).
|
||||
useEffect(() => {
|
||||
if (!activePlan) return;
|
||||
if (planSidebarOpen) return;
|
||||
const latestTurnId = activeLatestTurn?.turnId ?? null;
|
||||
if (latestTurnId && activePlan.turnId !== latestTurnId) return;
|
||||
const turnKey = activePlan.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
|
||||
if (planSidebarDismissedForTurnRef.current === turnKey) return;
|
||||
setPlanSidebarOpen(true);
|
||||
}, [activePlan, activeLatestTurn?.turnId, planSidebarOpen, sidebarProposedPlan?.turnId]);
|
||||
|
||||
useEffect(() => {
|
||||
setIsRevertingCheckpoint(false);
|
||||
}, [activeThread?.id]);
|
||||
@@ -2043,11 +2078,42 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}, []);
|
||||
|
||||
const activeWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const envMode: DraftThreadEnvMode = resolveEffectiveEnvMode({
|
||||
const derivedEnvMode: DraftThreadEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread: isServerThread,
|
||||
draftThreadEnvMode: isLocalDraftThread ? draftThread?.envMode : undefined,
|
||||
});
|
||||
const canOverrideServerThreadEnvMode = Boolean(
|
||||
isServerThread &&
|
||||
activeThread &&
|
||||
activeThread.messages.length === 0 &&
|
||||
activeThread.worktreePath === null &&
|
||||
!envLocked,
|
||||
);
|
||||
const envMode: DraftThreadEnvMode = canOverrideServerThreadEnvMode
|
||||
? (pendingServerThreadEnvMode ?? draftThread?.envMode ?? derivedEnvMode)
|
||||
: derivedEnvMode;
|
||||
const activeThreadBranch =
|
||||
canOverrideServerThreadEnvMode && pendingServerThreadBranch !== undefined
|
||||
? pendingServerThreadBranch
|
||||
: (activeThread?.branch ?? null);
|
||||
const sendEnvMode = resolveSendEnvMode({
|
||||
requestedEnvMode: envMode,
|
||||
isGitRepo,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setPendingServerThreadEnvMode(null);
|
||||
setPendingServerThreadBranch(undefined);
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (canOverrideServerThreadEnvMode) {
|
||||
return;
|
||||
}
|
||||
setPendingServerThreadEnvMode(null);
|
||||
setPendingServerThreadBranch(undefined);
|
||||
}, [canOverrideServerThreadEnvMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) {
|
||||
@@ -2360,15 +2426,15 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const threadIdForSend = activeThread.id;
|
||||
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
|
||||
const baseBranchForWorktree =
|
||||
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
|
||||
? activeThread.branch
|
||||
isFirstMessage && sendEnvMode === "worktree" && !activeThread.worktreePath
|
||||
? activeThreadBranch
|
||||
: null;
|
||||
|
||||
// In worktree mode, require an explicit base branch so we don't silently
|
||||
// fall back to local execution when branch selection is missing.
|
||||
const shouldCreateWorktree =
|
||||
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;
|
||||
if (shouldCreateWorktree && !activeThread.branch) {
|
||||
isFirstMessage && sendEnvMode === "worktree" && !activeThread.worktreePath;
|
||||
if (shouldCreateWorktree && !activeThreadBranch) {
|
||||
setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
|
||||
return;
|
||||
}
|
||||
@@ -2507,7 +2573,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
modelSelection: threadCreateModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
branch: activeThread.branch,
|
||||
branch: activeThreadBranch,
|
||||
worktreePath: activeThread.worktreePath,
|
||||
createdAt: activeThread.createdAt,
|
||||
},
|
||||
@@ -2959,7 +3025,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
modelSelection: nextThreadModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode: "default",
|
||||
branch: activeThread.branch,
|
||||
branch: activeThreadBranch,
|
||||
worktreePath: activeThread.worktreePath,
|
||||
createdAt,
|
||||
})
|
||||
@@ -3018,6 +3084,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}, [
|
||||
activeProject,
|
||||
activeProposedPlan,
|
||||
activeThreadBranch,
|
||||
activeThread,
|
||||
beginLocalDispatch,
|
||||
isConnecting,
|
||||
@@ -3066,6 +3133,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
);
|
||||
const onEnvModeChange = useCallback(
|
||||
(mode: DraftThreadEnvMode) => {
|
||||
if (canOverrideServerThreadEnvMode) {
|
||||
setPendingServerThreadEnvMode(mode);
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
if (isLocalDraftThread) {
|
||||
setDraftThreadContext(composerDraftTarget, {
|
||||
envMode: mode,
|
||||
@@ -3075,9 +3147,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[
|
||||
canOverrideServerThreadEnvMode,
|
||||
composerDraftTarget,
|
||||
draftThread?.worktreePath,
|
||||
isLocalDraftThread,
|
||||
setPendingServerThreadEnvMode,
|
||||
scheduleComposerFocus,
|
||||
setDraftThreadContext,
|
||||
],
|
||||
@@ -3186,7 +3260,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
{/* Messages — LegendList handles virtualization and scrolling internally */}
|
||||
<MessagesTimeline
|
||||
key={activeThread.id}
|
||||
hasMessages={timelineEntries.length > 0}
|
||||
isWorking={isWorking}
|
||||
activeTurnInProgress={isWorking || !latestTurnSettled}
|
||||
activeTurnId={activeLatestTurn?.turnId ?? null}
|
||||
@@ -3256,6 +3329,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
@@ -3300,6 +3374,13 @@ export default function ChatView(props: ChatViewProps) {
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
{...(canOverrideServerThreadEnvMode ? { effectiveEnvModeOverride: envMode } : {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
@@ -3333,22 +3414,17 @@ export default function ChatView(props: ChatViewProps) {
|
||||
{/* end chat column */}
|
||||
|
||||
{/* Plan sidebar */}
|
||||
{planSidebarOpen ? (
|
||||
{planSidebarOpen && !shouldUsePlanSidebarSheet ? (
|
||||
<PlanSidebar
|
||||
activePlan={activePlan}
|
||||
activeProposedPlan={sidebarProposedPlan}
|
||||
label={planSidebarLabel}
|
||||
environmentId={environmentId}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
workspaceRoot={activeWorkspaceRoot}
|
||||
timestampFormat={timestampFormat}
|
||||
onClose={() => {
|
||||
setPlanSidebarOpen(false);
|
||||
// Track that the user explicitly dismissed for this turn so auto-open won't fight them.
|
||||
const turnKey = activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? null;
|
||||
if (turnKey) {
|
||||
planSidebarDismissedForTurnRef.current = turnKey;
|
||||
}
|
||||
}}
|
||||
mode="sidebar"
|
||||
onClose={closePlanSidebar}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -3370,6 +3446,21 @@ export default function ChatView(props: ChatViewProps) {
|
||||
onAddTerminalContext={addTerminalContextToDraft}
|
||||
/>
|
||||
))}
|
||||
{shouldUsePlanSidebarSheet ? (
|
||||
<RightPanelSheet open={planSidebarOpen} onClose={closePlanSidebar}>
|
||||
<PlanSidebar
|
||||
activePlan={activePlan}
|
||||
activeProposedPlan={sidebarProposedPlan}
|
||||
label={planSidebarLabel}
|
||||
environmentId={environmentId}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
workspaceRoot={activeWorkspaceRoot}
|
||||
timestampFormat={timestampFormat}
|
||||
mode="sheet"
|
||||
onClose={closePlanSidebar}
|
||||
/>
|
||||
</RightPanelSheet>
|
||||
) : null}
|
||||
|
||||
{expandedImage && (
|
||||
<ExpandedImageDialog preview={expandedImage} onClose={closeExpandedImage} />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type KeybindingCommand } from "@t3tools/contracts";
|
||||
import { type KeybindingCommand, type FilesystemBrowseEntry } from "@t3tools/contracts";
|
||||
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import { type ReactNode } from "react";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
@@ -45,7 +45,39 @@ export interface CommandPaletteView {
|
||||
readonly initialQuery?: string;
|
||||
}
|
||||
|
||||
export type CommandPaletteMode = "root" | "submenu";
|
||||
export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
|
||||
|
||||
export function filterBrowseEntries(input: {
|
||||
browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
|
||||
browseFilterQuery: string;
|
||||
highlightedItemValue: string | null;
|
||||
}): {
|
||||
filteredEntries: FilesystemBrowseEntry[];
|
||||
highlightedEntry: FilesystemBrowseEntry | null;
|
||||
exactEntry: FilesystemBrowseEntry | null;
|
||||
} {
|
||||
const lowerFilter = input.browseFilterQuery.toLowerCase();
|
||||
const showHidden = input.browseFilterQuery.startsWith(".");
|
||||
|
||||
const filteredEntries = input.browseEntries.filter(
|
||||
(entry) =>
|
||||
entry.name.toLowerCase().startsWith(lowerFilter) &&
|
||||
(showHidden || !entry.name.startsWith(".")),
|
||||
);
|
||||
|
||||
let highlightedEntry: FilesystemBrowseEntry | null = null;
|
||||
if (input.highlightedItemValue?.startsWith("browse:")) {
|
||||
const highlightedPath = input.highlightedItemValue.slice("browse:".length);
|
||||
highlightedEntry = filteredEntries.find((entry) => entry.fullPath === highlightedPath) ?? null;
|
||||
}
|
||||
|
||||
const exactEntry =
|
||||
input.browseFilterQuery.length > 0
|
||||
? (filteredEntries.find((entry) => entry.name === input.browseFilterQuery) ?? null)
|
||||
: null;
|
||||
|
||||
return { filteredEntries, highlightedEntry, exactEntry };
|
||||
}
|
||||
|
||||
export function normalizeSearchText(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/\s+/g, " ");
|
||||
@@ -114,7 +146,9 @@ export function buildThreadActionItems(input: {
|
||||
searchTerms: [thread.title, projectTitle ?? "", thread.branch ?? ""],
|
||||
title: thread.title,
|
||||
description: descriptionParts.join(" · "),
|
||||
timestamp: formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt),
|
||||
timestamp: formatRelativeTimeLabel(
|
||||
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
|
||||
),
|
||||
icon: input.icon,
|
||||
run: async () => {
|
||||
await input.runThread(thread);
|
||||
@@ -228,10 +262,56 @@ export function filterCommandPaletteGroups(input: {
|
||||
});
|
||||
}
|
||||
|
||||
export function buildBrowseGroups(input: {
|
||||
browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
|
||||
browseQuery: string;
|
||||
canBrowseUp: boolean;
|
||||
upIcon: ReactNode;
|
||||
directoryIcon: ReactNode;
|
||||
browseUp: () => void;
|
||||
browseTo: (name: string) => void;
|
||||
}): CommandPaletteGroup[] {
|
||||
const items: CommandPaletteActionItem[] = [];
|
||||
|
||||
if (input.canBrowseUp) {
|
||||
items.push({
|
||||
kind: "action",
|
||||
value: "browse:up",
|
||||
searchTerms: [input.browseQuery, ".."],
|
||||
title: "..",
|
||||
icon: input.upIcon,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
input.browseUp();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
for (const entry of input.browseEntries) {
|
||||
items.push({
|
||||
kind: "action",
|
||||
value: `browse:${entry.fullPath}`,
|
||||
searchTerms: [input.browseQuery, entry.fullPath, entry.name],
|
||||
title: entry.name,
|
||||
icon: input.directoryIcon,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
input.browseTo(entry.name);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return [{ value: "directories", label: "Directories", items }];
|
||||
}
|
||||
|
||||
export function getCommandPaletteMode(input: {
|
||||
currentView: CommandPaletteView | null;
|
||||
isBrowsing: boolean;
|
||||
}): CommandPaletteMode {
|
||||
return input.currentView ? "submenu" : "root";
|
||||
if (input.currentView) {
|
||||
return input.isBrowsing ? "submenu-browse" : "submenu";
|
||||
}
|
||||
return input.isBrowsing ? "root-browse" : "root";
|
||||
}
|
||||
|
||||
export function buildRootGroups(input: {
|
||||
@@ -256,7 +336,11 @@ export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): str
|
||||
switch (mode) {
|
||||
case "root":
|
||||
return "Search commands, projects, and threads...";
|
||||
case "root-browse":
|
||||
return "Enter project path (e.g. ~/projects/my-app)";
|
||||
case "submenu":
|
||||
return "Search...";
|
||||
case "submenu-browse":
|
||||
return "Enter path (e.g. ~/projects/my-app)";
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { ProjectId } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type EnvironmentId,
|
||||
type FilesystemBrowseResult,
|
||||
type ProjectId,
|
||||
} from "@t3tools/contracts";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import {
|
||||
ArrowDownIcon,
|
||||
ArrowLeftIcon,
|
||||
ArrowUpIcon,
|
||||
CornerLeftUpIcon,
|
||||
FolderIcon,
|
||||
FolderPlusIcon,
|
||||
MessageSquareIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
useCallback,
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
useMemo,
|
||||
@@ -22,15 +32,37 @@ import {
|
||||
} from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import { readEnvironmentApi } from "../environmentApi";
|
||||
import { readPrimaryEnvironmentDescriptor, usePrimaryEnvironmentId } from "../environments/primary";
|
||||
import {
|
||||
useSavedEnvironmentRegistryStore,
|
||||
useSavedEnvironmentRuntimeStore,
|
||||
} from "../environments/runtime";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import {
|
||||
startNewThreadInProjectFromContext,
|
||||
startNewThreadFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import {
|
||||
appendBrowsePathSegment,
|
||||
canNavigateUp,
|
||||
ensureBrowseDirectoryPath,
|
||||
findProjectByPath,
|
||||
getBrowseDirectoryPath,
|
||||
getBrowseLeafPathSegment,
|
||||
getBrowseParentPath,
|
||||
hasTrailingPathSeparator,
|
||||
inferProjectTitleFromPath,
|
||||
isExplicitRelativeProjectPath,
|
||||
isFilesystemBrowseQuery,
|
||||
isUnsupportedWindowsProjectPath,
|
||||
resolveProjectPathForDispatch,
|
||||
} from "../lib/projectPaths";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { getLatestThreadForProject } from "../lib/threadSort";
|
||||
import { cn } from "../lib/utils";
|
||||
import { cn, isMacPlatform, isWindowsPlatform, newCommandId, newProjectId } from "../lib/utils";
|
||||
import {
|
||||
selectProjectsAcrossEnvironments,
|
||||
selectSidebarThreadsAcrossEnvironments,
|
||||
@@ -40,18 +72,21 @@ import { selectThreadTerminalState, useTerminalStateStore } from "../terminalSta
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import {
|
||||
ADDON_ICON_CLASS,
|
||||
buildBrowseGroups,
|
||||
buildProjectActionItems,
|
||||
buildRootGroups,
|
||||
buildThreadActionItems,
|
||||
type CommandPaletteActionItem,
|
||||
type CommandPaletteSubmenuItem,
|
||||
type CommandPaletteView,
|
||||
filterBrowseEntries,
|
||||
filterCommandPaletteGroups,
|
||||
getCommandPaletteInputPlaceholder,
|
||||
getCommandPaletteMode,
|
||||
ITEM_ICON_CLASS,
|
||||
RECENT_THREAD_LIMIT,
|
||||
} from "./CommandPalette.logic";
|
||||
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
|
||||
import { CommandPaletteResults } from "./CommandPaletteResults";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
@@ -64,11 +99,44 @@ import {
|
||||
CommandInput,
|
||||
CommandPanel,
|
||||
} from "./ui/command";
|
||||
import { Button } from "./ui/button";
|
||||
import { Kbd, KbdGroup } from "./ui/kbd";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
|
||||
import type { ChatComposerHandle } from "./chat/ChatComposer";
|
||||
|
||||
const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
|
||||
const BROWSE_STALE_TIME_MS = 30_000;
|
||||
|
||||
function getLocalFileManagerName(platform: string): string {
|
||||
if (isMacPlatform(platform)) {
|
||||
return "Finder";
|
||||
}
|
||||
if (isWindowsPlatform(platform)) {
|
||||
return "Explorer";
|
||||
}
|
||||
return "Files";
|
||||
}
|
||||
|
||||
function getEnvironmentBrowsePlatform(os: string | null | undefined): string {
|
||||
if (os === "windows") {
|
||||
return "Win32";
|
||||
}
|
||||
if (os === "darwin") {
|
||||
return "MacIntel";
|
||||
}
|
||||
if (os === "linux") {
|
||||
return "Linux";
|
||||
}
|
||||
return typeof navigator === "undefined" ? "" : navigator.platform;
|
||||
}
|
||||
|
||||
interface AddProjectEnvironmentOption {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
readonly isPrimary: boolean;
|
||||
}
|
||||
|
||||
export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
@@ -136,10 +204,14 @@ function CommandPaletteDialog() {
|
||||
function OpenCommandPaletteDialog() {
|
||||
const navigate = useNavigate();
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
const openIntent = useCommandPaletteStore((store) => store.openIntent);
|
||||
const clearOpenIntent = useCommandPaletteStore((store) => store.clearOpenIntent);
|
||||
const composerHandleRef = useComposerHandleContext();
|
||||
const [query, setQuery] = useState("");
|
||||
const deferredQuery = useDeferredValue(query);
|
||||
const isActionsOnly = deferredQuery.startsWith(">");
|
||||
const queryClient = useQueryClient();
|
||||
const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);
|
||||
const settings = useSettings();
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
|
||||
useHandleNewThread();
|
||||
@@ -148,15 +220,199 @@ function OpenCommandPaletteDialog() {
|
||||
const keybindings = useServerKeybindings();
|
||||
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
|
||||
const currentView = viewStack.at(-1) ?? null;
|
||||
const paletteMode = getCommandPaletteMode({ currentView });
|
||||
const [browseGeneration, setBrowseGeneration] = useState(0);
|
||||
const [addProjectEnvironmentId, setAddProjectEnvironmentId] = useState<EnvironmentId | null>(
|
||||
null,
|
||||
);
|
||||
const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false);
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const primaryEnvironmentLabel = readPrimaryEnvironmentDescriptor()?.label ?? null;
|
||||
const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((state) => state.byId);
|
||||
const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((state) => state.byId);
|
||||
|
||||
const addProjectEnvironmentOptions = useMemo(() => {
|
||||
const options: AddProjectEnvironmentOption[] = [];
|
||||
const seenEnvironmentIds = new Set<EnvironmentId>();
|
||||
|
||||
if (primaryEnvironmentId) {
|
||||
seenEnvironmentIds.add(primaryEnvironmentId);
|
||||
options.push({
|
||||
environmentId: primaryEnvironmentId,
|
||||
label: resolveEnvironmentOptionLabel({
|
||||
isPrimary: true,
|
||||
environmentId: primaryEnvironmentId,
|
||||
runtimeLabel: primaryEnvironmentLabel,
|
||||
}),
|
||||
isPrimary: true,
|
||||
});
|
||||
}
|
||||
|
||||
for (const record of Object.values(savedEnvironmentRegistry)) {
|
||||
if (seenEnvironmentIds.has(record.environmentId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const runtimeState = savedEnvironmentRuntimeById[record.environmentId];
|
||||
options.push({
|
||||
environmentId: record.environmentId,
|
||||
label: resolveEnvironmentOptionLabel({
|
||||
isPrimary: false,
|
||||
environmentId: record.environmentId,
|
||||
runtimeLabel: runtimeState?.descriptor?.label ?? null,
|
||||
savedLabel: record.label,
|
||||
}),
|
||||
isPrimary: false,
|
||||
});
|
||||
}
|
||||
|
||||
options.sort((left, right) => {
|
||||
if (left.isPrimary !== right.isPrimary) {
|
||||
return left.isPrimary ? -1 : 1;
|
||||
}
|
||||
return left.label.localeCompare(right.label);
|
||||
});
|
||||
|
||||
return options;
|
||||
}, [
|
||||
primaryEnvironmentId,
|
||||
primaryEnvironmentLabel,
|
||||
savedEnvironmentRegistry,
|
||||
savedEnvironmentRuntimeById,
|
||||
]);
|
||||
const defaultAddProjectEnvironmentId = addProjectEnvironmentOptions[0]?.environmentId ?? null;
|
||||
const browseEnvironmentId = addProjectEnvironmentId ?? defaultAddProjectEnvironmentId;
|
||||
const browseEnvironmentPlatform = useMemo(() => {
|
||||
const os =
|
||||
browseEnvironmentId && primaryEnvironmentId && browseEnvironmentId === primaryEnvironmentId
|
||||
? (readPrimaryEnvironmentDescriptor()?.platform.os ?? null)
|
||||
: browseEnvironmentId
|
||||
? (savedEnvironmentRuntimeById[browseEnvironmentId]?.descriptor?.platform.os ??
|
||||
savedEnvironmentRuntimeById[browseEnvironmentId]?.serverConfig?.environment.platform
|
||||
.os ??
|
||||
null)
|
||||
: null;
|
||||
return getEnvironmentBrowsePlatform(os);
|
||||
}, [browseEnvironmentId, primaryEnvironmentId, savedEnvironmentRuntimeById]);
|
||||
const isBrowsing = isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
|
||||
const paletteMode = getCommandPaletteMode({ currentView, isBrowsing });
|
||||
const getAddProjectInitialQueryForEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId | null): string => {
|
||||
const environmentSettings =
|
||||
environmentId && primaryEnvironmentId && environmentId === primaryEnvironmentId
|
||||
? settings
|
||||
: environmentId
|
||||
? savedEnvironmentRuntimeById[environmentId]?.serverConfig?.settings
|
||||
: null;
|
||||
const baseDirectory = environmentSettings?.addProjectBaseDirectory?.trim() ?? "";
|
||||
if (baseDirectory.length === 0) {
|
||||
return "~/";
|
||||
}
|
||||
return ensureBrowseDirectoryPath(baseDirectory);
|
||||
},
|
||||
[primaryEnvironmentId, savedEnvironmentRuntimeById, settings],
|
||||
);
|
||||
|
||||
const projectCwdById = useMemo(
|
||||
() => new Map<ProjectId, string>(projects.map((project) => [project.id, project.cwd])),
|
||||
[projects],
|
||||
);
|
||||
const projectTitleById = useMemo(
|
||||
() => new Map<ProjectId, string>(projects.map((project) => [project.id, project.name])),
|
||||
[projects],
|
||||
);
|
||||
|
||||
const activeThreadId = activeThread?.id;
|
||||
const currentProjectEnvironmentId =
|
||||
activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null;
|
||||
const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null;
|
||||
const currentProjectCwd = currentProjectId
|
||||
? (projectCwdById.get(currentProjectId) ?? null)
|
||||
: null;
|
||||
const currentProjectCwdForBrowse =
|
||||
browseEnvironmentId && currentProjectEnvironmentId === browseEnvironmentId
|
||||
? currentProjectCwd
|
||||
: null;
|
||||
const relativePathNeedsActiveProject =
|
||||
isExplicitRelativeProjectPath(query.trim()) && currentProjectCwdForBrowse === null;
|
||||
const browseDirectoryPath = isBrowsing ? getBrowseDirectoryPath(query) : "";
|
||||
const browseFilterQuery =
|
||||
isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : "";
|
||||
|
||||
const fetchBrowseResult = useCallback(
|
||||
async (partialPath: string): Promise<FilesystemBrowseResult | null> => {
|
||||
if (!browseEnvironmentId) return null;
|
||||
const api = readEnvironmentApi(browseEnvironmentId);
|
||||
if (!api) return null;
|
||||
return api.filesystem.browse({
|
||||
partialPath,
|
||||
...(currentProjectCwdForBrowse ? { cwd: currentProjectCwdForBrowse } : {}),
|
||||
});
|
||||
},
|
||||
[browseEnvironmentId, currentProjectCwdForBrowse],
|
||||
);
|
||||
|
||||
const { data: browseResult, isPending: isBrowsePending } = useQuery({
|
||||
queryKey: [
|
||||
"filesystemBrowse",
|
||||
browseEnvironmentId,
|
||||
browseDirectoryPath,
|
||||
currentProjectCwdForBrowse,
|
||||
],
|
||||
queryFn: () => fetchBrowseResult(browseDirectoryPath),
|
||||
staleTime: BROWSE_STALE_TIME_MS,
|
||||
enabled:
|
||||
isBrowsing &&
|
||||
browseDirectoryPath.length > 0 &&
|
||||
browseEnvironmentId !== null &&
|
||||
!relativePathNeedsActiveProject,
|
||||
});
|
||||
const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES;
|
||||
const {
|
||||
filteredEntries: filteredBrowseEntries,
|
||||
highlightedEntry: highlightedBrowseEntry,
|
||||
exactEntry: exactBrowseEntry,
|
||||
} = useMemo(
|
||||
() => filterBrowseEntries({ browseEntries, browseFilterQuery, highlightedItemValue }),
|
||||
[browseEntries, browseFilterQuery, highlightedItemValue],
|
||||
);
|
||||
|
||||
const prefetchBrowsePath = useCallback(
|
||||
(partialPath: string) => {
|
||||
void queryClient.prefetchQuery({
|
||||
queryKey: [
|
||||
"filesystemBrowse",
|
||||
browseEnvironmentId,
|
||||
partialPath,
|
||||
currentProjectCwdForBrowse,
|
||||
],
|
||||
queryFn: () => fetchBrowseResult(partialPath),
|
||||
staleTime: BROWSE_STALE_TIME_MS,
|
||||
});
|
||||
},
|
||||
[browseEnvironmentId, currentProjectCwdForBrowse, fetchBrowseResult, queryClient],
|
||||
);
|
||||
|
||||
// Prefetch the parent and the most likely next child so browse navigation
|
||||
// stays warm without scanning every child directory in large trees.
|
||||
useEffect(() => {
|
||||
if (!isBrowsing || filteredBrowseEntries.length === 0) return;
|
||||
|
||||
if (canNavigateUp(query)) {
|
||||
prefetchBrowsePath(getBrowseParentPath(query)!);
|
||||
}
|
||||
|
||||
const nextChild = highlightedBrowseEntry ?? exactBrowseEntry;
|
||||
if (nextChild) {
|
||||
prefetchBrowsePath(appendBrowsePathSegment(query, nextChild.name));
|
||||
}
|
||||
}, [
|
||||
exactBrowseEntry,
|
||||
filteredBrowseEntries.length,
|
||||
highlightedBrowseEntry,
|
||||
isBrowsing,
|
||||
prefetchBrowsePath,
|
||||
query,
|
||||
]);
|
||||
|
||||
const openProjectFromSearch = useMemo(
|
||||
() => async (project: (typeof projects)[number]) => {
|
||||
@@ -259,30 +515,117 @@ function OpenCommandPaletteDialog() {
|
||||
);
|
||||
const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
|
||||
|
||||
function pushView(item: CommandPaletteSubmenuItem): void {
|
||||
function pushPaletteView(view: CommandPaletteView): void {
|
||||
setViewStack((previousViews) => [
|
||||
...previousViews,
|
||||
{
|
||||
addonIcon: item.addonIcon,
|
||||
groups: item.groups,
|
||||
...(item.initialQuery ? { initialQuery: item.initialQuery } : {}),
|
||||
addonIcon: view.addonIcon,
|
||||
groups: view.groups,
|
||||
...(view.initialQuery ? { initialQuery: view.initialQuery } : {}),
|
||||
},
|
||||
]);
|
||||
setQuery(item.initialQuery ?? "");
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(view.initialQuery ?? "");
|
||||
}
|
||||
|
||||
function pushView(item: CommandPaletteSubmenuItem): void {
|
||||
pushPaletteView({
|
||||
addonIcon: item.addonIcon,
|
||||
groups: item.groups,
|
||||
...(item.initialQuery ? { initialQuery: item.initialQuery } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function popView(): void {
|
||||
if (viewStack.length <= 1) {
|
||||
setAddProjectEnvironmentId(null);
|
||||
}
|
||||
setViewStack((previousViews) => previousViews.slice(0, -1));
|
||||
setHighlightedItemValue(null);
|
||||
setQuery("");
|
||||
}
|
||||
|
||||
function handleQueryChange(nextQuery: string): void {
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(nextQuery);
|
||||
if (nextQuery === "" && currentView?.initialQuery) {
|
||||
popView();
|
||||
}
|
||||
}
|
||||
|
||||
const startAddProjectBrowse = useCallback(
|
||||
(environmentId: EnvironmentId): void => {
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
pushPaletteView({
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: [],
|
||||
initialQuery: getAddProjectInitialQueryForEnvironment(environmentId),
|
||||
});
|
||||
},
|
||||
[getAddProjectInitialQueryForEnvironment],
|
||||
);
|
||||
|
||||
const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map(
|
||||
(option) => ({
|
||||
kind: "action",
|
||||
value: `action:add-project:environment:${option.environmentId}`,
|
||||
searchTerms: [option.label, option.environmentId, option.isPrimary ? "this device" : ""],
|
||||
title: option.label,
|
||||
description: option.isPrimary ? "This device" : option.environmentId,
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
startAddProjectBrowse(option.environmentId);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const addProjectEnvironmentGroups = useMemo<CommandPaletteView["groups"]>(
|
||||
() => [
|
||||
{
|
||||
value: "environments",
|
||||
label: "Environments",
|
||||
items: addProjectEnvironmentItems,
|
||||
},
|
||||
],
|
||||
[addProjectEnvironmentItems],
|
||||
);
|
||||
|
||||
const openAddProjectFlow = useCallback(() => {
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
pushPaletteView({
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: addProjectEnvironmentGroups,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const environmentId = defaultAddProjectEnvironmentId;
|
||||
if (!environmentId) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to browse projects",
|
||||
description: "No environment is available.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
startAddProjectBrowse(environmentId);
|
||||
}, [
|
||||
addProjectEnvironmentGroups,
|
||||
addProjectEnvironmentOptions.length,
|
||||
defaultAddProjectEnvironmentId,
|
||||
startAddProjectBrowse,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (openIntent?.kind !== "add-project") {
|
||||
return;
|
||||
}
|
||||
clearOpenIntent();
|
||||
openAddProjectFlow();
|
||||
}, [clearOpenIntent, openAddProjectFlow, openIntent]);
|
||||
|
||||
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (projects.length > 0) {
|
||||
@@ -325,6 +668,30 @@ function OpenCommandPaletteDialog() {
|
||||
});
|
||||
}
|
||||
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
actionItems.push({
|
||||
kind: "submenu",
|
||||
value: "action:add-project",
|
||||
searchTerms: ["add project", "folder", "directory", "browse", "environment"],
|
||||
title: "Add project",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: addProjectEnvironmentGroups,
|
||||
});
|
||||
} else {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:add-project",
|
||||
searchTerms: ["add project", "folder", "directory", "browse"],
|
||||
title: "Add project",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
openAddProjectFlow();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:settings",
|
||||
@@ -339,7 +706,7 @@ function OpenCommandPaletteDialog() {
|
||||
const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
|
||||
const activeGroups = currentView ? currentView.groups : rootGroups;
|
||||
|
||||
const displayedGroups = filterCommandPaletteGroups({
|
||||
const filteredGroups = filterCommandPaletteGroups({
|
||||
activeGroups,
|
||||
query: deferredQuery,
|
||||
isInSubmenu: currentView !== null,
|
||||
@@ -347,10 +714,206 @@ function OpenCommandPaletteDialog() {
|
||||
threadSearchItems: allThreadItems,
|
||||
});
|
||||
|
||||
const handleAddProject = useCallback(
|
||||
async (rawCwd: string) => {
|
||||
if (!browseEnvironmentId) return;
|
||||
const api = readEnvironmentApi(browseEnvironmentId);
|
||||
if (!api) return;
|
||||
|
||||
if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to add project",
|
||||
description: "Windows-style paths are only supported on Windows.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to add project",
|
||||
description: "Relative paths require an active project.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const cwd = resolveProjectPathForDispatch(rawCwd, currentProjectCwdForBrowse);
|
||||
if (cwd.length === 0) return;
|
||||
|
||||
const existing = findProjectByPath(
|
||||
projects.filter((project) => project.environmentId === browseEnvironmentId),
|
||||
cwd,
|
||||
);
|
||||
if (existing) {
|
||||
const latestThread = getLatestThreadForProject(
|
||||
threads.filter((thread) => thread.environmentId === existing.environmentId),
|
||||
existing.id,
|
||||
settings.sidebarThreadSortOrder,
|
||||
);
|
||||
if (latestThread) {
|
||||
await navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(
|
||||
scopeThreadRef(latestThread.environmentId, latestThread.id),
|
||||
),
|
||||
});
|
||||
} else {
|
||||
await handleNewThread(scopeProjectRef(existing.environmentId, existing.id), {
|
||||
envMode: settings.defaultThreadEnvMode,
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const projectId = newProjectId();
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "project.create",
|
||||
commandId: newCommandId(),
|
||||
projectId,
|
||||
title: inferProjectTitleFromPath(cwd),
|
||||
workspaceRoot: cwd,
|
||||
createWorkspaceRootIfMissing: true,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
await handleNewThread(scopeProjectRef(browseEnvironmentId, projectId), {
|
||||
envMode: settings.defaultThreadEnvMode,
|
||||
}).catch(() => undefined);
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to add project",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
},
|
||||
[
|
||||
browseEnvironmentId,
|
||||
browseEnvironmentPlatform,
|
||||
currentProjectCwdForBrowse,
|
||||
handleNewThread,
|
||||
navigate,
|
||||
projects,
|
||||
setOpen,
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.sidebarThreadSortOrder,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
function browseTo(name: string): void {
|
||||
const nextQuery = appendBrowsePathSegment(query, name);
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(nextQuery);
|
||||
setBrowseGeneration((generation) => generation + 1);
|
||||
}
|
||||
|
||||
function browseUp(): void {
|
||||
const parentPath = getBrowseParentPath(query);
|
||||
if (parentPath === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(parentPath);
|
||||
setBrowseGeneration((generation) => generation + 1);
|
||||
}
|
||||
|
||||
// Resolve the add-project path from browse data when available. When the
|
||||
// query has a trailing separator (e.g. "~/projects/foo/"), parentPath is the
|
||||
// directory itself. Otherwise the user typed a partial leaf name, so we need
|
||||
// the exact browse entry's fullPath or fall back to the raw query.
|
||||
const resolvedAddProjectPath = hasTrailingPathSeparator(query)
|
||||
? (browseResult?.parentPath ?? query.trim())
|
||||
: (exactBrowseEntry?.fullPath ?? query.trim());
|
||||
|
||||
const canBrowseUp =
|
||||
isBrowsing && !relativePathNeedsActiveProject && canNavigateUp(browseDirectoryPath);
|
||||
|
||||
const browseGroups = buildBrowseGroups({
|
||||
browseEntries: filteredBrowseEntries,
|
||||
browseQuery: query,
|
||||
canBrowseUp,
|
||||
upIcon: <CornerLeftUpIcon className={ITEM_ICON_CLASS} />,
|
||||
directoryIcon: <FolderIcon className={ITEM_ICON_CLASS} />,
|
||||
browseUp,
|
||||
browseTo,
|
||||
});
|
||||
|
||||
let displayedGroups = filteredGroups;
|
||||
if (isBrowsing) {
|
||||
displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups;
|
||||
}
|
||||
|
||||
const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
|
||||
const isSubmenu = paletteMode === "submenu";
|
||||
const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
|
||||
const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
|
||||
const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject;
|
||||
const willCreateProjectPath =
|
||||
canSubmitBrowsePath &&
|
||||
!isBrowsePending &&
|
||||
query.trim().length > 0 &&
|
||||
!hasHighlightedBrowseItem &&
|
||||
(hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null);
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl";
|
||||
const submitActionLabel = willCreateProjectPath ? "Create & Add" : "Add";
|
||||
const addShortcutLabel = hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter";
|
||||
const fileManagerName = getLocalFileManagerName(navigator.platform);
|
||||
const canOpenProjectFromFileManager =
|
||||
isBrowsing &&
|
||||
browseEnvironmentId !== null &&
|
||||
primaryEnvironmentId !== null &&
|
||||
browseEnvironmentId === primaryEnvironmentId &&
|
||||
typeof window !== "undefined" &&
|
||||
window.desktopBridge !== undefined;
|
||||
const fileManagerInitialPath = useMemo(() => {
|
||||
if (!canOpenProjectFromFileManager) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const trimmedQuery = query.trim();
|
||||
if (trimmedQuery.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const initialPath = hasTrailingPathSeparator(query)
|
||||
? (browseResult?.parentPath ?? trimmedQuery)
|
||||
: browseDirectoryPath || trimmedQuery;
|
||||
|
||||
const resolvedPath = resolveProjectPathForDispatch(initialPath, currentProjectCwdForBrowse);
|
||||
return resolvedPath.length > 0 ? resolvedPath : undefined;
|
||||
}, [
|
||||
browseDirectoryPath,
|
||||
browseResult?.parentPath,
|
||||
canOpenProjectFromFileManager,
|
||||
currentProjectCwdForBrowse,
|
||||
query,
|
||||
]);
|
||||
|
||||
function isPrimaryModifierPressed(event: KeyboardEvent<HTMLInputElement>): boolean {
|
||||
return useMetaForMod ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
|
||||
}
|
||||
|
||||
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
|
||||
const shouldSubmitBrowsePath =
|
||||
canSubmitBrowsePath &&
|
||||
event.key === "Enter" &&
|
||||
(!hasHighlightedBrowseItem || isPrimaryModifierPressed(event));
|
||||
|
||||
if (shouldSubmitBrowsePath) {
|
||||
event.preventDefault();
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === "Backspace" && query === "" && isSubmenu) {
|
||||
event.preventDefault();
|
||||
popView();
|
||||
@@ -376,6 +939,38 @@ function OpenCommandPaletteDialog() {
|
||||
});
|
||||
}
|
||||
|
||||
const handleOpenProjectFromFileManager = useCallback(async () => {
|
||||
if (!canOpenProjectFromFileManager || isPickingProjectFolder) {
|
||||
return;
|
||||
}
|
||||
const api = readLocalApi();
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPickingProjectFolder(true);
|
||||
let pickedPath: string | null = null;
|
||||
try {
|
||||
pickedPath = await api.dialogs.pickFolder(
|
||||
fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : undefined,
|
||||
);
|
||||
} catch {
|
||||
// Ignore picker failures and leave the palette open.
|
||||
setIsPickingProjectFolder(false);
|
||||
return;
|
||||
}
|
||||
setIsPickingProjectFolder(false);
|
||||
if (!pickedPath) {
|
||||
return;
|
||||
}
|
||||
await handleAddProject(pickedPath);
|
||||
}, [
|
||||
canOpenProjectFromFileManager,
|
||||
fileManagerInitialPath,
|
||||
handleAddProject,
|
||||
isPickingProjectFolder,
|
||||
]);
|
||||
|
||||
return (
|
||||
<CommandDialogPopup
|
||||
aria-label="Command palette"
|
||||
@@ -387,42 +982,86 @@ function OpenCommandPaletteDialog() {
|
||||
}}
|
||||
>
|
||||
<Command
|
||||
key={viewStack.length}
|
||||
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}`}
|
||||
aria-label="Command palette"
|
||||
autoHighlight="always"
|
||||
autoHighlight={isBrowsing ? false : "always"}
|
||||
mode="none"
|
||||
onItemHighlighted={(value) => {
|
||||
setHighlightedItemValue(typeof value === "string" ? value : null);
|
||||
}}
|
||||
onValueChange={handleQueryChange}
|
||||
value={query}
|
||||
>
|
||||
<CommandInput
|
||||
placeholder={inputPlaceholder}
|
||||
wrapperClassName={
|
||||
isSubmenu
|
||||
? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto [&_[data-slot=autocomplete-start-addon]]:cursor-pointer"
|
||||
: undefined
|
||||
}
|
||||
{...(isSubmenu
|
||||
? {
|
||||
startAddon: (
|
||||
<button
|
||||
type="button"
|
||||
className="flex cursor-pointer items-center"
|
||||
aria-label="Back"
|
||||
onClick={popView}
|
||||
>
|
||||
<ArrowLeftIcon />
|
||||
</button>
|
||||
),
|
||||
}
|
||||
: {})}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
<div className="relative">
|
||||
<CommandInput
|
||||
className={isBrowsing ? (willCreateProjectPath ? "pe-36" : "pe-16") : undefined}
|
||||
placeholder={inputPlaceholder}
|
||||
wrapperClassName={
|
||||
isSubmenu ? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto" : undefined
|
||||
}
|
||||
{...(isSubmenu
|
||||
? {
|
||||
startAddon: (
|
||||
<button
|
||||
type="button"
|
||||
className="flex cursor-pointer items-center"
|
||||
aria-label="Back"
|
||||
onClick={popView}
|
||||
>
|
||||
<ArrowLeftIcon />
|
||||
</button>
|
||||
),
|
||||
}
|
||||
: isBrowsing && !isSubmenu
|
||||
? {
|
||||
startAddon: <FolderPlusIcon />,
|
||||
}
|
||||
: {})}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
{isBrowsing ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className={cn(
|
||||
"absolute end-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
|
||||
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
|
||||
)}
|
||||
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
disabled={relativePathNeedsActiveProject}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (relativePathNeedsActiveProject) {
|
||||
return;
|
||||
}
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
}}
|
||||
title={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
>
|
||||
<span>{submitActionLabel}</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
|
||||
</KbdGroup>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<CommandPanel className="max-h-[min(28rem,70vh)]">
|
||||
<CommandPaletteResults
|
||||
groups={displayedGroups}
|
||||
highlightedItemValue={highlightedItemValue}
|
||||
isActionsOnly={isActionsOnly}
|
||||
keybindings={keybindings}
|
||||
onExecuteItem={executeItem}
|
||||
{...(relativePathNeedsActiveProject
|
||||
? { emptyStateMessage: "Relative paths require an active project." }
|
||||
: willCreateProjectPath
|
||||
? {
|
||||
emptyStateMessage: "Press Enter to create this folder and add it as a project.",
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
</CommandPanel>
|
||||
<CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
|
||||
@@ -436,10 +1075,12 @@ function OpenCommandPaletteDialog() {
|
||||
</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Navigate</span>
|
||||
</KbdGroup>
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Select</span>
|
||||
</KbdGroup>
|
||||
{!canSubmitBrowsePath || hasHighlightedBrowseItem ? (
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Select</span>
|
||||
</KbdGroup>
|
||||
) : null}
|
||||
{isSubmenu ? (
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Backspace</Kbd>
|
||||
@@ -451,6 +1092,19 @@ function OpenCommandPaletteDialog() {
|
||||
<span className={cn("text-muted-foreground/80")}>Close</span>
|
||||
</KbdGroup>
|
||||
</div>
|
||||
{canOpenProjectFromFileManager ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
className="h-auto px-2 text-xs text-muted-foreground/80 hover:bg-transparent hover:text-foreground"
|
||||
disabled={isPickingProjectFolder}
|
||||
onClick={() => {
|
||||
void handleOpenProjectFromFileManager();
|
||||
}}
|
||||
>
|
||||
{`Open in ${fileManagerName}`}
|
||||
</Button>
|
||||
) : null}
|
||||
</CommandFooter>
|
||||
</Command>
|
||||
</CommandDialogPopup>
|
||||
|
||||
@@ -14,10 +14,12 @@ import {
|
||||
CommandList,
|
||||
CommandShortcut,
|
||||
} from "./ui/command";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
interface CommandPaletteResultsProps {
|
||||
emptyStateMessage?: string;
|
||||
groups: ReadonlyArray<CommandPaletteGroup>;
|
||||
highlightedItemValue?: string | null;
|
||||
isActionsOnly: boolean;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
|
||||
@@ -46,6 +48,7 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
|
||||
item={item}
|
||||
key={item.value}
|
||||
keybindings={props.keybindings}
|
||||
isActive={props.highlightedItemValue === item.value}
|
||||
onExecuteItem={props.onExecuteItem}
|
||||
/>
|
||||
)}
|
||||
@@ -58,6 +61,7 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
|
||||
|
||||
function CommandPaletteResultRow(props: {
|
||||
item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
|
||||
isActive: boolean;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
|
||||
}) {
|
||||
@@ -68,7 +72,10 @@ function CommandPaletteResultRow(props: {
|
||||
return (
|
||||
<CommandItem
|
||||
value={props.item.value}
|
||||
className="cursor-pointer gap-2"
|
||||
className={cn(
|
||||
"cursor-pointer gap-2 hover:bg-transparent hover:text-inherit data-highlighted:bg-transparent data-highlighted:text-inherit data-selected:bg-transparent data-selected:text-inherit [&[data-highlighted][data-selected]]:bg-transparent [&[data-highlighted][data-selected]]:text-inherit",
|
||||
props.isActive && "bg-accent! text-accent-foreground!",
|
||||
)}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
|
||||
@@ -32,11 +32,8 @@ import {
|
||||
type ElementNode,
|
||||
type LexicalNode,
|
||||
type SerializedLexicalNode,
|
||||
TextNode,
|
||||
type EditorConfig,
|
||||
type EditorState,
|
||||
type NodeKey,
|
||||
type SerializedTextNode,
|
||||
type Spread,
|
||||
} from "lexical";
|
||||
import {
|
||||
@@ -103,7 +100,7 @@ type SerializedComposerMentionNode = Spread<
|
||||
type: "composer-mention";
|
||||
version: 1;
|
||||
},
|
||||
SerializedTextNode
|
||||
SerializedLexicalNode
|
||||
>;
|
||||
|
||||
type SerializedComposerSkillNode = Spread<
|
||||
@@ -132,7 +129,40 @@ const ComposerTerminalContextActionsContext = createContext<{
|
||||
onRemoveTerminalContext: () => {},
|
||||
});
|
||||
|
||||
class ComposerMentionNode extends TextNode {
|
||||
function ComposerMentionDecorator(props: { path: string }) {
|
||||
const theme = resolvedThemeFromDocument();
|
||||
const chip = (
|
||||
<span
|
||||
className={COMPOSER_INLINE_CHIP_CLASS_NAME}
|
||||
contentEditable={false}
|
||||
spellCheck={false}
|
||||
data-composer-mention-chip="true"
|
||||
>
|
||||
<img
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
|
||||
loading="lazy"
|
||||
src={getVscodeIconUrlForEntry(props.path, inferEntryKindFromPath(props.path), theme)}
|
||||
/>
|
||||
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{basenameOfPath(props.path)}</span>
|
||||
</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={chip} />
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-[30rem] whitespace-normal leading-tight wrap-anywhere"
|
||||
>
|
||||
{props.path}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
class ComposerMentionNode extends DecoratorNode<ReactElement> {
|
||||
__path: string;
|
||||
|
||||
static override getType(): string {
|
||||
@@ -144,12 +174,12 @@ class ComposerMentionNode extends TextNode {
|
||||
}
|
||||
|
||||
static override importJSON(serializedNode: SerializedComposerMentionNode): ComposerMentionNode {
|
||||
return $createComposerMentionNode(serializedNode.path);
|
||||
return $createComposerMentionNode(serializedNode.path).updateFromJSON(serializedNode);
|
||||
}
|
||||
|
||||
constructor(path: string, key?: NodeKey) {
|
||||
super(key);
|
||||
const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
|
||||
super(`@${normalizedPath}`, key);
|
||||
this.__path = normalizedPath;
|
||||
}
|
||||
|
||||
@@ -162,41 +192,26 @@ class ComposerMentionNode extends TextNode {
|
||||
};
|
||||
}
|
||||
|
||||
override createDOM(_config: EditorConfig): HTMLElement {
|
||||
override createDOM(): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className = COMPOSER_INLINE_CHIP_CLASS_NAME;
|
||||
dom.contentEditable = "false";
|
||||
dom.setAttribute("spellcheck", "false");
|
||||
renderMentionChipDom(dom, this.__path);
|
||||
dom.className = "inline-flex align-middle leading-none";
|
||||
return dom;
|
||||
}
|
||||
|
||||
override updateDOM(
|
||||
prevNode: ComposerMentionNode,
|
||||
dom: HTMLElement,
|
||||
_config: EditorConfig,
|
||||
): boolean {
|
||||
dom.contentEditable = "false";
|
||||
if (prevNode.__text !== this.__text || prevNode.__path !== this.__path) {
|
||||
renderMentionChipDom(dom, this.__path);
|
||||
}
|
||||
override updateDOM(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override canInsertTextBefore(): false {
|
||||
return false;
|
||||
override getTextContent(): string {
|
||||
return `@${this.__path}`;
|
||||
}
|
||||
|
||||
override canInsertTextAfter(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override isTextEntity(): true {
|
||||
override isInline(): true {
|
||||
return true;
|
||||
}
|
||||
|
||||
override isToken(): true {
|
||||
return true;
|
||||
override decorate(): ReactElement {
|
||||
return <ComposerMentionDecorator path={this.__path} />;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,26 +449,6 @@ function resolvedThemeFromDocument(): "light" | "dark" {
|
||||
return document.documentElement.classList.contains("dark") ? "dark" : "light";
|
||||
}
|
||||
|
||||
function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
|
||||
container.textContent = "";
|
||||
container.style.setProperty("user-select", "none");
|
||||
container.style.setProperty("-webkit-user-select", "none");
|
||||
|
||||
const theme = resolvedThemeFromDocument();
|
||||
const icon = document.createElement("img");
|
||||
icon.alt = "";
|
||||
icon.ariaHidden = "true";
|
||||
icon.className = COMPOSER_INLINE_CHIP_ICON_CLASS_NAME;
|
||||
icon.loading = "lazy";
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferEntryKindFromPath(pathValue), theme);
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME;
|
||||
label.textContent = basenameOfPath(pathValue);
|
||||
|
||||
container.append(icon, label);
|
||||
}
|
||||
|
||||
function terminalContextSignature(contexts: ReadonlyArray<TerminalContextDraft>): string {
|
||||
return contexts
|
||||
.map((context) =>
|
||||
@@ -595,12 +590,9 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) {
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
@@ -642,12 +634,9 @@ function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: numbe
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) {
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
@@ -673,10 +662,7 @@ function findSelectionPointAtOffset(
|
||||
node: LexicalNode,
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "text" | "element" } | null {
|
||||
if (node instanceof ComposerMentionNode || node instanceof ComposerSkillNode) {
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
|
||||
|
||||
@@ -1020,6 +1020,15 @@ describe("resolveLiveThreadBranchUpdate", () => {
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
|
||||
it("does not regress a semantic thread branch back to a temporary worktree branch", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "t3code/github-query-rate-limit",
|
||||
gitStatus: status({ branch: "t3code/bda76797" }),
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAutoFeatureBranchName", () => {
|
||||
|
||||
Loaded 100 of 218 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user