Compare commits

..
Author SHA1 Message Date
Cursor Agent c0aed107dc Fix missing terminal focus bump after close and clarify toggleOpen predicate
- Add setTerminalFocusRequestId bump in closeTerminal for non-final tabs,
  matching the pattern used by splitTerminal and createNewTerminal.
- Refactor toggleOpen to use a named 'next' variable so the predicate reads
  identically to setOpen, reducing maintenance hazard.
2026-04-16 00:47:58 +00:00
Julius Marminge b5281f994e Add composable chat and workspace layout modes
- Move thread terminal into an inline chat drawer
- Add split/paper workspace layout switching and scrolling
- Update route sync, command palette, and tests for new state
2026-04-15 17:40:23 -07:00
Julius Marminge 5c8504d602 Add composable workspace pane controls
- add workspace pane focus, split, resize, and zoom commands
- wire chat composer focus repair across workspace activation
- enable dragging threads into workspace surfaces
2026-04-14 17:47:30 -07:00
Julius Marminge d3d096c6f7 Refactor chat into composable workspace shell
- Add workspace document storage and store tests
- Route terminal and command-palette actions through workspace surfaces
- Update chat layout, sidebar, and thread terminal handling
2026-04-13 19:41:56 -07:00
184 changed files with 7988 additions and 10868 deletions

No files matched your search

