Compare commits

..
Author SHA1 Message Date
Julius Marminge 3631d0a8ee Install Spectre MSVC libs for Windows release builds
- Fix Windows release artifact builds by adding the Spectre-mitigated MSVC components
- Verify the libraries are installed before continuing
- Co-authored-by: codex <[email protected]>
2026-04-16 20:28:16 -07:00
Julius Marminge 505db9f696 try out blacksmith for releases (#2101) 2026-04-16 20:12:09 -07:00
t3-code[bot] 2d87574e62 chore(release): prepare v0.0.20 2026-04-17 03:00:57 +00:00
Julius Marminge b2cca674df ci(release): install deps before finalize version bump (#2100) 2026-04-16 19:42:17 -07:00
Julius Marminge 549043863a fix: guard against missing sidebarProjectGroupingOverrides in client settings (#2099) 2026-04-17 02:36:39 +00:00
Julius Marminge b7df3dfca0 [codex] Fix Windows release manifest publishing (#2095) 2026-04-16 17:56:16 -07:00
Evan YuandJulius Marminge 6891c77d3e Build for Windows ARM (#2080)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 17:01:27 -07:00
m9d5m d90e15d1d7 fix(server): extend negative repository identity cache ttl (#2083) 2026-04-16 16:57:39 -07:00
e0117b271a Fix Claude Process leak[MEMORY INTENSIVE], archiving, and stale claude session monitoring. (#2042)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-16 16:30:56 -07:00
188a40c315 feat: configurable project grouping (#2055)
Co-authored-by: tlh38 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-16 16:29:25 -07:00
Utkarsh Patil 7a08fcf2e8 fix(server): drop stale text generation options when resetting text-gen model selection (#2076) 2026-04-16 20:01:35 +00:00
Utkarsh Patil 19d47408a5 fix(web): prevent composer controls overlap on narrow windows (make plan sidebar responsive) (#1198) 2026-04-16 11:13:59 -07:00
Ibrahim ElkamaliandJulius Marminge 3e07f5a6a4 feat: add Claude Opus 4.7 to built-in models (#2072)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 11:11:59 -07:00
Marcus Grando d22c6f5280 fix: prevent user-input activities from leaking into pending approvals projection (#2051) 2026-04-16 05:09:29 +00:00
Marcus Grando 5e13f53571 fix: remove trailing newline from CLAUDE.md symlink (#2052) 2026-04-15 22:05:10 -07:00
f9580ff088 Default nightly desktop builds to the nightly update channel (#2049)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-15 21:31:24 -07:00
AndreiandJulius Marminge 5e1dd56d2c feat: add Launch Args setting for Claude provider (#1971)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 21:26:36 +00:00
legsandJulius Marminge 68061af042 Improve markdown file link UX (#1956)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 14:20:28 -07:00
Guilherme Vieira 28cb9db20b feat(web): add tooltip to composer file mention pill (#1944) 2026-04-15 13:29:13 -07:00
SakethandJulius Marminge 7968f278ee Fix terminal Cmd+Backspace on macOS (#2027)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 06:29:45 +00:00
44afe784a3 Add filesystem browse API and command palette project picker (#2024)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-14 23:26:05 -07:00
Julius Marmingeandcodex 9ff31f8c35 Fix nightly desktop product name (#2025)
Co-authored-by: codex <[email protected]>
2026-04-14 19:12:36 -07:00
409ff90a14 Nightly release channel (#2012)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-14 18:18:37 -07:00
0d280262f6 fix(claude): emit plan events for TodoWrite during input streaming (#1541)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-13 19:35:40 -07:00
183 changed files with 10865 additions and 6969 deletions

No files matched your search

+5 -2
View File
@@ -9,7 +9,7 @@ on:
jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -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
View File
@@ -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
View File
@@ -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": {}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.17",
"version": "0.0.20",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+67 -1
View File
@@ -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 });
+47
View File
@@ -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)",
});
});
});
+28
View File
@@ -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})`,
};
}
@@ -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",
+15 -2
View File
@@ -1,8 +1,13 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import {
ClientSettingsSchema,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { Predicate } from "effect";
import * as Schema from "effect/Schema";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
@@ -83,7 +88,15 @@ function toPersistedSavedEnvironmentRecord(
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
if (!raw) {
return null;
}
try {
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
} catch {
return null;
}
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
+86 -3
View File
@@ -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,
});
});
});
+45 -4
View File
@@ -1,15 +1,28 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels";
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;
}
}
+196 -49
View File
@@ -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,7 @@ 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,
@@ -69,6 +73,7 @@ import {
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
import { resolveDesktopAppBranding } from "./appBranding";
syncShellEnvironment();
@@ -80,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";
@@ -101,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";
@@ -116,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;
@@ -125,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"
@@ -156,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;
@@ -167,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();
@@ -975,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}`);
}
@@ -1074,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);
@@ -1193,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;
}
@@ -1205,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;
@@ -1222,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,
@@ -1486,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 = {
@@ -1599,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;
});
@@ -1636,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;
}
@@ -1664,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,
@@ -1713,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();
+11 -1
View File
@@ -9,9 +9,11 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -24,6 +26,13 @@ const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
const result = ipcRenderer.sendSync(GET_APP_BRANDING_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
@@ -44,7 +53,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
@@ -61,6 +70,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) => ipcRenderer.invoke(UPDATE_SET_CHANNEL_CHANNEL, channel),
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
+41
View File
@@ -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);
});
});
+18
View File
@@ -0,0 +1,18 @@
import type { DesktopUpdateChannel } from "@t3tools/contracts";
const NIGHTLY_VERSION_PATTERN = /-nightly\.\d{8}\.\d+$/;
export function isNightlyDesktopVersion(version: string): boolean {
return NIGHTLY_VERSION_PATTERN.test(version);
}
export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
return isNightlyDesktopVersion(appVersion) ? "nightly" : "latest";
}
export function doesVersionMatchDesktopUpdateChannel(
version: string,
channel: DesktopUpdateChannel,
): boolean {
return resolveDefaultDesktopUpdateChannel(version) === channel;
}
+7 -6
View File
@@ -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);
+7 -1
View File
@@ -1,14 +1,20 @@
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
import type {
DesktopRuntimeInfo,
DesktopUpdateChannel,
DesktopUpdateState,
} from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
export function createInitialDesktopUpdateState(
currentVersion: string,
runtimeInfo: DesktopRuntimeInfo,
channel: DesktopUpdateChannel,
): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
channel,
currentVersion,
hostArch: runtimeInfo.hostArch,
appArch: runtimeInfo.appArch,
+1
View File
@@ -11,6 +11,7 @@ import {
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
+4 -3
View File
@@ -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", () => {
+36 -2
View File
@@ -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[] {
@@ -166,6 +166,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
[
"exec",
"--ephemeral",
"--skip-git-repo-check",
"-s",
"read-only",
"--model",
-15
View File
@@ -188,21 +188,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const),
);
assert.equal(defaultsByCommand.get("workspace.pane.splitRight"), "mod+d");
assert.equal(defaultsByCommand.get("workspace.pane.splitDown"), "mod+shift+d");
assert.equal(defaultsByCommand.get("workspace.pane.close"), "mod+w");
assert.equal(defaultsByCommand.get("workspace.focus.previous"), "mod+[");
assert.equal(defaultsByCommand.get("workspace.focus.next"), "mod+]");
assert.equal(defaultsByCommand.get("workspace.focus.left"), "mod+alt+arrowleft");
assert.equal(defaultsByCommand.get("workspace.focus.right"), "mod+alt+arrowright");
assert.equal(defaultsByCommand.get("workspace.focus.up"), "mod+alt+arrowup");
assert.equal(defaultsByCommand.get("workspace.focus.down"), "mod+alt+arrowdown");
assert.equal(defaultsByCommand.get("workspace.pane.toggleZoom"), "mod+shift+enter");
assert.equal(defaultsByCommand.get("workspace.pane.resizeLeft"), "mod+ctrl+arrowleft");
assert.equal(defaultsByCommand.get("workspace.pane.resizeRight"), "mod+ctrl+arrowright");
assert.equal(defaultsByCommand.get("workspace.pane.resizeUp"), "mod+ctrl+arrowup");
assert.equal(defaultsByCommand.get("workspace.pane.resizeDown"), "mod+ctrl+arrowdown");
assert.equal(defaultsByCommand.get("workspace.pane.equalize"), "mod+ctrl+=");
assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+[");
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
+1 -16
View File
@@ -60,22 +60,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+d", command: "workspace.pane.splitRight", when: "!terminalFocus" },
{ key: "mod+shift+d", command: "workspace.pane.splitDown", when: "!terminalFocus" },
{ key: "mod+w", command: "workspace.pane.close", when: "!terminalFocus" },
{ key: "mod+[", command: "workspace.focus.previous" },
{ key: "mod+]", command: "workspace.focus.next" },
{ key: "mod+alt+arrowup", command: "workspace.focus.up" },
{ key: "mod+alt+arrowdown", command: "workspace.focus.down" },
{ key: "mod+alt+arrowleft", command: "workspace.focus.left" },
{ key: "mod+alt+arrowright", command: "workspace.focus.right" },
{ key: "mod+shift+enter", command: "workspace.pane.toggleZoom" },
{ key: "mod+ctrl+arrowup", command: "workspace.pane.resizeUp" },
{ key: "mod+ctrl+arrowdown", command: "workspace.pane.resizeDown" },
{ key: "mod+ctrl+arrowleft", command: "workspace.pane.resizeLeft" },
{ key: "mod+ctrl+arrowright", command: "workspace.pane.resizeRight" },
{ key: "mod+ctrl+=", command: "workspace.pane.equalize" },
{ key: "mod+alt+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
@@ -1284,6 +1284,14 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
return;
}
// Only approval-requested activities should create pending-approval
// rows. Other activity kinds that happen to carry a requestId
// (e.g. user-input.requested / user-input.resolved) must not
// pollute this projection — they have their own accounting via
// derivePendingUserInputCountFromActivities.
if (event.payload.activity.kind !== "approval.requested") {
return;
}
if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
return;
}
@@ -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,
+22 -1
View File
@@ -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;
}
@@ -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.
+174 -27
View File
@@ -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,7 +710,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
...parsed.auth,
...(authMetadata ? authMetadata : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
...(parsed.message
? { message: parsed.message }
: opus47UpgradeMessage
? { message: opus47UpgradeMessage }
: {}),
},
});
});
@@ -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();
@@ -973,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"));
@@ -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);
});
});
+123
View File
@@ -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;
}
+4 -120
View File
@@ -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 {
+449 -6
View File
@@ -11,6 +11,7 @@ import {
KeybindingRule,
MessageId,
OpenError,
type OrchestrationThreadShell,
TerminalNotRunningError,
type OrchestrationCommand,
type OrchestrationEvent,
@@ -166,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)),
@@ -2039,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;
@@ -2911,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,
},
}),
),
),
},
},
});
@@ -2941,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)),
);
+16 -7
View File
@@ -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),
+6 -1
View File
@@ -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,
@@ -281,6 +282,7 @@ 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;
@@ -325,7 +327,10 @@ export 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));
}),
);
const welcomeBase = yield* resolveWelcomeBase;
+35
View File
@@ -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",
+18 -2
View File
@@ -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.
+52
View File
@@ -17,6 +17,7 @@ import {
ProjectSearchEntriesError,
ProjectWriteFileError,
OrchestrationReplayEventsError,
FilesystemBrowseError,
ThreadId,
type TerminalEvent,
WS_METHODS,
@@ -549,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", {
@@ -768,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,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.17",
"version": "0.0.20",
"private": true,
"type": "module",
"scripts": {
+37
View File
@@ -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)");
});
});
+17 -3
View File
@@ -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";
@@ -77,54 +77,4 @@ describe("clientPersistenceStorage", () => {
],
});
});
it("reads and writes workspace documents as JSON blobs", async () => {
const testWindow = getTestWindow();
const {
WORKSPACE_DOCUMENT_STORAGE_KEY,
readBrowserWorkspaceDocument,
writeBrowserWorkspaceDocument,
} = await import("./clientPersistenceStorage");
const workspaceDocument = {
version: 1 as const,
layoutEngine: "split" as const,
rootNodeId: "node-1",
nodesById: {
"node-1": {
id: "node-1",
kind: "window" as const,
windowId: "window-1",
},
},
windowsById: {
"window-1": {
id: "window-1",
tabIds: ["surface-1"],
activeTabId: "surface-1",
},
},
surfacesById: {
"surface-1": {
id: "surface-1",
kind: "thread" as const,
input: {
scope: "server" as const,
threadRef: {
environmentId: testEnvironmentId,
threadId: "thread-1",
},
},
},
},
focusedWindowId: "window-1",
mobileActiveWindowId: "window-1",
};
writeBrowserWorkspaceDocument(workspaceDocument);
expect(readBrowserWorkspaceDocument<typeof workspaceDocument>()).toEqual(workspaceDocument);
expect(JSON.parse(testWindow.localStorage.getItem(WORKSPACE_DOCUMENT_STORAGE_KEY)!)).toEqual(
workspaceDocument,
);
});
});
-37
View File
@@ -11,7 +11,6 @@ import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorag
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
export const WORKSPACE_DOCUMENT_STORAGE_KEY = "t3code:workspace-document:v1";
const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
environmentId: EnvironmentId,
@@ -35,34 +34,6 @@ function hasWindow(): boolean {
return typeof window !== "undefined";
}
function readBrowserJsonDocument<T>(storageKey: string): T | null {
if (!hasWindow()) {
return null;
}
try {
const raw = window.localStorage.getItem(storageKey);
if (!raw) {
return null;
}
return JSON.parse(raw) as T;
} catch {
return null;
}
}
function writeBrowserJsonDocument<T>(storageKey: string, document: T): void {
if (!hasWindow()) {
return;
}
try {
window.localStorage.setItem(storageKey, JSON.stringify(document));
} catch {
// Ignore quota/storage errors to avoid breaking the app.
}
}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
@@ -221,11 +192,3 @@ export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentId
}),
});
}
export function readBrowserWorkspaceDocument<T>(): T | null {
return readBrowserJsonDocument<T>(WORKSPACE_DOCUMENT_STORAGE_KEY);
}
export function writeBrowserWorkspaceDocument<T>(document: T): void {
writeBrowserJsonDocument(WORKSPACE_DOCUMENT_STORAGE_KEY, document);
}
+16 -11
View File
@@ -1,27 +1,32 @@
import { create } from "zustand";
export interface CommandPaletteWorkspaceTarget {
disposition: "split-right" | "split-down";
interface CommandPaletteOpenIntent {
kind: "add-project";
requestId: number;
}
interface CommandPaletteStore {
open: boolean;
workspaceTarget: CommandPaletteWorkspaceTarget | null;
openIntent: CommandPaletteOpenIntent | null;
setOpen: (open: boolean) => void;
toggleOpen: () => void;
openWorkspaceTarget: (target: CommandPaletteWorkspaceTarget) => void;
clearWorkspaceTarget: () => void;
openAddProject: () => void;
clearOpenIntent: () => void;
}
export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
open: false,
workspaceTarget: null,
setOpen: (open) => set({ open, ...(open ? {} : { workspaceTarget: null }) }),
openIntent: null,
setOpen: (open) => set({ open, ...(open ? {} : { openIntent: null }) }),
toggleOpen: () =>
set((state) => ({ open: !state.open, ...(state.open ? { openIntent: null } : {}) })),
openAddProject: () =>
set((state) => ({
open: !state.open,
...(!state.open ? {} : { workspaceTarget: null }),
open: true,
openIntent: {
kind: "add-project",
requestId: (state.openIntent?.requestId ?? 0) + 1,
},
})),
openWorkspaceTarget: (target) => set({ open: true, workspaceTarget: target }),
clearWorkspaceTarget: () => set({ workspaceTarget: null }),
clearOpenIntent: () => set({ openIntent: null }),
}));
@@ -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();
}
});
});
+283 -17
View File
@@ -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 (
+840 -11
View File
@@ -5,6 +5,7 @@ import {
EventId,
ORCHESTRATION_WS_METHODS,
EnvironmentId,
type EnvironmentApi,
type MessageId,
type OrchestrationReadModel,
type ProjectId,
@@ -16,12 +17,7 @@ import {
OrchestrationSessionStatus,
DEFAULT_SERVER_SETTINGS,
} from "@t3tools/contracts";
import {
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
@@ -31,6 +27,16 @@ import { render } from "vitest-browser-react";
import { useCommandPaletteStore } from "../commandPaletteStore";
import { useComposerDraftStore, DraftId } from "../composerDraftStore";
import {
__resetEnvironmentApiOverridesForTests,
__setEnvironmentApiOverrideForTests,
} from "../environmentApi";
import {
resetSavedEnvironmentRegistryStoreForTests,
resetSavedEnvironmentRuntimeStoreForTests,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
} from "../environments/runtime";
import {
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
removeInlineTerminalContextPlaceholder,
@@ -41,6 +47,7 @@ import { __resetLocalApiForTests } from "../localApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getRouter } from "../router";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import { selectBootstrapCompleteForActiveEnvironment, useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { useUiStateStore } from "../uiStateStore";
@@ -62,14 +69,27 @@ const ARCHIVED_SECONDARY_THREAD_ID = "thread-secondary-project-archived" as Thre
const PROJECT_ID = "project-1" as ProjectId;
const SECOND_PROJECT_ID = "project-2" as ProjectId;
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const REMOTE_ENVIRONMENT_ID = EnvironmentId.make("environment-remote");
const THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, THREAD_ID);
const THREAD_KEY = scopedThreadKey(THREAD_REF);
const UUID_ROUTE_RE = /^\/draft\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const PROJECT_DRAFT_KEY = `${LOCAL_ENVIRONMENT_ID}:${PROJECT_ID}`;
const PROJECT_KEY = scopedProjectKey(scopeProjectRef(LOCAL_ENVIRONMENT_ID, PROJECT_ID));
const PROJECT_LOGICAL_KEY = deriveLogicalProjectKeyFromSettings(
{
environmentId: LOCAL_ENVIRONMENT_ID,
id: PROJECT_ID,
cwd: "/repo/project",
repositoryIdentity: null,
},
{
sidebarProjectGroupingMode: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingOverrides,
},
);
const NOW_ISO = "2026-03-04T12:00:00.000Z";
const BASE_TIME_MS = Date.parse(NOW_ISO);
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'></svg>";
const ADD_PROJECT_SUBMENU_PLACEHOLDER = "Enter path (e.g. ~/projects/my-app)";
interface TestFixture {
snapshot: OrchestrationReadModel;
@@ -172,6 +192,32 @@ function createBaseServerConfig(): ServerConfig {
};
}
function createMockEnvironmentApi(input: {
browse: EnvironmentApi["filesystem"]["browse"];
dispatchCommand: EnvironmentApi["orchestration"]["dispatchCommand"];
}): EnvironmentApi {
return {
terminal: {} as EnvironmentApi["terminal"],
projects: {} as EnvironmentApi["projects"],
filesystem: {
browse: input.browse,
},
git: {} as EnvironmentApi["git"],
orchestration: {
dispatchCommand: input.dispatchCommand,
getTurnDiff: (() => {
throw new Error("Not implemented in browser test.");
}) as EnvironmentApi["orchestration"]["getTurnDiff"],
getFullThreadDiff: (() => {
throw new Error("Not implemented in browser test.");
}) as EnvironmentApi["orchestration"]["getFullThreadDiff"],
subscribeShell: (() => () => undefined) as EnvironmentApi["orchestration"]["subscribeShell"],
subscribeThread: (() => () =>
undefined) as EnvironmentApi["orchestration"]["subscribeThread"],
},
};
}
function createUserMessage(options: {
id: MessageId;
text: string;
@@ -1383,6 +1429,44 @@ async function waitForCommandPaletteShortcutLabel(): Promise<void> {
);
}
async function waitForCommandPaletteInput(placeholder: string): Promise<HTMLInputElement> {
return waitForElement(
() => document.querySelector(`input[placeholder="${placeholder}"]`) as HTMLInputElement | null,
`Command palette input with placeholder "${placeholder}" did not render.`,
);
}
function getCommandPaletteLegendEntries(): string[] {
const footer = document.querySelector('[data-slot="command-footer"]');
if (!footer) {
return [];
}
return Array.from(footer.querySelectorAll('[data-slot="kbd-group"]'))
.map((group) =>
Array.from(group.children)
.map((child) => child.textContent?.trim() ?? "")
.filter((value) => value.length > 0)
.join(" "),
)
.filter((value) => value.length > 0);
}
async function dispatchInputKey(
input: HTMLInputElement,
init: Pick<KeyboardEventInit, "key" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey">,
): Promise<void> {
input.focus();
input.dispatchEvent(
new KeyboardEvent("keydown", {
bubbles: true,
cancelable: true,
...init,
}),
);
await waitForLayout();
}
async function mountChatView(options: {
viewport: ViewportSpec;
snapshot: OrchestrationReadModel;
@@ -1524,6 +1608,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
document.body.innerHTML = "";
wsRequests.length = 0;
customWsRpcResolver = null;
__resetEnvironmentApiOverridesForTests();
resetSavedEnvironmentRegistryStoreForTests();
resetSavedEnvironmentRuntimeStoreForTests();
Reflect.deleteProperty(window, "desktopBridge");
useComposerDraftStore.setState({
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
@@ -1533,6 +1621,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
useCommandPaletteStore.setState({
open: false,
openIntent: null,
});
useStore.setState({
activeEnvironmentId: null,
@@ -1556,12 +1645,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
customWsRpcResolver = null;
document.body.innerHTML = "";
});
it("re-expands the bootstrap project using its scoped key", async () => {
it("re-expands the bootstrap project using its logical key", async () => {
useUiStateStore.setState({
projectExpandedById: {
[PROJECT_KEY]: false,
[PROJECT_LOGICAL_KEY]: false,
},
projectOrder: [PROJECT_KEY],
projectOrder: [PROJECT_LOGICAL_KEY],
threadLastVisitedAtById: {},
});
@@ -1576,7 +1665,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
await vi.waitFor(
() => {
expect(useUiStateStore.getState().projectExpandedById[PROJECT_KEY]).toBe(true);
expect(useUiStateStore.getState().projectExpandedById[PROJECT_LOGICAL_KEY]).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
@@ -4079,6 +4168,746 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("adds a project from browse mode with Enter when no directory is highlighted", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-add-project-enter" as MessageId,
targetText: "command palette add project enter",
}),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
keybindings: [
{
command: "commandPalette.toggle",
shortcut: {
key: "k",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
],
};
},
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Development/") {
return {
parentPath: "~/Development/",
entries: [
{ name: "alpha", fullPath: "~/Development/alpha" },
{ name: "beta", fullPath: "~/Development/beta" },
],
};
}
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
await waitForCommandPaletteShortcutLabel();
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Add project", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/");
await expect.element(palette.getByText("alpha", { exact: true })).toBeInTheDocument();
await expect
.element(palette.getByRole("button", { name: "Add (Enter)" }))
.toBeInTheDocument();
await dispatchInputKey(browseInput, { key: "Enter" });
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) =>
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
request.type === "project.create",
) as
| {
_tag: string;
type?: string;
workspaceRoot?: string;
title?: string;
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "project.create",
workspaceRoot: "~/Development",
title: "Development",
});
},
{ timeout: 8_000, interval: 16 },
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread after adding a project with Enter.",
);
} finally {
await mounted.cleanup();
}
});
it("opens add project browse mode from the sidebar add button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-sidebar-add-project-trigger" as MessageId,
targetText: "sidebar add project trigger",
}),
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
await page.getByTestId("sidebar-add-project-trigger").click();
const palette = page.getByTestId("command-palette");
await expect.element(palette).toBeInTheDocument();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await expect.element(browseInput).toHaveValue("~/");
await vi.waitFor(
() => {
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.filesystemBrowse && request.partialPath === "~/",
),
).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("starts add project browse mode from the configured base directory", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-sidebar-add-project-custom-base-dir" as MessageId,
targetText: "sidebar add project custom base directory",
}),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
settings: {
...nextFixture.serverConfig.settings,
addProjectBaseDirectory: "~/Development",
},
};
},
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Development/") {
return {
parentPath: "~/Development/",
entries: [{ name: "codething", fullPath: "~/Development/codething" }],
};
}
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
await page.getByTestId("sidebar-add-project-trigger").click();
const palette = page.getByTestId("command-palette");
await expect.element(palette).toBeInTheDocument();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await expect.element(browseInput).toHaveValue("~/Development/");
await vi.waitFor(
() => {
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.filesystemBrowse &&
request.partialPath === "~/Development/",
),
).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("shows create-folder affordances for missing project paths", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-create-missing-project" as MessageId,
targetText: "command palette create missing project",
}),
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Desktop/") {
return {
parentPath: "~/Desktop/",
entries: [{ name: "existing", fullPath: "~/Desktop/existing" }],
};
}
return {
parentPath: "~/",
entries: [{ name: "Desktop", fullPath: "~/Desktop" }],
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
const palette = page.getByTestId("command-palette");
await page.getByTestId("sidebar-add-project-trigger").click();
await expect.element(palette).toBeInTheDocument();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Desktop/fresh-project");
await expect
.element(palette.getByRole("button", { name: "Create & Add (Enter)" }))
.toBeInTheDocument();
await expect.element(palette.getByText("Will create this folder")).not.toBeInTheDocument();
await dispatchInputKey(browseInput, { key: "Enter" });
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) =>
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
request.type === "project.create",
) as
| {
_tag: string;
type?: string;
workspaceRoot?: string;
title?: string;
createWorkspaceRootIfMissing?: boolean;
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "project.create",
workspaceRoot: "~/Desktop/fresh-project",
title: "fresh-project",
createWorkspaceRootIfMissing: true,
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("does not show create affordances for an existing directory with a trailing slash", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-existing-trailing-directory" as MessageId,
targetText: "command palette existing trailing directory",
}),
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Development/codex/") {
return {
parentPath: "~/Development/codex/",
entries: [{ name: "Codex.app", fullPath: "~/Development/codex/Codex.app" }],
};
}
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
const palette = page.getByTestId("command-palette");
await page.getByTestId("sidebar-add-project-trigger").click();
await expect.element(palette).toBeInTheDocument();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/codex/");
await vi.waitFor(
() => {
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.filesystemBrowse &&
request.partialPath === "~/Development/codex/",
),
).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
await expect
.element(palette.getByRole("button", { name: "Add (Enter)" }))
.toBeInTheDocument();
await expect
.element(palette.getByRole("button", { name: "Create & Add (Enter)" }))
.not.toBeInTheDocument();
await dispatchInputKey(browseInput, { key: "Enter" });
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) =>
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
request.type === "project.create",
) as
| {
_tag: string;
type?: string;
workspaceRoot?: string;
title?: string;
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "project.create",
workspaceRoot: "~/Development/codex",
title: "codex",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("selects an environment before browsing when multiple environments are available", async () => {
const remoteBrowseMock = vi.fn(async ({ partialPath }: { partialPath: string }) => {
if (partialPath === "~/workspaces/") {
return {
parentPath: "~/workspaces/",
entries: [{ name: "codething", fullPath: "~/workspaces/codething" }],
};
}
return {
parentPath: "~/",
entries: [{ name: "workspaces", fullPath: "~/workspaces" }],
};
});
const remoteDispatchMock = vi.fn(async () => ({
sequence: fixture.snapshot.snapshotSequence + 1,
}));
__setEnvironmentApiOverrideForTests(
REMOTE_ENVIRONMENT_ID,
createMockEnvironmentApi({
browse: remoteBrowseMock,
dispatchCommand: remoteDispatchMock,
}),
);
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-add-project-multi-env" as MessageId,
targetText: "command palette add project multi env",
}),
});
try {
await waitForServerConfigToApply();
useSavedEnvironmentRegistryStore.getState().upsert({
environmentId: REMOTE_ENVIRONMENT_ID,
label: "Staging",
httpBaseUrl: "https://staging.example.test",
wsBaseUrl: "wss://staging.example.test/ws",
createdAt: NOW_ISO,
lastConnectedAt: NOW_ISO,
});
useSavedEnvironmentRuntimeStore.getState().patch(REMOTE_ENVIRONMENT_ID, {
connectionState: "connected",
authState: "authenticated",
descriptor: {
...fixture.serverConfig.environment,
environmentId: REMOTE_ENVIRONMENT_ID,
label: "Staging",
},
serverConfig: {
...fixture.serverConfig,
environment: {
...fixture.serverConfig.environment,
environmentId: REMOTE_ENVIRONMENT_ID,
label: "Staging",
},
settings: {
...fixture.serverConfig.settings,
addProjectBaseDirectory: "~/workspaces",
},
},
connectedAt: NOW_ISO,
});
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Add project", { exact: true }).click();
await expect.element(palette.getByText("Environments", { exact: true })).toBeInTheDocument();
await expect
.element(palette.getByText("This device", { exact: true }).first())
.toBeInTheDocument();
await palette.getByText("Staging", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await expect.element(browseInput).toHaveValue("~/workspaces/");
await vi.waitFor(
() => {
expect(remoteBrowseMock).toHaveBeenCalledWith({ partialPath: "~/workspaces/" });
},
{ timeout: 8_000, interval: 16 },
);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/workspaces/");
await vi.waitFor(
() => {
expect(remoteBrowseMock).toHaveBeenCalledWith({ partialPath: "~/workspaces/" });
},
{ timeout: 8_000, interval: 16 },
);
await expect.element(palette.getByText("codething", { exact: true })).toBeInTheDocument();
await expect
.element(palette.getByRole("button", { name: "Add (Enter)" }))
.toBeInTheDocument();
await dispatchInputKey(browseInput, { key: "Enter" });
await vi.waitFor(
() => {
expect(remoteDispatchMock).toHaveBeenCalledWith(
expect.objectContaining({
type: "project.create",
workspaceRoot: "~/workspaces",
title: "workspaces",
}),
);
},
{ timeout: 8_000, interval: 16 },
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread after adding a remote project.",
);
} finally {
await mounted.cleanup();
}
});
it("picks a local project from the native file manager", async () => {
const pickFolder = vi.fn().mockResolvedValue("/Users/julius/Projects/finder-picked");
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-add-project-file-manager" as MessageId,
targetText: "command palette add project file manager",
}),
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Applications/") {
return {
parentPath: "~/Applications/",
entries: [{ name: "Utilities", fullPath: "~/Applications/Utilities" }],
};
}
return {
parentPath: "~/",
entries: [{ name: "Applications", fullPath: "~/Applications" }],
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
window.desktopBridge = {
pickFolder,
setTheme: vi.fn().mockResolvedValue(undefined),
} as unknown as NonNullable<typeof window.desktopBridge>;
await page.getByTestId("sidebar-add-project-trigger").click();
const palette = page.getByTestId("command-palette");
await expect.element(palette).toBeInTheDocument();
const browseInput = palette.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await browseInput.fill("~/Applications/access");
const fileManagerLabel = isMacPlatform(navigator.platform)
? "Open in Finder"
: navigator.platform.toLowerCase().startsWith("win")
? "Open in Explorer"
: "Open in Files";
await palette.getByRole("button", { name: fileManagerLabel }).click();
await vi.waitFor(
() => {
expect(pickFolder).toHaveBeenCalledWith({ initialPath: "~/Applications" });
},
{ timeout: 8_000, interval: 16 },
);
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) =>
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
request.type === "project.create",
) as
| {
_tag: string;
type?: string;
workspaceRoot?: string;
title?: string;
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "project.create",
workspaceRoot: "/Users/julius/Projects/finder-picked",
title: "finder-picked",
});
},
{ timeout: 8_000, interval: 16 },
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread after adding a project from the native file manager.",
);
} finally {
await mounted.cleanup();
}
});
it("adds a project from browse mode with Mod+Enter when a directory is highlighted", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-add-project-mod-enter" as MessageId,
targetText: "command palette add project mod enter",
}),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
keybindings: [
{
command: "commandPalette.toggle",
shortcut: {
key: "k",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
],
};
},
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Development/") {
return {
parentPath: "~/Development/",
entries: [
{ name: "alpha", fullPath: "~/Development/alpha" },
{ name: "beta", fullPath: "~/Development/beta" },
],
};
}
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
await waitForCommandPaletteShortcutLabel();
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Add project", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/");
await expect.element(palette.getByText("alpha", { exact: true })).toBeInTheDocument();
await dispatchInputKey(browseInput, { key: "ArrowDown" });
const addButtonLabel = isMacPlatform(navigator.platform)
? "Add (\u2318 Enter)"
: "Add (Ctrl Enter)";
await vi.waitFor(
() => {
const legendEntries = getCommandPaletteLegendEntries();
expect(legendEntries).toContain("Enter Select");
},
{ timeout: 8_000, interval: 16 },
);
await expect
.element(palette.getByRole("button", { name: addButtonLabel }))
.toBeInTheDocument();
await dispatchInputKey(browseInput, {
key: "Enter",
metaKey: isMacPlatform(navigator.platform),
ctrlKey: !isMacPlatform(navigator.platform),
});
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) =>
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
request.type === "project.create",
) as
| {
_tag: string;
type?: string;
workspaceRoot?: string;
title?: string;
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "project.create",
workspaceRoot: "~/Development",
title: "Development",
});
},
{ timeout: 8_000, interval: 16 },
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread after adding a project with Mod+Enter.",
);
} finally {
await mounted.cleanup();
}
});
it("keeps project-context thread matches available when searching by project name", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
+441 -120
View File
@@ -1,7 +1,7 @@
import {
type ApprovalRequestId,
DEFAULT_MODEL_BY_PROVIDER,
type ClaudeCodeEffort,
type ClaudeAgentEffort,
type EnvironmentId,
type MessageId,
type ModelSelection,
@@ -19,12 +19,17 @@ import {
RuntimeMode,
TerminalOpenInput,
} from "@t3tools/contracts";
import { scopedThreadKey, scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import {
parseScopedThreadKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { truncate } from "@t3tools/shared/String";
import { Debouncer } from "@tanstack/react-pacer";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { useShallow } from "zustand/react/shallow";
import { useGitStatus } from "~/lib/gitStatusState";
@@ -61,7 +66,11 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { selectProjectsAcrossEnvironments, useStore } from "../store";
import {
selectProjectsAcrossEnvironments,
selectThreadsAcrossEnvironments,
useStore,
} from "../store";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
import {
@@ -80,16 +89,15 @@ import {
type TurnDiffSummary,
} from "../types";
import { useTheme } from "../hooks/useTheme";
import {
isWorkspaceCommandId,
useWorkspaceCommandExecutor,
} from "../hooks/useWorkspaceCommandExecutor";
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";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { ChevronDownIcon } from "lucide-react";
import { cn, randomUUID } from "~/lib/utils";
import { toastManager } from "./ui/toast";
@@ -105,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,
@@ -121,6 +129,7 @@ import {
appendTerminalContextsToPrompt,
formatTerminalContextLabel,
type TerminalContextDraft,
type TerminalContextSelection,
} from "../lib/terminalContext";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
@@ -134,6 +143,7 @@ import { resolveEffectiveEnvMode, resolveEnvironmentOptionLabel } from "./Branch
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
collectUserMessageBlobPreviewUrls,
@@ -163,7 +173,7 @@ import {
} from "~/rpc/serverState";
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import { retainThreadDetailSubscription } from "../environments/runtime/service";
import { useWorkspaceStore, useWorkspaceThreadTerminalOpen } from "../workspace/store";
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).]";
@@ -296,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;
}
@@ -305,8 +315,6 @@ const SCRIPT_TERMINAL_ROWS = 30;
type ChatViewProps =
| {
activationFocusRequestId?: number;
bindSharedComposerHandle?: boolean;
environmentId: EnvironmentId;
threadId: ThreadId;
onDiffPanelOpen?: () => void;
@@ -315,8 +323,6 @@ type ChatViewProps =
draftId?: never;
}
| {
activationFocusRequestId?: number;
bindSharedComposerHandle?: boolean;
environmentId: EnvironmentId;
threadId: ThreadId;
onDiffPanelOpen?: () => void;
@@ -325,6 +331,14 @@ type ChatViewProps =
draftId: DraftId;
};
interface TerminalLaunchContext {
threadId: ThreadId;
cwd: string;
worktreePath: string | null;
}
type PersistentTerminalLaunchContext = Pick<TerminalLaunchContext, "cwd" | "worktreePath">;
function useLocalDispatchState(input: {
activeThread: Thread | undefined;
activeLatestTurn: Thread["latestTurn"] | null;
@@ -392,10 +406,181 @@ function useLocalDispatchState(input: {
};
}
interface PersistentThreadTerminalDrawerProps {
threadRef: { environmentId: EnvironmentId; threadId: ThreadId };
threadId: ThreadId;
visible: boolean;
launchContext: PersistentTerminalLaunchContext | null;
focusRequestId: number;
splitShortcutLabel: string | undefined;
newShortcutLabel: string | undefined;
closeShortcutLabel: string | undefined;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
}
const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDrawer({
threadRef,
threadId,
visible,
launchContext,
focusRequestId,
splitShortcutLabel,
newShortcutLabel,
closeShortcutLabel,
onAddTerminalContext,
}: PersistentThreadTerminalDrawerProps) {
const serverThread = useStore(useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]));
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
const projectRef = serverThread
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
: draftThread
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
: null;
const project = useStore(useMemo(() => createProjectSelectorByRef(projectRef), [projectRef]));
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadKey, threadRef),
);
const storeSetTerminalHeight = useTerminalStateStore((state) => state.setTerminalHeight);
const storeSplitTerminal = useTerminalStateStore((state) => state.splitTerminal);
const storeNewTerminal = useTerminalStateStore((state) => state.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((state) => state.setActiveTerminal);
const storeCloseTerminal = useTerminalStateStore((state) => state.closeTerminal);
const [localFocusRequestId, setLocalFocusRequestId] = useState(0);
const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const effectiveWorktreePath = useMemo(() => {
if (launchContext !== null) {
return launchContext.worktreePath;
}
return worktreePath;
}, [launchContext, worktreePath]);
const cwd = useMemo(
() =>
launchContext?.cwd ??
(project
? projectScriptCwd({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
})
: null),
[effectiveWorktreePath, launchContext?.cwd, project],
);
const runtimeEnv = useMemo(
() =>
project
? projectScriptRuntimeEnv({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
})
: {},
[effectiveWorktreePath, project],
);
const bumpFocusRequestId = useCallback(() => {
if (!visible) {
return;
}
setLocalFocusRequestId((value) => value + 1);
}, [visible]);
const setTerminalHeight = useCallback(
(height: number) => {
storeSetTerminalHeight(threadRef, height);
},
[storeSetTerminalHeight, threadRef],
);
const splitTerminal = useCallback(() => {
storeSplitTerminal(threadRef, `terminal-${randomUUID()}`);
bumpFocusRequestId();
}, [bumpFocusRequestId, storeSplitTerminal, threadRef]);
const createNewTerminal = useCallback(() => {
storeNewTerminal(threadRef, `terminal-${randomUUID()}`);
bumpFocusRequestId();
}, [bumpFocusRequestId, storeNewTerminal, threadRef]);
const activateTerminal = useCallback(
(terminalId: string) => {
storeSetActiveTerminal(threadRef, terminalId);
bumpFocusRequestId();
},
[bumpFocusRequestId, storeSetActiveTerminal, threadRef],
);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readEnvironmentApi(threadRef.environmentId);
if (!api) return;
const isFinalTerminal = terminalState.terminalIds.length <= 1;
const fallbackExitWrite = () =>
api.terminal.write({ threadId, terminalId, data: "exit\n" }).catch(() => undefined);
if ("close" in api.terminal && typeof api.terminal.close === "function") {
void (async () => {
if (isFinalTerminal) {
await api.terminal.clear({ threadId, terminalId }).catch(() => undefined);
}
await api.terminal.close({
threadId,
terminalId,
deleteHistory: true,
});
})().catch(() => fallbackExitWrite());
} else {
void fallbackExitWrite();
}
storeCloseTerminal(threadRef, terminalId);
bumpFocusRequestId();
},
[bumpFocusRequestId, storeCloseTerminal, terminalState.terminalIds.length, threadId, threadRef],
);
const handleAddTerminalContext = useCallback(
(selection: TerminalContextSelection) => {
if (!visible) {
return;
}
onAddTerminalContext(selection);
},
[onAddTerminalContext, visible],
);
if (!project || !terminalState.terminalOpen || !cwd) {
return null;
}
return (
<div className={visible ? undefined : "hidden"}>
<ThreadTerminalDrawer
threadRef={threadRef}
threadId={threadId}
cwd={cwd}
worktreePath={effectiveWorktreePath}
runtimeEnv={runtimeEnv}
visible={visible}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
splitShortcutLabel={visible ? splitShortcutLabel : undefined}
newShortcutLabel={visible ? newShortcutLabel : undefined}
closeShortcutLabel={visible ? closeShortcutLabel : undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={setTerminalHeight}
onAddTerminalContext={handleAddTerminalContext}
/>
</div>
);
});
export default function ChatView(props: ChatViewProps) {
const {
activationFocusRequestId,
bindSharedComposerHandle = true,
environmentId,
threadId,
routeKind,
@@ -472,8 +657,7 @@ export default function ChatView(props: ChatViewProps) {
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
const localComposerRef = useRef<ChatComposerHandle | null>(null);
const sharedComposerRef = useComposerHandleContext();
const composerRef = localComposerRef;
const composerRef = useComposerHandleContext() ?? localComposerRef;
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
@@ -494,15 +678,18 @@ 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.
// Used by "Implement in a new thread" to carry the sidebar-open intent across navigation.
const planSidebarOpenOnNextThreadRef = useRef(false);
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [nowTick, setNowTick] = useState(() => Date.now());
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
const [terminalLaunchContext, setTerminalLaunchContext] = useState<TerminalLaunchContext | null>(
null,
);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
@@ -521,40 +708,51 @@ export default function ChatView(props: ChatViewProps) {
const sendInFlightRef = useRef(false);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
useLayoutEffect(() => {
if (!sharedComposerRef) {
return;
}
const localComposerHandle = localComposerRef.current;
if (bindSharedComposerHandle) {
sharedComposerRef.current = localComposerHandle;
return () => {
if (sharedComposerRef.current === localComposerHandle) {
sharedComposerRef.current = null;
}
};
}
if (sharedComposerRef.current === localComposerHandle) {
sharedComposerRef.current = null;
}
});
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef),
);
const openTerminalThreadKeys = useTerminalStateStore(
useShallow((state) =>
Object.entries(state.terminalStateByThreadKey).flatMap(([nextThreadKey, nextTerminalState]) =>
nextTerminalState.terminalOpen ? [nextThreadKey] : [],
),
),
);
const storeSetTerminalOpen = useTerminalStateStore((s) => s.setTerminalOpen);
const storeSplitTerminal = useTerminalStateStore((s) => s.splitTerminal);
const storeNewTerminal = useTerminalStateStore((s) => s.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal);
const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal);
const storeSetTerminalLaunchContext = useTerminalStateStore((s) => s.setTerminalLaunchContext);
const serverThreadKeys = useStore(
useShallow((state) =>
selectThreadsAcrossEnvironments(state).map((thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
),
),
);
const storeServerTerminalLaunchContext = useTerminalStateStore(
(s) => s.terminalLaunchContextByThreadKey[scopedThreadKey(routeThreadRef)] ?? null,
);
const storeClearTerminalLaunchContext = useTerminalStateStore(
(s) => s.clearTerminalLaunchContext,
);
const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey);
const draftThreadKeys = useMemo(
() =>
Object.values(draftThreadsByThreadKey).map((draftThread) =>
scopedThreadKey(scopeThreadRef(draftThread.environmentId, draftThread.threadId)),
),
[draftThreadsByThreadKey],
);
const [mountedTerminalThreadKeys, setMountedTerminalThreadKeys] = useState<string[]>([]);
const mountedTerminalThreadRefs = useMemo(
() =>
mountedTerminalThreadKeys.flatMap((mountedThreadKey) => {
const mountedThreadRef = parseScopedThreadKey(mountedThreadKey);
return mountedThreadRef ? [{ key: mountedThreadKey, threadRef: mountedThreadRef }] : [];
}),
[mountedTerminalThreadKeys],
);
const fallbackDraftProjectRef = draftThread
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
@@ -595,16 +793,10 @@ export default function ChatView(props: ChatViewProps) {
[activeThread],
);
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
const terminalSurfaceOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
const ensureTerminalSurfaceForThread = useWorkspaceStore(
(state) => state.ensureTerminalSurfaceForThread,
);
const toggleTerminalSurfaceForThread = useWorkspaceStore(
(state) => state.toggleTerminalSurfaceForThread,
);
const closeTerminalSurfacesForThread = useWorkspaceStore(
(state) => state.closeTerminalSurfacesForThread,
);
const existingOpenTerminalThreadKeys = useMemo(() => {
const existingThreadKeys = new Set<string>([...serverThreadKeys, ...draftThreadKeys]);
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
}, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);
const activeLatestTurn = activeThread?.latestTurn ?? null;
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
@@ -619,6 +811,21 @@ export default function ChatView(props: ChatViewProps) {
return threadIds;
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]),
);
useEffect(() => {
setMountedTerminalThreadKeys((currentThreadIds) => {
const nextThreadIds = reconcileMountedTerminalThreadIds({
currentThreadIds,
openThreadIds: existingOpenTerminalThreadKeys,
activeThreadId: activeThreadKey,
activeThreadTerminalOpen: Boolean(activeThreadKey && terminalState.terminalOpen),
maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
});
return currentThreadIds.length === nextThreadIds.length &&
currentThreadIds.every((nextThreadId, index) => nextThreadId === nextThreadIds[index])
? currentThreadIds
: nextThreadIds;
});
}, [activeThreadKey, existingOpenTerminalThreadKeys, terminalState.terminalOpen]);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProjectRef = activeThread
? scopeProjectRef(activeThread.environmentId, activeThread.projectId)
@@ -640,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;
@@ -679,6 +892,7 @@ export default function ChatView(props: ChatViewProps) {
}, [
activeProject,
allProjects,
projectGroupingSettings,
primaryEnvironmentId,
savedEnvironmentRegistry,
savedEnvironmentRuntimeById,
@@ -708,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);
@@ -769,6 +986,7 @@ export default function ChatView(props: ChatViewProps) {
getDraftSessionByLogicalProjectKey,
isServerThread,
navigate,
projectGroupingSettings,
routeKind,
setDraftThreadContext,
setLogicalProjectDraftThreadId,
@@ -904,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" &&
@@ -1200,7 +1419,6 @@ export default function ChatView(props: ChatViewProps) {
const gitStatusQuery = useGitStatus({ environmentId, cwd: gitCwd });
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
const { executeWorkspaceCommand } = useWorkspaceCommandExecutor();
const activeProviderStatus = useMemo(
() => providerStatuses.find((status) => status.provider === selectedProvider) ?? null,
[selectedProvider, providerStatuses],
@@ -1208,21 +1426,46 @@ export default function ChatView(props: ChatViewProps) {
const activeProjectCwd = activeProject?.cwd ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
const activeTerminalLaunchContext =
terminalLaunchContext?.threadId === activeThreadId
? terminalLaunchContext
: (storeServerTerminalLaunchContext ?? null);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
terminalFocus: true,
terminalOpen: Boolean(terminalState.terminalOpen),
},
}),
[terminalState.terminalOpen],
);
const nonTerminalShortcutLabelOptions = useMemo(
() => ({
context: {
terminalFocus: false,
terminalOpen: terminalSurfaceOpen,
terminalOpen: Boolean(terminalState.terminalOpen),
},
}),
[terminalSurfaceOpen],
[terminalState.terminalOpen],
);
const terminalToggleShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.toggle"),
[keybindings],
);
const splitTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.split", terminalShortcutLabelOptions),
[keybindings, terminalShortcutLabelOptions],
);
const newTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.new", terminalShortcutLabelOptions),
[keybindings, terminalShortcutLabelOptions],
);
const closeTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions),
[keybindings, terminalShortcutLabelOptions],
);
const diffPanelShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "diff.toggle", nonTerminalShortcutLabelOptions),
[keybindings, nonTerminalShortcutLabelOptions],
@@ -1316,22 +1559,32 @@ export default function ChatView(props: ChatViewProps) {
focusComposer();
});
}, [focusComposer]);
const addTerminalContextToDraft = useCallback((selection: TerminalContextSelection) => {
composerRef.current?.addTerminalContext(selection);
}, []);
const setTerminalOpen = useCallback(
(open: boolean) => {
if (!activeThreadRef) return;
storeSetTerminalOpen(activeThreadRef, open);
},
[activeThreadRef, storeSetTerminalOpen],
);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadRef) return;
toggleTerminalSurfaceForThread(activeThreadRef);
}, [activeThreadRef, toggleTerminalSurfaceForThread]);
setTerminalOpen(!terminalState.terminalOpen);
}, [activeThreadRef, setTerminalOpen, terminalState.terminalOpen]);
const splitTerminal = useCallback(() => {
if (!activeThreadRef || hasReachedSplitLimit) return;
const terminalId = `terminal-${randomUUID()}`;
storeSplitTerminal(activeThreadRef, terminalId);
ensureTerminalSurfaceForThread(activeThreadRef);
}, [activeThreadRef, ensureTerminalSurfaceForThread, hasReachedSplitLimit, storeSplitTerminal]);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadRef, hasReachedSplitLimit, storeSplitTerminal]);
const createNewTerminal = useCallback(() => {
if (!activeThreadRef) return;
const terminalId = `terminal-${randomUUID()}`;
storeNewTerminal(activeThreadRef, terminalId);
ensureTerminalSurfaceForThread(activeThreadRef);
}, [activeThreadRef, ensureTerminalSurfaceForThread, storeNewTerminal]);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadRef, storeNewTerminal]);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readEnvironmentApi(environmentId);
@@ -1359,15 +1612,12 @@ export default function ChatView(props: ChatViewProps) {
}
if (activeThreadRef) {
storeCloseTerminal(activeThreadRef, terminalId);
if (isFinalTerminal) {
closeTerminalSurfacesForThread(activeThreadRef);
}
}
setTerminalFocusRequestId((value) => value + 1);
},
[
activeThreadId,
activeThreadRef,
closeTerminalSurfacesForThread,
environmentId,
storeCloseTerminal,
terminalState.terminalIds.length,
@@ -1405,19 +1655,21 @@ export default function ChatView(props: ChatViewProps) {
: baseTerminalId;
const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
if (!activeThreadRef) {
return;
}
storeSetTerminalLaunchContext(activeThreadRef, {
setTerminalLaunchContext({
threadId: activeThreadId,
cwd: targetCwd,
worktreePath: targetWorktreePath,
});
ensureTerminalSurfaceForThread(activeThreadRef);
setTerminalOpen(true);
if (!activeThreadRef) {
return;
}
if (shouldCreateNewTerminal) {
storeNewTerminal(activeThreadRef, targetTerminalId);
} else {
storeSetActiveTerminal(activeThreadRef, targetTerminalId);
}
setTerminalFocusRequestId((value) => value + 1);
const runtimeEnv = projectScriptRuntimeEnv({
project: {
@@ -1463,11 +1715,10 @@ export default function ChatView(props: ChatViewProps) {
activeThread,
activeThreadId,
activeThreadRef,
ensureTerminalSurfaceForThread,
gitCwd,
setTerminalOpen,
setThreadError,
storeNewTerminal,
storeSetTerminalLaunchContext,
storeSetActiveTerminal,
setLastInvokedScriptByProjectId,
environmentId,
@@ -1653,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: {
@@ -1754,26 +2008,31 @@ 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]);
useEffect(() => {
if (!activeThread?.id || terminalSurfaceOpen) return;
if (!activeThread?.id || terminalState.terminalOpen) return;
const frame = window.requestAnimationFrame(() => {
focusComposer();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [activeThread?.id, focusComposer, terminalSurfaceOpen]);
useLayoutEffect(() => {
if (activationFocusRequestId === undefined) {
return;
}
focusComposer();
}, [activationFocusRequestId, focusComposer]);
}, [activeThread?.id, focusComposer, terminalState.terminalOpen]);
useEffect(() => {
if (!activeThread?.id) return;
@@ -1858,11 +2117,48 @@ export default function ChatView(props: ChatViewProps) {
useEffect(() => {
if (!activeThreadId) {
setTerminalLaunchContext(null);
storeClearTerminalLaunchContext(routeThreadRef);
return;
}
setTerminalLaunchContext((current) => {
if (!current) return current;
if (current.threadId === activeThreadId) return current;
return null;
});
}, [activeThreadId, routeThreadRef, storeClearTerminalLaunchContext]);
useEffect(() => {
if (!activeThreadId || !activeProjectCwd) {
return;
}
setTerminalLaunchContext((current) => {
if (!current || current.threadId !== activeThreadId) {
return current;
}
const settledCwd = projectScriptCwd({
project: { cwd: activeProjectCwd },
worktreePath: activeThreadWorktreePath,
});
if (
settledCwd === current.cwd &&
(activeThreadWorktreePath ?? null) === current.worktreePath
) {
if (activeThreadRef) {
storeClearTerminalLaunchContext(activeThreadRef);
}
return null;
}
return current;
});
}, [
activeProjectCwd,
activeThreadId,
activeThreadRef,
activeThreadWorktreePath,
storeClearTerminalLaunchContext,
]);
useEffect(() => {
if (!activeThreadId || !activeProjectCwd || !storeServerTerminalLaunchContext) {
return;
@@ -1889,21 +2185,28 @@ export default function ChatView(props: ChatViewProps) {
]);
useEffect(() => {
if (terminalSurfaceOpen) {
if (terminalState.terminalOpen) {
return;
}
if (activeThreadRef) {
storeClearTerminalLaunchContext(activeThreadRef);
}
}, [activeThreadRef, storeClearTerminalLaunchContext, terminalSurfaceOpen]);
setTerminalLaunchContext((current) => (current?.threadId === activeThreadId ? null : current));
}, [
activeThreadId,
activeThreadRef,
storeClearTerminalLaunchContext,
terminalState.terminalOpen,
]);
useEffect(() => {
if (!activeThreadKey) return;
const previous = terminalOpenByThreadRef.current[activeThreadKey] ?? false;
const current = terminalSurfaceOpen;
const current = Boolean(terminalState.terminalOpen);
if (!previous && current) {
terminalOpenByThreadRef.current[activeThreadKey] = current;
setTerminalFocusRequestId((value) => value + 1);
return;
} else if (previous && !current) {
terminalOpenByThreadRef.current[activeThreadKey] = current;
@@ -1916,7 +2219,7 @@ export default function ChatView(props: ChatViewProps) {
}
terminalOpenByThreadRef.current[activeThreadKey] = current;
}, [activeThreadKey, focusComposer, terminalSurfaceOpen]);
}, [activeThreadKey, focusComposer, terminalState.terminalOpen]);
useEffect(() => {
const handler = (event: globalThis.KeyboardEvent) => {
@@ -1925,7 +2228,7 @@ export default function ChatView(props: ChatViewProps) {
}
const shortcutContext = {
terminalFocus: isTerminalFocused(),
terminalOpen: terminalSurfaceOpen,
terminalOpen: Boolean(terminalState.terminalOpen),
};
const command = resolveShortcutCommand(event, keybindings, {
@@ -1933,13 +2236,6 @@ export default function ChatView(props: ChatViewProps) {
});
if (!command) return;
if (isWorkspaceCommandId(command)) {
event.preventDefault();
event.stopPropagation();
void executeWorkspaceCommand(command);
return;
}
if (command === "terminal.toggle") {
event.preventDefault();
event.stopPropagation();
@@ -1950,8 +2246,8 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
if (!terminalSurfaceOpen && activeThreadRef) {
ensureTerminalSurfaceForThread(activeThreadRef);
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
}
splitTerminal();
return;
@@ -1960,7 +2256,7 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.close") {
event.preventDefault();
event.stopPropagation();
if (!terminalSurfaceOpen) return;
if (!terminalState.terminalOpen) return;
closeTerminal(terminalState.activeTerminalId);
return;
}
@@ -1968,8 +2264,8 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.new") {
event.preventDefault();
event.stopPropagation();
if (!terminalSurfaceOpen && activeThreadRef) {
ensureTerminalSurfaceForThread(activeThreadRef);
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
}
createNewTerminal();
return;
@@ -1994,18 +2290,16 @@ export default function ChatView(props: ChatViewProps) {
return () => window.removeEventListener("keydown", handler);
}, [
activeProject,
terminalState.terminalOpen,
terminalState.activeTerminalId,
activeThreadRef,
activeThreadId,
closeTerminal,
createNewTerminal,
executeWorkspaceCommand,
ensureTerminalSurfaceForThread,
setTerminalOpen,
runProjectScript,
splitTerminal,
keybindings,
onToggleDiff,
terminalSurfaceOpen,
toggleTerminalVisibility,
]);
@@ -2908,7 +3202,7 @@ export default function ChatView(props: ChatViewProps) {
}
return (
<div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
{/* Top bar */}
<header
className={cn(
@@ -2937,7 +3231,7 @@ export default function ChatView(props: ChatViewProps) {
keybindings={keybindings}
availableEditors={availableEditors}
terminalAvailable={activeProject !== undefined}
terminalOpen={terminalSurfaceOpen}
terminalOpen={terminalState.terminalOpen}
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
diffToggleShortcutLabel={diffPanelShortcutLabel}
gitCwd={gitCwd}
@@ -3008,7 +3302,6 @@ export default function ChatView(props: ChatViewProps) {
<div className={cn("px-3 pt-1.5 sm:px-5 sm:pt-2", isGitRepo ? "pb-1" : "pb-3 sm:pb-4")}>
<ChatComposer
ref={composerRef}
{...(activationFocusRequestId === undefined ? {} : { activationFocusRequestId })}
composerDraftTarget={composerDraftTarget}
environmentId={environmentId}
routeKind={routeKind}
@@ -3036,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}
@@ -3120,27 +3414,54 @@ 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>
{/* end horizontal flex container */}
{mountedTerminalThreadRefs.map(({ key: mountedThreadKey, threadRef: mountedThreadRef }) => (
<PersistentThreadTerminalDrawer
key={mountedThreadKey}
threadRef={mountedThreadRef}
threadId={mountedThreadRef.threadId}
visible={mountedThreadKey === activeThreadKey && terminalState.terminalOpen}
launchContext={
mountedThreadKey === activeThreadKey ? (activeTerminalLaunchContext ?? null) : null
}
focusRequestId={mountedThreadKey === activeThreadKey ? terminalFocusRequestId : 0}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
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, " ");
@@ -230,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: {
@@ -258,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)";
}
}
File diff suppressed because it is too large. Load diff
@@ -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);
}
@@ -890,7 +876,6 @@ export interface ComposerPromptEditorHandle {
focus: () => void;
focusAt: (cursor: number) => void;
focusAtEnd: () => void;
isFocused: () => boolean;
readSnapshot: () => {
value: string;
cursor: number;
@@ -1384,6 +1369,7 @@ function ComposerSurroundSelectionPlugin(props: {
const onCompositionEnd = () => {
tryApplyDeadKeyBacktickSurround({ finalAttempt: true });
};
let activeRootElement: HTMLElement | null = null;
const unregisterRootListener = editor.registerRootListener((rootElement, prevRootElement) => {
prevRootElement?.removeEventListener("keydown", onKeyDown);
@@ -1493,7 +1479,7 @@ function ComposerPromptEditorInner({
if (shouldRewriteEditorState) {
$setComposerEditorPrompt(value, terminalContexts, skillMetadataRef.current);
}
if (isFocused) {
if (shouldRewriteEditorState || isFocused) {
$setSelectionAtComposerOffset(normalizedCursor);
}
});
@@ -1508,19 +1494,22 @@ function ComposerPromptEditorInner({
if (!rootElement) return;
const boundedCursor = clampCollapsedComposerCursor(snapshotRef.current.value, nextCursor);
rootElement.focus();
isApplyingControlledUpdateRef.current = true;
editor.update(() => {
$setSelectionAtComposerOffset(boundedCursor);
});
queueMicrotask(() => {
isApplyingControlledUpdateRef.current = false;
});
snapshotRef.current = {
value: snapshotRef.current.value,
cursor: boundedCursor,
expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
terminalContextIds: snapshotRef.current.terminalContextIds,
};
onChangeRef.current(
snapshotRef.current.value,
boundedCursor,
snapshotRef.current.expandedCursor,
false,
snapshotRef.current.terminalContextIds,
);
},
[editor],
);
@@ -1574,13 +1563,9 @@ function ComposerPromptEditorInner({
),
);
},
isFocused: () => {
const rootElement = editor.getRootElement();
return Boolean(rootElement && document.activeElement === rootElement);
},
readSnapshot,
}),
[editor, focusAt, readSnapshot],
[focusAt, readSnapshot],
);
const handleEditorChange = useCallback((editorState: EditorState) => {
@@ -98,7 +98,7 @@ function createBaseServerConfig(): ServerConfig {
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
providers: {
codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
claudeAgent: { enabled: true, binaryPath: "", customModels: [], launchArgs: "" },
},
},
};
+14 -3
View File
@@ -54,20 +54,24 @@ function stepStatusIcon(status: string): React.ReactNode {
interface PlanSidebarProps {
activePlan: ActivePlanState | null;
activeProposedPlan: LatestProposedPlanState | null;
label?: string;
environmentId: EnvironmentId;
markdownCwd: string | undefined;
workspaceRoot: string | undefined;
timestampFormat: TimestampFormat;
mode?: "sheet" | "sidebar";
onClose: () => void;
}
const PlanSidebar = memo(function PlanSidebar({
activePlan,
activeProposedPlan,
label = "Plan",
environmentId,
markdownCwd,
workspaceRoot,
timestampFormat,
mode = "sidebar",
onClose,
}: PlanSidebarProps) {
const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false);
@@ -121,7 +125,14 @@ const PlanSidebar = memo(function PlanSidebar({
}, [environmentId, planMarkdown, workspaceRoot]);
return (
<div className="flex h-full w-[340px] shrink-0 flex-col border-l border-border/70 bg-card/50">
<div
className={cn(
"flex min-h-0 flex-col bg-card/50",
mode === "sidebar"
? "h-full w-[340px] shrink-0 border-l border-border/70"
: "h-full w-full",
)}
>
{/* Header */}
<div className="flex h-12 shrink-0 items-center justify-between border-b border-border/60 px-3">
<div className="flex items-center gap-2">
@@ -129,7 +140,7 @@ const PlanSidebar = memo(function PlanSidebar({
variant="secondary"
className="rounded-md bg-blue-500/10 px-1.5 py-0 text-[10px] font-semibold tracking-wide text-blue-400 uppercase"
>
Plan
{label}
</Badge>
{activePlan ? (
<span className="text-[11px] text-muted-foreground/60">
@@ -170,7 +181,7 @@ const PlanSidebar = memo(function PlanSidebar({
size="icon-xs"
variant="ghost"
onClick={onClose}
aria-label="Close plan sidebar"
aria-label={`Close ${label.toLowerCase()} sidebar`}
className="text-muted-foreground/50 hover:text-foreground/70"
>
<PanelRightCloseIcon className="size-3.5" />
@@ -0,0 +1,30 @@
import { type ReactNode } from "react";
import { RIGHT_PANEL_SHEET_CLASS_NAME } from "../rightPanelLayout";
import { Sheet, SheetPopup } from "./ui/sheet";
export function RightPanelSheet(props: {
children: ReactNode;
open: boolean;
onClose: () => void;
}) {
return (
<Sheet
open={props.open}
onOpenChange={(open) => {
if (!open) {
props.onClose();
}
}}
>
<SheetPopup
side="right"
showCloseButton={false}
keepMounted
className={RIGHT_PANEL_SHEET_CLASS_NAME}
>
{props.children}
</SheetPopup>
</Sheet>
);
}
File diff suppressed because it is too large. Load diff
@@ -28,7 +28,11 @@ import {
resolveWrappedTerminalLinkRange,
wrappedTerminalLinkRangeIntersectsBufferLine,
} from "../terminal-links";
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
import {
isTerminalClearShortcut,
terminalDeleteShortcutData,
terminalNavigationShortcutData,
} from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -407,6 +411,14 @@ export function TerminalViewport({
return false;
}
const deleteData = terminalDeleteShortcutData(event);
if (deleteData !== null) {
event.preventDefault();
event.stopPropagation();
void sendTerminalInput(deleteData, "Failed to delete terminal input");
return false;
}
if (!isTerminalClearShortcut(event)) return true;
event.preventDefault();
event.stopPropagation();
@@ -783,7 +795,6 @@ interface ThreadTerminalDrawerProps {
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
showResizeHandle?: boolean;
}
interface TerminalActionButtonProps {
@@ -837,7 +848,6 @@ export default function ThreadTerminalDrawer({
onCloseTerminal,
onHeightChange,
onAddTerminalContext,
showResizeHandle = true,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const [resizeEpoch, setResizeEpoch] = useState(0);
@@ -1074,20 +1084,16 @@ export default function ThreadTerminalDrawer({
return (
<aside
className={`thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden bg-background ${
showResizeHandle ? "border-t border-border/80" : ""
}`}
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
style={{ height: `${drawerHeight}px` }}
>
{showResizeHandle ? (
<div
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd}
/>
) : null}
<div
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd}
/>
{!hasTerminalSidebar && (
<div className="pointer-events-none absolute right-2 top-2 z-20">
+12 -30
View File
@@ -162,6 +162,7 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
interactionMode: ProviderInteractionMode;
runtimeMode: RuntimeMode;
showPlanToggle: boolean;
planSidebarLabel: string;
planSidebarOpen: boolean;
onToggleInteractionMode: () => void;
onRuntimeModeChange: (mode: RuntimeMode) => void;
@@ -243,10 +244,14 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
size="sm"
type="button"
onClick={props.onTogglePlanSidebar}
title={props.planSidebarOpen ? "Hide plan sidebar" : "Show plan sidebar"}
title={
props.planSidebarOpen
? `Hide ${props.planSidebarLabel.toLowerCase()} sidebar`
: `Show ${props.planSidebarLabel.toLowerCase()} sidebar`
}
>
<ListTodoIcon />
<span className="sr-only sm:not-sr-only">Plan</span>
<span className="sr-only sm:not-sr-only">{props.planSidebarLabel}</span>
</Button>
</>
) : null}
@@ -339,7 +344,6 @@ export interface ChatComposerHandle {
// --------------------------------------------------------------------------
export interface ChatComposerProps {
activationFocusRequestId?: number;
composerDraftTarget: ScopedThreadRef | DraftId;
environmentId: EnvironmentId;
routeKind: "server" | "draft";
@@ -381,6 +385,7 @@ export interface ChatComposerProps {
activeProposedPlan: Thread["proposedPlans"][number] | null;
activePlan: { turnId?: TurnId } | null;
sidebarProposedPlan: { turnId?: TurnId } | null;
planSidebarLabel: string;
planSidebarOpen: boolean;
// Mode
@@ -448,7 +453,6 @@ export interface ChatComposerProps {
export const ChatComposer = memo(
forwardRef<ChatComposerHandle, ChatComposerProps>(function ChatComposer(props, ref) {
const {
activationFocusRequestId,
composerDraftTarget,
environmentId,
routeKind,
@@ -476,6 +480,7 @@ export const ChatComposer = memo(
activeProposedPlan,
activePlan,
sidebarProposedPlan,
planSidebarLabel,
planSidebarOpen,
runtimeMode,
interactionMode,
@@ -655,7 +660,6 @@ export const ChatComposer = memo(
// Refs
// ------------------------------------------------------------------
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
const pendingActivationFocusRepairRef = useRef(false);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerFormHeightRef = useRef(0);
const composerSelectLockRef = useRef(false);
@@ -664,13 +668,6 @@ export const ChatComposer = memo(
const activeComposerMenuItemRef = useRef<ComposerCommandItem | null>(null);
const dragDepthRef = useRef(0);
useEffect(() => {
if (activationFocusRequestId === undefined) {
return;
}
pendingActivationFocusRepairRef.current = true;
}, [activationFocusRequestId]);
// ------------------------------------------------------------------
// Derived: composer send state
// ------------------------------------------------------------------
@@ -1237,11 +1234,8 @@ export const ChatComposer = memo(
);
return;
}
const previousPrompt = promptRef.current;
promptRef.current = nextPrompt;
if (previousPrompt !== nextPrompt) {
setPrompt(nextPrompt);
}
setPrompt(nextPrompt);
if (!terminalContextIdListsEqual(composerTerminalContexts, terminalContextIds)) {
setComposerDraftTerminalContexts(
composerDraftTarget,
@@ -1252,20 +1246,6 @@ export const ChatComposer = memo(
setComposerTrigger(
cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor),
);
if (pendingActivationFocusRepairRef.current) {
const repairCursor = nextCursor;
window.requestAnimationFrame(() => {
const composerEditor = composerEditorRef.current;
if (!composerEditor) {
pendingActivationFocusRepairRef.current = false;
return;
}
if (!composerEditor.isFocused()) {
composerEditor.focusAt(repairCursor);
}
pendingActivationFocusRepairRef.current = false;
});
}
},
[
activePendingProgress?.activeQuestion,
@@ -1950,6 +1930,7 @@ export const ChatComposer = memo(
<CompactComposerControlsMenu
activePlan={showPlanSidebarToggle}
interactionMode={interactionMode}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
traitsMenuContent={providerTraitsMenuContent}
@@ -1972,6 +1953,7 @@ export const ChatComposer = memo(
interactionMode={interactionMode}
runtimeMode={runtimeMode}
showPlanToggle={showPlanSidebarToggle}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
onToggleInteractionMode={toggleInteractionMode}
onRuntimeModeChange={handleRuntimeModeChange}
+3 -3
View File
@@ -122,7 +122,7 @@ export const ChatHeader = memo(function ChatHeader({
className="shrink-0"
pressed={terminalOpen}
onPressedChange={onToggleTerminal}
aria-label="Toggle terminal split"
aria-label="Toggle terminal drawer"
variant="outline"
size="xs"
disabled={!terminalAvailable}
@@ -135,8 +135,8 @@ export const ChatHeader = memo(function ChatHeader({
{!terminalAvailable
? "Terminal is unavailable until this thread has an active project."
: terminalToggleShortcutLabel
? `Toggle terminal split (${terminalToggleShortcutLabel})`
: "Toggle terminal split"}
? `Toggle terminal drawer (${terminalToggleShortcutLabel})`
: "Toggle terminal drawer"}
</TooltipPopup>
</Tooltip>
<Tooltip>
@@ -123,6 +123,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
<CompactComposerControlsMenu
activePlan={false}
interactionMode="default"
planSidebarLabel="Plan"
planSidebarOpen={false}
runtimeMode="approval-required"
traitsMenuContent={
@@ -15,6 +15,7 @@ import {
export const CompactComposerControlsMenu = memo(function CompactComposerControlsMenu(props: {
activePlan: boolean;
interactionMode: ProviderInteractionMode;
planSidebarLabel: string;
planSidebarOpen: boolean;
runtimeMode: RuntimeMode;
traitsMenuContent?: ReactNode;
@@ -72,7 +73,9 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
<MenuDivider />
<MenuItem onClick={props.onTogglePlanSidebar}>
<ListTodoIcon className="size-4 shrink-0" />
{props.planSidebarOpen ? "Hide plan sidebar" : "Show plan sidebar"}
{props.planSidebarOpen
? `Hide ${props.planSidebarLabel.toLowerCase()} sidebar`
: `Show ${props.planSidebarLabel.toLowerCase()} sidebar`}
</MenuItem>
</>
) : null}
@@ -0,0 +1,189 @@
import { EnvironmentId, MessageId } from "@t3tools/contracts";
import { createRef } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { beforeAll, describe, expect, it, vi } from "vitest";
import type { LegendListRef } from "@legendapp/list/react";
vi.mock("@legendapp/list/react", async () => {
const React = await import("react");
const LegendList = React.forwardRef(function MockLegendList(
props: {
data: Array<{ id: string }>;
keyExtractor: (item: { id: string }) => string;
renderItem: (args: { item: { id: string } }) => React.ReactNode;
ListHeaderComponent?: React.ReactNode;
ListFooterComponent?: React.ReactNode;
},
_ref: React.ForwardedRef<LegendListRef>,
) {
return (
<div data-testid="legend-list">
{props.ListHeaderComponent}
{props.data.map((item) => (
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
))}
{props.ListFooterComponent}
</div>
);
});
return { LegendList };
});
function matchMedia() {
return {
matches: false,
addEventListener: () => {},
removeEventListener: () => {},
};
}
beforeAll(() => {
const classList = {
add: () => {},
remove: () => {},
toggle: () => {},
contains: () => false,
};
vi.stubGlobal("localStorage", {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
clear: () => {},
});
vi.stubGlobal("window", {
matchMedia,
addEventListener: () => {},
removeEventListener: () => {},
requestAnimationFrame: (callback: FrameRequestCallback) => {
callback(0);
return 0;
},
cancelAnimationFrame: () => {},
desktopBridge: undefined,
});
vi.stubGlobal("document", {
documentElement: {
classList,
offsetHeight: 0,
},
});
});
const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
function buildProps() {
return {
isWorking: false,
activeTurnInProgress: false,
activeTurnId: null,
activeTurnStartedAt: null,
listRef: createRef<LegendListRef | null>(),
completionDividerBeforeEntryId: null,
completionSummary: null,
turnDiffSummaryByAssistantMessageId: new Map(),
routeThreadKey: "environment-local:thread-1",
onOpenTurnDiff: () => {},
revertTurnCountByUserMessageId: new Map(),
onRevertUserMessage: () => {},
isRevertingCheckpoint: false,
onImageExpand: () => {},
activeThreadEnvironmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
markdownCwd: undefined,
resolvedTheme: "light" as const,
timestampFormat: "locale" as const,
workspaceRoot: undefined,
onIsAtEndChange: () => {},
};
}
describe("MessagesTimeline", () => {
it("renders inline terminal labels with the composer chip UI", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-1",
kind: "message",
createdAt: "2026-03-17T19:12:28.000Z",
message: {
id: MessageId.make("message-2"),
role: "user",
text: [
"yoo what's @terminal-1:1-5 mean",
"",
"<terminal_context>",
"- Terminal 1 lines 1-5:",
" 1 | julius@mac effect-http-ws-cli % bun i",
" 2 | bun install v1.3.9 (cf6cdbbb)",
"</terminal_context>",
].join("\n"),
createdAt: "2026-03-17T19:12:28.000Z",
streaming: false,
},
},
]}
/>,
);
expect(markup).toContain("Terminal 1 lines 1-5");
expect(markup).toContain("lucide-terminal");
expect(markup).toContain("yoo what&#x27;s ");
}, 20_000);
it("renders context compaction entries in the normal work log", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-1",
kind: "work",
createdAt: "2026-03-17T19:12:28.000Z",
entry: {
id: "work-1",
createdAt: "2026-03-17T19:12:28.000Z",
label: "Context compacted",
tone: "info",
},
},
]}
/>,
);
expect(markup).toContain("Context compacted");
expect(markup).toContain("Work log");
});
it("formats changed file paths from the workspace root", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-1",
kind: "work",
createdAt: "2026-03-17T19:12:28.000Z",
entry: {
id: "work-1",
createdAt: "2026-03-17T19:12:28.000Z",
label: "Updated files",
tone: "tool",
changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
},
},
]}
workspaceRoot="C:/Users/mike/dev-stuff/t3code"
/>,
);
expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
});
});
@@ -60,6 +60,7 @@ import {
formatInlineTerminalContextLabel,
textContainsInlineTerminalContextLabels,
} from "./userMessageTerminalContexts";
import { formatWorkspaceRelativePath } from "../../filePathDisplay";
// ---------------------------------------------------------------------------
// Context — shared state consumed by every row component via useContext.
@@ -528,6 +529,7 @@ const WorkGroupSection = memo(function WorkGroupSection({
}: {
groupedEntries: Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"];
}) {
const { workspaceRoot } = use(TimelineRowCtx);
const [isExpanded, setIsExpanded] = useState(false);
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
@@ -559,7 +561,11 @@ const WorkGroupSection = memo(function WorkGroupSection({
)}
<div className="space-y-0.5">
{visibleEntries.map((workEntry) => (
<SimpleWorkEntryRow key={`work-row:${workEntry.id}`} workEntry={workEntry} />
<SimpleWorkEntryRow
key={`work-row:${workEntry.id}`}
workEntry={workEntry}
workspaceRoot={workspaceRoot}
/>
))}
</div>
</div>
@@ -861,15 +867,17 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
function workEntryPreview(
workEntry: Pick<TimelineWorkEntry, "detail" | "command" | "changedFiles">,
workspaceRoot: string | undefined,
) {
if (workEntry.command) return workEntry.command;
if (workEntry.detail) return workEntry.detail;
if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
const [firstPath] = workEntry.changedFiles ?? [];
if (!firstPath) return null;
const displayPath = formatWorkspaceRelativePath(firstPath, workspaceRoot);
return workEntry.changedFiles!.length === 1
? firstPath
: `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
? displayPath
: `${displayPath} +${workEntry.changedFiles!.length - 1} more`;
}
function workEntryRawCommand(
@@ -924,12 +932,13 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
workEntry: TimelineWorkEntry;
workspaceRoot: string | undefined;
}) {
const { workEntry } = props;
const { workEntry, workspaceRoot } = props;
const iconConfig = workToneIcon(workEntry.tone);
const EntryIcon = workEntryIcon(workEntry);
const heading = toolWorkEntryHeading(workEntry);
const preview = workEntryPreview(workEntry);
const preview = workEntryPreview(workEntry, workspaceRoot);
const rawCommand = workEntryRawCommand(workEntry);
const displayText = preview ? `${heading} - ${preview}` : heading;
const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
@@ -988,15 +997,18 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
</div>
{hasChangedFiles && !previewIsChangedFiles && (
<div className="mt-1 flex flex-wrap gap-1 pl-6">
{workEntry.changedFiles?.slice(0, 4).map((filePath) => (
<span
key={`${workEntry.id}:${filePath}`}
className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
title={filePath}
>
{filePath}
</span>
))}
{workEntry.changedFiles?.slice(0, 4).map((filePath) => {
const displayPath = formatWorkspaceRelativePath(filePath, workspaceRoot);
return (
<span
key={`${workEntry.id}:${filePath}`}
className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
title={displayPath}
>
{displayPath}
</span>
);
})}
{(workEntry.changedFiles?.length ?? 0) > 4 && (
<span className="px-1 text-[10px] text-muted-foreground/55">
+{(workEntry.changedFiles?.length ?? 0) - 4}
@@ -17,6 +17,7 @@ import {
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
@@ -7,6 +7,7 @@ import {
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
type DesktopBridge,
type DesktopUpdateChannel,
type DesktopUpdateState,
type LocalApi,
type ServerConfig,
@@ -258,10 +259,12 @@ function makeClientSession(input: {
const createDesktopBridgeStub = (overrides?: {
readonly serverExposureState?: Awaited<ReturnType<DesktopBridge["getServerExposureState"]>>;
readonly setServerExposureMode?: DesktopBridge["setServerExposureMode"];
readonly setUpdateChannel?: DesktopBridge["setUpdateChannel"];
}): DesktopBridge => {
const idleUpdateState: DesktopUpdateState = {
enabled: false,
status: "idle",
channel: "latest",
currentVersion: "0.0.0-test",
hostArch: "arm64",
appArch: "arm64",
@@ -276,6 +279,7 @@ const createDesktopBridgeStub = (overrides?: {
};
return {
getAppBranding: vi.fn().mockReturnValue(null),
getLocalEnvironmentBootstrap: () => ({
label: "Local environment",
httpBaseUrl: "http://127.0.0.1:3773",
@@ -310,6 +314,12 @@ const createDesktopBridgeStub = (overrides?: {
openExternal: vi.fn().mockResolvedValue(true),
onMenuAction: () => () => {},
getUpdateState: vi.fn().mockResolvedValue(idleUpdateState),
setUpdateChannel:
overrides?.setUpdateChannel ??
vi.fn().mockImplementation(async (channel: DesktopUpdateChannel) => ({
...idleUpdateState,
channel,
})),
checkForUpdate: vi.fn().mockResolvedValue({ checked: false, state: idleUpdateState }),
downloadUpdate: vi
.fn()
@@ -12,6 +12,7 @@ import { useQueryClient } from "@tanstack/react-query";
import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";
import {
PROVIDER_DISPLAY_NAMES,
type DesktopUpdateChannel,
type ScopedThreadRef,
type ProviderKind,
type ServerProvider,
@@ -232,8 +233,42 @@ function AboutVersionTitle() {
function AboutVersionSection() {
const queryClient = useQueryClient();
const updateStateQuery = useDesktopUpdateState();
const [isChangingUpdateChannel, setIsChangingUpdateChannel] = useState(false);
const updateState = updateStateQuery.data ?? null;
const hasDesktopBridge = typeof window !== "undefined" && Boolean(window.desktopBridge);
const selectedUpdateChannel = updateState?.channel ?? "latest";
const handleUpdateChannelChange = useCallback(
(channel: DesktopUpdateChannel) => {
const bridge = window.desktopBridge;
if (
!bridge ||
typeof bridge.setUpdateChannel !== "function" ||
channel === selectedUpdateChannel
) {
return;
}
setIsChangingUpdateChannel(true);
void bridge
.setUpdateChannel(channel)
.then((state) => {
setDesktopUpdateStateQueryData(queryClient, state);
})
.catch((error: unknown) => {
toastManager.add({
type: "error",
title: "Could not change update track",
description: error instanceof Error ? error.message : "Update track change failed.",
});
})
.finally(() => {
setIsChangingUpdateChannel(false);
});
},
[queryClient, selectedUpdateChannel],
);
const handleButtonClick = useCallback(() => {
const bridge = window.desktopBridge;
@@ -323,27 +358,59 @@ function AboutVersionSection() {
: "Current version of the application.";
return (
<SettingsRow
title={<AboutVersionTitle />}
description={description}
control={
<Tooltip>
<TooltipTrigger
render={
<Button
size="xs"
variant={action === "install" ? "default" : "outline"}
disabled={buttonDisabled}
onClick={handleButtonClick}
>
{buttonLabel}
</Button>
}
/>
{buttonTooltip ? <TooltipPopup>{buttonTooltip}</TooltipPopup> : null}
</Tooltip>
}
/>
<>
<SettingsRow
title={<AboutVersionTitle />}
description={description}
control={
<Tooltip>
<TooltipTrigger
render={
<Button
size="xs"
variant={action === "install" ? "default" : "outline"}
disabled={buttonDisabled}
onClick={handleButtonClick}
>
{buttonLabel}
</Button>
}
/>
{buttonTooltip ? <TooltipPopup>{buttonTooltip}</TooltipPopup> : null}
</Tooltip>
}
/>
<SettingsRow
title="Update track"
description="Stable follows full releases. Nightly follows the nightly desktop channel and can switch back to stable immediately."
control={
<Select
value={selectedUpdateChannel}
onValueChange={(value) => {
handleUpdateChannelChange(value as DesktopUpdateChannel);
}}
>
<SelectTrigger
className="w-full sm:w-40"
aria-label="Update track"
disabled={!hasDesktopBridge || isChangingUpdateChannel}
>
<SelectValue>
{selectedUpdateChannel === "nightly" ? "Nightly" : "Stable"}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="latest">
Stable
</SelectItem>
<SelectItem hideIndicator value="nightly">
Nightly
</SelectItem>
</SelectPopup>
</Select>
}
/>
</>
);
}
@@ -377,6 +444,9 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
? ["New thread mode"]
: []),
...(settings.addProjectBaseDirectory !== DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory
? ["Add project base directory"]
: []),
...(settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive
? ["Archive confirmation"]
: []),
@@ -391,6 +461,7 @@ export function useSettingsRestore(onRestored?: () => void) {
isGitWritingModelDirty,
settings.confirmThreadArchive,
settings.confirmThreadDelete,
settings.addProjectBaseDirectory,
settings.defaultThreadEnvMode,
settings.diffWordWrap,
settings.enableAssistantStreaming,
@@ -440,7 +511,8 @@ export function GeneralSettingsPanel() {
claudeAgent: Boolean(
settings.providers.claudeAgent.binaryPath !==
DEFAULT_UNIFIED_SETTINGS.providers.claudeAgent.binaryPath ||
settings.providers.claudeAgent.customModels.length > 0,
settings.providers.claudeAgent.customModels.length > 0 ||
settings.providers.claudeAgent.launchArgs !== "",
),
});
const [customModelInputByProvider, setCustomModelInputByProvider] = useState<
@@ -852,6 +924,34 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
title="Add project starts in"
description='Leave empty to use "~/" when the Add Project browser opens.'
resetAction={
settings.addProjectBaseDirectory !==
DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory ? (
<SettingResetButton
label="add project base directory"
onClick={() =>
updateSettings({
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
})
}
/>
) : null
}
control={
<Input
className="w-full sm:w-72"
value={settings.addProjectBaseDirectory}
onChange={(event) => updateSettings({ addProjectBaseDirectory: event.target.value })}
placeholder="~/"
spellCheck={false}
aria-label="Add project base directory"
/>
}
/>
<SettingsRow
title="Archive confirmation"
description="Require a second click on the inline archive action before a thread is archived."
@@ -1179,6 +1279,37 @@ export function GeneralSettingsPanel() {
</div>
) : null}
{providerCard.provider === "claudeAgent" ? (
<div className="border-t border-border/60 px-4 py-3 sm:px-5">
<label htmlFor="provider-install-claudeAgent-launch-args" className="block">
<span className="text-xs font-medium text-foreground">
Launch arguments
</span>
<Input
id="provider-install-claudeAgent-launch-args"
className="mt-1.5"
value={settings.providers.claudeAgent.launchArgs}
onChange={(event) =>
updateSettings({
providers: {
...settings.providers,
claudeAgent: {
...settings.providers.claudeAgent,
launchArgs: event.target.value,
},
},
})
}
placeholder="e.g. --chrome"
spellCheck={false}
/>
<span className="mt-1 block text-xs text-muted-foreground">
Additional CLI arguments passed to Claude Code on session start.
</span>
</label>
</div>
) : null}
<div className="border-t border-border/60 px-4 py-3 sm:px-5">
<div className="text-xs font-medium text-foreground">Models</div>
<div className="mt-1 text-xs text-muted-foreground">
@@ -1,100 +0,0 @@
import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useEffect, useMemo, useRef, useState } from "react";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../../storeSelectors";
import { useStore } from "../../store";
import { useTerminalStateStore } from "../../terminalStateStore";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { TerminalViewport } from "../ThreadTerminalDrawer";
import { useWorkspaceStore } from "../../workspace/store";
export function ThreadTerminalSurface(props: {
surfaceId: string;
terminalId: string;
threadRef: ScopedThreadRef;
activationFocusRequestId?: number;
}) {
const { activationFocusRequestId, surfaceId, terminalId, threadRef } = props;
const thread = useStore(useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]));
const projectRef = thread ? scopeProjectRef(thread.environmentId, thread.projectId) : null;
const project = useStore(useMemo(() => createProjectSelectorByRef(projectRef), [projectRef]));
const closeTerminal = useTerminalStateStore((state) => state.closeTerminal);
const terminalLaunchContext = useTerminalStateStore(
(state) => state.terminalLaunchContextByThreadKey[scopedThreadKey(threadRef)] ?? null,
);
const [containerHeight, setContainerHeight] = useState(320);
const [focusRequestId, setFocusRequestId] = useState(1);
const closeSurface = useWorkspaceStore((state) => state.closeSurface);
const containerRef = useRef<HTMLDivElement | null>(null);
const worktreePath = terminalLaunchContext?.worktreePath ?? thread?.worktreePath ?? null;
const cwd = useMemo(
() =>
terminalLaunchContext?.cwd ??
(project
? projectScriptCwd({
project: { cwd: project.cwd },
worktreePath,
})
: null),
[project, terminalLaunchContext?.cwd, worktreePath],
);
const runtimeEnv = useMemo(
() =>
project
? projectScriptRuntimeEnv({
project: { cwd: project.cwd },
worktreePath,
})
: {},
[project, worktreePath],
);
useEffect(() => {
const element = containerRef.current;
if (!element) {
return;
}
const observer = new ResizeObserver((entries) => {
const nextHeight = Math.max(180, Math.floor(entries[0]?.contentRect.height ?? 0));
setContainerHeight((current) => (current === nextHeight ? current : nextHeight));
});
observer.observe(element);
return () => observer.disconnect();
}, []);
useEffect(() => {
if (activationFocusRequestId === undefined) {
return;
}
setFocusRequestId((current) => current + 1);
}, [activationFocusRequestId]);
if (!thread || !project || !cwd) {
return <div ref={containerRef} className="min-h-0 flex-1 bg-background" />;
}
return (
<div ref={containerRef} className="min-h-0 flex-1 overflow-hidden bg-background">
<TerminalViewport
threadRef={threadRef}
threadId={thread.id}
terminalId={terminalId}
terminalLabel={thread.title}
cwd={cwd}
worktreePath={worktreePath}
runtimeEnv={runtimeEnv}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={0}
drawerHeight={containerHeight}
onAddTerminalContext={() => undefined}
onSessionExited={() => {
closeTerminal(threadRef, terminalId);
closeSurface(surfaceId);
}}
/>
</div>
);
}
@@ -1,130 +0,0 @@
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
import { useEffect, useMemo, useRef } from "react";
import { useComposerDraftStore } from "../../composerDraftStore";
import { resolveThreadRouteTarget } from "../../threadRoutes";
import { useFocusedWorkspaceRouteTarget, useWorkspaceStore } from "../../workspace/store";
import type { ThreadSurfaceInput } from "../../workspace/types";
function sameRouteTarget(
left: ReturnType<typeof resolveThreadRouteTarget>,
right: ReturnType<typeof resolveThreadRouteTarget>,
): boolean {
if (!left && !right) {
return true;
}
if (!left || !right || left.kind !== right.kind) {
return false;
}
if (left.kind === "server" && right.kind === "server") {
return (
left.threadRef.environmentId === right.threadRef.environmentId &&
left.threadRef.threadId === right.threadRef.threadId
);
}
if (left.kind === "draft" && right.kind === "draft") {
return left.draftId === right.draftId;
}
return false;
}
export function WorkspaceRouteSync() {
const navigate = useNavigate();
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const currentRouteTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
});
const focusedRouteTarget = useFocusedWorkspaceRouteTarget();
const pathname = useLocation({
select: (location) => location.pathname,
});
const previousPathnameRef = useRef(pathname);
const draftSession = useComposerDraftStore((store) =>
currentRouteTarget?.kind === "draft" ? store.getDraftSession(currentRouteTarget.draftId) : null,
);
const currentRouteSurfaceInput = useMemo<ThreadSurfaceInput | null>(() => {
if (!currentRouteTarget) {
return null;
}
if (currentRouteTarget.kind === "server") {
return {
scope: "server",
threadRef: currentRouteTarget.threadRef,
};
}
if (!draftSession) {
return null;
}
return {
scope: "draft",
draftId: currentRouteTarget.draftId,
environmentId: draftSession.environmentId,
threadId: draftSession.threadId,
};
}, [currentRouteTarget, draftSession]);
useEffect(() => {
const pathnameChanged = previousPathnameRef.current !== pathname;
previousPathnameRef.current = pathname;
if (currentRouteTarget) {
if (!currentRouteSurfaceInput) {
return;
}
if (!focusedRouteTarget || pathnameChanged) {
openThreadSurface(currentRouteSurfaceInput, "focus-or-tab");
return;
}
if (sameRouteTarget(currentRouteTarget, focusedRouteTarget)) {
return;
}
void navigateToRouteTarget(navigate, focusedRouteTarget);
return;
}
if (!focusedRouteTarget) {
return;
}
void navigateToRouteTarget(navigate, focusedRouteTarget);
}, [
currentRouteSurfaceInput,
currentRouteTarget,
focusedRouteTarget,
navigate,
openThreadSurface,
pathname,
]);
return null;
}
function navigateToRouteTarget(
navigate: ReturnType<typeof useNavigate>,
target: NonNullable<ReturnType<typeof resolveThreadRouteTarget>>,
) {
if (target.kind === "server") {
return navigate({
to: "/$environmentId/$threadId",
params: {
environmentId: target.threadRef.environmentId,
threadId: target.threadRef.threadId,
},
replace: true,
search: {},
});
}
return navigate({
to: "/draft/$draftId",
params: {
draftId: target.draftId,
},
replace: true,
search: {},
});
}
@@ -1,984 +0,0 @@
import { useParams } from "@tanstack/react-router";
import { Columns2Icon, Rows2Icon, TerminalSquareIcon, XIcon } from "lucide-react";
import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { createThreadSelectorByRef } from "../../storeSelectors";
import { useStore } from "../../store";
import { cn } from "../../lib/utils";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import { SidebarInset } from "../ui/sidebar";
import ChatView from "../ChatView";
import { useComposerDraftStore } from "../../composerDraftStore";
import { resolveThreadRouteTarget } from "../../threadRoutes";
import { ThreadTerminalSurface } from "./ThreadTerminalSurface";
import { useWorkspaceDragStore } from "../../workspace/dragStore";
import {
useWorkspaceFocusedWindowId,
useWorkspaceMobileActiveWindowId,
useWorkspaceNode,
useWorkspaceRootNodeId,
useWorkspaceStore,
useWorkspaceSurface,
useWorkspaceWindow,
useWorkspaceWindowIds,
useWorkspaceZoomedWindowId,
} from "../../workspace/store";
import {
normalizeWorkspaceSplitSizes,
type WorkspaceNode,
type WorkspaceDropPlacement,
type WorkspacePlacementTarget,
type WorkspaceSurfaceInstance,
} from "../../workspace/types";
const WORKSPACE_MIN_PANE_SIZE_PX = 220;
const WORKSPACE_DROP_EDGE_THRESHOLD = 0.22;
const INTERACTIVE_PANE_TARGET_SELECTOR = [
"button",
"a[href]",
"input",
"textarea",
"select",
"summary",
"[contenteditable='true']",
"[contenteditable='']",
"[role='button']",
"[role='link']",
"[role='menuitem']",
"[draggable='true']",
"[data-pane-autofocus-prevent='true']",
].join(", ");
function isWorkspaceDropTarget(
value: WorkspaceDropPlacement | string | null,
target: WorkspaceDropPlacement | string,
): boolean {
return value === target;
}
function resolveWorkspaceDropPlacementFromPoint(
rect: DOMRect,
clientX: number,
clientY: number,
): WorkspaceDropPlacement {
if (rect.width <= 0 || rect.height <= 0) {
return "center";
}
const normalizedX = (clientX - rect.left) / rect.width;
const normalizedY = (clientY - rect.top) / rect.height;
const distanceLeft = normalizedX;
const distanceRight = 1 - normalizedX;
const distanceTop = normalizedY;
const distanceBottom = 1 - normalizedY;
const minEdgeDistance = Math.min(distanceLeft, distanceRight, distanceTop, distanceBottom);
if (minEdgeDistance > WORKSPACE_DROP_EDGE_THRESHOLD) {
return "center";
}
if (minEdgeDistance === distanceLeft) {
return "left";
}
if (minEdgeDistance === distanceRight) {
return "right";
}
if (minEdgeDistance === distanceTop) {
return "top";
}
return "bottom";
}
function workspaceDropPreviewClass(target: WorkspaceDropPlacement | string | null): string {
switch (target) {
case "left":
return "left-2 top-2 bottom-2 w-1/2";
case "right":
return "right-2 top-2 bottom-2 w-1/2";
case "top":
return "left-2 right-2 top-2 h-1/2";
case "bottom":
return "left-2 right-2 bottom-2 h-1/2";
case "center":
return "inset-2";
default:
return "hidden";
}
}
function shouldSuppressPaneActivationAutoFocus(target: EventTarget | null): boolean {
if (!(target instanceof Element)) {
return false;
}
if (target.closest("[data-pane-autofocus-allow='true']")) {
return false;
}
return target.closest(INTERACTIVE_PANE_TARGET_SELECTOR) !== null;
}
function applyWorkspaceDrop(params: {
clearDragItem: () => void;
dragItem:
| {
kind: "surface";
surfaceId: string;
}
| {
kind: "thread";
input: Parameters<ReturnType<typeof useWorkspaceStore.getState>["placeThreadSurface"]>[0];
};
placeSurface: ReturnType<typeof useWorkspaceStore.getState>["placeSurface"];
placeThreadSurface: ReturnType<typeof useWorkspaceStore.getState>["placeThreadSurface"];
target: WorkspacePlacementTarget;
}) {
if (params.dragItem.kind === "surface") {
params.placeSurface(params.dragItem.surfaceId, params.target);
} else {
params.placeThreadSurface(params.dragItem.input, params.target);
}
params.clearDragItem();
}
function WorkspaceEmptyState() {
return (
<div className="flex min-h-0 flex-1 items-center justify-center px-6">
<div className="w-full max-w-lg rounded-xl border border-border/55 bg-card/20 px-8 py-12 shadow-sm/5">
<p className="text-xl text-foreground">Pick a thread to continue</p>
<p className="mt-2 text-sm text-muted-foreground/78">
Select an existing thread or create a new one to get started.
</p>
</div>
</div>
);
}
export function WorkspaceShell() {
const rootNodeId = useWorkspaceRootNodeId();
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
{rootNodeId ? <WorkspaceLayoutRoot /> : <WorkspaceRouteFallback />}
</div>
</SidebarInset>
);
}
function WorkspaceRouteFallback() {
const routeTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
});
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const draftSession = useComposerDraftStore((store) =>
routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
);
useEffect(() => {
if (!routeTarget) {
return;
}
if (routeTarget.kind === "server") {
openThreadSurface(
{
scope: "server",
threadRef: routeTarget.threadRef,
},
"focus-or-tab",
);
return;
}
if (!draftSession) {
return;
}
openThreadSurface(
{
scope: "draft",
draftId: routeTarget.draftId,
environmentId: draftSession.environmentId,
threadId: draftSession.threadId,
},
"focus-or-tab",
);
}, [draftSession, openThreadSurface, routeTarget]);
if (!routeTarget) {
return <WorkspaceEmptyState />;
}
if (routeTarget.kind === "server") {
return (
<ChatView
environmentId={routeTarget.threadRef.environmentId}
threadId={routeTarget.threadRef.threadId}
routeKind="server"
/>
);
}
if (!draftSession) {
return <WorkspaceEmptyState />;
}
return (
<ChatView
draftId={routeTarget.draftId}
environmentId={draftSession.environmentId}
threadId={draftSession.threadId}
routeKind="draft"
/>
);
}
function WorkspaceLayoutRoot() {
const rootNodeId = useWorkspaceRootNodeId();
const focusedWindowId = useWorkspaceFocusedWindowId();
const mobileActiveWindowId = useWorkspaceMobileActiveWindowId();
const windowIds = useWorkspaceWindowIds();
const zoomedWindowId = useWorkspaceZoomedWindowId();
const setMobileActiveWindow = useWorkspaceStore((state) => state.setMobileActiveWindow);
const isDesktopViewport = useMediaQuery("md");
const activeWindowId =
zoomedWindowId ?? mobileActiveWindowId ?? focusedWindowId ?? windowIds[0] ?? null;
return (
<div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
{windowIds.length > 1 ? (
<div className="flex items-center gap-2 border-b border-border px-3 py-2 md:hidden">
{windowIds.map((windowId, index) => {
const isActive = (mobileActiveWindowId ?? focusedWindowId ?? windowIds[0]) === windowId;
return (
<button
key={windowId}
type="button"
className={cn(
"rounded-md border px-2 py-1 text-xs",
isActive
? "border-border bg-accent text-foreground"
: "border-border/60 text-muted-foreground",
)}
onClick={() => setMobileActiveWindow(windowId)}
>
Window {index + 1}
</button>
);
})}
</div>
) : null}
<div className="min-h-0 min-w-0 flex-1 overflow-hidden">
{isDesktopViewport ? (
zoomedWindowId ? (
<WorkspaceWindowView windowId={zoomedWindowId} />
) : (
<WorkspaceNodeView nodeId={rootNodeId} />
)
) : (
<MobileWorkspaceWindow windowId={activeWindowId} />
)}
</div>
</div>
);
}
const MobileWorkspaceWindow = memo(function MobileWorkspaceWindow(props: {
windowId: string | null;
}) {
const window = useWorkspaceWindow(props.windowId);
if (!props.windowId) {
return <WorkspaceEmptyState />;
}
if (!window) {
return <WorkspaceEmptyState />;
}
return <WorkspaceWindowView windowId={window.id} />;
});
const WorkspaceNodeView = memo(function WorkspaceNodeView(props: { nodeId: string | null }) {
const node = useWorkspaceNode(props.nodeId);
if (!props.nodeId) {
return null;
}
if (!node) {
return null;
}
if (node.kind === "window") {
return <WorkspaceWindowView windowId={node.windowId} />;
}
return <WorkspaceSplitNodeView node={node} />;
});
const WorkspaceSplitNodeView = memo(function WorkspaceSplitNodeView(props: {
node: Extract<WorkspaceNode, { kind: "split" }>;
}) {
const setSplitNodeSizes = useWorkspaceStore((state) => state.setSplitNodeSizes);
const containerRef = useRef<HTMLDivElement | null>(null);
const resizeStateRef = useRef<{
handle: HTMLButtonElement;
handleIndex: number;
pendingSizes: number[];
pointerId: number;
rafId: number | null;
startCoordinate: number;
startSizes: number[];
totalPx: number;
} | null>(null);
const sizes = useMemo(
() => normalizeWorkspaceSplitSizes(props.node.sizes, props.node.childIds.length),
[props.node.childIds.length, props.node.sizes],
);
const stopResize = useCallback(
(pointerId: number) => {
const resizeState = resizeStateRef.current;
if (!resizeState) {
return;
}
if (resizeState.rafId !== null) {
window.cancelAnimationFrame(resizeState.rafId);
setSplitNodeSizes(props.node.id, resizeState.pendingSizes);
}
resizeStateRef.current = null;
if (resizeState.handle.hasPointerCapture(pointerId)) {
resizeState.handle.releasePointerCapture(pointerId);
}
document.body.style.removeProperty("cursor");
document.body.style.removeProperty("user-select");
},
[props.node.id, setSplitNodeSizes],
);
useEffect(() => {
return () => {
const resizeState = resizeStateRef.current;
if (resizeState && resizeState.rafId !== null) {
window.cancelAnimationFrame(resizeState.rafId);
}
document.body.style.removeProperty("cursor");
document.body.style.removeProperty("user-select");
};
}, []);
const handleResizePointerDown = useCallback(
(handleIndex: number, event: React.PointerEvent<HTMLButtonElement>) => {
if (event.button !== 0) {
return;
}
const container = containerRef.current;
if (!container) {
return;
}
const rect = container.getBoundingClientRect();
const totalPx = props.node.axis === "x" ? rect.width : rect.height;
if (totalPx <= 0) {
return;
}
event.preventDefault();
event.stopPropagation();
resizeStateRef.current = {
handle: event.currentTarget,
handleIndex,
pendingSizes: sizes,
pointerId: event.pointerId,
rafId: null,
startCoordinate: props.node.axis === "x" ? event.clientX : event.clientY,
startSizes: sizes,
totalPx,
};
event.currentTarget.setPointerCapture(event.pointerId);
document.body.style.cursor = props.node.axis === "x" ? "col-resize" : "row-resize";
document.body.style.userSelect = "none";
},
[props.node.axis, sizes],
);
const handleResizePointerMove = useCallback(
(event: React.PointerEvent<HTMLButtonElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) {
return;
}
event.preventDefault();
const deltaPx =
(props.node.axis === "x" ? event.clientX : event.clientY) - resizeState.startCoordinate;
const deltaFraction = deltaPx / resizeState.totalPx;
const pairTotal =
resizeState.startSizes[resizeState.handleIndex]! +
resizeState.startSizes[resizeState.handleIndex + 1]!;
const requestedMinFraction = WORKSPACE_MIN_PANE_SIZE_PX / resizeState.totalPx;
const minFraction = Math.min(requestedMinFraction, Math.max(pairTotal / 2 - 0.001, 0));
const nextBefore = Math.min(
pairTotal - minFraction,
Math.max(minFraction, resizeState.startSizes[resizeState.handleIndex]! + deltaFraction),
);
const nextAfter = pairTotal - nextBefore;
const nextSizes = [...resizeState.startSizes];
nextSizes[resizeState.handleIndex] = nextBefore;
nextSizes[resizeState.handleIndex + 1] = nextAfter;
resizeState.pendingSizes = nextSizes;
if (resizeState.rafId !== null) {
return;
}
resizeState.rafId = window.requestAnimationFrame(() => {
const activeResizeState = resizeStateRef.current;
if (!activeResizeState) {
return;
}
activeResizeState.rafId = null;
setSplitNodeSizes(props.node.id, activeResizeState.pendingSizes);
});
},
[props.node.axis, props.node.id, setSplitNodeSizes],
);
const endResizeInteraction = useCallback(
(event: React.PointerEvent<HTMLButtonElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) {
return;
}
event.preventDefault();
stopResize(event.pointerId);
},
[stopResize],
);
return (
<div
ref={containerRef}
className={cn(
"flex h-full min-h-0 min-w-0 flex-1 overflow-hidden",
props.node.axis === "x" ? "flex-row" : "flex-col",
)}
>
{props.node.childIds.map((childId, index) => (
<Fragment key={childId}>
<div
className="h-full min-h-0 min-w-0 overflow-hidden"
style={{
flexBasis: 0,
flexGrow: sizes[index] ?? 1,
flexShrink: 1,
}}
>
<WorkspaceNodeView nodeId={childId} />
</div>
{index < props.node.childIds.length - 1 ? (
<button
type="button"
className={cn(
"relative z-10 shrink-0 bg-border/80 transition hover:bg-foreground/40",
props.node.axis === "x"
? "h-full w-1 cursor-col-resize touch-none"
: "h-1 w-full cursor-row-resize touch-none",
)}
aria-label={
props.node.axis === "x" ? "Resize panes horizontally" : "Resize panes vertically"
}
title={props.node.axis === "x" ? "Drag to resize panes" : "Drag to resize panes"}
onPointerCancel={endResizeInteraction}
onPointerDown={(event) => handleResizePointerDown(index, event)}
onPointerMove={handleResizePointerMove}
onPointerUp={endResizeInteraction}
>
<span
className={cn(
"pointer-events-none absolute rounded-full bg-background/90",
props.node.axis === "x"
? "top-1/2 left-1/2 h-10 w-px -translate-x-1/2 -translate-y-1/2"
: "top-1/2 left-1/2 h-px w-10 -translate-x-1/2 -translate-y-1/2",
)}
/>
</button>
) : null}
</Fragment>
))}
</div>
);
});
const WorkspaceWindowView = memo(function WorkspaceWindowView(props: { windowId: string }) {
const dragItem = useWorkspaceDragStore((state) => state.item);
const clearDragItem = useWorkspaceDragStore((state) => state.clearItem);
const focusWindow = useWorkspaceStore((state) => state.focusWindow);
const focusTab = useWorkspaceStore((state) => state.focusTab);
const closeSurface = useWorkspaceStore((state) => state.closeSurface);
const placeSurface = useWorkspaceStore((state) => state.placeSurface);
const placeThreadSurface = useWorkspaceStore((state) => state.placeThreadSurface);
const splitWindowSurface = useWorkspaceStore((state) => state.splitWindowSurface);
const window = useWorkspaceWindow(props.windowId);
const activeSurface = useWorkspaceSurface(window?.activeTabId ?? null);
const focusedWindowId = useWorkspaceFocusedWindowId();
const [isWindowDragActive, setIsWindowDragActive] = useState(false);
const [threadActivationFocusRequestId, setThreadActivationFocusRequestId] = useState(0);
const [terminalActivationFocusRequestId, setTerminalActivationFocusRequestId] = useState(0);
const [hoveredDropTarget, setHoveredDropTarget] = useState<
WorkspaceDropPlacement | string | null
>(null);
const shouldAutoFocusOnActivationRef = useRef(true);
const wasFocusedRef = useRef(focusedWindowId === props.windowId);
const windowElementRef = useRef<HTMLElement | null>(null);
const pendingFocusWindowFrameRef = useRef<number | null>(null);
const resetHoveredDropTarget = useCallback(() => {
setHoveredDropTarget(null);
}, []);
useEffect(() => {
if (!dragItem) {
setIsWindowDragActive(false);
setHoveredDropTarget(null);
}
}, [dragItem]);
useEffect(() => {
return () => {
if (pendingFocusWindowFrameRef.current !== null) {
globalThis.cancelAnimationFrame(pendingFocusWindowFrameRef.current);
}
};
}, []);
useEffect(() => {
const isFocused = focusedWindowId === props.windowId;
const wasFocused = wasFocusedRef.current;
wasFocusedRef.current = isFocused;
if (!isFocused || wasFocused || !activeSurface) {
return;
}
const shouldAutoFocus = shouldAutoFocusOnActivationRef.current;
shouldAutoFocusOnActivationRef.current = true;
if (!shouldAutoFocus) {
return;
}
const activeElement = document.activeElement;
const windowElement = windowElementRef.current;
if (
activeElement instanceof HTMLElement &&
windowElement &&
!windowElement.contains(activeElement)
) {
activeElement.blur();
}
if (activeSurface.kind === "thread") {
setThreadActivationFocusRequestId((current) => current + 1);
return;
}
setTerminalActivationFocusRequestId((current) => current + 1);
}, [activeSurface, focusedWindowId, props.windowId]);
const handleWindowDragOver = useCallback(
(event: React.DragEvent<HTMLElement>) => {
if (!dragItem) {
return;
}
event.preventDefault();
event.dataTransfer.dropEffect = "move";
setIsWindowDragActive(true);
setHoveredDropTarget(
resolveWorkspaceDropPlacementFromPoint(
event.currentTarget.getBoundingClientRect(),
event.clientX,
event.clientY,
),
);
},
[dragItem],
);
const handleWindowDragLeave = useCallback((event: React.DragEvent<HTMLElement>) => {
const relatedTarget = event.relatedTarget;
if (relatedTarget instanceof Node && event.currentTarget.contains(relatedTarget)) {
return;
}
setIsWindowDragActive(false);
setHoveredDropTarget(null);
}, []);
const handleDropTarget = useCallback(
(target: WorkspacePlacementTarget) => (event: React.DragEvent<HTMLElement>) => {
if (!dragItem) {
return;
}
event.preventDefault();
event.stopPropagation();
applyWorkspaceDrop({
clearDragItem,
dragItem,
placeSurface,
placeThreadSurface,
target,
});
setIsWindowDragActive(false);
setHoveredDropTarget(null);
},
[clearDragItem, dragItem, placeSurface, placeThreadSurface],
);
const handleDragOverTarget = useCallback(
(hoverTarget: WorkspaceDropPlacement | string) => (event: React.DragEvent<HTMLElement>) => {
if (!dragItem) {
return;
}
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = "move";
setHoveredDropTarget(hoverTarget);
},
[dragItem],
);
const handleWindowDrop = useCallback(
(event: React.DragEvent<HTMLElement>) => {
if (!dragItem) {
return;
}
event.preventDefault();
event.stopPropagation();
const targetPlacement = resolveWorkspaceDropPlacementFromPoint(
event.currentTarget.getBoundingClientRect(),
event.clientX,
event.clientY,
);
applyWorkspaceDrop({
clearDragItem,
dragItem,
placeSurface,
placeThreadSurface,
target: {
kind: "window",
windowId: props.windowId,
placement: targetPlacement,
},
});
setIsWindowDragActive(false);
setHoveredDropTarget(null);
},
[clearDragItem, dragItem, placeSurface, placeThreadSurface, props.windowId],
);
const handleTabDragStart = useCallback(
(surfaceId: string) => (event: React.DragEvent<HTMLElement>) => {
event.stopPropagation();
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", surfaceId);
useWorkspaceDragStore.getState().setItem({
kind: "surface",
surfaceId,
});
focusWindow(props.windowId);
focusTab(props.windowId, surfaceId);
},
[focusTab, focusWindow, props.windowId],
);
const handleTabDragEnd = useCallback(() => {
useWorkspaceDragStore.getState().clearItem();
setHoveredDropTarget(null);
}, []);
if (!window) {
return null;
}
return (
<section
ref={windowElementRef}
className={cn(
"relative flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden border border-border/70 bg-background",
focusedWindowId === props.windowId ? "ring-1 ring-border/80" : "",
)}
onPointerDownCapture={(event) => {
if (event.button !== 0) {
shouldAutoFocusOnActivationRef.current = true;
return;
}
const shouldSuppressAutoFocus = shouldSuppressPaneActivationAutoFocus(event.target);
shouldAutoFocusOnActivationRef.current = !shouldSuppressAutoFocus;
if (pendingFocusWindowFrameRef.current !== null) {
globalThis.cancelAnimationFrame(pendingFocusWindowFrameRef.current);
pendingFocusWindowFrameRef.current = null;
}
if (!shouldSuppressAutoFocus) {
focusWindow(props.windowId);
return;
}
pendingFocusWindowFrameRef.current = globalThis.requestAnimationFrame(() => {
pendingFocusWindowFrameRef.current = null;
focusWindow(props.windowId);
});
}}
>
<div className="flex min-w-0 items-center gap-1 border-b border-border/70 bg-muted/20 px-2 py-1.5">
<div
className={cn(
"flex min-w-0 flex-1 items-center gap-1 overflow-x-auto rounded-md transition",
isWorkspaceDropTarget(hoveredDropTarget, "tab-strip") ? "bg-accent/60" : "",
)}
onDragLeave={resetHoveredDropTarget}
onDragOver={handleDragOverTarget("tab-strip")}
onDrop={handleDropTarget({
kind: "window",
windowId: props.windowId,
placement: "center",
})}
>
{window.tabIds.map((surfaceId) => {
return (
<WorkspaceTabView
key={surfaceId}
closeSurface={closeSurface}
focusTab={focusTab}
handleDragOverTarget={handleDragOverTarget}
handleDropTarget={handleDropTarget}
handleTabDragEnd={handleTabDragEnd}
handleTabDragStart={handleTabDragStart}
hoveredDropTarget={hoveredDropTarget}
resetHoveredDropTarget={resetHoveredDropTarget}
surfaceId={surfaceId}
windowId={props.windowId}
isActive={window.activeTabId === surfaceId}
/>
);
})}
</div>
<div className="hidden items-center gap-1 md:flex">
<button
type="button"
className="rounded-sm p-1 text-muted-foreground transition hover:bg-accent hover:text-foreground"
onClick={() => splitWindowSurface(props.windowId, "x")}
aria-label="Split active tab right"
title="Split active tab right"
>
<Columns2Icon className="size-3.5" />
</button>
<button
type="button"
className="rounded-sm p-1 text-muted-foreground transition hover:bg-accent hover:text-foreground"
onClick={() => splitWindowSurface(props.windowId, "y")}
aria-label="Split active tab down"
title="Split active tab down"
>
<Rows2Icon className="size-3.5" />
</button>
</div>
</div>
<div
className={cn(
"h-0.5 shrink-0 transition-colors",
focusedWindowId === props.windowId ? "bg-primary" : "bg-transparent",
)}
/>
<div
className="relative flex h-full min-h-0 min-w-0 flex-1 overflow-hidden"
onDragLeave={handleWindowDragLeave}
onDrop={handleWindowDrop}
onDragOver={handleWindowDragOver}
>
{activeSurface ? (
<WorkspaceSurfaceView
activationFocusRequestId={
activeSurface.kind === "thread"
? threadActivationFocusRequestId
: terminalActivationFocusRequestId
}
surface={activeSurface}
bindSharedComposerHandle={focusedWindowId === props.windowId}
/>
) : null}
{dragItem && isWindowDragActive ? (
<>
<div className="pointer-events-none absolute inset-0 z-10 bg-background/10" />
<div
className={cn(
"pointer-events-none absolute z-20 rounded-lg border-2 border-primary/70 bg-primary/10 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.08)] transition-all",
workspaceDropPreviewClass(hoveredDropTarget),
)}
/>
</>
) : null}
</div>
</section>
);
});
const WorkspaceTabView = memo(function WorkspaceTabView(props: {
closeSurface: (surfaceId: string) => void;
focusTab: (windowId: string, surfaceId: string) => void;
handleDragOverTarget: (
hoverTarget: WorkspaceDropPlacement | string,
) => (event: React.DragEvent<HTMLElement>) => void;
handleDropTarget: (
target: WorkspacePlacementTarget,
) => (event: React.DragEvent<HTMLElement>) => void;
handleTabDragEnd: () => void;
handleTabDragStart: (surfaceId: string) => (event: React.DragEvent<HTMLElement>) => void;
hoveredDropTarget: WorkspaceDropPlacement | string | null;
isActive: boolean;
resetHoveredDropTarget: () => void;
surfaceId: string;
windowId: string;
}) {
const surface = useWorkspaceSurface(props.surfaceId);
if (!surface) {
return null;
}
return (
<div
className={cn(
"group flex max-w-[18rem] min-w-0 items-center gap-1 rounded-md border px-2 py-1 text-xs",
props.isActive
? "border-border bg-background text-foreground"
: "border-transparent text-muted-foreground hover:bg-accent/50",
isWorkspaceDropTarget(props.hoveredDropTarget, props.surfaceId)
? "ring-1 ring-primary/50"
: "",
)}
onDragLeave={props.resetHoveredDropTarget}
onDragOver={props.handleDragOverTarget(props.surfaceId)}
onDrop={props.handleDropTarget({
kind: "tab",
windowId: props.windowId,
surfaceId: props.surfaceId,
})}
>
<button
type="button"
className="min-w-0 flex-1 truncate text-left"
data-pane-autofocus-allow="true"
draggable
onClick={() => props.focusTab(props.windowId, props.surfaceId)}
onDragEnd={props.handleTabDragEnd}
onDragStart={props.handleTabDragStart(props.surfaceId)}
>
<WorkspaceSurfaceTitle surface={surface} />
</button>
<button
type="button"
draggable={false}
className="rounded-sm p-0.5 text-muted-foreground opacity-0 transition group-hover:opacity-100 hover:bg-accent hover:text-foreground"
onClick={() => props.closeSurface(props.surfaceId)}
aria-label="Close tab"
>
<XIcon className="size-3" />
</button>
</div>
);
});
const WorkspaceSurfaceView = memo(function WorkspaceSurfaceView(props: {
activationFocusRequestId?: number;
bindSharedComposerHandle?: boolean;
surface: WorkspaceSurfaceInstance;
}) {
if (props.surface.kind === "thread") {
if (props.surface.input.scope === "server") {
return (
<ChatView
{...(props.activationFocusRequestId === undefined
? {}
: { activationFocusRequestId: props.activationFocusRequestId })}
environmentId={props.surface.input.threadRef.environmentId}
threadId={props.surface.input.threadRef.threadId}
routeKind="server"
{...(props.bindSharedComposerHandle === undefined
? {}
: { bindSharedComposerHandle: props.bindSharedComposerHandle })}
/>
);
}
return (
<ChatView
{...(props.activationFocusRequestId === undefined
? {}
: { activationFocusRequestId: props.activationFocusRequestId })}
draftId={props.surface.input.draftId}
environmentId={props.surface.input.environmentId}
threadId={props.surface.input.threadId}
routeKind="draft"
{...(props.bindSharedComposerHandle === undefined
? {}
: { bindSharedComposerHandle: props.bindSharedComposerHandle })}
/>
);
}
return (
<ThreadTerminalSurface
surfaceId={props.surface.id}
terminalId={props.surface.input.terminalId}
threadRef={props.surface.input.threadRef}
{...(props.activationFocusRequestId === undefined
? {}
: { activationFocusRequestId: props.activationFocusRequestId })}
/>
);
});
function WorkspaceSurfaceTitle(props: { surface: WorkspaceSurfaceInstance }) {
if (props.surface.kind === "terminal") {
return <TerminalSurfaceTitle threadRef={props.surface.input.threadRef} />;
}
return <ThreadSurfaceTitle surface={props.surface} />;
}
function ThreadSurfaceTitle(props: {
surface: Extract<WorkspaceSurfaceInstance, { kind: "thread" }>;
}) {
const thread = useStore(
useMemo(
() =>
createThreadSelectorByRef(
props.surface.input.scope === "server" ? props.surface.input.threadRef : null,
),
[props.surface.input],
),
);
if (props.surface.input.scope === "server") {
return <>{thread?.title ?? props.surface.input.threadRef.threadId}</>;
}
return <>{thread?.title ?? props.surface.input.threadId ?? "Draft thread"}</>;
}
function TerminalSurfaceTitle(props: {
threadRef: Extract<WorkspaceSurfaceInstance, { kind: "terminal" }>["input"]["threadRef"];
}) {
const thread = useStore(
useMemo(() => createThreadSelectorByRef(props.threadRef), [props.threadRef]),
);
const label = thread?.title ?? props.threadRef.threadId;
return (
<span className="inline-flex items-center gap-1">
<TerminalSquareIcon className="size-3 shrink-0" />
<span className="truncate">{label}</span>
</span>
);
}
+12 -27
View File
@@ -1,7 +1,6 @@
import {
CODEX_REASONING_EFFORT_OPTIONS,
type ClaudeCodeEffort,
type CodexReasoningEffort,
ClaudeAgentEffort,
CodexReasoningEffort,
DEFAULT_MODEL_BY_PROVIDER,
type EnvironmentId,
ModelSelection,
@@ -105,7 +104,7 @@ const PersistedComposerThreadDraftState = Schema.Struct({
type PersistedComposerThreadDraftState = typeof PersistedComposerThreadDraftState.Type;
const LegacyCodexFields = Schema.Struct({
effort: Schema.optionalKey(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)),
effort: Schema.optionalKey(CodexReasoningEffort),
codexFastMode: Schema.optionalKey(Schema.Boolean),
serviceTier: Schema.optionalKey(Schema.String),
});
@@ -546,19 +545,13 @@ function normalizeProviderModelOptions(
? (candidate.claudeAgent as Record<string, unknown>)
: null;
const codexReasoningEffort: CodexReasoningEffort | undefined =
codexCandidate?.reasoningEffort === "low" ||
codexCandidate?.reasoningEffort === "medium" ||
codexCandidate?.reasoningEffort === "high" ||
codexCandidate?.reasoningEffort === "xhigh"
? codexCandidate.reasoningEffort
: provider === "codex" &&
(legacy?.effort === "low" ||
legacy?.effort === "medium" ||
legacy?.effort === "high" ||
legacy?.effort === "xhigh")
const codexReasoningEffort = Schema.is(CodexReasoningEffort)(codexCandidate?.reasoningEffort)
? codexCandidate.reasoningEffort
: provider === "codex"
? Schema.is(CodexReasoningEffort)(legacy?.effort)
? legacy.effort
: undefined;
: undefined
: undefined;
const codexFastMode =
codexCandidate?.fastMode === true
? true
@@ -582,14 +575,9 @@ function normalizeProviderModelOptions(
: claudeCandidate?.thinking === false
? false
: undefined;
const claudeEffort: ClaudeCodeEffort | undefined =
claudeCandidate?.effort === "low" ||
claudeCandidate?.effort === "medium" ||
claudeCandidate?.effort === "high" ||
claudeCandidate?.effort === "max" ||
claudeCandidate?.effort === "ultrathink"
? claudeCandidate.effort
: undefined;
const claudeEffort = Schema.is(ClaudeAgentEffort)(claudeCandidate?.effort)
? claudeCandidate.effort
: undefined;
const claudeFastMode =
claudeCandidate?.fastMode === true
? true
@@ -2158,9 +2146,6 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
}
set((state) => {
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
if (existing.prompt === prompt) {
return state;
}
const nextDraft: ComposerThreadDraftState = {
...existing,
prompt,
+221
View File
@@ -0,0 +1,221 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { showContextMenuFallback } from "./contextMenuFallback";
type FakeListener = (event: FakeDomEvent) => void;
class FakeDomEvent {
defaultPrevented = false;
constructor(
readonly type: string,
init: Record<string, unknown> = {},
) {
Object.assign(this, init);
}
preventDefault() {
this.defaultPrevented = true;
}
}
class FakeElement {
children: FakeElement[] = [];
parent: FakeElement | null = null;
style: Record<string, string> & { cssText?: string } = {};
dataset: Record<string, string> = {};
className = "";
disabled = false;
type = "";
private textValue = "";
private readonly listeners = new Map<string, FakeListener[]>();
constructor(readonly tagName: string) {}
appendChild(child: FakeElement) {
child.parent = this;
this.children.push(child);
return child;
}
remove() {
if (!this.parent) {
return;
}
const index = this.parent.children.indexOf(this);
if (index >= 0) {
this.parent.children.splice(index, 1);
}
this.parent = null;
}
addEventListener(type: string, listener: FakeListener) {
const existing = this.listeners.get(type) ?? [];
existing.push(listener);
this.listeners.set(type, existing);
}
dispatchEvent(event: FakeDomEvent) {
for (const listener of this.listeners.get(event.type) ?? []) {
listener(event);
}
return true;
}
set textContent(value: string) {
this.textValue = value;
}
get textContent() {
return `${this.textValue}${this.children.map((child) => child.textContent).join("")}`;
}
querySelectorAll(tagName: string): FakeElement[] {
const matches: FakeElement[] = [];
if (this.tagName === tagName) {
matches.push(this);
}
for (const child of this.children) {
matches.push(...child.querySelectorAll(tagName));
}
return matches;
}
getBoundingClientRect() {
const left = Number.parseInt(this.style.left ?? "0", 10) || 0;
const top = Number.parseInt(this.style.top ?? "0", 10) || 0;
const width = this.tagName === "div" ? 180 : 140;
const height = this.tagName === "div" ? 120 : 28;
return {
left,
top,
width,
height,
right: left + width,
bottom: top + height,
};
}
}
class FakeBody extends FakeElement {
private html = "";
constructor() {
super("body");
}
set innerHTML(value: string) {
this.html = value;
this.children = [];
}
get innerHTML() {
return this.html;
}
}
class FakeDocument {
body = new FakeBody();
private readonly listeners = new Map<string, FakeListener[]>();
createElement(tagName: string) {
return new FakeElement(tagName);
}
addEventListener(type: string, listener: FakeListener) {
const existing = this.listeners.get(type) ?? [];
existing.push(listener);
this.listeners.set(type, existing);
}
removeEventListener(type: string, listener: FakeListener) {
const existing = this.listeners.get(type);
if (!existing) {
return;
}
const index = existing.indexOf(listener);
if (index >= 0) {
existing.splice(index, 1);
}
}
querySelectorAll(tagName: string) {
return this.body.querySelectorAll(tagName);
}
}
function findButton(label: string): FakeElement | undefined {
return (document as unknown as FakeDocument)
.querySelectorAll("button")
.find((button) => button.textContent.includes(label));
}
beforeEach(() => {
vi.stubGlobal("document", new FakeDocument());
vi.stubGlobal("window", {
innerWidth: 1280,
innerHeight: 800,
});
vi.stubGlobal("requestAnimationFrame", (callback: (time: number) => void) => {
callback(0);
return 0;
});
vi.stubGlobal(
"MouseEvent",
class extends FakeDomEvent {
constructor(type: string, init: Record<string, unknown> = {}) {
super(type, init);
}
},
);
vi.stubGlobal(
"KeyboardEvent",
class extends FakeDomEvent {
constructor(type: string, init: Record<string, unknown> = {}) {
super(type, init);
}
},
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("showContextMenuFallback", () => {
it("resolves a clicked flat menu item", async () => {
const selectionPromise = showContextMenuFallback([
{ id: "rename", label: "Rename" },
{ id: "delete", label: "Delete", destructive: true },
]);
const renameButton = findButton("Rename");
expect(renameButton).toBeTruthy();
renameButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await expect(selectionPromise).resolves.toBe("rename");
});
it("opens nested submenus and resolves the clicked leaf id", async () => {
const selectionPromise = showContextMenuFallback([
{
id: "rename:submenu",
label: "Rename project",
children: [
{ id: "rename:project-a", label: "/tmp/project-a" },
{ id: "rename:project-b", label: "/tmp/project-b" },
],
},
]);
const parentButton = findButton("Rename project");
expect(parentButton).toBeTruthy();
parentButton?.dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
const childButton = findButton("/tmp/project-b");
expect(childButton).toBeTruthy();
childButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await expect(selectionPromise).resolves.toBe("rename:project-b");
});
});
+116 -48
View File
@@ -1,9 +1,22 @@
import type { ContextMenuItem } from "@t3tools/contracts";
function clampMenuPosition(menu: HTMLDivElement, preferredLeft: number, preferredTop: number) {
const rect = menu.getBoundingClientRect();
const left = Math.min(
Math.max(4, preferredLeft),
Math.max(4, window.innerWidth - rect.width - 4),
);
const top = Math.min(
Math.max(4, preferredTop),
Math.max(4, window.innerHeight - rect.height - 4),
);
menu.style.left = `${left}px`;
menu.style.top = `${top}px`;
}
/**
* Imperative DOM-based context menu for non-Electron environments.
* Shows a positioned dropdown and returns a promise that resolves
* with the clicked item id, or null if dismissed.
* Supports nested submenus and resolves with the clicked leaf item id.
*/
export function showContextMenuFallback<T extends string>(
items: readonly ContextMenuItem<T>[],
@@ -13,62 +26,117 @@ export function showContextMenuFallback<T extends string>(
const overlay = document.createElement("div");
overlay.style.cssText = "position:fixed;inset:0;z-index:9999";
const menu = document.createElement("div");
menu.className =
"fixed z-[10000] min-w-[140px] rounded-md border border-border bg-popover py-1 shadow-xl animate-in fade-in zoom-in-95";
const menuStack: HTMLDivElement[] = [];
const x = position?.x ?? 0;
const y = position?.y ?? 0;
menu.style.top = `${y}px`;
menu.style.left = `${x}px`;
function cleanup(result: T | null) {
const cleanup = (result: T | null) => {
document.removeEventListener("keydown", onKeyDown);
overlay.remove();
menu.remove();
for (const menu of menuStack) {
menu.remove();
}
resolve(result);
}
};
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
e.preventDefault();
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
cleanup(null);
}
}
};
const closeMenusFromLevel = (level: number) => {
while (menuStack.length > level) {
menuStack.pop()?.remove();
}
};
const openMenu = (
entries: readonly ContextMenuItem<T>[],
preferredLeft: number,
preferredTop: number,
level: number,
) => {
closeMenusFromLevel(level);
const menu = document.createElement("div");
menu.className =
"fixed z-[10000] min-w-[160px] rounded-md border border-border bg-popover py-1 shadow-xl animate-in fade-in zoom-in-95";
menu.style.left = `${preferredLeft}px`;
menu.style.top = `${preferredTop}px`;
menu.dataset.level = String(level);
for (const item of entries) {
const button = document.createElement("button");
button.type = "button";
const hasChildren = Array.isArray(item.children) && item.children.length > 0;
const isLeafDestructive =
!hasChildren && (item.destructive === true || item.id === ("delete" as T));
const isDisabled = item.disabled === true;
button.disabled = isDisabled;
button.className = isDisabled
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed"
: isLeafDestructive
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
const label = document.createElement("span");
label.className = "min-w-0 flex-1 truncate";
label.textContent = item.label;
button.appendChild(label);
if (hasChildren) {
const chevron = document.createElement("span");
chevron.className = "shrink-0 text-muted-foreground/70";
chevron.textContent = "›";
button.appendChild(chevron);
}
if (!isDisabled) {
if (hasChildren) {
button.addEventListener("mouseenter", () => {
const rect = button.getBoundingClientRect();
const nextLeft = rect.right + 4;
const nextTop = rect.top;
openMenu(item.children!, nextLeft, nextTop, level + 1);
const childMenu = menuStack[level + 1];
if (!childMenu) {
return;
}
const childRect = childMenu.getBoundingClientRect();
if (childRect.right > window.innerWidth) {
clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
}
});
button.addEventListener("click", (event) => {
event.preventDefault();
});
} else {
button.addEventListener("mouseenter", () => {
closeMenusFromLevel(level + 1);
});
button.addEventListener("click", () => cleanup(item.id));
}
}
menu.appendChild(button);
}
menu.addEventListener("mouseenter", () => {
closeMenusFromLevel(level + 1);
});
document.body.appendChild(menu);
menuStack[level] = menu;
requestAnimationFrame(() => {
clampMenuPosition(menu, preferredLeft, preferredTop);
});
};
overlay.addEventListener("mousedown", () => cleanup(null));
document.addEventListener("keydown", onKeyDown);
for (const item of items) {
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = item.label;
const isDestructiveAction = item.destructive === true || item.id === "delete";
const isDisabled = item.disabled === true;
btn.disabled = isDisabled;
btn.className = isDisabled
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed"
: isDestructiveAction
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
if (!isDisabled) {
btn.addEventListener("click", () => cleanup(item.id));
}
menu.appendChild(btn);
}
document.body.appendChild(overlay);
document.body.appendChild(menu);
// Adjust if menu overflows viewport
requestAnimationFrame(() => {
const rect = menu.getBoundingClientRect();
if (rect.right > window.innerWidth) {
menu.style.left = `${window.innerWidth - rect.width - 4}px`;
}
if (rect.bottom > window.innerHeight) {
menu.style.top = `${window.innerHeight - rect.height - 4}px`;
}
});
openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
});
}
+21
View File
@@ -3,6 +3,8 @@ import type { EnvironmentId, EnvironmentApi } from "@t3tools/contracts";
import type { WsRpcClient } from "./rpc/wsRpcClient";
import { readEnvironmentConnection } from "./environments/runtime";
const environmentApiOverridesForTests = new Map<EnvironmentId, EnvironmentApi>();
export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
return {
terminal: {
@@ -18,6 +20,9 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
searchEntries: rpcClient.projects.searchEntries,
writeFile: rpcClient.projects.writeFile,
},
filesystem: {
browse: rpcClient.filesystem.browse,
},
git: {
pull: rpcClient.git.pull,
refreshStatus: rpcClient.git.refreshStatus,
@@ -52,6 +57,11 @@ export function readEnvironmentApi(environmentId: EnvironmentId): EnvironmentApi
return undefined;
}
const overriddenApi = environmentApiOverridesForTests.get(environmentId);
if (overriddenApi) {
return overriddenApi;
}
const connection = readEnvironmentConnection(environmentId);
return connection ? createEnvironmentApi(connection.client) : undefined;
}
@@ -63,3 +73,14 @@ export function ensureEnvironmentApi(environmentId: EnvironmentId): EnvironmentA
}
return api;
}
export function __setEnvironmentApiOverrideForTests(
environmentId: EnvironmentId,
api: EnvironmentApi,
): void {
environmentApiOverridesForTests.set(environmentId, api);
}
export function __resetEnvironmentApiOverridesForTests(): void {
environmentApiOverridesForTests.clear();
}
+165 -4
View File
@@ -10,7 +10,12 @@ import {
type AppState,
type EnvironmentState,
} from "./store";
import { deriveLogicalProjectKey } from "./logicalProject";
import {
deriveLogicalProjectKey,
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKey,
resolveProjectGroupingMode,
} from "./logicalProject";
import type { Project, SidebarThreadSummary } from "./types";
import { DEFAULT_INTERACTION_MODE } from "./types";
@@ -31,6 +36,10 @@ const threadL1 = ThreadId.make("thread-local-only-1");
const threadRO1 = ThreadId.make("thread-remote-only-1");
const SHARED_REPO_CANONICAL_KEY = "github.com/example/shared-repo";
const DEFAULT_GROUPING_SETTINGS = {
sidebarProjectGroupingMode: "repository" as const,
sidebarProjectGroupingOverrides: {},
};
// ── Factory Helpers ──────────────────────────────────────────────────
@@ -238,9 +247,7 @@ describe("environment grouping", () => {
environmentId: primaryEnvId,
name: "local-only",
});
const key = deriveLogicalProjectKey(project);
expect(key).toContain(primaryEnvId);
expect(key).toContain(localOnlyProjectId);
expect(deriveLogicalProjectKey(project)).toBe(derivePhysicalProjectKey(project));
});
it("groups projects from different environments that share the same canonical key", () => {
@@ -273,6 +280,134 @@ describe("environment grouping", () => {
expect(deriveLogicalProjectKey(primary)).toBe(deriveLogicalProjectKey(remote));
});
it("groups repo root and nested projects from the same repository by default", () => {
const rootProject = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "shared-repo",
cwd: "/workspace/repo",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
const nestedProject = makeProject({
id: localOnlyProjectId,
environmentId: primaryEnvId,
name: "web",
cwd: "/workspace/repo/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(deriveLogicalProjectKey(rootProject)).toBe(SHARED_REPO_CANONICAL_KEY);
expect(deriveLogicalProjectKey(nestedProject)).toBe(SHARED_REPO_CANONICAL_KEY);
});
it("uses repository path grouping when requested", () => {
const rootProject = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "shared-repo",
cwd: "/workspace/repo",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
const nestedProject = makeProject({
id: localOnlyProjectId,
environmentId: primaryEnvId,
name: "web",
cwd: "/workspace/repo/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(
deriveLogicalProjectKey(rootProject, {
groupingMode: "repository_path",
}),
).toBe(SHARED_REPO_CANONICAL_KEY);
expect(
deriveLogicalProjectKey(nestedProject, {
groupingMode: "repository_path",
}),
).toBe(`${SHARED_REPO_CANONICAL_KEY}::apps/web`);
});
it("groups matching nested project paths across environments when repo roots differ", () => {
const primary = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "web",
cwd: "/workspace/repo/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
const remote = makeProject({
id: sharedProjectRemoteId,
environmentId: remoteEnvId,
name: "web",
cwd: "/srv/checkout/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/srv/checkout",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(
deriveLogicalProjectKey(primary, {
groupingMode: "repository_path",
}),
).toBe(`${SHARED_REPO_CANONICAL_KEY}::apps/web`);
expect(
deriveLogicalProjectKey(primary, {
groupingMode: "repository_path",
}),
).toBe(
deriveLogicalProjectKey(remote, {
groupingMode: "repository_path",
}),
);
});
it("does NOT group projects without shared canonical key", () => {
const local = makeProject({
id: localOnlyProjectId,
@@ -286,6 +421,32 @@ describe("environment grouping", () => {
});
expect(deriveLogicalProjectKey(local)).not.toBe(deriveLogicalProjectKey(remote));
});
it("uses per-project overrides from settings", () => {
const project = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "shared-repo",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(resolveProjectGroupingMode(project, DEFAULT_GROUPING_SETTINGS)).toBe("repository");
expect(
deriveLogicalProjectKeyFromSettings(project, {
...DEFAULT_GROUPING_SETTINGS,
sidebarProjectGroupingOverrides: {
[derivePhysicalProjectKey(project)]: "separate",
},
}),
).toBe(derivePhysicalProjectKey(project));
});
});
describe("selectProjectsAcrossEnvironments", () => {
+3 -4
View File
@@ -13,9 +13,7 @@ import { Throttler } from "@tanstack/react-pacer";
import {
createKnownEnvironment,
getKnownEnvironmentWsBaseUrl,
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
@@ -62,6 +60,7 @@ import { useTerminalStateStore } from "~/terminalStateStore";
import { useUiStateStore } from "~/uiStateStore";
import { WsTransport } from "../../rpc/wsTransport";
import { createWsRpcClient, type WsRpcClient } from "../../rpc/wsRpcClient";
import { derivePhysicalProjectKey } from "../../logicalProject";
type EnvironmentServiceState = {
readonly queryClient: QueryClient;
@@ -470,7 +469,7 @@ function syncProjectUiFromStore() {
const projects = selectProjectsAcrossEnvironments(useStore.getState());
useUiStateStore.getState().syncProjects(
projects.map((project) => ({
key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
key: derivePhysicalProjectKey(project),
cwd: project.cwd,
})),
);
@@ -543,7 +542,7 @@ function applyRecoveredEventBatch(
const projects = selectProjectsAcrossEnvironments(useStore.getState());
useUiStateStore.getState().syncProjects(
projects.map((project) => ({
key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
key: derivePhysicalProjectKey(project),
cwd: project.cwd,
})),
);
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import { formatWorkspaceRelativePath } from "./filePathDisplay";
describe("formatWorkspaceRelativePath", () => {
it("formats absolute workspace paths from the workspace root", () => {
expect(
formatWorkspaceRelativePath(
"C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts:501",
"C:/Users/mike/dev-stuff/t3code",
),
).toBe("t3code/apps/web/src/session-logic.ts:501");
});
it("prefixes relative paths with the workspace root label", () => {
expect(
formatWorkspaceRelativePath(
"apps/web/src/session-logic.ts:501",
"C:/Users/mike/dev-stuff/t3code",
),
).toBe("t3code/apps/web/src/session-logic.ts:501");
});
it("keeps paths already rooted at the workspace label stable", () => {
expect(
formatWorkspaceRelativePath(
"t3code/apps/web/src/session-logic.ts:501",
"C:/Users/mike/dev-stuff/t3code",
),
).toBe("t3code/apps/web/src/session-logic.ts:501");
});
it("preserves columns when present", () => {
expect(
formatWorkspaceRelativePath(
"/C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts:501:9",
"C:/Users/mike/dev-stuff/t3code",
),
).toBe("t3code/apps/web/src/session-logic.ts:501:9");
});
});
+57
View File
@@ -0,0 +1,57 @@
import { splitPathAndPosition } from "./terminal-links";
function normalizePathSeparators(path: string): string {
return path.replaceAll("\\", "/");
}
function canonicalizeWindowsDrivePath(path: string): string {
return /^\/[A-Za-z]:\//.test(path) ? path.slice(1) : path;
}
function trimTrailingPathSeparators(path: string): string {
return path.replace(/[\\/]+$/, "");
}
function basenameOfPath(path: string): string {
const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
}
function stripRelativePrefixes(path: string): string {
return path.replace(/^\.\/+/, "").replace(/^\/+/, "");
}
export function formatWorkspaceRelativePath(
pathWithPosition: string,
workspaceRoot: string | undefined,
): string {
const { path, line, column } = splitPathAndPosition(pathWithPosition);
const normalizedPath = canonicalizeWindowsDrivePath(normalizePathSeparators(path));
let displayPath = normalizedPath;
if (workspaceRoot) {
const normalizedWorkspaceRoot = canonicalizeWindowsDrivePath(
normalizePathSeparators(trimTrailingPathSeparators(workspaceRoot)),
);
const workspaceLabel = basenameOfPath(normalizedWorkspaceRoot);
const pathForCompare = normalizedPath.toLowerCase();
const workspaceForCompare = normalizedWorkspaceRoot.toLowerCase();
const workspaceWithSeparator = `${workspaceForCompare}/`;
const workspaceLabelWithSeparator = `${workspaceLabel.toLowerCase()}/`;
if (pathForCompare === workspaceForCompare) {
displayPath = workspaceLabel;
} else if (pathForCompare.startsWith(workspaceWithSeparator)) {
const relativeSuffix = normalizedPath.slice(normalizedWorkspaceRoot.length + 1);
displayPath = `${workspaceLabel}/${relativeSuffix}`;
} else if (!normalizedPath.startsWith("/")) {
const relativePath = stripRelativePrefixes(normalizedPath);
displayPath = pathForCompare.startsWith(workspaceLabelWithSeparator)
? normalizedPath
: `${workspaceLabel}/${relativePath}`;
}
}
if (!line) return displayPath;
return `${displayPath}:${line}${column ? `:${column}` : ""}`;
}
+8 -3
View File
@@ -10,14 +10,19 @@ import {
} from "../composerDraftStore";
import { newDraftId, newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import { deriveLogicalProjectKey } from "../logicalProject";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import { selectProjectsAcrossEnvironments, useStore } from "../store";
import { createThreadSelectorByRef } from "../storeSelectors";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { useUiStateStore } from "../uiStateStore";
import { useSettings } from "./useSettings";
function useNewThreadState() {
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const router = useRouter();
const getCurrentRouteTarget = useCallback(() => {
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
@@ -48,7 +53,7 @@ function useNewThreadState() {
candidate.environmentId === projectRef.environmentId,
);
const logicalProjectKey = project
? deriveLogicalProjectKey(project)
? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)
: scopedProjectKey(projectRef);
const hasBranchOption = options?.branch !== undefined;
const hasWorktreePathOption = options?.worktreePath !== undefined;
@@ -129,7 +134,7 @@ function useNewThreadState() {
});
})();
},
[getCurrentRouteTarget, router, projects],
[getCurrentRouteTarget, projectGroupingSettings, router, projects],
);
}
+3 -3
View File
@@ -19,7 +19,7 @@ import {
} from "@t3tools/contracts/settings";
import { ensureLocalApi } from "~/localApi";
import { Struct } from "effect";
import { deepMerge } from "@t3tools/shared/Struct";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
@@ -64,7 +64,7 @@ async function hydrateClientSettings(): Promise<void> {
try {
const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
if (persistedSettings) {
replaceClientSettingsSnapshot(persistedSettings);
replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
}
} catch (error) {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
@@ -154,7 +154,7 @@ export function useUpdateSettings() {
if (Object.keys(serverPatch).length > 0) {
const currentServerConfig = getServerConfig();
if (currentServerConfig) {
applySettingsUpdated(deepMerge(currentServerConfig.settings, serverPatch));
applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));
}
// Fire-and-forget RPC — push will reconcile on success
void ensureLocalApi().server.updateSettings(serverPatch);
@@ -1,333 +0,0 @@
import type { KeybindingCommand, ScopedThreadRef } from "@t3tools/contracts";
import { useCallback, useMemo } from "react";
import { useCommandPaletteStore } from "../commandPaletteStore";
import {
useFocusedWorkspaceSurface,
useWorkspaceDocument,
useWorkspaceStore,
} from "../workspace/store";
import type { WorkspaceSurfaceInstance } from "../workspace/types";
export const WORKSPACE_COMMAND_IDS = [
"workspace.terminal.splitRight",
"workspace.terminal.splitDown",
"workspace.terminal.newTab",
"workspace.pane.splitRight",
"workspace.pane.splitDown",
"workspace.focus.previous",
"workspace.focus.next",
"workspace.focus.left",
"workspace.focus.right",
"workspace.focus.up",
"workspace.focus.down",
"workspace.pane.close",
"workspace.pane.toggleZoom",
"workspace.pane.resizeLeft",
"workspace.pane.resizeRight",
"workspace.pane.resizeUp",
"workspace.pane.resizeDown",
"workspace.pane.equalize",
"workspace.pane.moveLeft",
"workspace.pane.moveRight",
"workspace.pane.moveUp",
"workspace.pane.moveDown",
"workspace.tab.moveLeft",
"workspace.tab.moveRight",
"workspace.tab.moveUp",
"workspace.tab.moveDown",
] as const satisfies readonly KeybindingCommand[];
export type WorkspaceCommandId = (typeof WORKSPACE_COMMAND_IDS)[number];
export const WORKSPACE_COMMAND_METADATA: Record<
WorkspaceCommandId,
{
searchTerms: readonly string[];
title: string;
}
> = {
"workspace.terminal.splitRight": {
title: "Open terminal in split right",
searchTerms: ["terminal", "split", "right", "pane", "workspace"],
},
"workspace.terminal.splitDown": {
title: "Open terminal in split down",
searchTerms: ["terminal", "split", "down", "bottom", "pane", "workspace"],
},
"workspace.terminal.newTab": {
title: "Open terminal as tab",
searchTerms: ["terminal", "tab", "pane", "workspace"],
},
"workspace.pane.splitRight": {
title: "Open in split right",
searchTerms: ["split", "pane", "right", "open", "workspace"],
},
"workspace.pane.splitDown": {
title: "Open in split down",
searchTerms: ["split", "pane", "down", "open", "workspace"],
},
"workspace.focus.left": {
title: "Focus pane left",
searchTerms: ["focus", "pane", "left", "workspace"],
},
"workspace.focus.previous": {
title: "Focus previous pane",
searchTerms: ["focus", "previous", "pane", "workspace"],
},
"workspace.focus.next": {
title: "Focus next pane",
searchTerms: ["focus", "next", "pane", "workspace"],
},
"workspace.focus.right": {
title: "Focus pane right",
searchTerms: ["focus", "pane", "right", "workspace"],
},
"workspace.focus.up": {
title: "Focus pane up",
searchTerms: ["focus", "pane", "up", "workspace"],
},
"workspace.focus.down": {
title: "Focus pane down",
searchTerms: ["focus", "pane", "down", "workspace"],
},
"workspace.pane.close": {
title: "Close current pane",
searchTerms: ["close", "pane", "window", "workspace"],
},
"workspace.pane.toggleZoom": {
title: "Toggle pane zoom",
searchTerms: ["zoom", "maximize", "pane", "workspace"],
},
"workspace.pane.resizeLeft": {
title: "Resize pane left",
searchTerms: ["resize", "pane", "left", "workspace"],
},
"workspace.pane.resizeRight": {
title: "Resize pane right",
searchTerms: ["resize", "pane", "right", "workspace"],
},
"workspace.pane.resizeUp": {
title: "Resize pane up",
searchTerms: ["resize", "pane", "up", "workspace"],
},
"workspace.pane.resizeDown": {
title: "Resize pane down",
searchTerms: ["resize", "pane", "down", "workspace"],
},
"workspace.pane.equalize": {
title: "Equalize splits",
searchTerms: ["equalize", "reset", "split", "pane", "workspace"],
},
"workspace.pane.moveLeft": {
title: "Move pane left",
searchTerms: ["move", "pane", "left", "workspace"],
},
"workspace.pane.moveRight": {
title: "Move pane right",
searchTerms: ["move", "pane", "right", "workspace"],
},
"workspace.pane.moveUp": {
title: "Move pane up",
searchTerms: ["move", "pane", "up", "workspace"],
},
"workspace.pane.moveDown": {
title: "Move pane down",
searchTerms: ["move", "pane", "down", "workspace"],
},
"workspace.tab.moveLeft": {
title: "Move tab left",
searchTerms: ["move", "tab", "left", "workspace"],
},
"workspace.tab.moveRight": {
title: "Move tab right",
searchTerms: ["move", "tab", "right", "workspace"],
},
"workspace.tab.moveUp": {
title: "Move tab up",
searchTerms: ["move", "tab", "up", "workspace"],
},
"workspace.tab.moveDown": {
title: "Move tab down",
searchTerms: ["move", "tab", "down", "workspace"],
},
};
function threadRefForWorkspaceSurface(
surface: WorkspaceSurfaceInstance | null | undefined,
): ScopedThreadRef | null {
if (!surface) {
return null;
}
if (surface.kind === "terminal") {
return surface.input.threadRef;
}
if (surface.input.scope === "server") {
return surface.input.threadRef;
}
return null;
}
export function isWorkspaceCommandId(
command: string | null | undefined,
): command is WorkspaceCommandId {
return WORKSPACE_COMMAND_IDS.includes(command as WorkspaceCommandId);
}
export function useWorkspaceCommandExecutor() {
const document = useWorkspaceDocument();
const focusedSurface = useFocusedWorkspaceSurface();
const openWorkspaceTarget = useCommandPaletteStore((state) => state.openWorkspaceTarget);
const closeFocusedWindow = useWorkspaceStore((state) => state.closeFocusedWindow);
const equalizeSplits = useWorkspaceStore((state) => state.equalizeSplits);
const focusWindowByStep = useWorkspaceStore((state) => state.focusWindowByStep);
const focusAdjacentWindow = useWorkspaceStore((state) => state.focusAdjacentWindow);
const moveActiveTabToAdjacentWindow = useWorkspaceStore(
(state) => state.moveActiveTabToAdjacentWindow,
);
const moveFocusedWindow = useWorkspaceStore((state) => state.moveFocusedWindow);
const openTerminalSurfaceForThread = useWorkspaceStore(
(state) => state.openTerminalSurfaceForThread,
);
const resizeFocusedWindow = useWorkspaceStore((state) => state.resizeFocusedWindow);
const toggleFocusedWindowZoom = useWorkspaceStore((state) => state.toggleFocusedWindowZoom);
const focusedWindowId = useMemo(() => {
if (document.focusedWindowId && document.windowsById[document.focusedWindowId]) {
return document.focusedWindowId;
}
return Object.keys(document.windowsById)[0] ?? null;
}, [document]);
const focusedThreadRef = useMemo(
() => threadRefForWorkspaceSurface(focusedSurface),
[focusedSurface],
);
const executeWorkspaceCommand = useCallback(
async (command: WorkspaceCommandId): Promise<boolean> => {
switch (command) {
case "workspace.terminal.splitRight":
if (!focusedThreadRef) {
return false;
}
openTerminalSurfaceForThread(focusedThreadRef, "split-right");
return true;
case "workspace.terminal.splitDown":
if (!focusedThreadRef) {
return false;
}
openTerminalSurfaceForThread(focusedThreadRef, "split-down");
return true;
case "workspace.terminal.newTab":
if (!focusedThreadRef) {
return false;
}
openTerminalSurfaceForThread(focusedThreadRef, "new-tab");
return true;
case "workspace.pane.splitRight":
if (!focusedWindowId) {
return false;
}
openWorkspaceTarget({ disposition: "split-right" });
return true;
case "workspace.pane.splitDown":
if (!focusedWindowId) {
return false;
}
openWorkspaceTarget({ disposition: "split-down" });
return true;
case "workspace.focus.left":
focusAdjacentWindow("left");
return true;
case "workspace.focus.previous":
focusWindowByStep(-1);
return true;
case "workspace.focus.next":
focusWindowByStep(1);
return true;
case "workspace.focus.right":
focusAdjacentWindow("right");
return true;
case "workspace.focus.up":
focusAdjacentWindow("up");
return true;
case "workspace.focus.down":
focusAdjacentWindow("down");
return true;
case "workspace.pane.close":
closeFocusedWindow();
return true;
case "workspace.pane.toggleZoom":
toggleFocusedWindowZoom();
return true;
case "workspace.pane.resizeLeft":
resizeFocusedWindow("left");
return true;
case "workspace.pane.resizeRight":
resizeFocusedWindow("right");
return true;
case "workspace.pane.resizeUp":
resizeFocusedWindow("up");
return true;
case "workspace.pane.resizeDown":
resizeFocusedWindow("down");
return true;
case "workspace.pane.equalize":
equalizeSplits();
return true;
case "workspace.pane.moveLeft":
moveFocusedWindow("left");
return true;
case "workspace.pane.moveRight":
moveFocusedWindow("right");
return true;
case "workspace.pane.moveUp":
moveFocusedWindow("up");
return true;
case "workspace.pane.moveDown":
moveFocusedWindow("down");
return true;
case "workspace.tab.moveLeft":
moveActiveTabToAdjacentWindow("left");
return true;
case "workspace.tab.moveRight":
moveActiveTabToAdjacentWindow("right");
return true;
case "workspace.tab.moveUp":
moveActiveTabToAdjacentWindow("up");
return true;
case "workspace.tab.moveDown":
moveActiveTabToAdjacentWindow("down");
return true;
}
},
[
closeFocusedWindow,
equalizeSplits,
focusAdjacentWindow,
focusWindowByStep,
focusedThreadRef,
focusedWindowId,
moveActiveTabToAdjacentWindow,
moveFocusedWindow,
openTerminalSurfaceForThread,
openWorkspaceTarget,
resizeFocusedWindow,
toggleFocusedWindowZoom,
],
);
return {
canOpenTerminalSurface: focusedThreadRef !== null,
canSplitFocusedPane: focusedWindowId !== null,
executeWorkspaceCommand,
focusedSurface,
focusedThreadRef,
focusedWindowId,
};
}
+59
View File
@@ -324,6 +324,47 @@ label:has(> select#reasoning-effort) select {
font-size: 0.75rem;
}
.chat-markdown-file-link {
display: inline-flex;
align-items: center;
gap: 0.28rem;
border: 1px solid color-mix(in srgb, var(--border) 92%, transparent);
border-radius: 0.375rem;
background: color-mix(in srgb, var(--muted) 88%, var(--background));
padding: 0.08rem 0.34rem;
color: var(--foreground);
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 0.75rem;
line-height: 1.15;
vertical-align: text-bottom;
transition:
background-color 120ms ease,
border-color 120ms ease,
color 120ms ease,
opacity 120ms ease;
}
.chat-markdown-file-link:hover {
opacity: 1;
color: var(--foreground);
border-color: color-mix(in srgb, var(--border) 65%, var(--foreground));
background: color-mix(in srgb, var(--muted) 72%, var(--background));
}
.chat-markdown-file-link:focus-visible {
outline: none;
box-shadow: 0 0 0 1px color-mix(in srgb, var(--ring) 70%, transparent);
}
.chat-markdown-file-link-icon {
opacity: 0.72;
}
.chat-markdown-file-link-label {
color: color-mix(in srgb, var(--foreground) 88%, transparent);
line-height: 1.1;
}
.chat-markdown pre {
max-width: 100%;
overflow-x: auto;
@@ -340,6 +381,24 @@ label:has(> select#reasoning-effort) select {
font-size: 0.75rem;
}
.markdown-file-link-tooltip-scroll {
scrollbar-width: thin;
scrollbar-color: color-mix(in srgb, var(--border) 78%, transparent) transparent;
}
.markdown-file-link-tooltip-scroll::-webkit-scrollbar {
height: 6px;
}
.markdown-file-link-tooltip-scroll::-webkit-scrollbar-track {
background: transparent;
}
.markdown-file-link-tooltip-scroll::-webkit-scrollbar-thumb {
border-radius: 999px;
background: color-mix(in srgb, var(--border) 78%, transparent);
}
.chat-markdown .chat-markdown-codeblock {
--chat-markdown-codeblock-copy-button-space: 1.5rem;
position: relative;
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff. Show more