+2 -5
View File
@@ -9,7 +9,7 @@ on:
jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -76,7 +76,7 @@ jobs:
release_smoke:
name: Release Smoke
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
@@ -92,8 +92,5 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+47 -230
View File
@@ -1,24 +1,14 @@
name: Release
name: Release Desktop
on:
push:
tags:
- "v*.*.*"
schedule:
- cron: "0 9 * * *"
workflow_dispatch:
inputs:
channel:
description: "Release channel"
required: false
default: stable
type: choice
options:
- stable
- nightly
version:
description: "Release version (for example 1.2.3 or v1.2.3)"
required: false
required: true
type: string
permissions:
@@ -28,24 +18,43 @@ permissions:
jobs:
preflight:
name: Preflight
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
outputs:
release_channel: ${{ steps.release_meta.outputs.release_channel }}
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
release_name: ${{ steps.release_meta.outputs.name }}
short_sha: ${{ steps.release_meta.outputs.short_sha }}
previous_tag: ${{ steps.previous_tag.outputs.previous_tag }}
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
make_latest: ${{ steps.release_meta.outputs.make_latest }}
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- id: release_meta
name: Resolve release version
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -60,60 +69,6 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- id: release_meta
name: Resolve release version
shell: bash
env:
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
DISPATCH_VERSION: ${{ github.event.inputs.version }}
NIGHTLY_DATE: ${{ github.run_started_at }}
NIGHTLY_SHA: ${{ github.sha }}
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
run: |
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
nightly_date="$(date -u -d "$NIGHTLY_DATE" +%Y%m%d)"
node scripts/resolve-nightly-release.ts \
--date "$nightly_date" \
--run-number "$NIGHTLY_RUN_NUMBER" \
--sha "$NIGHTLY_SHA" \
--github-output
echo "release_channel=nightly" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=nightly" >> "$GITHUB_OUTPUT"
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
else
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${DISPATCH_VERSION}"
if [[ -z "$raw" ]]; then
echo "workflow_dispatch stable releases require the version input." >&2
exit 1
fi
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "release_channel=stable" >> "$GITHUB_OUTPUT"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
echo "name=T3 Code v$version" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=latest" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
fi
- name: Lint
run: bun run lint
@@ -123,14 +78,6 @@ jobs:
- name: Test
run: bun run test
- id: previous_tag
name: Resolve previous release tag
run: |
node scripts/resolve-previous-release-tag.ts \
--channel "${{ steps.release_meta.outputs.release_channel }}" \
--current-tag "${{ steps.release_meta.outputs.tag }}" \
--github-output
build:
name: Build ${{ matrix.label }}
needs: preflight
@@ -141,30 +88,25 @@ jobs:
matrix:
include:
- label: macOS arm64
runner: blacksmith-12vcpu-macos-26
runner: macos-14
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: blacksmith-12vcpu-macos-26
runner: macos-15-intel
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: blacksmith-32vcpu-ubuntu-2404
runner: ubuntu-24.04
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: blacksmith-32vcpu-windows-2025
runner: windows-2022
platform: win
target: nsis
arch: x64
# - label: Windows arm64
# runner: windows-11-arm
# platform: win
# target: nsis
# arch: arm64
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -188,60 +130,6 @@ 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:
@@ -318,31 +206,18 @@ jobs:
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/*.yml"; do
"release/latest*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
shopt -s nullglob
for manifest in release-publish/*-mac.yml; do
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
done
if [[ -f release-publish/latest-mac.yml ]]; then
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
fi
fi
# Enable if Windows arm64 builds are enabled.
# Windows updater metadata is channel-specific (for example
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
# release job can merge matching arm64/x64 manifests back into one
# canonical manifest per channel.
# if [[ "${{ matrix.platform }}" == "win" ]]; then
# shopt -s nullglob
# for manifest in release-publish/*.yml; do
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
# done
# fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
@@ -353,7 +228,7 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
@@ -382,12 +257,12 @@ jobs:
run: bun run build --filter=@t3tools/web --filter=t3
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
release:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
@@ -409,71 +284,17 @@ jobs:
- name: Merge macOS updater manifests
run: |
shopt -s nullglob
for x64_manifest in release-assets/*-mac-x64.yml; do
arm64_manifest="${x64_manifest%-x64.yml}.yml"
if [[ -f "$arm64_manifest" ]]; then
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
rm -f "$x64_manifest"
fi
done
# - name: Merge Windows updater manifests
# run: |
# shopt -s nullglob
# found_windows_manifest=false
# for x64_manifest in release-assets/*-win-x64.yml; do
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
# continue
# fi
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
# if [[ ! -f "$arm64_manifest" ]]; then
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
# exit 1
# fi
# found_windows_manifest=true
# node scripts/merge-update-manifests.ts --platform win \
# "$arm64_manifest" \
# "$x64_manifest" \
# "$output_manifest"
# rm -f "$arm64_manifest" "$x64_manifest"
# done
# if [[ "$found_windows_manifest" != true ]]; then
# echo "No Windows updater manifests found to merge." >&2
# exit 1
# fi
node scripts/merge-mac-update-manifests.ts \
release-assets/latest-mac.yml \
release-assets/latest-mac-x64.yml
rm -f release-assets/latest-mac-x64.yml
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
previous_tag: ${{ needs.preflight.outputs.previous_tag }}
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
files: |
release-assets/*.dmg
release-assets/*.zip
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
name: T3 Code v${{ needs.preflight.outputs.version }}
generate_release_notes: true
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
@@ -483,14 +304,13 @@ jobs:
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
release-assets/latest*.yml
fail_on_unmatched_files: true
finalize:
name: Finalize release
if: needs.preflight.outputs.release_channel == 'stable'
needs: [preflight, release]
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- id: app_token
@@ -529,9 +349,6 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- id: update_versions
name: Update version strings
env:
+1 -2
View File
@@ -10,8 +10,7 @@
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts",
"*.icon/**"
"apps/web/src/lib/vendor/qrcodegen.ts"
],
"sortPackageJson": {}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.20",
"version": "0.0.17",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+1 -67
View File
@@ -6,7 +6,6 @@ import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
@@ -24,9 +23,6 @@ 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], {
@@ -47,68 +43,6 @@ function setPlistString(plistPath, key, value) {
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
}
function runChecked(command, args) {
const result = spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
return;
}
const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
if (!existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
}
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
return generatedIconPath;
}
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = join(iconsetRoot, "icon.iconset");
mkdirSync(iconsetDir, { recursive: true });
try {
for (const size of [16, 32, 128, 256, 512]) {
runChecked("sips", [
"-z",
String(size),
String(size),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}.png`),
]);
const retinaSize = size * 2;
runChecked("sips", [
"-z",
String(retinaSize),
String(retinaSize),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
}
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
return generatedIconPath;
} catch (error) {
console.warn(
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
error,
);
return defaultIconPath;
} finally {
rmSync(iconsetRoot, { recursive: true, force: true });
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
@@ -168,7 +102,7 @@ function buildMacLauncher(electronBinaryPath) {
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const iconPath = join(desktopDir, "resources", "icon.icns");
const metadataPath = join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
-47
View File
@@ -1,47 +0,0 @@
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
@@ -1,28 +0,0 @@
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,10 +52,6 @@ const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
},
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
+2 -15
View File
@@ -1,13 +1,8 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import {
ClientSettingsSchema,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { Predicate } from "effect";
import * as Schema from "effect/Schema";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
@@ -88,15 +83,7 @@ function toPersistedSavedEnvironmentRecord(
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
if (!raw) {
return null;
}
try {
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
} catch {
return null;
}
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
+3 -86
View File
@@ -7,9 +7,7 @@ import { afterEach, describe, expect, it } from "vitest";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
resolveDefaultDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings";
@@ -29,15 +27,7 @@ function makeSettingsPath() {
describe("desktopSettings", () => {
it("returns defaults when no settings file exists", () => {
expect(readDesktopSettings(makeSettingsPath(), "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("defaults packaged nightly builds to the nightly update channel", () => {
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("persists and reloads the configured server exposure mode", () => {
@@ -45,14 +35,10 @@ describe("desktopSettings", () => {
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
expect(readDesktopSettings(settingsPath)).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
@@ -61,32 +47,11 @@ describe("desktopSettings", () => {
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
"network-accessible",
),
).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("persists the requested nightly update channel", () => {
expect(
setDesktopUpdateChannelPreference(
{
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
"nightly",
),
).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
});
});
@@ -94,54 +59,6 @@ describe("desktopSettings", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, "{not-json", "utf8");
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("falls back to the nightly channel for legacy nightly settings without an update track", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, JSON.stringify({ serverExposureMode: "local-only" }), "utf8");
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("migrates legacy implicit stable settings to nightly when running a nightly build", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
serverExposureMode: "local-only",
updateChannel: "latest",
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("preserves an explicit stable choice on nightly builds", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
});
+4 -45
View File
@@ -1,28 +1,15 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
}
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
};
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
return {
...DEFAULT_DESKTOP_SETTINGS,
updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
};
}
export function setDesktopServerExposurePreference(
settings: DesktopSettings,
requestedMode: DesktopServerExposureMode,
@@ -35,51 +22,23 @@ export function setDesktopServerExposurePreference(
};
}
export function setDesktopUpdateChannelPreference(
settings: DesktopSettings,
requestedChannel: DesktopUpdateChannel,
): DesktopSettings {
return {
...settings,
updateChannel: requestedChannel,
updateChannelConfiguredByUser: true,
};
}
export function readDesktopSettings(settingsPath: string, appVersion: string): DesktopSettings {
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
export function readDesktopSettings(settingsPath: string): DesktopSettings {
try {
if (!FS.existsSync(settingsPath)) {
return defaultSettings;
return DEFAULT_DESKTOP_SETTINGS;
}
const raw = FS.readFileSync(settingsPath, "utf8");
const parsed = JSON.parse(raw) as {
readonly serverExposureMode?: unknown;
readonly updateChannel?: unknown;
readonly updateChannelConfiguredByUser?: unknown;
};
const parsedUpdateChannel =
parsed.updateChannel === "nightly" || parsed.updateChannel === "latest"
? parsed.updateChannel
: null;
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
const updateChannelConfiguredByUser =
parsed.updateChannelConfiguredByUser === true ||
(isLegacySettings && parsedUpdateChannel === "nightly");
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
updateChannel:
updateChannelConfiguredByUser && parsedUpdateChannel !== null
? parsedUpdateChannel
: defaultSettings.updateChannel,
updateChannelConfiguredByUser,
};
} catch {
return defaultSettings;
return DEFAULT_DESKTOP_SETTINGS;
}
}
+50 -197
View File
@@ -18,14 +18,12 @@ import {
safeStorage,
shell,
} from "electron";
import type { MenuItemConstructorOptions, OpenDialogOptions } from "electron";
import type { MenuItemConstructorOptions } from "electron";
import type {
ClientSettings,
DesktopTheme,
DesktopAppBranding,
DesktopServerExposureMode,
DesktopServerExposureState,
DesktopUpdateChannel,
PersistedSavedEnvironmentRecord,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
@@ -41,7 +39,6 @@ import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings";
import {
@@ -58,7 +55,6 @@ 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,
@@ -73,7 +69,6 @@ import {
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
import { resolveDesktopAppBranding } from "./appBranding";
syncShellEnvironment();
@@ -85,11 +80,9 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -108,11 +101,7 @@ const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
isDevelopment,
appVersion: app.getVersion(),
});
const APP_DISPLAY_NAME = desktopAppBranding.displayName;
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
@@ -127,32 +116,8 @@ const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
function resolvePickFolderDefaultPath(rawOptions: unknown): string | undefined {
if (typeof rawOptions !== "object" || rawOptions === null) {
return undefined;
}
const { initialPath } = rawOptions as { initialPath?: unknown };
if (typeof initialPath !== "string") {
return undefined;
}
const trimmedPath = initialPath.trim();
if (trimmedPath.length === 0) {
return undefined;
}
if (trimmedPath === "~") {
return OS.homedir();
}
if (trimmedPath.startsWith("~/") || trimmedPath.startsWith("~\\")) {
return Path.join(OS.homedir(), trimmedPath.slice(2));
}
return Path.resolve(trimmedPath);
}
const DESKTOP_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
const TITLEBAR_HEIGHT = 40;
@@ -160,35 +125,6 @@ const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linu
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
for (const sourceItem of source) {
if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
destructive: sourceItem.destructive === true,
disabled: sourceItem.disabled === true,
};
if (sourceItem.children) {
const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
if (normalizedChildren.length === 0) {
continue;
}
normalizedItem.children = normalizedChildren;
}
normalizedItems.push(normalizedItem);
}
return normalizedItems;
}
type WindowTitleBarOptions = Pick<
BrowserWindowConstructorOptions,
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
@@ -220,7 +156,7 @@ let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH, app.getVersion());
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
@@ -231,11 +167,7 @@ const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(
app.getVersion(),
desktopRuntimeInfo,
desktopSettings.updateChannel,
);
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
function logTimestamp(): string {
return new Date().toISOString();
@@ -1043,18 +975,6 @@ function resolveResourcePath(fileName: string): string | null {
}
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
if (isDevelopment && process.platform === "darwin" && ext === "png") {
const developmentDockIconPath = Path.join(
ROOT_DIR,
"assets",
"dev",
"blueprint-macos-1024.png",
);
if (FS.existsSync(developmentDockIconPath)) {
return developmentDockIconPath;
}
}
return resolveResourcePath(`icon.${ext}`);
}
@@ -1154,26 +1074,6 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
emitUpdateState();
}
function createBaseUpdateState(
channel: DesktopUpdateChannel,
enabled: boolean,
): DesktopUpdateState {
return {
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo, channel),
enabled,
status: enabled ? "idle" : "disabled",
};
}
function applyAutoUpdaterChannel(channel: DesktopUpdateChannel): void {
autoUpdater.channel = channel;
autoUpdater.allowPrerelease = channel === "nightly";
autoUpdater.allowDowngrade = channel === "nightly";
console.info(
`[desktop-updater] Using update channel '${channel}' (allowPrerelease=${channel === "nightly"}, allowDowngrade=${channel === "nightly"}).`,
);
}
function shouldEnableAutoUpdates(): boolean {
const hasUpdateFeedConfig =
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
@@ -1293,7 +1193,11 @@ function configureAutoUpdater(): void {
}
const enabled = shouldEnableAutoUpdates();
setUpdateState(createBaseUpdateState(desktopSettings.updateChannel, enabled));
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
if (!enabled) {
return;
}
@@ -1301,7 +1205,10 @@ function configureAutoUpdater(): void {
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
applyAutoUpdaterChannel(desktopSettings.updateChannel);
// Keep alpha branding, but force all installs onto the stable update track.
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
autoUpdater.allowDowngrade = false;
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
let lastLoggedDownloadMilestone = -1;
@@ -1315,15 +1222,6 @@ function configureAutoUpdater(): void {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
if (!doesVersionMatchDesktopUpdateChannel(info.version, updateState.channel)) {
console.info(
`[desktop-updater] Ignoring ${info.version} because it does not match the selected '${updateState.channel}' channel.`,
);
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
lastLoggedDownloadMilestone = -1;
return;
}
setUpdateState(
reduceDesktopUpdateStateOnUpdateAvailable(
updateState,
@@ -1588,11 +1486,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
}
function registerIpcHandlers(): void {
ipcMain.removeAllListeners(GET_APP_BRANDING_CHANNEL);
ipcMain.on(GET_APP_BRANDING_CHANNEL, (event) => {
event.returnValue = desktopAppBranding;
});
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
event.returnValue = {
@@ -1706,16 +1599,15 @@ function registerIpcHandlers(): void {
});
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
const defaultPath = resolvePickFolderDefaultPath(rawOptions);
const openDialogOptions: OpenDialogOptions = {
properties: ["openDirectory", "createDirectory"],
...(defaultPath ? { defaultPath } : {}),
};
const result = owner
? await dialog.showOpenDialog(owner, openDialogOptions)
: await dialog.showOpenDialog(openDialogOptions);
? await dialog.showOpenDialog(owner, {
properties: ["openDirectory", "createDirectory"],
})
: await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
});
if (result.canceled) return null;
return result.filePaths[0] ?? null;
});
@@ -1744,7 +1636,14 @@ function registerIpcHandlers(): void {
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
const normalizedItems = normalizeContextMenuItems(items);
const normalizedItems = items
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
.map((item) => ({
id: item.id,
label: item.label,
destructive: item.destructive === true,
disabled: item.disabled === true,
}));
if (normalizedItems.length === 0) {
return null;
}
@@ -1765,37 +1664,28 @@ function registerIpcHandlers(): void {
if (!window) return null;
return new Promise<string | null>((resolve) => {
const buildTemplate = (
entries: readonly ContextMenuItem[],
): MenuItemConstructorOptions[] => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children);
} else {
itemOption.click = () => resolve(item.id);
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
}
}
template.push(itemOption);
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of normalizedItems) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
return template;
};
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
click: () => resolve(item.id),
};
if (item.destructive) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
}
}
template.push(itemOption);
}
const menu = Menu.buildFromTemplate(buildTemplate(normalizedItems));
const menu = Menu.buildFromTemplate(template);
menu.popup({
window,
...popupPosition,
@@ -1823,43 +1713,6 @@ function registerIpcHandlers(): void {
ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
ipcMain.removeHandler(UPDATE_SET_CHANNEL_CHANNEL);
ipcMain.handle(UPDATE_SET_CHANNEL_CHANNEL, async (_event, rawChannel: unknown) => {
if (rawChannel !== "latest" && rawChannel !== "nightly") {
throw new Error("Invalid desktop update channel input.");
}
if (updateCheckInFlight || updateDownloadInFlight || updateInstallInFlight) {
throw new Error("Cannot change update tracks while an update action is in progress.");
}
const nextChannel = rawChannel as DesktopUpdateChannel;
desktopSettings = setDesktopUpdateChannelPreference(desktopSettings, nextChannel);
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
if (nextChannel === updateState.channel) {
return updateState;
}
const enabled = shouldEnableAutoUpdates();
setUpdateState(createBaseUpdateState(nextChannel, enabled));
if (!enabled || !updaterConfigured) {
return updateState;
}
applyAutoUpdaterChannel(nextChannel);
const allowDowngrade = autoUpdater.allowDowngrade;
// An explicit channel switch should allow the immediate nightly->stable rollback path.
autoUpdater.allowDowngrade = true;
try {
await checkForUpdates("channel-change");
} finally {
autoUpdater.allowDowngrade = allowDowngrade;
}
return updateState;
});
ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
const result = await downloadAvailableUpdate();
+1 -11
View File
@@ -9,11 +9,9 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -26,13 +24,6 @@ const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
const result = ipcRenderer.sendSync(GET_APP_BRANDING_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
@@ -53,7 +44,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
@@ -70,7 +61,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) => ipcRenderer.invoke(UPDATE_SET_CHANNEL_CHANNEL, channel),
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
-41
View File
@@ -1,41 +0,0 @@
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
@@ -1,18 +0,0 @@
import type { DesktopUpdateChannel } from "@t3tools/contracts";
const NIGHTLY_VERSION_PATTERN = /-nightly\.\d{8}\.\d+$/;
export function isNightlyDesktopVersion(version: string): boolean {
return NIGHTLY_VERSION_PATTERN.test(version);
}
export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
return isNightlyDesktopVersion(appVersion) ? "nightly" : "latest";
}
export function doesVersionMatchDesktopUpdateChannel(
version: string,
channel: DesktopUpdateChannel,
): boolean {
return resolveDefaultDesktopUpdateChannel(version) === channel;
}
+6 -7
View File
@@ -23,7 +23,7 @@ describe("updateMachine", () => {
it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "error",
message: "network",
@@ -42,7 +42,7 @@ describe("updateMachine", () => {
it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "checking",
},
@@ -58,7 +58,7 @@ describe("updateMachine", () => {
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -76,7 +76,7 @@ describe("updateMachine", () => {
it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -98,7 +98,7 @@ describe("updateMachine", () => {
it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "error",
availableVersion: "1.1.0",
@@ -120,7 +120,7 @@ describe("updateMachine", () => {
it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "checking",
},
@@ -131,7 +131,6 @@ describe("updateMachine", () => {
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
expect(available.status).toBe("available");
expect(available.channel).toBe("latest");
expect(downloading.status).toBe("downloading");
expect(downloading.downloadPercent).toBe(0);
expect(progress.downloadPercent).toBe(55.5);
+1 -7
View File
@@ -1,20 +1,14 @@
import type {
DesktopRuntimeInfo,
DesktopUpdateChannel,
DesktopUpdateState,
} from "@t3tools/contracts";
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
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,7 +11,6 @@ import {
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
+3 -4
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.20",
"version": "0.0.17",
"license": "MIT",
"repository": {
"type": "git",
@@ -20,11 +20,10 @@
"start": "node dist/bin.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
@@ -470,154 +470,6 @@ describe("startSession", () => {
manager.stopAll();
}
});
it("disposes an existing session before starting a replacement for the same thread", async () => {
const manager = new CodexAppServerManager();
const existingContext = {
session: {
provider: "codex",
status: "ready",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.set(asThreadId("thread-1"), existingContext);
const disposeSession = vi
.spyOn(
manager as unknown as {
disposeSession: (
context: typeof existingContext,
options?: { readonly emitLifecycleEvent?: boolean },
) => void;
},
"disposeSession",
)
.mockImplementation(() => {});
const assertSupportedCodexCliVersion = vi
.spyOn(
manager as unknown as {
assertSupportedCodexCliVersion: (input: {
binaryPath: string;
cwd: string;
homePath?: string;
}) => void;
},
"assertSupportedCodexCliVersion",
)
.mockImplementation(() => {});
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("cwd missing");
});
try {
await expect(
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow("cwd missing");
expect(disposeSession).toHaveBeenCalledWith(existingContext, {
emitLifecycleEvent: false,
});
expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
} finally {
disposeSession.mockRestore();
assertSupportedCodexCliVersion.mockRestore();
processCwd.mockRestore();
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.clear();
manager.stopAll();
}
});
it("continues replacement start when existing session disposal fails", async () => {
const manager = new CodexAppServerManager();
const existingContext = {
session: {
provider: "codex",
status: "ready",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.set(asThreadId("thread-1"), existingContext);
const disposeSession = vi
.spyOn(
manager as unknown as {
disposeSession: (
context: typeof existingContext,
options?: { readonly emitLifecycleEvent?: boolean },
) => void;
},
"disposeSession",
)
.mockImplementation(() => {
throw new Error("dispose failed");
});
const assertSupportedCodexCliVersion = vi
.spyOn(
manager as unknown as {
assertSupportedCodexCliVersion: (input: {
binaryPath: string;
cwd: string;
homePath?: string;
}) => void;
},
"assertSupportedCodexCliVersion",
)
.mockImplementation(() => {});
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("cwd missing");
});
try {
await expect(
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow("cwd missing");
expect(disposeSession).toHaveBeenCalledWith(existingContext, {
emitLifecycleEvent: false,
});
expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
} finally {
disposeSession.mockRestore();
assertSupportedCodexCliVersion.mockRestore();
processCwd.mockRestore();
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.clear();
manager.stopAll();
}
});
});
describe("sendTurn", () => {
+2 -36
View File
@@ -450,25 +450,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
let context: CodexSessionContext | undefined;
try {
const existingContext = this.sessions.get(threadId);
if (existingContext) {
await Effect.logWarning("codex app-server replacing existing session", {
threadId,
existingStatus: existingContext.session.status,
}).pipe(this.runPromise);
try {
this.disposeSession(existingContext, {
emitLifecycleEvent: false,
});
} catch (error) {
await Effect.logWarning("codex app-server failed to dispose existing session", {
threadId,
existingStatus: existingContext.session.status,
cause: error instanceof Error ? error.message : String(error),
}).pipe(this.runPromise);
}
}
const resolvedCwd = input.cwd ?? process.cwd();
const session: ProviderSession = {
@@ -920,19 +901,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return;
}
this.disposeSession(context, {
emitLifecycleEvent: true,
});
}
private disposeSession(
context: CodexSessionContext,
options?: { readonly emitLifecycleEvent?: boolean },
): void {
if (context.stopping) {
return;
}
context.stopping = true;
for (const pending of context.pending.values()) {
@@ -953,10 +921,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
status: "closed",
activeTurnId: undefined,
});
if (options?.emitLifecycleEvent !== false) {
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
}
this.sessions.delete(context.session.threadId);
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
this.sessions.delete(threadId);
}
listSessions(): ProviderSession[] {
@@ -166,7 +166,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
[
"exec",
"--ephemeral",
"--skip-git-repo-check",
"-s",
"read-only",
"--model",
+15
View File
@@ -188,6 +188,21 @@ 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");
+16 -1
View File
@@ -60,7 +60,22 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+d", command: "workspace.pane.splitRight", when: "!terminalFocus" },
{ key: "mod+shift+d", command: "workspace.pane.splitDown", when: "!terminalFocus" },
{ key: "mod+w", command: "workspace.pane.close", when: "!terminalFocus" },
{ key: "mod+[", command: "workspace.focus.previous" },
{ key: "mod+]", command: "workspace.focus.next" },
{ key: "mod+alt+arrowup", command: "workspace.focus.up" },
{ key: "mod+alt+arrowdown", command: "workspace.focus.down" },
{ key: "mod+alt+arrowleft", command: "workspace.focus.left" },
{ key: "mod+alt+arrowright", command: "workspace.focus.right" },
{ key: "mod+shift+enter", command: "workspace.pane.toggleZoom" },
{ key: "mod+ctrl+arrowup", command: "workspace.pane.resizeUp" },
{ key: "mod+ctrl+arrowdown", command: "workspace.pane.resizeDown" },
{ key: "mod+ctrl+arrowleft", command: "workspace.pane.resizeLeft" },
{ key: "mod+ctrl+arrowright", command: "workspace.pane.resizeRight" },
{ key: "mod+ctrl+=", command: "workspace.pane.equalize" },
{ key: "mod+alt+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
@@ -1284,14 +1284,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
return;
}
// Only approval-requested activities should create pending-approval
// rows. Other activity kinds that happen to carry a requestId
// (e.g. user-input.requested / user-input.resolved) must not
// pollute this projection — they have their own accounting via
// derivePendingUserInputCountFromActivities.
if (event.payload.activity.kind !== "approval.requested") {
return;
}
if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
return;
}
@@ -465,7 +465,6 @@ function runtimeEventToActivities(
payload: {
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
+1 -22
View File
@@ -28,31 +28,10 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
),
);
const normalizeProjectWorkspaceRootForCreate = (
workspaceRoot: string,
createIfMissing: boolean | undefined,
) =>
workspacePaths
.normalizeWorkspaceRoot(workspaceRoot, {
createIfMissing: createIfMissing === true,
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationDispatchCommandError({
message: cause.message,
}),
),
);
if (command.type === "project.create") {
return {
...command,
workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(
command.workspaceRoot,
command.createWorkspaceRootIfMissing,
),
createWorkspaceRootIfMissing: command.createWorkspaceRootIfMissing === true,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
} satisfies OrchestrationCommand;
}
@@ -1,5 +1,3 @@
import { realpathSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Duration, Effect, FileSystem, Layer } from "effect";
@@ -12,10 +10,6 @@ import {
RepositoryIdentityResolverLive,
} from "./RepositoryIdentityResolver.ts";
const normalizePathSeparators = (value: string) => value.replaceAll("\\", "/");
const normalizeResolvedPath = (value: string) =>
normalizePathSeparators(realpathSync.native(value));
const git = (cwd: string, args: ReadonlyArray<string>) =>
Effect.promise(() => runProcess("git", ["-C", cwd, ...args]));
@@ -47,7 +41,6 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(cwd));
expect(identity?.displayName).toBe("t3tools/t3code");
expect(identity?.provider).toBe("github");
expect(identity?.owner).toBe("t3tools");
@@ -55,27 +48,6 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
);
it.effect("returns the git top-level root path when resolving from a nested workspace", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const repoRoot = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-repository-identity-nested-root-test-",
});
const nestedWorkspace = `${repoRoot}/packages/web`;
yield* fileSystem.makeDirectory(nestedWorkspace, { recursive: true });
yield* git(repoRoot, ["init"]);
yield* git(repoRoot, ["remote", "add", "origin", "[email protected]:T3Tools/t3code.git"]);
const resolver = yield* RepositoryIdentityResolver;
const identity = yield* resolver.resolve(nestedWorkspace);
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(repoRoot));
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
);
it.effect("returns null for non-git folders and repos without remotes", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -140,7 +112,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
);
it.effect(
"keeps null identities cached across repeated resolves until the negative TTL expires",
"refreshes cached null identities after the negative TTL when a remote is configured later",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -156,10 +128,8 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
yield* git(cwd, ["remote", "add", "origin", "[email protected]:T3Tools/t3code.git"]);
for (const _attempt of [1, 2, 3]) {
const cachedIdentity = yield* resolver.resolve(cwd);
expect(cachedIdentity).toBeNull();
}
const cachedIdentity = yield* resolver.resolve(cwd);
expect(cachedIdentity).toBeNull();
yield* TestClock.adjust(Duration.millis(120));
@@ -42,7 +42,6 @@ function pickPrimaryRemote(
function buildRepositoryIdentity(input: {
readonly remoteName: string;
readonly remoteUrl: string;
readonly rootPath: string;
}): RepositoryIdentity {
const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
const hostingProvider = detectGitHostingProviderFromRemoteUrl(input.remoteUrl);
@@ -58,7 +57,6 @@ function buildRepositoryIdentity(input: {
remoteName: input.remoteName,
remoteUrl: input.remoteUrl,
},
rootPath: input.rootPath,
...(repositoryPath ? { displayName: repositoryPath } : {}),
...(hostingProvider ? { provider: hostingProvider.kind } : {}),
...(owner ? { owner } : {}),
@@ -68,7 +66,7 @@ function buildRepositoryIdentity(input: {
const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(1);
const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
const DEFAULT_NEGATIVE_CACHE_TTL = Duration.seconds(10);
interface RepositoryIdentityResolverOptions {
readonly cacheCapacity?: number;
@@ -110,7 +108,7 @@ async function resolveRepositoryIdentityFromCacheKey(
}
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.stdout));
return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
return remote ? buildRepositoryIdentity(remote) : null;
} catch {
return null;
}
@@ -351,53 +351,6 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("maps the Claude Opus 4.7 default effort to the SDK-supported max value", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-7",
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "max");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("maps xhigh effort for Claude Opus 4.7 to the SDK-supported max value", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-7",
options: {
effort: "xhigh",
},
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "max");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -1013,97 +966,6 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("falls back to a default plan step label for blank TodoWrite content", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 10).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-todo-plan",
uuid: "stream-todo-start",
parent_tool_use_id: null,
event: {
type: "content_block_start",
index: 1,
content_block: {
type: "tool_use",
id: "tool-todo-1",
name: "TodoWrite",
input: {},
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-todo-plan",
uuid: "stream-todo-input",
parent_tool_use_id: null,
event: {
type: "content_block_delta",
index: 1,
delta: {
type: "input_json_delta",
partial_json:
'{"todos":[{"content":" ","status":"in_progress"},{"content":"Ship it","status":"completed"}]}',
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-todo-plan",
uuid: "stream-todo-stop",
parent_tool_use_id: null,
event: {
type: "content_block_stop",
index: 1,
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-todo-plan",
uuid: "result-todo-plan",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const planUpdated = runtimeEvents.find((event) => event.type === "turn.plan.updated");
assert.equal(planUpdated?.type, "turn.plan.updated");
if (planUpdated?.type === "turn.plan.updated") {
assert.equal(String(planUpdated.turnId), String(turn.turnId));
assert.deepEqual(planUpdated.payload.plan, [
{ step: "Task", status: "inProgress" },
{ step: "Ship it", status: "completed" },
]);
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("classifies Claude Task tool invocations as collaboration agent work", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -1307,71 +1169,6 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("closes the previous session before replacing an existing thread session", () => {
const queries: FakeClaudeQuery[] = [];
const layer = makeClaudeAdapterLive({
createQuery: () => {
const query = new FakeClaudeQuery();
queries.push(query);
return query;
},
}).pipe(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
Stream.runCollect,
Effect.forkChild,
);
const firstSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
const secondSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
resumeCursor: firstSession.resumeCursor,
});
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const activeSessions = yield* adapter.listSessions();
assert.equal(queries.length, 2);
assert.equal(queries[0]?.closeCalls, 1);
assert.equal(queries[1]?.closeCalls, 0);
assert.equal(yield* adapter.hasSession(THREAD_ID), true);
assert.equal(activeSessions.length, 1);
assert.deepEqual(activeSessions[0]?.resumeCursor, secondSession.resumeCursor);
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"session.started",
"session.configured",
"session.state.changed",
],
);
assert.equal(
runtimeEvents.some((event) => event.type === "session.exited"),
false,
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(layer),
);
});
it.effect("stopSession does not throw into the SDK prompt consumer", () => {
// The SDK consumes user messages via `for await (... of prompt)`.
// Stopping a session must end that loop cleanly — not throw an error.
+27 -174
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,
ClaudeAgentEffort,
ClaudeCodeEffort,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
@@ -84,7 +84,6 @@ type ClaudeToolResultStreamKind = Extract<
RuntimeContentStreamKind,
"command_output" | "file_change_output"
>;
type ClaudeSdkEffort = NonNullable<ClaudeQueryOptions["effort"]>;
type PromptQueueItem =
| {
@@ -216,19 +215,13 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray
return squashed.length > 0 ? [squashed] : [];
}
function getEffectiveClaudeAgentEffort(
effort: ClaudeAgentEffort | null | undefined,
): ClaudeSdkEffort | null {
function getEffectiveClaudeCodeEffort(
effort: ClaudeCodeEffort | null | undefined,
): Exclude<ClaudeCodeEffort, "ultrathink"> | null {
if (!effort) {
return null;
}
if (effort === "ultrathink") {
return null;
}
if (effort === "xhigh") {
return "max";
}
return effort;
return effort === "ultrathink" ? null : effort;
}
function isClaudeInterruptedMessage(message: string): boolean {
@@ -296,7 +289,7 @@ function maxClaudeContextWindowFromModelUsage(
}
function normalizeClaudeTokenUsage(
value: unknown,
value: NonNullableUsage | undefined,
contextWindow?: number,
): ThreadTokenUsageSnapshot | undefined {
if (!value || typeof value !== "object") {
@@ -466,37 +459,6 @@ function classifyRequestType(toolName: string): CanonicalRequestType {
: "dynamic_tool_call";
}
function isTodoTool(toolName: string): boolean {
return toolName.toLowerCase().includes("todowrite");
}
type PlanStep = {
step: string;
status: "pending" | "inProgress" | "completed";
};
function extractPlanStepsFromTodoInput(input: Record<string, unknown>): PlanStep[] | null {
// TodoWrite format: { todos: [{ content, status, activeForm? }] }
const todos = input.todos;
if (!Array.isArray(todos) || todos.length === 0) {
return null;
}
return todos
.filter((t): t is Record<string, unknown> => t !== null && typeof t === "object")
.map((todo) => ({
step:
typeof todo.content === "string" && todo.content.trim().length > 0
? todo.content.trim()
: "Task",
status:
todo.status === "completed"
? "completed"
: todo.status === "in_progress"
? "inProgress"
: "pending",
}));
}
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
const commandValue = input.command ?? input.cmd;
const command = typeof commandValue === "string" ? commandValue : undefined;
@@ -504,20 +466,6 @@ function summarizeToolRequest(toolName: string, input: Record<string, unknown>):
return `${toolName}: ${command.trim().slice(0, 400)}`;
}
// For agent/subagent tools, prefer human-readable description or prompt over raw JSON
const itemType = classifyToolItemType(toolName);
if (itemType === "collab_agent_tool_call") {
const description =
typeof input.description === "string" ? input.description.trim() : undefined;
const prompt = typeof input.prompt === "string" ? input.prompt.trim() : undefined;
const subagentType =
typeof input.subagent_type === "string" ? input.subagent_type.trim() : undefined;
const label = description || (prompt ? prompt.slice(0, 200) : undefined);
if (label) {
return subagentType ? `${subagentType}: ${label}` : label;
}
}
const serialized = JSON.stringify(input);
if (serialized.length <= 400) {
return `${toolName}: ${serialized}`;
@@ -976,11 +924,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
((input: {
readonly prompt: AsyncIterable<SDKUserMessage>;
readonly options: ClaudeQueryOptions;
}) =>
query({
prompt: input.prompt,
options: input.options,
}) as ClaudeQueryRuntime);
}) => query({ prompt: input.prompt, options: input.options }) as ClaudeQueryRuntime);
const sessions = new Map<ThreadId, ClaudeSessionContext>();
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
@@ -1019,11 +963,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(typeof message.session_id === "string"
? { providerThreadId: message.session_id }
: {}),
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
...(itemId ? { itemId: ProviderItemId.make(itemId) } : {}),
payload: message,
},
@@ -1412,9 +1352,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(typeof accumulatedTotalProcessedTokens === "number" &&
Number.isFinite(accumulatedTotalProcessedTokens) &&
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
? {
totalProcessedTokens: accumulatedTotalProcessedTokens,
}
? { totalProcessedTokens: accumulatedTotalProcessedTokens }
: {}),
}
: accumulatedSnapshot;
@@ -1478,9 +1416,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
input: tool.input,
},
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/result",
@@ -1602,9 +1538,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
threadId: context.session.threadId,
turnId: context.turnState.turnId,
...(assistantBlockEntry?.block
? {
itemId: asRuntimeItemId(assistantBlockEntry.block.itemId),
}
? { itemId: asRuntimeItemId(assistantBlockEntry.block.itemId) }
: {}),
payload: {
streamKind,
@@ -1663,11 +1597,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
itemId: asRuntimeItemId(nextTool.itemId),
payload: {
itemType: nextTool.itemType,
@@ -1679,39 +1609,13 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
input: nextTool.input,
},
},
providerRefs: nativeProviderRefs(context, {
providerItemId: nextTool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: nextTool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/stream_event/content_block_delta/input_json_delta",
payload: message,
},
});
// Emit plan update when TodoWrite input is parsed
if (parsedInput && isTodoTool(nextTool.toolName)) {
const planSteps = extractPlanStepsFromTodoInput(parsedInput);
if (planSteps && planSteps.length > 0) {
const planStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.plan.updated",
eventId: planStamp.eventId,
provider: PROVIDER,
createdAt: planStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
payload: {
plan: planSteps,
},
providerRefs: nativeProviderRefs(context),
});
}
}
}
return;
}
@@ -1774,9 +1678,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
input: toolInput,
},
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/stream_event/content_block_start",
@@ -1848,9 +1750,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(tool.detail ? { detail: tool.detail } : {}),
data: toolData,
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/user",
@@ -1873,9 +1773,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
streamKind,
delta: toolResult.text,
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/user",
@@ -1900,9 +1798,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(tool.detail ? { detail: tool.detail } : {}),
data: toolData,
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
raw: {
source: "claude.sdk.message",
method: "claude/user",
@@ -2258,9 +2154,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
payload: {
summary: message.summary,
...(message.preceding_tool_use_ids.length > 0
? {
precedingToolUseIds: message.preceding_tool_use_ids,
}
? { precedingToolUseIds: message.preceding_tool_use_ids }
: {}),
},
});
@@ -2477,27 +2371,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
const existingContext = sessions.get(input.threadId);
if (existingContext) {
yield* Effect.logWarning("claude.session.replacing", {
threadId: input.threadId,
existingSessionStatus: existingContext.session.status,
reason: "startSession called with existing active session",
});
yield* stopSessionInternal(existingContext, {
emitExitEvent: false,
}).pipe(
// Replacement cleanup is best-effort: never block the new session on
// either typed failures or unexpected defects from tearing down the old one.
Effect.catchCause((cause) =>
Effect.logWarning("claude.session.replace.stop-failed", {
threadId: input.threadId,
cause,
}),
),
);
}
const startedAt = yield* nowIso;
const resumeState = readClaudeResumeState(input.resumeCursor);
const threadId = input.threadId;
@@ -2533,10 +2406,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const handleAskUserQuestion = Effect.fn("handleAskUserQuestion")(function* (
context: ClaudeSessionContext,
toolInput: Record<string, unknown>,
callbackOptions: {
readonly signal: AbortSignal;
readonly toolUseID?: string;
},
callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string },
) {
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
@@ -2572,11 +2442,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
provider: PROVIDER,
createdAt: requestedStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
requestId: asRuntimeRequestId(requestId),
payload: { questions },
providerRefs: nativeProviderRefs(context, {
@@ -2585,10 +2451,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
raw: {
source: "claude.sdk.permission",
method: "canUseTool/AskUserQuestion",
payload: {
toolName: "AskUserQuestion",
input: toolInput,
},
payload: { toolName: "AskUserQuestion", input: toolInput },
},
});
@@ -2603,9 +2466,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
pendingUserInputs.delete(requestId);
runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers));
};
callbackOptions.signal.addEventListener("abort", onAbort, {
once: true,
});
callbackOptions.signal.addEventListener("abort", onAbort, { once: true });
// Block until the user provides answers.
const answers = yield* Deferred.await(answersDeferred);
@@ -2619,11 +2480,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
provider: PROVIDER,
createdAt: resolvedStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
requestId: asRuntimeRequestId(requestId),
payload: { answers },
providerRefs: nativeProviderRefs(context, {
@@ -2793,9 +2650,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
behavior: "allow",
updatedInput: toolInput,
...(decision === "acceptForSession" && pendingApproval.suggestions
? {
updatedPermissions: [...pendingApproval.suggestions],
}
? { updatedPermissions: [...pendingApproval.suggestions] }
: {}),
} satisfies PermissionResult;
}
@@ -2825,19 +2680,18 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
),
);
const claudeBinaryPath = claudeSettings.binaryPath;
const extraArgs = parseCliArgs(claudeSettings.launchArgs).flags;
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
const caps = getClaudeModelCapabilities(modelSelection?.model);
const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
null) as ClaudeAgentEffort | null;
null) as ClaudeCodeEffort | null;
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
const thinking =
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
? modelSelection.options.thinking
: undefined;
const effectiveEffort = getEffectiveClaudeAgentEffort(effort);
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
const runtimeModeToPermission: Record<string, PermissionMode> = {
"auto-accept-edits": "acceptEdits",
"full-access": "bypassPermissions",
@@ -2865,7 +2719,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
canUseTool,
env: process.env,
...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
};
const queryRuntime = yield* Effect.try({
@@ -26,7 +26,6 @@ import {
spawnAndCollect,
type CommandResult,
} from "../providerSnapshot";
import { compareCliVersions } from "../cliVersion";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import { ClaudeProvider } from "../Services/ClaudeProvider";
import { ServerSettingsService } from "../../serverSettings";
@@ -41,30 +40,7 @@ const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = {
};
const PROVIDER = "claudeAgent" as const;
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-7",
name: "Claude Opus 4.7",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
},
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
@@ -120,24 +96,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
function supportsClaudeOpus47(version: string | null | undefined): boolean {
return version ? compareCliVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
}
function getBuiltInClaudeModelsForVersion(
version: string | null | undefined,
): ReadonlyArray<ServerProviderModel> {
if (supportsClaudeOpus47(version)) {
return BUILT_IN_MODELS;
}
return BUILT_IN_MODELS.filter((model) => model.slug !== "claude-opus-4-7");
}
function formatClaudeOpus47UpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Claude Code ${versionLabel} is too old for Claude Opus 4.7. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_7_VERSION} or newer to access it.`;
}
export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {
const slug = model?.trim();
return (
@@ -526,7 +484,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const allModels = providerModelsFromSettings(
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
@@ -538,7 +496,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: false,
checkedAt,
models: allModels,
models,
probe: {
installed: false,
version: null,
@@ -560,7 +518,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: allModels,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
@@ -578,7 +536,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: allModels,
models,
probe: {
installed: true,
version: null,
@@ -598,7 +556,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: allModels,
models,
probe: {
installed: true,
version: parsedVersion,
@@ -611,16 +569,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
});
}
const models = providerModelsFromSettings(
getBuiltInClaudeModelsForVersion(parsedVersion),
PROVIDER,
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
const opus47UpgradeMessage = supportsClaudeOpus47(parsedVersion)
? undefined
: formatClaudeOpus47UpgradeMessage(parsedVersion);
const slashCommands =
(resolveSlashCommands
? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe(
@@ -710,11 +658,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
...parsed.auth,
...(authMetadata ? authMetadata : {}),
},
...(parsed.message
? { message: parsed.message }
: opus47UpgradeMessage
? { message: opus47UpgradeMessage }
: {}),
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
@@ -146,7 +146,6 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
getBinding: () => Effect.succeed(Option.none()),
remove: () => Effect.void,
listThreadIds: () => Effect.succeed([]),
listBindings: () => Effect.succeed([]),
});
const validationManager = new FakeCodexManager();
@@ -973,69 +973,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
),
);
it.effect(
"includes Claude Opus 4.7 with xhigh as the default effort on supported versions",
() =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
const opus47 = status.models.find((model) => model.slug === "claude-opus-4-7");
if (!opus47) {
assert.fail("Expected Claude Opus 4.7 to be present for Claude Code v2.1.111.");
}
if (!opus47.capabilities) {
assert.fail(
"Expected Claude Opus 4.7 capabilities to be present for Claude Code v2.1.111.",
);
}
assert.deepStrictEqual(
opus47.capabilities.reasoningEffortLevels.find((level) => level.isDefault),
{ value: "xhigh", label: "Extra High", isDefault: true },
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.111\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides Claude Opus 4.7 on older Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(
status.models.some((model) => model.slug === "claude-opus-4-7"),
false,
);
assert.strictEqual(
status.message,
"Claude Code v2.1.110 is too old for Claude Opus 4.7. Upgrade to v2.1.111 or newer to access it.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.110\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns a display label for claude subscription types", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
@@ -654,43 +654,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("stops stale sessions in other providers after a successful replacement start", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const threadId = asThreadId("thread-provider-replacement");
const codexSession = yield* provider.startSession(threadId, {
provider: "codex",
threadId,
cwd: "/tmp/project-provider-replacement",
runtimeMode: "full-access",
});
routing.codex.stopSession.mockClear();
routing.claude.stopSession.mockClear();
const claudeSession = yield* provider.startSession(threadId, {
provider: "claudeAgent",
threadId,
cwd: "/tmp/project-provider-replacement",
runtimeMode: "full-access",
});
assert.equal(codexSession.provider, "codex");
assert.equal(claudeSession.provider, "claudeAgent");
assert.deepEqual(routing.codex.stopSession.mock.calls, [[threadId]]);
assert.equal(routing.claude.stopSession.mock.calls.length, 0);
const sessions = yield* provider.listSessions();
assert.deepEqual(
sessions
.filter((session) => session.threadId === threadId)
.map((session) => session.provider),
["claudeAgent"],
);
}),
);
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -297,40 +297,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
});
const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: {
readonly threadId: ThreadId;
readonly currentProvider: ProviderSession["provider"];
}) {
yield* Effect.forEach(
adapters,
(adapter) =>
adapter.provider === input.currentProvider
? Effect.void
: Effect.gen(function* () {
const hasSession = yield* adapter.hasSession(input.threadId);
if (!hasSession) {
return;
}
yield* adapter.stopSession(input.threadId).pipe(
Effect.tap(() =>
analytics.record("provider.session.stopped", {
provider: adapter.provider,
}),
),
Effect.catchCause((cause) =>
Effect.logWarning("provider.session.stop-stale-failed", {
threadId: input.threadId,
provider: adapter.provider,
cause,
}),
),
);
}),
{ discard: true },
);
});
const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")(
function* (threadId, rawInput) {
const parsed = yield* decodeInputOrValidationError({
@@ -385,10 +351,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
);
}
yield* stopStaleSessionsForThread({
threadId,
currentProvider: adapter.provider,
});
yield* upsertSessionBinding(session, threadId, {
modelSelection: input.modelSelection,
});
@@ -133,78 +133,6 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
}
}));
it("lists persisted bindings with metadata in oldest-first order", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
const olderThreadId = ThreadId.make("thread-runtime-older");
const newerThreadId = ThreadId.make("thread-runtime-newer");
yield* runtimeRepository.upsert({
threadId: newerThreadId,
providerName: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T12:05:00.000Z",
resumeCursor: {
opaque: "resume-newer",
},
runtimePayload: {
cwd: "/tmp/newer",
},
});
yield* runtimeRepository.upsert({
threadId: olderThreadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "approval-required",
status: "starting",
lastSeenAt: "2026-04-14T12:00:00.000Z",
resumeCursor: {
opaque: "resume-older",
},
runtimePayload: {
cwd: "/tmp/older",
},
});
const bindings = yield* directory.listBindings();
assert.deepEqual(bindings, [
{
threadId: olderThreadId,
provider: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "approval-required",
status: "starting",
lastSeenAt: "2026-04-14T12:00:00.000Z",
resumeCursor: {
opaque: "resume-older",
},
runtimePayload: {
cwd: "/tmp/older",
},
},
{
threadId: newerThreadId,
provider: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T12:05:00.000Z",
resumeCursor: {
opaque: "resume-newer",
},
runtimePayload: {
cwd: "/tmp/newer",
},
},
]);
}));
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
@@ -1,13 +1,11 @@
import { type ProviderKind, type ThreadId } from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";
import {
ProviderSessionDirectory,
type ProviderRuntimeBinding,
type ProviderRuntimeBindingWithMetadata,
type ProviderSessionDirectoryShape,
} from "../Services/ProviderSessionDirectory.ts";
@@ -52,27 +50,6 @@ function mergeRuntimePayload(
return next;
}
function toRuntimeBinding(
runtime: ProviderSessionRuntime,
operation: string,
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
return decodeProviderKind(runtime.providerName, operation).pipe(
Effect.map(
(provider) =>
({
threadId: runtime.threadId,
provider,
adapterKey: runtime.adapterKey,
runtimeMode: runtime.runtimeMode,
status: runtime.status,
resumeCursor: runtime.resumeCursor,
runtimePayload: runtime.runtimePayload,
lastSeenAt: runtime.lastSeenAt,
}) satisfies ProviderRuntimeBindingWithMetadata,
),
);
}
const makeProviderSessionDirectory = Effect.gen(function* () {
const repository = yield* ProviderSessionRuntimeRepository;
@@ -83,8 +60,18 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
Option.match(runtime, {
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
onSome: (value) =>
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
Effect.map((binding) => Option.some(binding)),
decodeProviderKind(value.providerName, "ProviderSessionDirectory.getBinding").pipe(
Effect.map((provider) =>
Option.some({
threadId: value.threadId,
provider,
adapterKey: value.adapterKey,
runtimeMode: value.runtimeMode,
status: value.status,
resumeCursor: value.resumeCursor,
runtimePayload: value.runtimePayload,
}),
),
),
}),
),
@@ -158,25 +145,12 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
Effect.map((rows) => rows.map((row) => row.threadId)),
);
const listBindings: ProviderSessionDirectoryShape["listBindings"] = () =>
repository.list().pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listBindings:list")),
Effect.flatMap((rows) =>
Effect.forEach(
rows,
(row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
{ concurrency: "unbounded" },
),
),
);
return {
upsert,
getProvider,
getBinding,
remove,
listThreadIds,
listBindings,
} satisfies ProviderSessionDirectoryShape;
});
@@ -1,522 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../../orchestration/Services/OrchestrationEngine.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderValidationError } from "../Errors.ts";
import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
const defaultModelSelection = {
provider: "codex",
model: "gpt-5-codex",
} as const;
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2_000,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (await predicate()) {
return;
}
if (Date.now() >= deadline) {
throw new Error("Timed out waiting for expectation.");
}
await new Promise((resolve) => setTimeout(resolve, 10));
return poll();
};
return poll();
}
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
function makeReadModel(
threads: ReadonlyArray<{
readonly id: ThreadId;
readonly session: {
readonly threadId: ThreadId;
readonly status: "starting" | "running" | "ready" | "interrupted" | "stopped" | "error";
readonly providerName: "codex" | "claudeAgent";
readonly runtimeMode: "approval-required" | "full-access" | "auto-accept-edits";
readonly activeTurnId: TurnId | null;
readonly lastError: string | null;
readonly updatedAt: string;
} | null;
}>,
) {
const now = new Date().toISOString();
const projectId = ProjectId.make("project-provider-session-reaper");
return {
snapshotSequence: 0,
updatedAt: now,
projects: [
{
id: projectId,
title: "Provider Reaper Project",
workspaceRoot: "/tmp/provider-reaper-project",
defaultModelSelection,
scripts: [],
createdAt: now,
updatedAt: now,
deletedAt: null,
},
],
threads: threads.map((thread) => ({
id: thread.id,
projectId,
title: `Thread ${thread.id}`,
modelSelection: defaultModelSelection,
interactionMode: "default" as const,
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
latestTurn: null,
messages: [],
session: thread.session,
activities: [],
proposedPlans: [],
checkpoints: [],
deletedAt: null,
})),
};
}
describe("ProviderSessionReaper", () => {
let runtime: ManagedRuntime.ManagedRuntime<
ProviderSessionReaper | ProviderSessionRuntimeRepository,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
afterEach(async () => {
if (scope) {
await Effect.runPromise(Scope.close(scope, Exit.void));
}
scope = null;
if (runtime) {
await runtime.dispose();
}
runtime = null;
});
async function createHarness(input: {
readonly readModel: ReturnType<typeof makeReadModel>;
readonly stopSessionImplementation?: (input: {
readonly threadId: ThreadId;
}) => ReturnType<ProviderServiceShape["stopSession"]>;
}) {
const stoppedThreadIds = new Set<ThreadId>();
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
(request) =>
(input.stopSessionImplementation
? input.stopSessionImplementation(request)
: Effect.sync(() => {
stoppedThreadIds.add(request.threadId);
})) as ReturnType<ProviderServiceShape["stopSession"]>,
);
const providerService: ProviderServiceShape = {
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession,
listSessions: () => Effect.succeed([]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
streamEvents: Stream.empty,
};
const orchestrationEngine: OrchestrationEngineShape = {
getReadModel: () => Effect.succeed(input.readModel),
readEvents: () => Stream.empty,
dispatch: () => unsupported(),
streamDomainEvents: Stream.empty,
};
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const layer = makeProviderSessionReaperLive({
inactivityThresholdMs: 1_000,
sweepIntervalMs: 60_000,
}).pipe(
Layer.provideMerge(providerSessionDirectoryLayer),
Layer.provideMerge(runtimeRepositoryLayer),
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)),
Layer.provideMerge(NodeServices.layer),
);
runtime = ManagedRuntime.make(layer);
return { stopSession, stoppedThreadIds };
}
it("reaps stale persisted sessions without active turns", async () => {
const threadId = ThreadId.make("thread-reaper-stale");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-stale",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await waitFor(() => harness.stopSession.mock.calls.length === 1);
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId });
expect(harness.stoppedThreadIds.has(threadId)).toBe(true);
});
it("skips stale sessions when the thread still has an active turn", async () => {
const threadId = ThreadId.make("thread-reaper-active-turn");
const turnId = TurnId.make("turn-reaper-active");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "running",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-active-turn",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await new Promise((resolve) => setTimeout(resolve, 50));
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("does not reap sessions that are still within the inactivity threshold", async () => {
const threadId = ThreadId.make("thread-reaper-fresh");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: now,
resumeCursor: {
opaque: "resume-fresh",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await new Promise((resolve) => setTimeout(resolve, 50));
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("skips persisted sessions that are already marked stopped", async () => {
const threadId = ThreadId.make("thread-reaper-stopped");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "stopped",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "stopped",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-stopped",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await new Promise((resolve) => setTimeout(resolve, 50));
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("continues reaping other sessions when one stop attempt fails", async () => {
const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: failedThreadId,
session: {
threadId: failedThreadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
{
id: reapedThreadId,
session: {
threadId: reapedThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
stopSessionImplementation: (request) =>
request.threadId === failedThreadId
? Effect.fail(
new ProviderValidationError({
operation: "ProviderSessionReaper.test",
issue: "simulated stop failure",
}),
)
: Effect.void,
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId: failedThreadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-failure",
},
runtimePayload: null,
}),
);
await runtime!.runPromise(
repository.upsert({
threadId: reapedThreadId,
providerName: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:01:00.000Z",
resumeCursor: {
opaque: "resume-success",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await waitFor(() => harness.stopSession.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
failedThreadId,
reapedThreadId,
]);
});
it("continues reaping other sessions when one stop attempt defects", async () => {
const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: defectThreadId,
session: {
threadId: defectThreadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
{
id: reapedThreadId,
session: {
threadId: reapedThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
stopSessionImplementation: (request) =>
request.threadId === defectThreadId
? Effect.die(new Error("simulated stop defect"))
: Effect.void,
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId: defectThreadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-defect",
},
runtimePayload: null,
}),
);
await runtime!.runPromise(
repository.upsert({
threadId: reapedThreadId,
providerName: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:01:00.000Z",
resumeCursor: {
opaque: "resume-after-defect",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await waitFor(() => harness.stopSession.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
defectThreadId,
reapedThreadId,
]);
});
});
@@ -1,133 +0,0 @@
import { Duration, Effect, Layer, Schedule } from "effect";
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
ProviderSessionReaper,
type ProviderSessionReaperShape,
} from "../Services/ProviderSessionReaper.ts";
import { ProviderService } from "../Services/ProviderService.ts";
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
export interface ProviderSessionReaperLiveOptions {
readonly inactivityThresholdMs?: number;
readonly sweepIntervalMs?: number;
}
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
Effect.gen(function* () {
const providerService = yield* ProviderService;
const directory = yield* ProviderSessionDirectory;
const orchestrationEngine = yield* OrchestrationEngineService;
const inactivityThresholdMs = Math.max(
1,
options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,
);
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
const sweep = Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
const threadsById = new Map(readModel.threads.map((thread) => [thread.id, thread] as const));
const bindings = yield* directory.listBindings();
const now = Date.now();
let reapedCount = 0;
for (const binding of bindings) {
if (binding.status === "stopped") {
continue;
}
const lastSeenMs = Date.parse(binding.lastSeenAt);
if (Number.isNaN(lastSeenMs)) {
yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
threadId: binding.threadId,
provider: binding.provider,
lastSeenAt: binding.lastSeenAt,
});
continue;
}
const idleDurationMs = now - lastSeenMs;
if (idleDurationMs < inactivityThresholdMs) {
continue;
}
const thread = threadsById.get(binding.threadId);
if (thread?.session?.activeTurnId != null) {
yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
threadId: binding.threadId,
activeTurnId: thread.session.activeTurnId,
idleDurationMs,
});
continue;
}
const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
Effect.tap(() =>
Effect.logInfo("provider.session.reaped", {
threadId: binding.threadId,
provider: binding.provider,
idleDurationMs,
reason: "inactivity_threshold",
}),
),
Effect.as(true),
Effect.catchCause((cause) =>
Effect.logWarning("provider.session.reaper.stop-failed", {
threadId: binding.threadId,
provider: binding.provider,
idleDurationMs,
cause,
}).pipe(Effect.as(false)),
),
);
if (reaped) {
reapedCount += 1;
}
}
if (reapedCount > 0) {
yield* Effect.logInfo("provider.session.reaper.sweep-complete", {
reapedCount,
totalBindings: bindings.length,
});
}
});
const start: ProviderSessionReaperShape["start"] = () =>
Effect.gen(function* () {
yield* Effect.forkScoped(
sweep.pipe(
Effect.catch((error: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-failed", {
error,
}),
),
Effect.catchDefect((defect: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-defect", {
defect,
}),
),
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
),
);
yield* Effect.logInfo("provider.session.reaper.started", {
inactivityThresholdMs,
sweepIntervalMs,
});
});
return {
start,
} satisfies ProviderSessionReaperShape;
});
export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
export const ProviderSessionReaperLive = makeProviderSessionReaperLive();
@@ -22,10 +22,6 @@ export interface ProviderRuntimeBinding {
readonly runtimeMode?: RuntimeMode;
}
export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {
readonly lastSeenAt: string;
}
export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;
export type ProviderSessionDirectoryWriteError =
@@ -53,11 +49,6 @@ export interface ProviderSessionDirectoryShape {
ReadonlyArray<ThreadId>,
ProviderSessionDirectoryPersistenceError
>;
readonly listBindings: () => Effect.Effect<
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
ProviderSessionDirectoryPersistenceError
>;
}
export class ProviderSessionDirectory extends Context.Service<
@@ -1,14 +0,0 @@
import { Context } from "effect";
import type { Effect, Scope } from "effect";
export interface ProviderSessionReaperShape {
/**
* Start the background provider session reaper within the provided scope.
*/
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
}
export class ProviderSessionReaper extends Context.Service<
ProviderSessionReaper,
ProviderSessionReaperShape
>()("t3/provider/Services/ProviderSessionReaper") {}
@@ -1,17 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { compareCliVersions, normalizeCliVersion } from "./cliVersion";
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
@@ -1,123 +0,0 @@
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;
}
+120 -4
View File
@@ -1,10 +1,121 @@
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";
export const compareCodexCliVersions = compareCliVersions;
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 function parseCodexCliVersion(output: string): string | null {
const match = CODEX_VERSION_PATTERN.exec(output);
@@ -12,7 +123,12 @@ export function parseCodexCliVersion(output: string): string | null {
return null;
}
return normalizeCliVersion(match[1]);
const parsed = parseSemver(match[1]);
if (!parsed) {
return null;
}
return normalizeCodexVersion(match[1]);
}
export function isCodexCliVersionSupported(version: string): boolean {
+6 -449
View File
@@ -11,7 +11,6 @@ import {
KeybindingRule,
MessageId,
OpenError,
type OrchestrationThreadShell,
TerminalNotRunningError,
type OrchestrationCommand,
type OrchestrationEvent,
@@ -167,32 +166,6 @@ 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)),
@@ -2066,40 +2039,6 @@ 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;
@@ -2972,48 +2911,21 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("stops the provider session and closes thread terminals after archive", () =>
it.effect("closes thread terminals after a successful archive command", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-archive");
const effects: string[] = [];
const dispatchedCommands: Array<OrchestrationCommand> = [];
const now = new Date().toISOString();
const closeInputs: Array<Parameters<TerminalManagerShape["close"]>[0]> = [];
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
effects.push(`terminal.close:${input.threadId}`);
closeInputs.push(input);
}),
},
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: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
}),
),
),
dispatch: () => Effect.succeed({ sequence: 8 }),
},
},
});
@@ -3029,363 +2941,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
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"],
);
assert.equal(dispatchResult.sequence, 8);
assert.deepEqual(closeInputs, [{ threadId }]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+7 -16
View File
@@ -23,7 +23,6 @@ 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";
@@ -135,10 +134,6 @@ 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;
@@ -148,6 +143,9 @@ const ProviderLayerLive = Layer.unwrap(
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
});
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
const codexAdapterLayer = makeCodexAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
@@ -157,14 +155,11 @@ const ProviderLayerLive = Layer.unwrap(
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
Layer.provide(codexAdapterLayer),
Layer.provide(claudeAdapterLayer),
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
Layer.provideMerge(providerSessionDirectoryLayer),
);
return makeProviderServiceLive(
canonicalEventLogger ? { canonicalEventLogger } : undefined,
).pipe(
Layer.provide(adapterRegistryLayer),
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
);
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
}),
);
@@ -199,16 +194,12 @@ 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(ProviderRuntimeLayerLive),
Layer.provideMerge(OrchestrationLayerLive),
Layer.provideMerge(ProviderLayerLive),
Layer.provideMerge(TerminalLayerLive),
Layer.provideMerge(PersistenceLayerLive),
Layer.provideMerge(KeybindingsLive),
+1 -6
View File
@@ -32,7 +32,6 @@ 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,
@@ -282,7 +281,6 @@ 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;
@@ -327,10 +325,7 @@ export const makeServerRuntimeStartup = Effect.gen(function* () {
yield* Effect.logDebug("startup phase: starting orchestration reactors");
yield* runStartupPhase(
"reactors.start",
Effect.gen(function* () {
yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
}),
orchestrationReactor.start().pipe(Scope.provide(reactorScope)),
);
const welcomeBase = yield* resolveWelcomeBase;
-35
View File
@@ -92,7 +92,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
enabled: true,
binaryPath: "/usr/local/bin/claude",
customModels: ["claude-custom"],
launchArgs: "",
});
assert.deepEqual(next.textGenerationModelSelection, {
provider: "codex",
@@ -142,35 +141,6 @@ 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;
@@ -197,7 +167,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
enabled: true,
binaryPath: "/opt/homebrew/bin/claude",
customModels: [],
launchArgs: "",
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
@@ -207,14 +176,12 @@ 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",
@@ -248,7 +215,6 @@ 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",
@@ -264,7 +230,6 @@ 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",
+2 -18
View File
@@ -42,7 +42,6 @@ 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. */
@@ -81,20 +80,7 @@ export class ServerSettingsService extends Context.Service<
getSettings: Ref.get(currentSettingsRef),
updateSettings: (patch) =>
Ref.get(currentSettingsRef).pipe(
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.map((currentSettings) => deepMerge(currentSettings, patch)),
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
),
streamChanges: Stream.empty,
@@ -328,9 +314,7 @@ const makeServerSettings = Effect.gen(function* () {
writeSemaphore.withPermits(1)(
Effect.gen(function* () {
const current = yield* getSettingsFromCache;
const next = yield* Schema.decodeEffect(ServerSettings)(
applyServerSettingsPatch(current, patch),
).pipe(
const next = yield* Schema.decodeEffect(ServerSettings)(deepMerge(current, patch)).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
@@ -68,11 +68,6 @@ 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();
@@ -280,85 +275,4 @@ 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,11 +1,9 @@
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 FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
import { type ProjectEntry } from "@t3tools/contracts";
import {
insertRankedSearchResult,
normalizeSearchQuery,
@@ -16,7 +14,6 @@ import {
import { GitCore } from "../../git/Services/GitCore.ts";
import {
WorkspaceEntries,
WorkspaceEntriesBrowseError,
WorkspaceEntriesError,
type WorkspaceEntriesShape,
} from "../Services/WorkspaceEntries.ts";
@@ -55,16 +52,6 @@ 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) {
@@ -142,36 +129,6 @@ 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);
@@ -422,46 +379,6 @@ 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);
@@ -498,7 +415,6 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
);
return {
browse,
invalidate,
search,
} satisfies WorkspaceEntriesShape;
@@ -58,24 +58,6 @@ 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,7 +4,6 @@ import { Effect, FileSystem, Layer, Path } from "effect";
import {
WorkspacePaths,
WorkspacePathOutsideRootError,
WorkspaceRootCreateFailedError,
WorkspaceRootNotDirectoryError,
WorkspaceRootNotExistsError,
type WorkspacePathsShape,
@@ -30,25 +29,11 @@ export const makeWorkspacePaths = Effect.gen(function* () {
const normalizeWorkspaceRoot: WorkspacePathsShape["normalizeWorkspaceRoot"] = Effect.fn(
"WorkspacePaths.normalizeWorkspaceRoot",
)(function* (workspaceRoot, options) {
)(function* (workspaceRoot) {
const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));
let workspaceStat = yield* fileSystem
const 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,12 +9,7 @@
import { Schema, Context } from "effect";
import type { Effect } from "effect";
import type {
FilesystemBrowseInput,
FilesystemBrowseResult,
ProjectSearchEntriesInput,
ProjectSearchEntriesResult,
} from "@t3tools/contracts";
import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "@t3tools/contracts";
export class WorkspaceEntriesError extends Schema.TaggedErrorClass<WorkspaceEntriesError>()(
"WorkspaceEntriesError",
@@ -26,29 +21,11 @@ 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,18 +21,6 @@ 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",
{
@@ -59,7 +47,6 @@ export class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass<Works
export const WorkspacePathsError = Schema.Union([
WorkspaceRootNotExistsError,
WorkspaceRootCreateFailedError,
WorkspaceRootNotDirectoryError,
WorkspacePathOutsideRootError,
]);
@@ -74,11 +61,7 @@ export interface WorkspacePathsShape {
*/
readonly normalizeWorkspaceRoot: (
workspaceRoot: string,
options?: { readonly createIfMissing?: boolean },
) => Effect.Effect<
string,
WorkspaceRootNotExistsError | WorkspaceRootCreateFailedError | WorkspaceRootNotDirectoryError
>;
) => Effect.Effect<string, WorkspaceRootNotExistsError | WorkspaceRootNotDirectoryError>;
/**
* Resolve a relative path within a validated workspace root.
-52
View File
@@ -17,7 +17,6 @@ import {
ProjectSearchEntriesError,
ProjectWriteFileError,
OrchestrationReplayEventsError,
FilesystemBrowseError,
ThreadId,
type TerminalEvent,
WS_METHODS,
@@ -550,45 +549,8 @@ 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", {
@@ -806,20 +768,6 @@ 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.20",
"version": "0.0.17",
"private": true,
"type": "module",
"scripts": {
-37
View File
@@ -1,37 +0,0 @@
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)");
});
});
+3 -17
View File
@@ -1,18 +1,4 @@
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_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})`;
export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0";
@@ -77,4 +77,53 @@ 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",
surfaceId: "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,6 +11,7 @@ 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,
@@ -34,6 +35,34 @@ 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 {
@@ -192,3 +221,11 @@ 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);
}
+13 -18
View File
@@ -1,32 +1,27 @@
import { create } from "zustand";
interface CommandPaletteOpenIntent {
kind: "add-project";
requestId: number;
export interface CommandPaletteWorkspaceTarget {
disposition: "split-right" | "split-down";
}
interface CommandPaletteStore {
open: boolean;
openIntent: CommandPaletteOpenIntent | null;
workspaceTarget: CommandPaletteWorkspaceTarget | null;
setOpen: (open: boolean) => void;
toggleOpen: () => void;
openAddProject: () => void;
clearOpenIntent: () => void;
openWorkspaceTarget: (target: CommandPaletteWorkspaceTarget) => void;
clearWorkspaceTarget: () => void;
}
export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
open: false,
openIntent: null,
setOpen: (open) => set({ open, ...(open ? {} : { openIntent: null }) }),
workspaceTarget: null,
setOpen: (open) => set({ open, ...(open ? {} : { workspaceTarget: null }) }),
toggleOpen: () =>
set((state) => ({ open: !state.open, ...(state.open ? { openIntent: null } : {}) })),
openAddProject: () =>
set((state) => ({
open: true,
openIntent: {
kind: "add-project",
requestId: (state.openIntent?.requestId ?? 0) + 1,
},
})),
clearOpenIntent: () => set({ openIntent: null }),
set((state) => {
const next = !state.open;
return { open: next, ...(next ? {} : { workspaceTarget: null }) };
}),
openWorkspaceTarget: (target) => set({ open: true, workspaceTarget: target }),
clearWorkspaceTarget: () => set({ workspaceTarget: null }),
}));
@@ -63,7 +63,7 @@ describe("ChatMarkdown", () => {
);
try {
const link = page.getByRole("link", { name: "PermissionRule.ts · L1" });
const link = page.getByRole("link", { name: "PermissionRule.ts:1" });
await expect.element(link).toBeInTheDocument();
await expect.element(link).toHaveAttribute("href", `${filePath}#L1`);
@@ -76,66 +76,4 @@ 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();
}
});
});
+17 -283
View File
@@ -3,7 +3,6 @@ import { CheckIcon, CopyIcon } from "lucide-react";
import React, {
Children,
Suspense,
type MouseEvent as ReactMouseEvent,
isValidElement,
use,
useCallback,
@@ -18,17 +17,13 @@ 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 { resolveMarkdownFileLinkMeta, rewriteMarkdownFileUriHref } from "../markdown-links";
import { resolveMarkdownFileLinkTarget, rewriteMarkdownFileUriHref } from "../markdown-links";
import { readLocalApi } from "../localApi";
import { cn } from "../lib/utils";
class CodeHighlightErrorBoundary extends React.Component<
{ fallback: ReactNode; children: ReactNode },
@@ -241,289 +236,34 @@ 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 normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
if (!fileLinkMeta) {
const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
if (!targetPath) {
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 (
<MarkdownFileLink
href={href ?? fileLinkMeta.targetPath}
targetPath={fileLinkMeta.targetPath}
displayPath={fileLinkMeta.displayPath}
filePath={fileLinkMeta.filePath}
label={labelParts.join(" · ")}
theme={resolvedTheme}
className={props.className}
<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.");
}
}}
/>
);
},
@@ -549,13 +289,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
);
},
}),
[
diffThemeName,
fileLinkParentSuffixByPath,
isStreaming,
markdownFileLinkMetaByHref,
resolvedTheme,
],
[cwd, diffThemeName, isStreaming],
);
return (
+11 -840
View File
@@ -5,7 +5,6 @@ import {
EventId,
ORCHESTRATION_WS_METHODS,
EnvironmentId,
type EnvironmentApi,
type MessageId,
type OrchestrationReadModel,
type ProjectId,
@@ -17,7 +16,12 @@ import {
OrchestrationSessionStatus,
DEFAULT_SERVER_SETTINGS,
} from "@t3tools/contracts";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import {
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
@@ -27,16 +31,6 @@ 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,
@@ -47,7 +41,6 @@ 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";
@@ -69,27 +62,14 @@ 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_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 PROJECT_KEY = scopedProjectKey(scopeProjectRef(LOCAL_ENVIRONMENT_ID, PROJECT_ID));
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;
@@ -192,32 +172,6 @@ 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;
@@ -1429,44 +1383,6 @@ 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;
@@ -1608,10 +1524,6 @@ 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: {},
@@ -1621,7 +1533,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
useCommandPaletteStore.setState({
open: false,
openIntent: null,
});
useStore.setState({
activeEnvironmentId: null,
@@ -1645,12 +1556,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
customWsRpcResolver = null;
document.body.innerHTML = "";
});
it("re-expands the bootstrap project using its logical key", async () => {
it("re-expands the bootstrap project using its scoped key", async () => {
useUiStateStore.setState({
projectExpandedById: {
[PROJECT_LOGICAL_KEY]: false,
[PROJECT_KEY]: false,
},
projectOrder: [PROJECT_LOGICAL_KEY],
projectOrder: [PROJECT_KEY],
threadLastVisitedAtById: {},
});
@@ -1665,7 +1576,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
await vi.waitFor(
() => {
expect(useUiStateStore.getState().projectExpandedById[PROJECT_LOGICAL_KEY]).toBe(true);
expect(useUiStateStore.getState().projectExpandedById[PROJECT_KEY]).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
@@ -4168,746 +4079,6 @@ 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,
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,4 @@
import { type KeybindingCommand, type FilesystemBrowseEntry } from "@t3tools/contracts";
import { type KeybindingCommand } from "@t3tools/contracts";
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import { type ReactNode } from "react";
import { sortThreads } from "../lib/threadSort";
@@ -45,39 +45,7 @@ export interface CommandPaletteView {
readonly initialQuery?: string;
}
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 type CommandPaletteMode = "root" | "submenu";
export function normalizeSearchText(value: string): string {
return value.trim().toLowerCase().replace(/\s+/g, " ");
@@ -262,56 +230,10 @@ 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 {
if (input.currentView) {
return input.isBrowsing ? "submenu-browse" : "submenu";
}
return input.isBrowsing ? "root-browse" : "root";
return input.currentView ? "submenu" : "root";
}
export function buildRootGroups(input: {
@@ -336,11 +258,7 @@ 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,12 +14,10 @@ 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;
@@ -48,7 +46,6 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
item={item}
key={item.value}
keybindings={props.keybindings}
isActive={props.highlightedItemValue === item.value}
onExecuteItem={props.onExecuteItem}
/>
)}
@@ -61,7 +58,6 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
function CommandPaletteResultRow(props: {
item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
isActive: boolean;
keybindings: ResolvedKeybindingsConfig;
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
}) {
@@ -72,10 +68,7 @@ function CommandPaletteResultRow(props: {
return (
<CommandItem
value={props.item.value}
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!",
)}
className="cursor-pointer gap-2"
onMouseDown={(event) => {
event.preventDefault();
}}
@@ -32,8 +32,11 @@ import {
type ElementNode,
type LexicalNode,
type SerializedLexicalNode,
TextNode,
type EditorConfig,
type EditorState,
type NodeKey,
type SerializedTextNode,
type Spread,
} from "lexical";
import {
@@ -100,7 +103,7 @@ type SerializedComposerMentionNode = Spread<
type: "composer-mention";
version: 1;
},
SerializedLexicalNode
SerializedTextNode
>;
type SerializedComposerSkillNode = Spread<
@@ -129,40 +132,7 @@ const ComposerTerminalContextActionsContext = createContext<{
onRemoveTerminalContext: () => {},
});
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> {
class ComposerMentionNode extends TextNode {
__path: string;
static override getType(): string {
@@ -174,12 +144,12 @@ class ComposerMentionNode extends DecoratorNode<ReactElement> {
}
static override importJSON(serializedNode: SerializedComposerMentionNode): ComposerMentionNode {
return $createComposerMentionNode(serializedNode.path).updateFromJSON(serializedNode);
return $createComposerMentionNode(serializedNode.path);
}
constructor(path: string, key?: NodeKey) {
super(key);
const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
super(`@${normalizedPath}`, key);
this.__path = normalizedPath;
}
@@ -192,26 +162,41 @@ class ComposerMentionNode extends DecoratorNode<ReactElement> {
};
}
override createDOM(): HTMLElement {
override createDOM(_config: EditorConfig): HTMLElement {
const dom = document.createElement("span");
dom.className = "inline-flex align-middle leading-none";
dom.className = COMPOSER_INLINE_CHIP_CLASS_NAME;
dom.contentEditable = "false";
dom.setAttribute("spellcheck", "false");
renderMentionChipDom(dom, this.__path);
return dom;
}
override updateDOM(): false {
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);
}
return false;
}
override getTextContent(): string {
return `@${this.__path}`;
override canInsertTextBefore(): false {
return false;
}
override isInline(): true {
override canInsertTextAfter(): false {
return false;
}
override isTextEntity(): true {
return true;
}
override decorate(): ReactElement {
return <ComposerMentionDecorator path={this.__path} />;
override isToken(): true {
return true;
}
}
@@ -449,6 +434,26 @@ 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) =>
@@ -590,9 +595,12 @@ 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 (isComposerInlineTokenNode(node)) {
if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) {
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
}
@@ -634,9 +642,12 @@ 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 (isComposerInlineTokenNode(node)) {
if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) {
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
}
@@ -662,7 +673,10 @@ function findSelectionPointAtOffset(
node: LexicalNode,
remainingRef: { value: number },
): { key: string; offset: number; type: "text" | "element" } | null {
if (isComposerInlineTokenNode(node)) {
if (node instanceof ComposerMentionNode || node instanceof ComposerSkillNode) {
return findSelectionPointForInlineToken(node, remainingRef);
}
if (node instanceof ComposerTerminalContextNode) {
return findSelectionPointForInlineToken(node, remainingRef);
}
@@ -876,6 +890,7 @@ export interface ComposerPromptEditorHandle {
focus: () => void;
focusAt: (cursor: number) => void;
focusAtEnd: () => void;
isFocused: () => boolean;
readSnapshot: () => {
value: string;
cursor: number;
@@ -1369,7 +1384,6 @@ function ComposerSurroundSelectionPlugin(props: {
const onCompositionEnd = () => {
tryApplyDeadKeyBacktickSurround({ finalAttempt: true });
};
let activeRootElement: HTMLElement | null = null;
const unregisterRootListener = editor.registerRootListener((rootElement, prevRootElement) => {
prevRootElement?.removeEventListener("keydown", onKeyDown);
@@ -1479,7 +1493,7 @@ function ComposerPromptEditorInner({
if (shouldRewriteEditorState) {
$setComposerEditorPrompt(value, terminalContexts, skillMetadataRef.current);
}
if (shouldRewriteEditorState || isFocused) {
if (isFocused) {
$setSelectionAtComposerOffset(normalizedCursor);
}
});
@@ -1494,22 +1508,19 @@ 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],
);
@@ -1563,9 +1574,13 @@ function ComposerPromptEditorInner({
),
);
},
isFocused: () => {
const rootElement = editor.getRootElement();
return Boolean(rootElement && document.activeElement === rootElement);
},
readSnapshot,
}),
[focusAt, readSnapshot],
[editor, 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: [], launchArgs: "" },
claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
},
},
};
+3 -14
View File
@@ -54,24 +54,20 @@ 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);
@@ -125,14 +121,7 @@ const PlanSidebar = memo(function PlanSidebar({
}, [environmentId, planMarkdown, workspaceRoot]);
return (
<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",
)}
>
<div className="flex h-full w-[340px] shrink-0 flex-col border-l border-border/70 bg-card/50">
{/* 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">
@@ -140,7 +129,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"
>
{label}
Plan
</Badge>
{activePlan ? (
<span className="text-[11px] text-muted-foreground/60">
@@ -181,7 +170,7 @@ const PlanSidebar = memo(function PlanSidebar({
size="icon-xs"
variant="ghost"
onClick={onClose}
aria-label={`Close ${label.toLowerCase()} sidebar`}
aria-label="Close plan sidebar"
className="text-muted-foreground/50 hover:text-foreground/70"
>
<PanelRightCloseIcon className="size-3.5" />
@@ -1,30 +0,0 @@
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,11 +28,7 @@ import {
resolveWrappedTerminalLinkRange,
wrappedTerminalLinkRangeIntersectsBufferLine,
} from "../terminal-links";
import {
isTerminalClearShortcut,
terminalDeleteShortcutData,
terminalNavigationShortcutData,
} from "../keybindings";
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -411,14 +407,6 @@ 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();
@@ -795,6 +783,7 @@ interface ThreadTerminalDrawerProps {
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
showResizeHandle?: boolean;
}
interface TerminalActionButtonProps {
@@ -848,6 +837,7 @@ export default function ThreadTerminalDrawer({
onCloseTerminal,
onHeightChange,
onAddTerminalContext,
showResizeHandle = true,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const [resizeEpoch, setResizeEpoch] = useState(0);
@@ -1084,16 +1074,20 @@ export default function ThreadTerminalDrawer({
return (
<aside
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
className={`thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden bg-background ${
showResizeHandle ? "border-t border-border/80" : ""
}`}
style={{ height: `${drawerHeight}px` }}
>
<div
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd}
/>
{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}
{!hasTerminalSidebar && (
<div className="pointer-events-none absolute right-2 top-2 z-20">
+30 -12
View File
@@ -162,7 +162,6 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
interactionMode: ProviderInteractionMode;
runtimeMode: RuntimeMode;
showPlanToggle: boolean;
planSidebarLabel: string;
planSidebarOpen: boolean;
onToggleInteractionMode: () => void;
onRuntimeModeChange: (mode: RuntimeMode) => void;
@@ -244,14 +243,10 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
size="sm"
type="button"
onClick={props.onTogglePlanSidebar}
title={
props.planSidebarOpen
? `Hide ${props.planSidebarLabel.toLowerCase()} sidebar`
: `Show ${props.planSidebarLabel.toLowerCase()} sidebar`
}
title={props.planSidebarOpen ? "Hide plan sidebar" : "Show plan sidebar"}
>
<ListTodoIcon />
<span className="sr-only sm:not-sr-only">{props.planSidebarLabel}</span>
<span className="sr-only sm:not-sr-only">Plan</span>
</Button>
</>
) : null}
@@ -344,6 +339,7 @@ export interface ChatComposerHandle {
// --------------------------------------------------------------------------
export interface ChatComposerProps {
activationFocusRequestId?: number;
composerDraftTarget: ScopedThreadRef | DraftId;
environmentId: EnvironmentId;
routeKind: "server" | "draft";
@@ -385,7 +381,6 @@ export interface ChatComposerProps {
activeProposedPlan: Thread["proposedPlans"][number] | null;
activePlan: { turnId?: TurnId } | null;
sidebarProposedPlan: { turnId?: TurnId } | null;
planSidebarLabel: string;
planSidebarOpen: boolean;
// Mode
@@ -453,6 +448,7 @@ export interface ChatComposerProps {
export const ChatComposer = memo(
forwardRef<ChatComposerHandle, ChatComposerProps>(function ChatComposer(props, ref) {
const {
activationFocusRequestId,
composerDraftTarget,
environmentId,
routeKind,
@@ -480,7 +476,6 @@ export const ChatComposer = memo(
activeProposedPlan,
activePlan,
sidebarProposedPlan,
planSidebarLabel,
planSidebarOpen,
runtimeMode,
interactionMode,
@@ -660,6 +655,7 @@ 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);
@@ -668,6 +664,13 @@ 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
// ------------------------------------------------------------------
@@ -1234,8 +1237,11 @@ export const ChatComposer = memo(
);
return;
}
const previousPrompt = promptRef.current;
promptRef.current = nextPrompt;
setPrompt(nextPrompt);
if (previousPrompt !== nextPrompt) {
setPrompt(nextPrompt);
}
if (!terminalContextIdListsEqual(composerTerminalContexts, terminalContextIds)) {
setComposerDraftTerminalContexts(
composerDraftTarget,
@@ -1246,6 +1252,20 @@ 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,
@@ -1930,7 +1950,6 @@ export const ChatComposer = memo(
<CompactComposerControlsMenu
activePlan={showPlanSidebarToggle}
interactionMode={interactionMode}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
traitsMenuContent={providerTraitsMenuContent}
@@ -1953,7 +1972,6 @@ 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 drawer"
aria-label="Toggle terminal split"
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 drawer (${terminalToggleShortcutLabel})`
: "Toggle terminal drawer"}
? `Toggle terminal split (${terminalToggleShortcutLabel})`
: "Toggle terminal split"}
</TooltipPopup>
</Tooltip>
<Tooltip>
@@ -123,7 +123,6 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
<CompactComposerControlsMenu
activePlan={false}
interactionMode="default"
planSidebarLabel="Plan"
planSidebarOpen={false}
runtimeMode="approval-required"
traitsMenuContent={
@@ -15,7 +15,6 @@ import {
export const CompactComposerControlsMenu = memo(function CompactComposerControlsMenu(props: {
activePlan: boolean;
interactionMode: ProviderInteractionMode;
planSidebarLabel: string;
planSidebarOpen: boolean;
runtimeMode: RuntimeMode;
traitsMenuContent?: ReactNode;
@@ -73,9 +72,7 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
<MenuDivider />
<MenuItem onClick={props.onTogglePlanSidebar}>
<ListTodoIcon className="size-4 shrink-0" />
{props.planSidebarOpen
? `Hide ${props.planSidebarLabel.toLowerCase()} sidebar`
: `Show ${props.planSidebarLabel.toLowerCase()} sidebar`}
{props.planSidebarOpen ? "Hide plan sidebar" : "Show plan sidebar"}
</MenuItem>
</>
) : null}
@@ -1,189 +0,0 @@
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,7 +60,6 @@ import {
formatInlineTerminalContextLabel,
textContainsInlineTerminalContextLabels,
} from "./userMessageTerminalContexts";
import { formatWorkspaceRelativePath } from "../../filePathDisplay";
// ---------------------------------------------------------------------------
// Context — shared state consumed by every row component via useContext.
@@ -529,7 +528,6 @@ 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 =
@@ -561,11 +559,7 @@ const WorkGroupSection = memo(function WorkGroupSection({
)}
<div className="space-y-0.5">
{visibleEntries.map((workEntry) => (
<SimpleWorkEntryRow
key={`work-row:${workEntry.id}`}
workEntry={workEntry}
workspaceRoot={workspaceRoot}
/>
<SimpleWorkEntryRow key={`work-row:${workEntry.id}`} workEntry={workEntry} />
))}
</div>
</div>
@@ -867,17 +861,15 @@ 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
? displayPath
: `${displayPath} +${workEntry.changedFiles!.length - 1} more`;
? firstPath
: `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
}
function workEntryRawCommand(
@@ -932,13 +924,12 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
workEntry: TimelineWorkEntry;
workspaceRoot: string | undefined;
}) {
const { workEntry, workspaceRoot } = props;
const { workEntry } = props;
const iconConfig = workToneIcon(workEntry.tone);
const EntryIcon = workEntryIcon(workEntry);
const heading = toolWorkEntryHeading(workEntry);
const preview = workEntryPreview(workEntry, workspaceRoot);
const preview = workEntryPreview(workEntry);
const rawCommand = workEntryRawCommand(workEntry);
const displayText = preview ? `${heading} - ${preview}` : heading;
const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
@@ -997,18 +988,15 @@ 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) => {
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?.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?.length ?? 0) > 4 && (
<span className="px-1 text-[10px] text-muted-foreground/55">
+{(workEntry.changedFiles?.length ?? 0) - 4}
@@ -17,7 +17,6 @@ import {
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
@@ -7,7 +7,6 @@ import {
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
type DesktopBridge,
type DesktopUpdateChannel,
type DesktopUpdateState,
type LocalApi,
type ServerConfig,
@@ -259,12 +258,10 @@ 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",
@@ -279,7 +276,6 @@ const createDesktopBridgeStub = (overrides?: {
};
return {
getAppBranding: vi.fn().mockReturnValue(null),
getLocalEnvironmentBootstrap: () => ({
label: "Local environment",
httpBaseUrl: "http://127.0.0.1:3773",
@@ -314,12 +310,6 @@ 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,7 +12,6 @@ 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,
@@ -233,42 +232,8 @@ 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;
@@ -358,59 +323,27 @@ 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="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>
}
/>
</>
<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>
}
/>
);
}
@@ -444,9 +377,6 @@ 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"]
: []),
@@ -461,7 +391,6 @@ export function useSettingsRestore(onRestored?: () => void) {
isGitWritingModelDirty,
settings.confirmThreadArchive,
settings.confirmThreadDelete,
settings.addProjectBaseDirectory,
settings.defaultThreadEnvMode,
settings.diffWordWrap,
settings.enableAssistantStreaming,
@@ -511,8 +440,7 @@ export function GeneralSettingsPanel() {
claudeAgent: Boolean(
settings.providers.claudeAgent.binaryPath !==
DEFAULT_UNIFIED_SETTINGS.providers.claudeAgent.binaryPath ||
settings.providers.claudeAgent.customModels.length > 0 ||
settings.providers.claudeAgent.launchArgs !== "",
settings.providers.claudeAgent.customModels.length > 0,
),
});
const [customModelInputByProvider, setCustomModelInputByProvider] = useState<
@@ -924,34 +852,6 @@ 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."
@@ -1279,37 +1179,6 @@ 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">
@@ -0,0 +1,100 @@
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>
);
}
@@ -0,0 +1,130 @@
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-replace");
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: {},
});
}
File diff suppressed because it is too large. Load diff
+27 -12
View File
@@ -1,6 +1,7 @@
import {
ClaudeAgentEffort,
CodexReasoningEffort,
CODEX_REASONING_EFFORT_OPTIONS,
type ClaudeCodeEffort,
type CodexReasoningEffort,
DEFAULT_MODEL_BY_PROVIDER,
type EnvironmentId,
ModelSelection,
@@ -104,7 +105,7 @@ const PersistedComposerThreadDraftState = Schema.Struct({
type PersistedComposerThreadDraftState = typeof PersistedComposerThreadDraftState.Type;
const LegacyCodexFields = Schema.Struct({
effort: Schema.optionalKey(CodexReasoningEffort),
effort: Schema.optionalKey(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)),
codexFastMode: Schema.optionalKey(Schema.Boolean),
serviceTier: Schema.optionalKey(Schema.String),
});
@@ -545,13 +546,19 @@ function normalizeProviderModelOptions(
? (candidate.claudeAgent as Record<string, unknown>)
: null;
const codexReasoningEffort = Schema.is(CodexReasoningEffort)(codexCandidate?.reasoningEffort)
? codexCandidate.reasoningEffort
: provider === "codex"
? Schema.is(CodexReasoningEffort)(legacy?.effort)
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")
? legacy.effort
: undefined
: undefined;
: undefined;
const codexFastMode =
codexCandidate?.fastMode === true
? true
@@ -575,9 +582,14 @@ function normalizeProviderModelOptions(
: claudeCandidate?.thinking === false
? false
: undefined;
const claudeEffort = Schema.is(ClaudeAgentEffort)(claudeCandidate?.effort)
? claudeCandidate.effort
: undefined;
const claudeEffort: ClaudeCodeEffort | undefined =
claudeCandidate?.effort === "low" ||
claudeCandidate?.effort === "medium" ||
claudeCandidate?.effort === "high" ||
claudeCandidate?.effort === "max" ||
claudeCandidate?.effort === "ultrathink"
? claudeCandidate.effort
: undefined;
const claudeFastMode =
claudeCandidate?.fastMode === true
? true
@@ -2146,6 +2158,9 @@ 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
@@ -1,221 +0,0 @@
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");
});
});
+48 -116
View File
@@ -1,22 +1,9 @@
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.
* Supports nested submenus and resolves with the clicked leaf item id.
* Shows a positioned dropdown and returns a promise that resolves
* with the clicked item id, or null if dismissed.
*/
export function showContextMenuFallback<T extends string>(
items: readonly ContextMenuItem<T>[],
@@ -26,117 +13,62 @@ export function showContextMenuFallback<T extends string>(
const overlay = document.createElement("div");
overlay.style.cssText = "position:fixed;inset:0;z-index:9999";
const menuStack: HTMLDivElement[] = [];
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 cleanup = (result: T | null) => {
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) {
document.removeEventListener("keydown", onKeyDown);
overlay.remove();
for (const menu of menuStack) {
menu.remove();
}
menu.remove();
resolve(result);
};
}
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
e.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);
openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
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`;
}
});
});
}
-21
View File
@@ -3,8 +3,6 @@ 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: {
@@ -20,9 +18,6 @@ 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,
@@ -57,11 +52,6 @@ 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;
}
@@ -73,14 +63,3 @@ 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();
}
+4 -165
View File
@@ -10,12 +10,7 @@ import {
type AppState,
type EnvironmentState,
} from "./store";
import {
deriveLogicalProjectKey,
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKey,
resolveProjectGroupingMode,
} from "./logicalProject";
import { deriveLogicalProjectKey } from "./logicalProject";
import type { Project, SidebarThreadSummary } from "./types";
import { DEFAULT_INTERACTION_MODE } from "./types";
@@ -36,10 +31,6 @@ 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 ──────────────────────────────────────────────────
@@ -247,7 +238,9 @@ describe("environment grouping", () => {
environmentId: primaryEnvId,
name: "local-only",
});
expect(deriveLogicalProjectKey(project)).toBe(derivePhysicalProjectKey(project));
const key = deriveLogicalProjectKey(project);
expect(key).toContain(primaryEnvId);
expect(key).toContain(localOnlyProjectId);
});
it("groups projects from different environments that share the same canonical key", () => {
@@ -280,134 +273,6 @@ 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,
@@ -421,32 +286,6 @@ 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", () => {
+4 -3
View File
@@ -13,7 +13,9 @@ import { Throttler } from "@tanstack/react-pacer";
import {
createKnownEnvironment,
getKnownEnvironmentWsBaseUrl,
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
@@ -60,7 +62,6 @@ 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;
@@ -469,7 +470,7 @@ function syncProjectUiFromStore() {
const projects = selectProjectsAcrossEnvironments(useStore.getState());
useUiStateStore.getState().syncProjects(
projects.map((project) => ({
key: derivePhysicalProjectKey(project),
key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
cwd: project.cwd,
})),
);
@@ -542,7 +543,7 @@ function applyRecoveredEventBatch(
const projects = selectProjectsAcrossEnvironments(useStore.getState());
useUiStateStore.getState().syncProjects(
projects.map((project) => ({
key: derivePhysicalProjectKey(project),
key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
cwd: project.cwd,
})),
);
-41
View File
@@ -1,41 +0,0 @@
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
@@ -1,57 +0,0 @@
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}` : ""}`;
}
+3 -8
View File
@@ -10,19 +10,14 @@ import {
} from "../composerDraftStore";
import { newDraftId, newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import { deriveLogicalProjectKey } 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 ?? {};
@@ -53,7 +48,7 @@ function useNewThreadState() {
candidate.environmentId === projectRef.environmentId,
);
const logicalProjectKey = project
? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)
? deriveLogicalProjectKey(project)
: scopedProjectKey(projectRef);
const hasBranchOption = options?.branch !== undefined;
const hasWorktreePathOption = options?.worktreePath !== undefined;
@@ -134,7 +129,7 @@ function useNewThreadState() {
});
})();
},
[getCurrentRouteTarget, projectGroupingSettings, router, projects],
[getCurrentRouteTarget, router, projects],
);
}
+3 -3
View File
@@ -19,7 +19,7 @@ import {
} from "@t3tools/contracts/settings";
import { ensureLocalApi } from "~/localApi";
import { Struct } from "effect";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { deepMerge } from "@t3tools/shared/Struct";
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({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
replaceClientSettingsSnapshot(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(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));
applySettingsUpdated(deepMerge(currentServerConfig.settings, serverPatch));
}
// Fire-and-forget RPC — push will reconcile on success
void ensureLocalApi().server.updateSettings(serverPatch);
@@ -0,0 +1,286 @@
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.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",
] 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.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"],
},
};
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 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.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;
}
},
[
closeFocusedWindow,
equalizeSplits,
focusAdjacentWindow,
focusWindowByStep,
focusedThreadRef,
focusedWindowId,
moveFocusedWindow,
openTerminalSurfaceForThread,
openWorkspaceTarget,
resizeFocusedWindow,
toggleFocusedWindowZoom,
],
);
return {
canOpenTerminalSurface: focusedThreadRef !== null,
canSplitFocusedPane: focusedWindowId !== null,
executeWorkspaceCommand,
focusedSurface,
focusedThreadRef,
focusedWindowId,
};
}
-59
View File
@@ -324,47 +324,6 @@ 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;
@@ -381,24 +340,6 @@ 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 184 files, more files were not shown because too many files have changed in this diff. Show more