Compare commits

...
Author SHA1 Message Date
Cursor Agent 689afc5e89 Remove unused highlightedItemValue from filterBrowseEntries
Remove the highlightedItemValue parameter and highlightedEntry computation
from filterBrowseEntries since the result was never destructured or used
by the caller. This eliminates unnecessary useMemo recomputation on every
hover/highlight change in the command palette.
2026-04-17 05:15:13 +00:00
Julius Marminge cb79e67b9a Prefetch browse parent and exact child paths
- Extract browse prefetch path selection into shared logic
- Warm parent directories and exact typed children only
2026-04-16 22:06:12 -07:00
Julius Marminge 505db9f696 try out blacksmith for releases (#2101) 2026-04-16 20:12:09 -07:00
t3-code[bot] 2d87574e62 chore(release): prepare v0.0.20 2026-04-17 03:00:57 +00:00
Julius Marminge b2cca674df ci(release): install deps before finalize version bump (#2100) 2026-04-16 19:42:17 -07:00
Julius Marminge 549043863a fix: guard against missing sidebarProjectGroupingOverrides in client settings (#2099) 2026-04-17 02:36:39 +00:00
Julius Marminge b7df3dfca0 [codex] Fix Windows release manifest publishing (#2095) 2026-04-16 17:56:16 -07:00
Evan YuandJulius Marminge 6891c77d3e Build for Windows ARM (#2080)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 17:01:27 -07:00
m9d5m d90e15d1d7 fix(server): extend negative repository identity cache ttl (#2083) 2026-04-16 16:57:39 -07:00
e0117b271a Fix Claude Process leak[MEMORY INTENSIVE], archiving, and stale claude session monitoring. (#2042)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-16 16:30:56 -07:00
188a40c315 feat: configurable project grouping (#2055)
Co-authored-by: tlh38 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-16 16:29:25 -07:00
Utkarsh Patil 7a08fcf2e8 fix(server): drop stale text generation options when resetting text-gen model selection (#2076) 2026-04-16 20:01:35 +00:00
Utkarsh Patil 19d47408a5 fix(web): prevent composer controls overlap on narrow windows (make plan sidebar responsive) (#1198) 2026-04-16 11:13:59 -07:00
Ibrahim ElkamaliandJulius Marminge 3e07f5a6a4 feat: add Claude Opus 4.7 to built-in models (#2072)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 11:11:59 -07:00
Marcus Grando d22c6f5280 fix: prevent user-input activities from leaking into pending approvals projection (#2051) 2026-04-16 05:09:29 +00:00
Marcus Grando 5e13f53571 fix: remove trailing newline from CLAUDE.md symlink (#2052) 2026-04-15 22:05:10 -07:00
f9580ff088 Default nightly desktop builds to the nightly update channel (#2049)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-15 21:31:24 -07:00
AndreiandJulius Marminge 5e1dd56d2c feat: add Launch Args setting for Claude provider (#1971)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 21:26:36 +00:00
legsandJulius Marminge 68061af042 Improve markdown file link UX (#1956)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 14:20:28 -07:00
Guilherme Vieira 28cb9db20b feat(web): add tooltip to composer file mention pill (#1944) 2026-04-15 13:29:13 -07:00
SakethandJulius Marminge 7968f278ee Fix terminal Cmd+Backspace on macOS (#2027)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 06:29:45 +00:00
44afe784a3 Add filesystem browse API and command palette project picker (#2024)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-14 23:26:05 -07:00
Julius Marmingeandcodex 9ff31f8c35 Fix nightly desktop product name (#2025)
Co-authored-by: codex <[email protected]>
2026-04-14 19:12:36 -07:00
409ff90a14 Nightly release channel (#2012)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-14 18:18:37 -07:00
160 changed files with 10081 additions and 1440 deletions

No files matched your search

+5 -2
View File
@@ -9,7 +9,7 @@ on:
jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -76,7 +76,7 @@ jobs:
release_smoke:
name: Release Smoke
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -92,5 +92,8 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+176 -47
View File
@@ -1,14 +1,24 @@
name: Release Desktop
name: Release
on:
push:
tags:
- "v*.*.*"
schedule:
- cron: "0 9 * * *"
workflow_dispatch:
inputs:
channel:
description: "Release channel"
required: false
default: stable
type: choice
options:
- stable
- nightly
version:
description: "Release version (for example 1.2.3 or v1.2.3)"
required: true
required: false
type: string
permissions:
@@ -18,43 +28,24 @@ permissions:
jobs:
preflight:
name: Preflight
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
outputs:
release_channel: ${{ steps.release_meta.outputs.release_channel }}
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
release_name: ${{ steps.release_meta.outputs.name }}
short_sha: ${{ steps.release_meta.outputs.short_sha }}
previous_tag: ${{ steps.previous_tag.outputs.previous_tag }}
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
make_latest: ${{ steps.release_meta.outputs.make_latest }}
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
- id: release_meta
name: Resolve release version
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
with:
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -69,6 +60,60 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- id: release_meta
name: Resolve release version
shell: bash
env:
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
DISPATCH_VERSION: ${{ github.event.inputs.version }}
NIGHTLY_DATE: ${{ github.run_started_at }}
NIGHTLY_SHA: ${{ github.sha }}
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
run: |
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
nightly_date="$(date -u -d "$NIGHTLY_DATE" +%Y%m%d)"
node scripts/resolve-nightly-release.ts \
--date "$nightly_date" \
--run-number "$NIGHTLY_RUN_NUMBER" \
--sha "$NIGHTLY_SHA" \
--github-output
echo "release_channel=nightly" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=nightly" >> "$GITHUB_OUTPUT"
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
else
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${DISPATCH_VERSION}"
if [[ -z "$raw" ]]; then
echo "workflow_dispatch stable releases require the version input." >&2
exit 1
fi
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "release_channel=stable" >> "$GITHUB_OUTPUT"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
echo "name=T3 Code v$version" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=latest" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
fi
- name: Lint
run: bun run lint
@@ -78,6 +123,14 @@ jobs:
- name: Test
run: bun run test
- id: previous_tag
name: Resolve previous release tag
run: |
node scripts/resolve-previous-release-tag.ts \
--channel "${{ steps.release_meta.outputs.release_channel }}" \
--current-tag "${{ steps.release_meta.outputs.tag }}" \
--github-output
build:
name: Build ${{ matrix.label }}
needs: preflight
@@ -88,25 +141,30 @@ jobs:
matrix:
include:
- label: macOS arm64
runner: macos-14
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: macos-15-intel
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: ubuntu-24.04
runner: blacksmith-32vcpu-ubuntu-2404
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: windows-2022
runner: blacksmith-32vcpu-windows-2025
platform: win
target: nsis
arch: x64
# - label: Windows arm64
# runner: windows-11-arm
# platform: win
# target: nsis
# arch: arm64
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -206,18 +264,31 @@ jobs:
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/latest*.yml"; do
"release/*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
if [[ -f release-publish/latest-mac.yml ]]; then
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
fi
shopt -s nullglob
for manifest in release-publish/*-mac.yml; do
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
done
fi
# Enable if Windows arm64 builds are enabled.
# Windows updater metadata is channel-specific (for example
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
# release job can merge matching arm64/x64 manifests back into one
# canonical manifest per channel.
# if [[ "${{ matrix.platform }}" == "win" ]]; then
# shopt -s nullglob
# for manifest in release-publish/*.yml; do
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
# done
# fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
@@ -228,7 +299,7 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -257,12 +328,12 @@ jobs:
run: bun run build --filter=@t3tools/web --filter=t3
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
release:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
@@ -284,17 +355,71 @@ jobs:
- name: Merge macOS updater manifests
run: |
node scripts/merge-mac-update-manifests.ts \
release-assets/latest-mac.yml \
release-assets/latest-mac-x64.yml
rm -f release-assets/latest-mac-x64.yml
shopt -s nullglob
for x64_manifest in release-assets/*-mac-x64.yml; do
arm64_manifest="${x64_manifest%-x64.yml}.yml"
if [[ -f "$arm64_manifest" ]]; then
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
rm -f "$x64_manifest"
fi
done
# - name: Merge Windows updater manifests
# run: |
# shopt -s nullglob
# found_windows_manifest=false
# for x64_manifest in release-assets/*-win-x64.yml; do
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
# continue
# fi
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
# if [[ ! -f "$arm64_manifest" ]]; then
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
# exit 1
# fi
# found_windows_manifest=true
# node scripts/merge-update-manifests.ts --platform win \
# "$arm64_manifest" \
# "$x64_manifest" \
# "$output_manifest"
# rm -f "$arm64_manifest" "$x64_manifest"
# done
# if [[ "$found_windows_manifest" != true ]]; then
# echo "No Windows updater manifests found to merge." >&2
# exit 1
# fi
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: T3 Code v${{ needs.preflight.outputs.version }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
previous_tag: ${{ needs.preflight.outputs.previous_tag }}
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
files: |
release-assets/*.dmg
release-assets/*.zip
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
@@ -304,13 +429,14 @@ jobs:
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/latest*.yml
release-assets/*.yml
fail_on_unmatched_files: true
finalize:
name: Finalize release
if: needs.preflight.outputs.release_channel == 'stable'
needs: [preflight, release]
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- id: app_token
@@ -349,6 +475,9 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- id: update_versions
name: Update version strings
env:
+2 -1
View File
@@ -10,7 +10,8 @@
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts"
"apps/web/src/lib/vendor/qrcodegen.ts",
"*.icon/**"
],
"sortPackageJson": {}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.17",
"version": "0.0.20",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+67 -1
View File
@@ -6,6 +6,7 @@ import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
@@ -23,6 +24,9 @@ const LAUNCHER_VERSION = 1;
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
const repoRoot = resolve(desktopDir, "..", "..");
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
@@ -43,6 +47,68 @@ function setPlistString(plistPath, key, value) {
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
}
function runChecked(command, args) {
const result = spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
return;
}
const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
if (!existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
}
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
return generatedIconPath;
}
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = join(iconsetRoot, "icon.iconset");
mkdirSync(iconsetDir, { recursive: true });
try {
for (const size of [16, 32, 128, 256, 512]) {
runChecked("sips", [
"-z",
String(size),
String(size),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}.png`),
]);
const retinaSize = size * 2;
runChecked("sips", [
"-z",
String(retinaSize),
String(retinaSize),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
}
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
return generatedIconPath;
} catch (error) {
console.warn(
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
error,
);
return defaultIconPath;
} finally {
rmSync(iconsetRoot, { recursive: true, force: true });
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
@@ -102,7 +168,7 @@ function buildMacLauncher(electronBinaryPath) {
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = join(desktopDir, "resources", "icon.icns");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding";
describe("resolveDesktopAppStageLabel", () => {
it("uses Dev in desktop development", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: true,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toBe("Dev");
});
it("uses Nightly for packaged nightly builds", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: false,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toBe("Nightly");
});
it("uses Alpha for packaged stable builds", () => {
expect(
resolveDesktopAppStageLabel({
isDevelopment: false,
appVersion: "0.0.17",
}),
).toBe("Alpha");
});
});
describe("resolveDesktopAppBranding", () => {
it("returns a complete desktop branding payload", () => {
expect(
resolveDesktopAppBranding({
isDevelopment: false,
appVersion: "0.0.17-nightly.20260414.1",
}),
).toEqual({
baseName: "T3 Code",
stageLabel: "Nightly",
displayName: "T3 Code (Nightly)",
});
});
});
+28
View File
@@ -0,0 +1,28 @@
import type { DesktopAppBranding, DesktopAppStageLabel } from "@t3tools/contracts";
import { isNightlyDesktopVersion } from "./updateChannels";
const APP_BASE_NAME = "T3 Code";
export function resolveDesktopAppStageLabel(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppStageLabel {
if (input.isDevelopment) {
return "Dev";
}
return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Alpha";
}
export function resolveDesktopAppBranding(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppBranding {
const stageLabel = resolveDesktopAppStageLabel(input);
return {
baseName: APP_BASE_NAME,
stageLabel,
displayName: `${APP_BASE_NAME} (${stageLabel})`,
};
}
@@ -52,6 +52,10 @@ const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
},
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
+15 -2
View File
@@ -1,8 +1,13 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import {
ClientSettingsSchema,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { Predicate } from "effect";
import * as Schema from "effect/Schema";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
@@ -83,7 +88,15 @@ function toPersistedSavedEnvironmentRecord(
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
if (!raw) {
return null;
}
try {
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
} catch {
return null;
}
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
+86 -3
View File
@@ -7,7 +7,9 @@ import { afterEach, describe, expect, it } from "vitest";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
resolveDefaultDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings";
@@ -27,7 +29,15 @@ function makeSettingsPath() {
describe("desktopSettings", () => {
it("returns defaults when no settings file exists", () => {
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
expect(readDesktopSettings(makeSettingsPath(), "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("defaults packaged nightly builds to the nightly update channel", () => {
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("persists and reloads the configured server exposure mode", () => {
@@ -35,10 +45,14 @@ describe("desktopSettings", () => {
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath)).toEqual({
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
@@ -47,11 +61,32 @@ describe("desktopSettings", () => {
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
"network-accessible",
),
).toEqual({
serverExposureMode: "network-accessible",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("persists the requested nightly update channel", () => {
expect(
setDesktopUpdateChannelPreference(
{
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
"nightly",
),
).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
});
});
@@ -59,6 +94,54 @@ describe("desktopSettings", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, "{not-json", "utf8");
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("falls back to the nightly channel for legacy nightly settings without an update track", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, JSON.stringify({ serverExposureMode: "local-only" }), "utf8");
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("migrates legacy implicit stable settings to nightly when running a nightly build", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
serverExposureMode: "local-only",
updateChannel: "latest",
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
});
it("preserves an explicit stable choice on nightly builds", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
});
+45 -4
View File
@@ -1,15 +1,28 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
}
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: false,
};
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
return {
...DEFAULT_DESKTOP_SETTINGS,
updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
};
}
export function setDesktopServerExposurePreference(
settings: DesktopSettings,
requestedMode: DesktopServerExposureMode,
@@ -22,23 +35,51 @@ export function setDesktopServerExposurePreference(
};
}
export function readDesktopSettings(settingsPath: string): DesktopSettings {
export function setDesktopUpdateChannelPreference(
settings: DesktopSettings,
requestedChannel: DesktopUpdateChannel,
): DesktopSettings {
return {
...settings,
updateChannel: requestedChannel,
updateChannelConfiguredByUser: true,
};
}
export function readDesktopSettings(settingsPath: string, appVersion: string): DesktopSettings {
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
try {
if (!FS.existsSync(settingsPath)) {
return DEFAULT_DESKTOP_SETTINGS;
return defaultSettings;
}
const raw = FS.readFileSync(settingsPath, "utf8");
const parsed = JSON.parse(raw) as {
readonly serverExposureMode?: unknown;
readonly updateChannel?: unknown;
readonly updateChannelConfiguredByUser?: unknown;
};
const parsedUpdateChannel =
parsed.updateChannel === "nightly" || parsed.updateChannel === "latest"
? parsed.updateChannel
: null;
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
const updateChannelConfiguredByUser =
parsed.updateChannelConfiguredByUser === true ||
(isLegacySettings && parsedUpdateChannel === "nightly");
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
updateChannel:
updateChannelConfiguredByUser && parsedUpdateChannel !== null
? parsedUpdateChannel
: defaultSettings.updateChannel,
updateChannelConfiguredByUser,
};
} catch {
return DEFAULT_DESKTOP_SETTINGS;
return defaultSettings;
}
}
+196 -49
View File
@@ -18,12 +18,14 @@ import {
safeStorage,
shell,
} from "electron";
import type { MenuItemConstructorOptions } from "electron";
import type { MenuItemConstructorOptions, OpenDialogOptions } from "electron";
import type {
ClientSettings,
DesktopTheme,
DesktopAppBranding,
DesktopServerExposureMode,
DesktopServerExposureState,
DesktopUpdateChannel,
PersistedSavedEnvironmentRecord,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
@@ -39,6 +41,7 @@ import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings";
import {
@@ -55,6 +58,7 @@ import { showDesktopConfirmDialog } from "./confirmDialog";
import { resolveDesktopServerExposure } from "./serverExposure";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels";
import { ServerListeningDetector } from "./serverListeningDetector";
import {
createInitialDesktopUpdateState,
@@ -69,6 +73,7 @@ import {
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
import { resolveDesktopAppBranding } from "./appBranding";
syncShellEnvironment();
@@ -80,9 +85,11 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -101,7 +108,11 @@ const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
isDevelopment,
appVersion: app.getVersion(),
});
const APP_DISPLAY_NAME = desktopAppBranding.displayName;
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
@@ -116,8 +127,32 @@ const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
const DESKTOP_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
function resolvePickFolderDefaultPath(rawOptions: unknown): string | undefined {
if (typeof rawOptions !== "object" || rawOptions === null) {
return undefined;
}
const { initialPath } = rawOptions as { initialPath?: unknown };
if (typeof initialPath !== "string") {
return undefined;
}
const trimmedPath = initialPath.trim();
if (trimmedPath.length === 0) {
return undefined;
}
if (trimmedPath === "~") {
return OS.homedir();
}
if (trimmedPath.startsWith("~/") || trimmedPath.startsWith("~\\")) {
return Path.join(OS.homedir(), trimmedPath.slice(2));
}
return Path.resolve(trimmedPath);
}
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
const TITLEBAR_HEIGHT = 40;
@@ -125,6 +160,35 @@ const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linu
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
for (const sourceItem of source) {
if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
destructive: sourceItem.destructive === true,
disabled: sourceItem.disabled === true,
};
if (sourceItem.children) {
const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
if (normalizedChildren.length === 0) {
continue;
}
normalizedItem.children = normalizedChildren;
}
normalizedItems.push(normalizedItem);
}
return normalizedItems;
}
type WindowTitleBarOptions = Pick<
BrowserWindowConstructorOptions,
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
@@ -156,7 +220,7 @@ let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH, app.getVersion());
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
@@ -167,7 +231,11 @@ const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
createInitialDesktopUpdateState(
app.getVersion(),
desktopRuntimeInfo,
desktopSettings.updateChannel,
);
function logTimestamp(): string {
return new Date().toISOString();
@@ -975,6 +1043,18 @@ function resolveResourcePath(fileName: string): string | null {
}
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
if (isDevelopment && process.platform === "darwin" && ext === "png") {
const developmentDockIconPath = Path.join(
ROOT_DIR,
"assets",
"dev",
"blueprint-macos-1024.png",
);
if (FS.existsSync(developmentDockIconPath)) {
return developmentDockIconPath;
}
}
return resolveResourcePath(`icon.${ext}`);
}
@@ -1074,6 +1154,26 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
emitUpdateState();
}
function createBaseUpdateState(
channel: DesktopUpdateChannel,
enabled: boolean,
): DesktopUpdateState {
return {
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo, channel),
enabled,
status: enabled ? "idle" : "disabled",
};
}
function applyAutoUpdaterChannel(channel: DesktopUpdateChannel): void {
autoUpdater.channel = channel;
autoUpdater.allowPrerelease = channel === "nightly";
autoUpdater.allowDowngrade = channel === "nightly";
console.info(
`[desktop-updater] Using update channel '${channel}' (allowPrerelease=${channel === "nightly"}, allowDowngrade=${channel === "nightly"}).`,
);
}
function shouldEnableAutoUpdates(): boolean {
const hasUpdateFeedConfig =
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
@@ -1193,11 +1293,7 @@ function configureAutoUpdater(): void {
}
const enabled = shouldEnableAutoUpdates();
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
setUpdateState(createBaseUpdateState(desktopSettings.updateChannel, enabled));
if (!enabled) {
return;
}
@@ -1205,10 +1301,7 @@ function configureAutoUpdater(): void {
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
// Keep alpha branding, but force all installs onto the stable update track.
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
autoUpdater.allowDowngrade = false;
applyAutoUpdaterChannel(desktopSettings.updateChannel);
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
let lastLoggedDownloadMilestone = -1;
@@ -1222,6 +1315,15 @@ function configureAutoUpdater(): void {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
if (!doesVersionMatchDesktopUpdateChannel(info.version, updateState.channel)) {
console.info(
`[desktop-updater] Ignoring ${info.version} because it does not match the selected '${updateState.channel}' channel.`,
);
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
lastLoggedDownloadMilestone = -1;
return;
}
setUpdateState(
reduceDesktopUpdateStateOnUpdateAvailable(
updateState,
@@ -1486,6 +1588,11 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
}
function registerIpcHandlers(): void {
ipcMain.removeAllListeners(GET_APP_BRANDING_CHANNEL);
ipcMain.on(GET_APP_BRANDING_CHANNEL, (event) => {
event.returnValue = desktopAppBranding;
});
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
event.returnValue = {
@@ -1599,15 +1706,16 @@ function registerIpcHandlers(): void {
});
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
const defaultPath = resolvePickFolderDefaultPath(rawOptions);
const openDialogOptions: OpenDialogOptions = {
properties: ["openDirectory", "createDirectory"],
...(defaultPath ? { defaultPath } : {}),
};
const result = owner
? await dialog.showOpenDialog(owner, {
properties: ["openDirectory", "createDirectory"],
})
: await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
});
? await dialog.showOpenDialog(owner, openDialogOptions)
: await dialog.showOpenDialog(openDialogOptions);
if (result.canceled) return null;
return result.filePaths[0] ?? null;
});
@@ -1636,14 +1744,7 @@ function registerIpcHandlers(): void {
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
const normalizedItems = items
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
.map((item) => ({
id: item.id,
label: item.label,
destructive: item.destructive === true,
disabled: item.disabled === true,
}));
const normalizedItems = normalizeContextMenuItems(items);
if (normalizedItems.length === 0) {
return null;
}
@@ -1664,28 +1765,37 @@ function registerIpcHandlers(): void {
if (!window) return null;
return new Promise<string | null>((resolve) => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of normalizedItems) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
click: () => resolve(item.id),
};
if (item.destructive) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
const buildTemplate = (
entries: readonly ContextMenuItem[],
): MenuItemConstructorOptions[] => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children);
} else {
itemOption.click = () => resolve(item.id);
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
}
}
template.push(itemOption);
}
template.push(itemOption);
}
return template;
};
const menu = Menu.buildFromTemplate(template);
const menu = Menu.buildFromTemplate(buildTemplate(normalizedItems));
menu.popup({
window,
...popupPosition,
@@ -1713,6 +1823,43 @@ function registerIpcHandlers(): void {
ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
ipcMain.removeHandler(UPDATE_SET_CHANNEL_CHANNEL);
ipcMain.handle(UPDATE_SET_CHANNEL_CHANNEL, async (_event, rawChannel: unknown) => {
if (rawChannel !== "latest" && rawChannel !== "nightly") {
throw new Error("Invalid desktop update channel input.");
}
if (updateCheckInFlight || updateDownloadInFlight || updateInstallInFlight) {
throw new Error("Cannot change update tracks while an update action is in progress.");
}
const nextChannel = rawChannel as DesktopUpdateChannel;
desktopSettings = setDesktopUpdateChannelPreference(desktopSettings, nextChannel);
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
if (nextChannel === updateState.channel) {
return updateState;
}
const enabled = shouldEnableAutoUpdates();
setUpdateState(createBaseUpdateState(nextChannel, enabled));
if (!enabled || !updaterConfigured) {
return updateState;
}
applyAutoUpdaterChannel(nextChannel);
const allowDowngrade = autoUpdater.allowDowngrade;
// An explicit channel switch should allow the immediate nightly->stable rollback path.
autoUpdater.allowDowngrade = true;
try {
await checkForUpdates("channel-change");
} finally {
autoUpdater.allowDowngrade = allowDowngrade;
}
return updateState;
});
ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
const result = await downloadAvailableUpdate();
+11 -1
View File
@@ -9,9 +9,11 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
@@ -24,6 +26,13 @@ const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
const result = ipcRenderer.sendSync(GET_APP_BRANDING_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
@@ -44,7 +53,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
@@ -61,6 +70,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) => ipcRenderer.invoke(UPDATE_SET_CHANNEL_CHANNEL, channel),
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import {
doesVersionMatchDesktopUpdateChannel,
isNightlyDesktopVersion,
resolveDefaultDesktopUpdateChannel,
} from "./updateChannels";
describe("isNightlyDesktopVersion", () => {
it("detects packaged nightly versions", () => {
expect(isNightlyDesktopVersion("0.0.17-nightly.20260415.1")).toBe(true);
});
it("does not flag stable versions as nightly", () => {
expect(isNightlyDesktopVersion("0.0.17")).toBe(false);
});
});
describe("resolveDefaultDesktopUpdateChannel", () => {
it("defaults stable builds to latest", () => {
expect(resolveDefaultDesktopUpdateChannel("0.0.17")).toBe("latest");
});
it("defaults nightly builds to nightly", () => {
expect(resolveDefaultDesktopUpdateChannel("0.0.17-nightly.20260415.1")).toBe("nightly");
});
});
describe("doesVersionMatchDesktopUpdateChannel", () => {
it("accepts nightly releases on the nightly channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "nightly")).toBe(true);
});
it("rejects stable releases on the nightly channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17", "nightly")).toBe(false);
});
it("rejects nightly releases on the stable channel", () => {
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "latest")).toBe(false);
});
});
+18
View File
@@ -0,0 +1,18 @@
import type { DesktopUpdateChannel } from "@t3tools/contracts";
const NIGHTLY_VERSION_PATTERN = /-nightly\.\d{8}\.\d+$/;
export function isNightlyDesktopVersion(version: string): boolean {
return NIGHTLY_VERSION_PATTERN.test(version);
}
export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
return isNightlyDesktopVersion(appVersion) ? "nightly" : "latest";
}
export function doesVersionMatchDesktopUpdateChannel(
version: string,
channel: DesktopUpdateChannel,
): boolean {
return resolveDefaultDesktopUpdateChannel(version) === channel;
}
+7 -6
View File
@@ -23,7 +23,7 @@ describe("updateMachine", () => {
it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "error",
message: "network",
@@ -42,7 +42,7 @@ describe("updateMachine", () => {
it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "checking",
},
@@ -58,7 +58,7 @@ describe("updateMachine", () => {
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -76,7 +76,7 @@ describe("updateMachine", () => {
it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -98,7 +98,7 @@ describe("updateMachine", () => {
it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "error",
availableVersion: "1.1.0",
@@ -120,7 +120,7 @@ describe("updateMachine", () => {
it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
enabled: true,
status: "checking",
},
@@ -131,6 +131,7 @@ describe("updateMachine", () => {
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
expect(available.status).toBe("available");
expect(available.channel).toBe("latest");
expect(downloading.status).toBe("downloading");
expect(downloading.downloadPercent).toBe(0);
expect(progress.downloadPercent).toBe(55.5);
+7 -1
View File
@@ -1,14 +1,20 @@
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
import type {
DesktopRuntimeInfo,
DesktopUpdateChannel,
DesktopUpdateState,
} from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
export function createInitialDesktopUpdateState(
currentVersion: string,
runtimeInfo: DesktopRuntimeInfo,
channel: DesktopUpdateChannel,
): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
channel,
currentVersion,
hostArch: runtimeInfo.hostArch,
appArch: runtimeInfo.appArch,
+1
View File
@@ -11,6 +11,7 @@ import {
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.17",
"version": "0.0.20",
"license": "MIT",
"repository": {
"type": "git",
@@ -20,10 +20,11 @@
"start": "node dist/bin.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
"test": "vitest run",
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
@@ -470,6 +470,154 @@ describe("startSession", () => {
manager.stopAll();
}
});
it("disposes an existing session before starting a replacement for the same thread", async () => {
const manager = new CodexAppServerManager();
const existingContext = {
session: {
provider: "codex",
status: "ready",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.set(asThreadId("thread-1"), existingContext);
const disposeSession = vi
.spyOn(
manager as unknown as {
disposeSession: (
context: typeof existingContext,
options?: { readonly emitLifecycleEvent?: boolean },
) => void;
},
"disposeSession",
)
.mockImplementation(() => {});
const assertSupportedCodexCliVersion = vi
.spyOn(
manager as unknown as {
assertSupportedCodexCliVersion: (input: {
binaryPath: string;
cwd: string;
homePath?: string;
}) => void;
},
"assertSupportedCodexCliVersion",
)
.mockImplementation(() => {});
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("cwd missing");
});
try {
await expect(
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow("cwd missing");
expect(disposeSession).toHaveBeenCalledWith(existingContext, {
emitLifecycleEvent: false,
});
expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
} finally {
disposeSession.mockRestore();
assertSupportedCodexCliVersion.mockRestore();
processCwd.mockRestore();
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.clear();
manager.stopAll();
}
});
it("continues replacement start when existing session disposal fails", async () => {
const manager = new CodexAppServerManager();
const existingContext = {
session: {
provider: "codex",
status: "ready",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.set(asThreadId("thread-1"), existingContext);
const disposeSession = vi
.spyOn(
manager as unknown as {
disposeSession: (
context: typeof existingContext,
options?: { readonly emitLifecycleEvent?: boolean },
) => void;
},
"disposeSession",
)
.mockImplementation(() => {
throw new Error("dispose failed");
});
const assertSupportedCodexCliVersion = vi
.spyOn(
manager as unknown as {
assertSupportedCodexCliVersion: (input: {
binaryPath: string;
cwd: string;
homePath?: string;
}) => void;
},
"assertSupportedCodexCliVersion",
)
.mockImplementation(() => {});
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("cwd missing");
});
try {
await expect(
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow("cwd missing");
expect(disposeSession).toHaveBeenCalledWith(existingContext, {
emitLifecycleEvent: false,
});
expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
} finally {
disposeSession.mockRestore();
assertSupportedCodexCliVersion.mockRestore();
processCwd.mockRestore();
(
manager as unknown as {
sessions: Map<ThreadId, typeof existingContext>;
}
).sessions.clear();
manager.stopAll();
}
});
});
describe("sendTurn", () => {
+36 -2
View File
@@ -450,6 +450,25 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
let context: CodexSessionContext | undefined;
try {
const existingContext = this.sessions.get(threadId);
if (existingContext) {
await Effect.logWarning("codex app-server replacing existing session", {
threadId,
existingStatus: existingContext.session.status,
}).pipe(this.runPromise);
try {
this.disposeSession(existingContext, {
emitLifecycleEvent: false,
});
} catch (error) {
await Effect.logWarning("codex app-server failed to dispose existing session", {
threadId,
existingStatus: existingContext.session.status,
cause: error instanceof Error ? error.message : String(error),
}).pipe(this.runPromise);
}
}
const resolvedCwd = input.cwd ?? process.cwd();
const session: ProviderSession = {
@@ -901,6 +920,19 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return;
}
this.disposeSession(context, {
emitLifecycleEvent: true,
});
}
private disposeSession(
context: CodexSessionContext,
options?: { readonly emitLifecycleEvent?: boolean },
): void {
if (context.stopping) {
return;
}
context.stopping = true;
for (const pending of context.pending.values()) {
@@ -921,8 +953,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
status: "closed",
activeTurnId: undefined,
});
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
this.sessions.delete(threadId);
if (options?.emitLifecycleEvent !== false) {
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
}
this.sessions.delete(context.session.threadId);
}
listSessions(): ProviderSession[] {
@@ -166,6 +166,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
[
"exec",
"--ephemeral",
"--skip-git-repo-check",
"-s",
"read-only",
"--model",
@@ -1284,6 +1284,14 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
return;
}
// Only approval-requested activities should create pending-approval
// rows. Other activity kinds that happen to carry a requestId
// (e.g. user-input.requested / user-input.resolved) must not
// pollute this projection — they have their own accounting via
// derivePendingUserInputCountFromActivities.
if (event.payload.activity.kind !== "approval.requested") {
return;
}
if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
return;
}
+22 -1
View File
@@ -28,10 +28,31 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
),
);
const normalizeProjectWorkspaceRootForCreate = (
workspaceRoot: string,
createIfMissing: boolean | undefined,
) =>
workspacePaths
.normalizeWorkspaceRoot(workspaceRoot, {
createIfMissing: createIfMissing === true,
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationDispatchCommandError({
message: cause.message,
}),
),
);
if (command.type === "project.create") {
return {
...command,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(
command.workspaceRoot,
command.createWorkspaceRootIfMissing,
),
createWorkspaceRootIfMissing: command.createWorkspaceRootIfMissing === true,
} satisfies OrchestrationCommand;
}
@@ -1,3 +1,5 @@
import { realpathSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Duration, Effect, FileSystem, Layer } from "effect";
@@ -10,6 +12,10 @@ import {
RepositoryIdentityResolverLive,
} from "./RepositoryIdentityResolver.ts";
const normalizePathSeparators = (value: string) => value.replaceAll("\\", "/");
const normalizeResolvedPath = (value: string) =>
normalizePathSeparators(realpathSync.native(value));
const git = (cwd: string, args: ReadonlyArray<string>) =>
Effect.promise(() => runProcess("git", ["-C", cwd, ...args]));
@@ -41,6 +47,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(cwd));
expect(identity?.displayName).toBe("t3tools/t3code");
expect(identity?.provider).toBe("github");
expect(identity?.owner).toBe("t3tools");
@@ -48,6 +55,27 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
);
it.effect("returns the git top-level root path when resolving from a nested workspace", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const repoRoot = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-repository-identity-nested-root-test-",
});
const nestedWorkspace = `${repoRoot}/packages/web`;
yield* fileSystem.makeDirectory(nestedWorkspace, { recursive: true });
yield* git(repoRoot, ["init"]);
yield* git(repoRoot, ["remote", "add", "origin", "[email protected]:T3Tools/t3code.git"]);
const resolver = yield* RepositoryIdentityResolver;
const identity = yield* resolver.resolve(nestedWorkspace);
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(repoRoot));
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
);
it.effect("returns null for non-git folders and repos without remotes", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -112,7 +140,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
);
it.effect(
"refreshes cached null identities after the negative TTL when a remote is configured later",
"keeps null identities cached across repeated resolves until the negative TTL expires",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -128,8 +156,10 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
yield* git(cwd, ["remote", "add", "origin", "[email protected]:T3Tools/t3code.git"]);
const cachedIdentity = yield* resolver.resolve(cwd);
expect(cachedIdentity).toBeNull();
for (const _attempt of [1, 2, 3]) {
const cachedIdentity = yield* resolver.resolve(cwd);
expect(cachedIdentity).toBeNull();
}
yield* TestClock.adjust(Duration.millis(120));
@@ -42,6 +42,7 @@ function pickPrimaryRemote(
function buildRepositoryIdentity(input: {
readonly remoteName: string;
readonly remoteUrl: string;
readonly rootPath: string;
}): RepositoryIdentity {
const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
const hostingProvider = detectGitHostingProviderFromRemoteUrl(input.remoteUrl);
@@ -57,6 +58,7 @@ function buildRepositoryIdentity(input: {
remoteName: input.remoteName,
remoteUrl: input.remoteUrl,
},
rootPath: input.rootPath,
...(repositoryPath ? { displayName: repositoryPath } : {}),
...(hostingProvider ? { provider: hostingProvider.kind } : {}),
...(owner ? { owner } : {}),
@@ -66,7 +68,7 @@ function buildRepositoryIdentity(input: {
const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(1);
const DEFAULT_NEGATIVE_CACHE_TTL = Duration.seconds(10);
const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
interface RepositoryIdentityResolverOptions {
readonly cacheCapacity?: number;
@@ -108,7 +110,7 @@ async function resolveRepositoryIdentityFromCacheKey(
}
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.stdout));
return remote ? buildRepositoryIdentity(remote) : null;
return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
} catch {
return null;
}
@@ -351,6 +351,53 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("maps the Claude Opus 4.7 default effort to the SDK-supported max value", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-7",
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "max");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("maps xhigh effort for Claude Opus 4.7 to the SDK-supported max value", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-7",
options: {
effort: "xhigh",
},
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "max");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -1260,6 +1307,71 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("closes the previous session before replacing an existing thread session", () => {
const queries: FakeClaudeQuery[] = [];
const layer = makeClaudeAdapterLive({
createQuery: () => {
const query = new FakeClaudeQuery();
queries.push(query);
return query;
},
}).pipe(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
Stream.runCollect,
Effect.forkChild,
);
const firstSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
const secondSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
resumeCursor: firstSession.resumeCursor,
});
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const activeSessions = yield* adapter.listSessions();
assert.equal(queries.length, 2);
assert.equal(queries[0]?.closeCalls, 1);
assert.equal(queries[1]?.closeCalls, 0);
assert.equal(yield* adapter.hasSession(THREAD_ID), true);
assert.equal(activeSessions.length, 1);
assert.deepEqual(activeSessions[0]?.resumeCursor, secondSession.resumeCursor);
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"session.started",
"session.configured",
"session.state.changed",
],
);
assert.equal(
runtimeEvents.some((event) => event.type === "session.exited"),
false,
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(layer),
);
});
it.effect("stopSession does not throw into the SDK prompt consumer", () => {
// The SDK consumes user messages via `for await (... of prompt)`.
// Stopping a session must end that loop cleanly — not throw an error.
+114 -29
View File
@@ -18,8 +18,8 @@ import {
type SettingSource,
type SDKUserMessage,
ModelUsage,
NonNullableUsage,
} from "@anthropic-ai/claude-agent-sdk";
import { parseCliArgs } from "@t3tools/shared/cliArgs";
import {
ApprovalRequestId,
type CanonicalItemType,
@@ -40,7 +40,7 @@ import {
ThreadId,
TurnId,
type UserInputQuestion,
ClaudeCodeEffort,
ClaudeAgentEffort,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
@@ -84,6 +84,7 @@ type ClaudeToolResultStreamKind = Extract<
RuntimeContentStreamKind,
"command_output" | "file_change_output"
>;
type ClaudeSdkEffort = NonNullable<ClaudeQueryOptions["effort"]>;
type PromptQueueItem =
| {
@@ -215,13 +216,19 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray
return squashed.length > 0 ? [squashed] : [];
}
function getEffectiveClaudeCodeEffort(
effort: ClaudeCodeEffort | null | undefined,
): Exclude<ClaudeCodeEffort, "ultrathink"> | null {
function getEffectiveClaudeAgentEffort(
effort: ClaudeAgentEffort | null | undefined,
): ClaudeSdkEffort | null {
if (!effort) {
return null;
}
return effort === "ultrathink" ? null : effort;
if (effort === "ultrathink") {
return null;
}
if (effort === "xhigh") {
return "max";
}
return effort;
}
function isClaudeInterruptedMessage(message: string): boolean {
@@ -289,7 +296,7 @@ function maxClaudeContextWindowFromModelUsage(
}
function normalizeClaudeTokenUsage(
value: NonNullableUsage | undefined,
value: unknown,
contextWindow?: number,
): ThreadTokenUsageSnapshot | undefined {
if (!value || typeof value !== "object") {
@@ -463,7 +470,10 @@ function isTodoTool(toolName: string): boolean {
return toolName.toLowerCase().includes("todowrite");
}
type PlanStep = { step: string; status: "pending" | "inProgress" | "completed" };
type PlanStep = {
step: string;
status: "pending" | "inProgress" | "completed";
};
function extractPlanStepsFromTodoInput(input: Record<string, unknown>): PlanStep[] | null {
// TodoWrite format: { todos: [{ content, status, activeForm? }] }
@@ -966,7 +976,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
((input: {
readonly prompt: AsyncIterable<SDKUserMessage>;
readonly options: ClaudeQueryOptions;
}) => query({ prompt: input.prompt, options: input.options }) as ClaudeQueryRuntime);
}) =>
query({
prompt: input.prompt,
options: input.options,
}) as ClaudeQueryRuntime);
const sessions = new Map<ThreadId, ClaudeSessionContext>();
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
@@ -1005,7 +1019,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(typeof message.session_id === "string"
? { providerThreadId: message.session_id }
: {}),
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
...(itemId ? { itemId: ProviderItemId.make(itemId) } : {}),
payload: message,
},
@@ -1394,7 +1412,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(typeof accumulatedTotalProcessedTokens === "number" &&
Number.isFinite(accumulatedTotalProcessedTokens) &&
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
? { totalProcessedTokens: accumulatedTotalProcessedTokens }
? {
totalProcessedTokens: accumulatedTotalProcessedTokens,
}
: {}),
}
: accumulatedSnapshot;
@@ -1458,7 +1478,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
input: tool.input,
},
},
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
raw: {
source: "claude.sdk.message",
method: "claude/result",
@@ -1580,7 +1602,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
threadId: context.session.threadId,
turnId: context.turnState.turnId,
...(assistantBlockEntry?.block
? { itemId: asRuntimeItemId(assistantBlockEntry.block.itemId) }
? {
itemId: asRuntimeItemId(assistantBlockEntry.block.itemId),
}
: {}),
payload: {
streamKind,
@@ -1639,7 +1663,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
itemId: asRuntimeItemId(nextTool.itemId),
payload: {
itemType: nextTool.itemType,
@@ -1651,7 +1679,9 @@ 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",
@@ -1670,7 +1700,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
provider: PROVIDER,
createdAt: planStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
payload: {
plan: planSteps,
},
@@ -1740,7 +1774,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
input: toolInput,
},
},
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
raw: {
source: "claude.sdk.message",
method: "claude/stream_event/content_block_start",
@@ -1812,7 +1848,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(tool.detail ? { detail: tool.detail } : {}),
data: toolData,
},
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
raw: {
source: "claude.sdk.message",
method: "claude/user",
@@ -1835,7 +1873,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
streamKind,
delta: toolResult.text,
},
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
raw: {
source: "claude.sdk.message",
method: "claude/user",
@@ -1860,7 +1900,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(tool.detail ? { detail: tool.detail } : {}),
data: toolData,
},
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
raw: {
source: "claude.sdk.message",
method: "claude/user",
@@ -2216,7 +2258,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
payload: {
summary: message.summary,
...(message.preceding_tool_use_ids.length > 0
? { precedingToolUseIds: message.preceding_tool_use_ids }
? {
precedingToolUseIds: message.preceding_tool_use_ids,
}
: {}),
},
});
@@ -2433,6 +2477,27 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
const existingContext = sessions.get(input.threadId);
if (existingContext) {
yield* Effect.logWarning("claude.session.replacing", {
threadId: input.threadId,
existingSessionStatus: existingContext.session.status,
reason: "startSession called with existing active session",
});
yield* stopSessionInternal(existingContext, {
emitExitEvent: false,
}).pipe(
// Replacement cleanup is best-effort: never block the new session on
// either typed failures or unexpected defects from tearing down the old one.
Effect.catchCause((cause) =>
Effect.logWarning("claude.session.replace.stop-failed", {
threadId: input.threadId,
cause,
}),
),
);
}
const startedAt = yield* nowIso;
const resumeState = readClaudeResumeState(input.resumeCursor);
const threadId = input.threadId;
@@ -2468,7 +2533,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const handleAskUserQuestion = Effect.fn("handleAskUserQuestion")(function* (
context: ClaudeSessionContext,
toolInput: Record<string, unknown>,
callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string },
callbackOptions: {
readonly signal: AbortSignal;
readonly toolUseID?: string;
},
) {
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
@@ -2504,7 +2572,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
provider: PROVIDER,
createdAt: requestedStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
requestId: asRuntimeRequestId(requestId),
payload: { questions },
providerRefs: nativeProviderRefs(context, {
@@ -2513,7 +2585,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
raw: {
source: "claude.sdk.permission",
method: "canUseTool/AskUserQuestion",
payload: { toolName: "AskUserQuestion", input: toolInput },
payload: {
toolName: "AskUserQuestion",
input: toolInput,
},
},
});
@@ -2528,7 +2603,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
pendingUserInputs.delete(requestId);
runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers));
};
callbackOptions.signal.addEventListener("abort", onAbort, { once: true });
callbackOptions.signal.addEventListener("abort", onAbort, {
once: true,
});
// Block until the user provides answers.
const answers = yield* Deferred.await(answersDeferred);
@@ -2542,7 +2619,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
provider: PROVIDER,
createdAt: resolvedStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
requestId: asRuntimeRequestId(requestId),
payload: { answers },
providerRefs: nativeProviderRefs(context, {
@@ -2712,7 +2793,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
behavior: "allow",
updatedInput: toolInput,
...(decision === "acceptForSession" && pendingApproval.suggestions
? { updatedPermissions: [...pendingApproval.suggestions] }
? {
updatedPermissions: [...pendingApproval.suggestions],
}
: {}),
} satisfies PermissionResult;
}
@@ -2742,18 +2825,19 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
),
);
const claudeBinaryPath = claudeSettings.binaryPath;
const extraArgs = parseCliArgs(claudeSettings.launchArgs).flags;
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
const caps = getClaudeModelCapabilities(modelSelection?.model);
const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
null) as ClaudeCodeEffort | null;
null) as ClaudeAgentEffort | null;
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
const thinking =
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
? modelSelection.options.thinking
: undefined;
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
const effectiveEffort = getEffectiveClaudeAgentEffort(effort);
const runtimeModeToPermission: Record<string, PermissionMode> = {
"auto-accept-edits": "acceptEdits",
"full-access": "bypassPermissions",
@@ -2781,6 +2865,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
canUseTool,
env: process.env,
...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
};
const queryRuntime = yield* Effect.try({
@@ -26,6 +26,7 @@ import {
spawnAndCollect,
type CommandResult,
} from "../providerSnapshot";
import { compareCliVersions } from "../cliVersion";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import { ClaudeProvider } from "../Services/ClaudeProvider";
import { ServerSettingsService } from "../../serverSettings";
@@ -40,7 +41,30 @@ const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = {
};
const PROVIDER = "claudeAgent" as const;
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-7",
name: "Claude Opus 4.7",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
},
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
@@ -96,6 +120,24 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
function supportsClaudeOpus47(version: string | null | undefined): boolean {
return version ? compareCliVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
}
function getBuiltInClaudeModelsForVersion(
version: string | null | undefined,
): ReadonlyArray<ServerProviderModel> {
if (supportsClaudeOpus47(version)) {
return BUILT_IN_MODELS;
}
return BUILT_IN_MODELS.filter((model) => model.slug !== "claude-opus-4-7");
}
function formatClaudeOpus47UpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Claude Code ${versionLabel} is too old for Claude Opus 4.7. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_7_VERSION} or newer to access it.`;
}
export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {
const slug = model?.trim();
return (
@@ -484,7 +526,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
const allModels = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
@@ -496,7 +538,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: false,
checkedAt,
models,
models: allModels,
probe: {
installed: false,
version: null,
@@ -518,7 +560,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
models: allModels,
probe: {
installed: !isCommandMissingCause(error),
version: null,
@@ -536,7 +578,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
models: allModels,
probe: {
installed: true,
version: null,
@@ -556,7 +598,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
models: allModels,
probe: {
installed: true,
version: parsedVersion,
@@ -569,6 +611,16 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
});
}
const models = providerModelsFromSettings(
getBuiltInClaudeModelsForVersion(parsedVersion),
PROVIDER,
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
const opus47UpgradeMessage = supportsClaudeOpus47(parsedVersion)
? undefined
: formatClaudeOpus47UpgradeMessage(parsedVersion);
const slashCommands =
(resolveSlashCommands
? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe(
@@ -658,7 +710,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
...parsed.auth,
...(authMetadata ? authMetadata : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
...(parsed.message
? { message: parsed.message }
: opus47UpgradeMessage
? { message: opus47UpgradeMessage }
: {}),
},
});
});
@@ -146,6 +146,7 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
getBinding: () => Effect.succeed(Option.none()),
remove: () => Effect.void,
listThreadIds: () => Effect.succeed([]),
listBindings: () => Effect.succeed([]),
});
const validationManager = new FakeCodexManager();
@@ -973,6 +973,69 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
),
);
it.effect(
"includes Claude Opus 4.7 with xhigh as the default effort on supported versions",
() =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
const opus47 = status.models.find((model) => model.slug === "claude-opus-4-7");
if (!opus47) {
assert.fail("Expected Claude Opus 4.7 to be present for Claude Code v2.1.111.");
}
if (!opus47.capabilities) {
assert.fail(
"Expected Claude Opus 4.7 capabilities to be present for Claude Code v2.1.111.",
);
}
assert.deepStrictEqual(
opus47.capabilities.reasoningEffortLevels.find((level) => level.isDefault),
{ value: "xhigh", label: "Extra High", isDefault: true },
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.111\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides Claude Opus 4.7 on older Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(
status.models.some((model) => model.slug === "claude-opus-4-7"),
false,
);
assert.strictEqual(
status.message,
"Claude Code v2.1.110 is too old for Claude Opus 4.7. Upgrade to v2.1.111 or newer to access it.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.110\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns a display label for claude subscription types", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
@@ -654,6 +654,43 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("stops stale sessions in other providers after a successful replacement start", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const threadId = asThreadId("thread-provider-replacement");
const codexSession = yield* provider.startSession(threadId, {
provider: "codex",
threadId,
cwd: "/tmp/project-provider-replacement",
runtimeMode: "full-access",
});
routing.codex.stopSession.mockClear();
routing.claude.stopSession.mockClear();
const claudeSession = yield* provider.startSession(threadId, {
provider: "claudeAgent",
threadId,
cwd: "/tmp/project-provider-replacement",
runtimeMode: "full-access",
});
assert.equal(codexSession.provider, "codex");
assert.equal(claudeSession.provider, "claudeAgent");
assert.deepEqual(routing.codex.stopSession.mock.calls, [[threadId]]);
assert.equal(routing.claude.stopSession.mock.calls.length, 0);
const sessions = yield* provider.listSessions();
assert.deepEqual(
sessions
.filter((session) => session.threadId === threadId)
.map((session) => session.provider),
["claudeAgent"],
);
}),
);
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -297,6 +297,40 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
});
const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: {
readonly threadId: ThreadId;
readonly currentProvider: ProviderSession["provider"];
}) {
yield* Effect.forEach(
adapters,
(adapter) =>
adapter.provider === input.currentProvider
? Effect.void
: Effect.gen(function* () {
const hasSession = yield* adapter.hasSession(input.threadId);
if (!hasSession) {
return;
}
yield* adapter.stopSession(input.threadId).pipe(
Effect.tap(() =>
analytics.record("provider.session.stopped", {
provider: adapter.provider,
}),
),
Effect.catchCause((cause) =>
Effect.logWarning("provider.session.stop-stale-failed", {
threadId: input.threadId,
provider: adapter.provider,
cause,
}),
),
);
}),
{ discard: true },
);
});
const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")(
function* (threadId, rawInput) {
const parsed = yield* decodeInputOrValidationError({
@@ -351,6 +385,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
);
}
yield* stopStaleSessionsForThread({
threadId,
currentProvider: adapter.provider,
});
yield* upsertSessionBinding(session, threadId, {
modelSelection: input.modelSelection,
});
@@ -133,6 +133,78 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
}
}));
it("lists persisted bindings with metadata in oldest-first order", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
const olderThreadId = ThreadId.make("thread-runtime-older");
const newerThreadId = ThreadId.make("thread-runtime-newer");
yield* runtimeRepository.upsert({
threadId: newerThreadId,
providerName: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T12:05:00.000Z",
resumeCursor: {
opaque: "resume-newer",
},
runtimePayload: {
cwd: "/tmp/newer",
},
});
yield* runtimeRepository.upsert({
threadId: olderThreadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "approval-required",
status: "starting",
lastSeenAt: "2026-04-14T12:00:00.000Z",
resumeCursor: {
opaque: "resume-older",
},
runtimePayload: {
cwd: "/tmp/older",
},
});
const bindings = yield* directory.listBindings();
assert.deepEqual(bindings, [
{
threadId: olderThreadId,
provider: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "approval-required",
status: "starting",
lastSeenAt: "2026-04-14T12:00:00.000Z",
resumeCursor: {
opaque: "resume-older",
},
runtimePayload: {
cwd: "/tmp/older",
},
},
{
threadId: newerThreadId,
provider: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T12:05:00.000Z",
resumeCursor: {
opaque: "resume-newer",
},
runtimePayload: {
cwd: "/tmp/newer",
},
},
]);
}));
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
@@ -1,11 +1,13 @@
import { type ProviderKind, type ThreadId } from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";
import {
ProviderSessionDirectory,
type ProviderRuntimeBinding,
type ProviderRuntimeBindingWithMetadata,
type ProviderSessionDirectoryShape,
} from "../Services/ProviderSessionDirectory.ts";
@@ -50,6 +52,27 @@ function mergeRuntimePayload(
return next;
}
function toRuntimeBinding(
runtime: ProviderSessionRuntime,
operation: string,
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
return decodeProviderKind(runtime.providerName, operation).pipe(
Effect.map(
(provider) =>
({
threadId: runtime.threadId,
provider,
adapterKey: runtime.adapterKey,
runtimeMode: runtime.runtimeMode,
status: runtime.status,
resumeCursor: runtime.resumeCursor,
runtimePayload: runtime.runtimePayload,
lastSeenAt: runtime.lastSeenAt,
}) satisfies ProviderRuntimeBindingWithMetadata,
),
);
}
const makeProviderSessionDirectory = Effect.gen(function* () {
const repository = yield* ProviderSessionRuntimeRepository;
@@ -60,18 +83,8 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
Option.match(runtime, {
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
onSome: (value) =>
decodeProviderKind(value.providerName, "ProviderSessionDirectory.getBinding").pipe(
Effect.map((provider) =>
Option.some({
threadId: value.threadId,
provider,
adapterKey: value.adapterKey,
runtimeMode: value.runtimeMode,
status: value.status,
resumeCursor: value.resumeCursor,
runtimePayload: value.runtimePayload,
}),
),
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
Effect.map((binding) => Option.some(binding)),
),
}),
),
@@ -145,12 +158,25 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
Effect.map((rows) => rows.map((row) => row.threadId)),
);
const listBindings: ProviderSessionDirectoryShape["listBindings"] = () =>
repository.list().pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listBindings:list")),
Effect.flatMap((rows) =>
Effect.forEach(
rows,
(row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
{ concurrency: "unbounded" },
),
),
);
return {
upsert,
getProvider,
getBinding,
remove,
listThreadIds,
listBindings,
} satisfies ProviderSessionDirectoryShape;
});
@@ -0,0 +1,522 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../../orchestration/Services/OrchestrationEngine.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
import { ProviderValidationError } from "../Errors.ts";
import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
const defaultModelSelection = {
provider: "codex",
model: "gpt-5-codex",
} as const;
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2_000,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (await predicate()) {
return;
}
if (Date.now() >= deadline) {
throw new Error("Timed out waiting for expectation.");
}
await new Promise((resolve) => setTimeout(resolve, 10));
return poll();
};
return poll();
}
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
function makeReadModel(
threads: ReadonlyArray<{
readonly id: ThreadId;
readonly session: {
readonly threadId: ThreadId;
readonly status: "starting" | "running" | "ready" | "interrupted" | "stopped" | "error";
readonly providerName: "codex" | "claudeAgent";
readonly runtimeMode: "approval-required" | "full-access" | "auto-accept-edits";
readonly activeTurnId: TurnId | null;
readonly lastError: string | null;
readonly updatedAt: string;
} | null;
}>,
) {
const now = new Date().toISOString();
const projectId = ProjectId.make("project-provider-session-reaper");
return {
snapshotSequence: 0,
updatedAt: now,
projects: [
{
id: projectId,
title: "Provider Reaper Project",
workspaceRoot: "/tmp/provider-reaper-project",
defaultModelSelection,
scripts: [],
createdAt: now,
updatedAt: now,
deletedAt: null,
},
],
threads: threads.map((thread) => ({
id: thread.id,
projectId,
title: `Thread ${thread.id}`,
modelSelection: defaultModelSelection,
interactionMode: "default" as const,
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
latestTurn: null,
messages: [],
session: thread.session,
activities: [],
proposedPlans: [],
checkpoints: [],
deletedAt: null,
})),
};
}
describe("ProviderSessionReaper", () => {
let runtime: ManagedRuntime.ManagedRuntime<
ProviderSessionReaper | ProviderSessionRuntimeRepository,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
afterEach(async () => {
if (scope) {
await Effect.runPromise(Scope.close(scope, Exit.void));
}
scope = null;
if (runtime) {
await runtime.dispose();
}
runtime = null;
});
async function createHarness(input: {
readonly readModel: ReturnType<typeof makeReadModel>;
readonly stopSessionImplementation?: (input: {
readonly threadId: ThreadId;
}) => ReturnType<ProviderServiceShape["stopSession"]>;
}) {
const stoppedThreadIds = new Set<ThreadId>();
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
(request) =>
(input.stopSessionImplementation
? input.stopSessionImplementation(request)
: Effect.sync(() => {
stoppedThreadIds.add(request.threadId);
})) as ReturnType<ProviderServiceShape["stopSession"]>,
);
const providerService: ProviderServiceShape = {
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession,
listSessions: () => Effect.succeed([]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
streamEvents: Stream.empty,
};
const orchestrationEngine: OrchestrationEngineShape = {
getReadModel: () => Effect.succeed(input.readModel),
readEvents: () => Stream.empty,
dispatch: () => unsupported(),
streamDomainEvents: Stream.empty,
};
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const layer = makeProviderSessionReaperLive({
inactivityThresholdMs: 1_000,
sweepIntervalMs: 60_000,
}).pipe(
Layer.provideMerge(providerSessionDirectoryLayer),
Layer.provideMerge(runtimeRepositoryLayer),
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)),
Layer.provideMerge(NodeServices.layer),
);
runtime = ManagedRuntime.make(layer);
return { stopSession, stoppedThreadIds };
}
it("reaps stale persisted sessions without active turns", async () => {
const threadId = ThreadId.make("thread-reaper-stale");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-stale",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await waitFor(() => harness.stopSession.mock.calls.length === 1);
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId });
expect(harness.stoppedThreadIds.has(threadId)).toBe(true);
});
it("skips stale sessions when the thread still has an active turn", async () => {
const threadId = ThreadId.make("thread-reaper-active-turn");
const turnId = TurnId.make("turn-reaper-active");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "running",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-active-turn",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await new Promise((resolve) => setTimeout(resolve, 50));
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("does not reap sessions that are still within the inactivity threshold", async () => {
const threadId = ThreadId.make("thread-reaper-fresh");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: now,
resumeCursor: {
opaque: "resume-fresh",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await new Promise((resolve) => setTimeout(resolve, 50));
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("skips persisted sessions that are already marked stopped", async () => {
const threadId = ThreadId.make("thread-reaper-stopped");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "stopped",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "stopped",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-stopped",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await new Promise((resolve) => setTimeout(resolve, 50));
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("continues reaping other sessions when one stop attempt fails", async () => {
const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: failedThreadId,
session: {
threadId: failedThreadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
{
id: reapedThreadId,
session: {
threadId: reapedThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
stopSessionImplementation: (request) =>
request.threadId === failedThreadId
? Effect.fail(
new ProviderValidationError({
operation: "ProviderSessionReaper.test",
issue: "simulated stop failure",
}),
)
: Effect.void,
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId: failedThreadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-failure",
},
runtimePayload: null,
}),
);
await runtime!.runPromise(
repository.upsert({
threadId: reapedThreadId,
providerName: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:01:00.000Z",
resumeCursor: {
opaque: "resume-success",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await waitFor(() => harness.stopSession.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
failedThreadId,
reapedThreadId,
]);
});
it("continues reaping other sessions when one stop attempt defects", async () => {
const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
const now = new Date().toISOString();
const harness = await createHarness({
readModel: makeReadModel([
{
id: defectThreadId,
session: {
threadId: defectThreadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
{
id: reapedThreadId,
session: {
threadId: reapedThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
stopSessionImplementation: (request) =>
request.threadId === defectThreadId
? Effect.die(new Error("simulated stop defect"))
: Effect.void,
});
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
await runtime!.runPromise(
repository.upsert({
threadId: defectThreadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-defect",
},
runtimePayload: null,
}),
);
await runtime!.runPromise(
repository.upsert({
threadId: reapedThreadId,
providerName: "codex",
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:01:00.000Z",
resumeCursor: {
opaque: "resume-after-defect",
},
runtimePayload: null,
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await waitFor(() => harness.stopSession.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
defectThreadId,
reapedThreadId,
]);
});
});
@@ -0,0 +1,133 @@
import { Duration, Effect, Layer, Schedule } from "effect";
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
ProviderSessionReaper,
type ProviderSessionReaperShape,
} from "../Services/ProviderSessionReaper.ts";
import { ProviderService } from "../Services/ProviderService.ts";
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
export interface ProviderSessionReaperLiveOptions {
readonly inactivityThresholdMs?: number;
readonly sweepIntervalMs?: number;
}
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
Effect.gen(function* () {
const providerService = yield* ProviderService;
const directory = yield* ProviderSessionDirectory;
const orchestrationEngine = yield* OrchestrationEngineService;
const inactivityThresholdMs = Math.max(
1,
options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,
);
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
const sweep = Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
const threadsById = new Map(readModel.threads.map((thread) => [thread.id, thread] as const));
const bindings = yield* directory.listBindings();
const now = Date.now();
let reapedCount = 0;
for (const binding of bindings) {
if (binding.status === "stopped") {
continue;
}
const lastSeenMs = Date.parse(binding.lastSeenAt);
if (Number.isNaN(lastSeenMs)) {
yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
threadId: binding.threadId,
provider: binding.provider,
lastSeenAt: binding.lastSeenAt,
});
continue;
}
const idleDurationMs = now - lastSeenMs;
if (idleDurationMs < inactivityThresholdMs) {
continue;
}
const thread = threadsById.get(binding.threadId);
if (thread?.session?.activeTurnId != null) {
yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
threadId: binding.threadId,
activeTurnId: thread.session.activeTurnId,
idleDurationMs,
});
continue;
}
const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
Effect.tap(() =>
Effect.logInfo("provider.session.reaped", {
threadId: binding.threadId,
provider: binding.provider,
idleDurationMs,
reason: "inactivity_threshold",
}),
),
Effect.as(true),
Effect.catchCause((cause) =>
Effect.logWarning("provider.session.reaper.stop-failed", {
threadId: binding.threadId,
provider: binding.provider,
idleDurationMs,
cause,
}).pipe(Effect.as(false)),
),
);
if (reaped) {
reapedCount += 1;
}
}
if (reapedCount > 0) {
yield* Effect.logInfo("provider.session.reaper.sweep-complete", {
reapedCount,
totalBindings: bindings.length,
});
}
});
const start: ProviderSessionReaperShape["start"] = () =>
Effect.gen(function* () {
yield* Effect.forkScoped(
sweep.pipe(
Effect.catch((error: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-failed", {
error,
}),
),
Effect.catchDefect((defect: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-defect", {
defect,
}),
),
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
),
);
yield* Effect.logInfo("provider.session.reaper.started", {
inactivityThresholdMs,
sweepIntervalMs,
});
});
return {
start,
} satisfies ProviderSessionReaperShape;
});
export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
export const ProviderSessionReaperLive = makeProviderSessionReaperLive();
@@ -22,6 +22,10 @@ export interface ProviderRuntimeBinding {
readonly runtimeMode?: RuntimeMode;
}
export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {
readonly lastSeenAt: string;
}
export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;
export type ProviderSessionDirectoryWriteError =
@@ -49,6 +53,11 @@ export interface ProviderSessionDirectoryShape {
ReadonlyArray<ThreadId>,
ProviderSessionDirectoryPersistenceError
>;
readonly listBindings: () => Effect.Effect<
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
ProviderSessionDirectoryPersistenceError
>;
}
export class ProviderSessionDirectory extends Context.Service<
@@ -0,0 +1,14 @@
import { Context } from "effect";
import type { Effect, Scope } from "effect";
export interface ProviderSessionReaperShape {
/**
* Start the background provider session reaper within the provided scope.
*/
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
}
export class ProviderSessionReaper extends Context.Service<
ProviderSessionReaper,
ProviderSessionReaperShape
>()("t3/provider/Services/ProviderSessionReaper") {}
@@ -0,0 +1,17 @@
import { assert, describe, it } from "@effect/vitest";
import { compareCliVersions, normalizeCliVersion } from "./cliVersion";
describe("cliVersion", () => {
it("normalizes versions with a missing patch segment", () => {
assert.strictEqual(normalizeCliVersion("2.1"), "2.1.0");
});
it("compares prerelease versions before stable versions", () => {
assert.isTrue(compareCliVersions("2.1.111-beta.1", "2.1.111") < 0);
});
it("rejects malformed numeric segments", () => {
assert.isTrue(compareCliVersions("1.2.3abc", "1.2.10") > 0);
});
});
+123
View File
@@ -0,0 +1,123 @@
interface ParsedCliSemver {
readonly major: number;
readonly minor: number;
readonly patch: number;
readonly prerelease: ReadonlyArray<string>;
}
const CLI_VERSION_NUMBER_SEGMENT = /^\d+$/;
export function normalizeCliVersion(version: string): string {
const [main, prerelease] = version.trim().split("-", 2);
const segments = (main ?? "")
.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0);
if (segments.length === 2) {
segments.push("0");
}
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
}
function parseCliSemver(version: string): ParsedCliSemver | null {
const normalized = normalizeCliVersion(version);
const [main = "", prerelease] = normalized.split("-", 2);
const segments = main.split(".");
if (segments.length !== 3) {
return null;
}
const [majorSegment, minorSegment, patchSegment] = segments;
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
return null;
}
if (
!CLI_VERSION_NUMBER_SEGMENT.test(majorSegment) ||
!CLI_VERSION_NUMBER_SEGMENT.test(minorSegment) ||
!CLI_VERSION_NUMBER_SEGMENT.test(patchSegment)
) {
return null;
}
const major = Number.parseInt(majorSegment, 10);
const minor = Number.parseInt(minorSegment, 10);
const patch = Number.parseInt(patchSegment, 10);
if (![major, minor, patch].every(Number.isInteger)) {
return null;
}
return {
major,
minor,
patch,
prerelease:
prerelease
?.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0) ?? [],
};
}
function comparePrereleaseIdentifier(left: string, right: string): number {
const leftNumeric = /^\d+$/.test(left);
const rightNumeric = /^\d+$/.test(right);
if (leftNumeric && rightNumeric) {
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
}
if (leftNumeric) {
return -1;
}
if (rightNumeric) {
return 1;
}
return left.localeCompare(right);
}
export function compareCliVersions(left: string, right: string): number {
const parsedLeft = parseCliSemver(left);
const parsedRight = parseCliSemver(right);
if (!parsedLeft || !parsedRight) {
return left.localeCompare(right);
}
if (parsedLeft.major !== parsedRight.major) {
return parsedLeft.major - parsedRight.major;
}
if (parsedLeft.minor !== parsedRight.minor) {
return parsedLeft.minor - parsedRight.minor;
}
if (parsedLeft.patch !== parsedRight.patch) {
return parsedLeft.patch - parsedRight.patch;
}
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
return 0;
}
if (parsedLeft.prerelease.length === 0) {
return 1;
}
if (parsedRight.prerelease.length === 0) {
return -1;
}
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
for (let index = 0; index < length; index += 1) {
const leftIdentifier = parsedLeft.prerelease[index];
const rightIdentifier = parsedRight.prerelease[index];
if (leftIdentifier === undefined) {
return -1;
}
if (rightIdentifier === undefined) {
return 1;
}
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
if (comparison !== 0) {
return comparison;
}
}
return 0;
}
+4 -120
View File
@@ -1,121 +1,10 @@
import { compareCliVersions, normalizeCliVersion } from "./cliVersion";
const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/;
export const MINIMUM_CODEX_CLI_VERSION = "0.37.0";
interface ParsedSemver {
readonly major: number;
readonly minor: number;
readonly patch: number;
readonly prerelease: ReadonlyArray<string>;
}
function normalizeCodexVersion(version: string): string {
const [main, prerelease] = version.trim().split("-", 2);
const segments = (main ?? "")
.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0);
if (segments.length === 2) {
segments.push("0");
}
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
}
function parseSemver(version: string): ParsedSemver | null {
const normalized = normalizeCodexVersion(version);
const [main = "", prerelease] = normalized.split("-", 2);
const segments = main.split(".");
if (segments.length !== 3) {
return null;
}
const [majorSegment, minorSegment, patchSegment] = segments;
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
return null;
}
const major = Number.parseInt(majorSegment, 10);
const minor = Number.parseInt(minorSegment, 10);
const patch = Number.parseInt(patchSegment, 10);
if (![major, minor, patch].every(Number.isInteger)) {
return null;
}
return {
major,
minor,
patch,
prerelease:
prerelease
?.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0) ?? [],
};
}
function comparePrereleaseIdentifier(left: string, right: string): number {
const leftNumeric = /^\d+$/.test(left);
const rightNumeric = /^\d+$/.test(right);
if (leftNumeric && rightNumeric) {
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
}
if (leftNumeric) {
return -1;
}
if (rightNumeric) {
return 1;
}
return left.localeCompare(right);
}
export function compareCodexCliVersions(left: string, right: string): number {
const parsedLeft = parseSemver(left);
const parsedRight = parseSemver(right);
if (!parsedLeft || !parsedRight) {
return left.localeCompare(right);
}
if (parsedLeft.major !== parsedRight.major) {
return parsedLeft.major - parsedRight.major;
}
if (parsedLeft.minor !== parsedRight.minor) {
return parsedLeft.minor - parsedRight.minor;
}
if (parsedLeft.patch !== parsedRight.patch) {
return parsedLeft.patch - parsedRight.patch;
}
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
return 0;
}
if (parsedLeft.prerelease.length === 0) {
return 1;
}
if (parsedRight.prerelease.length === 0) {
return -1;
}
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
for (let index = 0; index < length; index += 1) {
const leftIdentifier = parsedLeft.prerelease[index];
const rightIdentifier = parsedRight.prerelease[index];
if (leftIdentifier === undefined) {
return -1;
}
if (rightIdentifier === undefined) {
return 1;
}
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
if (comparison !== 0) {
return comparison;
}
}
return 0;
}
export const compareCodexCliVersions = compareCliVersions;
export function parseCodexCliVersion(output: string): string | null {
const match = CODEX_VERSION_PATTERN.exec(output);
@@ -123,12 +12,7 @@ export function parseCodexCliVersion(output: string): string | null {
return null;
}
const parsed = parseSemver(match[1]);
if (!parsed) {
return null;
}
return normalizeCodexVersion(match[1]);
return normalizeCliVersion(match[1]);
}
export function isCodexCliVersionSupported(version: string): boolean {
+449 -6
View File
@@ -11,6 +11,7 @@ import {
KeybindingRule,
MessageId,
OpenError,
type OrchestrationThreadShell,
TerminalNotRunningError,
type OrchestrationCommand,
type OrchestrationEvent,
@@ -166,6 +167,32 @@ const makeDefaultOrchestrationReadModel = () => {
};
};
const makeDefaultOrchestrationThreadShell = (
overrides: Partial<OrchestrationThreadShell> = {},
): OrchestrationThreadShell => {
const now = new Date().toISOString();
return {
id: defaultThreadId,
projectId: defaultProjectId,
title: "Default Thread",
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...overrides,
};
};
const workspaceAndProjectServicesLayer = Layer.mergeAll(
WorkspacePathsLive,
WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)),
@@ -2039,6 +2066,40 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("creates a missing workspace root during websocket project.create dispatch", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const parentDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-create-" });
const missingWorkspaceRoot = path.join(parentDir, "nested", "new-project");
yield* buildAppUnderTest();
const wsUrl = yield* getWsServerUrl("/ws");
const response = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "project.create",
commandId: CommandId.make("cmd-project-create-missing-root"),
projectId: ProjectId.make("project-create-missing-root"),
title: "New Project",
workspaceRoot: missingWorkspaceRoot,
createWorkspaceRootIfMissing: true,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
createdAt: new Date().toISOString(),
}),
),
);
const stat = yield* fs.stat(missingWorkspaceRoot);
assert.isAtLeast(response.sequence, 0);
assert.equal(stat.type, "Directory");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("routes websocket rpc projects.writeFile errors", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -2911,21 +2972,48 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("closes thread terminals after a successful archive command", () =>
it.effect("stops the provider session and closes thread terminals after archive", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-archive");
const closeInputs: Array<Parameters<TerminalManagerShape["close"]>[0]> = [];
const effects: string[] = [];
const dispatchedCommands: Array<OrchestrationCommand> = [];
const now = new Date().toISOString();
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
closeInputs.push(input);
effects.push(`terminal.close:${input.threadId}`);
}),
},
orchestrationEngine: {
dispatch: () => Effect.succeed({ sequence: 8 }),
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
effects.push(`dispatch:${command.type}`);
return { sequence: dispatchedCommands.length };
}),
},
projectionSnapshotQuery: {
getThreadShellById: () =>
Effect.succeed(
Option.some(
makeDefaultOrchestrationThreadShell({
id: threadId,
updatedAt: now,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
}),
),
),
},
},
});
@@ -2941,8 +3029,363 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
assert.equal(dispatchResult.sequence, 8);
assert.deepEqual(closeInputs, [{ threadId }]);
assert.equal(dispatchResult.sequence, 1);
assert.deepEqual(effects, [
"dispatch:thread.archive",
"dispatch:thread.session.stop",
`terminal.close:${threadId}`,
]);
const sessionStopCommand = dispatchedCommands[1];
assert.equal(sessionStopCommand?.type, "thread.session.stop");
if (sessionStopCommand?.type === "thread.session.stop") {
assert.equal(sessionStopCommand.threadId, threadId);
}
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("checks session status before archiving removes the thread from active lookups", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-archive-precheck");
const effects: string[] = [];
const dispatchedCommands: Array<OrchestrationCommand> = [];
const now = new Date().toISOString();
let archived = false;
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
effects.push(`terminal.close:${input.threadId}`);
}),
},
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
effects.push(`dispatch:${command.type}`);
if (command.type === "thread.archive") {
archived = true;
}
return { sequence: dispatchedCommands.length };
}),
},
projectionSnapshotQuery: {
getThreadShellById: () =>
Effect.sync(() => {
effects.push(`query:thread-shell:${archived ? "archived" : "active"}`);
return archived
? Option.none()
: Option.some(
makeDefaultOrchestrationThreadShell({
id: threadId,
updatedAt: now,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
}),
);
}),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const dispatchResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.archive",
commandId: CommandId.make("cmd-thread-archive-precheck"),
threadId,
}),
),
);
assert.equal(dispatchResult.sequence, 1);
assert.deepEqual(effects, [
"query:thread-shell:active",
"dispatch:thread.archive",
"dispatch:thread.session.stop",
`terminal.close:${threadId}`,
]);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
["thread.archive", "thread.session.stop"],
);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("archives without dispatching session stop when the thread has no session", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-archive-no-session");
const effects: string[] = [];
const dispatchedCommands: Array<OrchestrationCommand> = [];
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
effects.push(`terminal.close:${input.threadId}`);
}),
},
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
effects.push(`dispatch:${command.type}`);
return { sequence: dispatchedCommands.length };
}),
},
projectionSnapshotQuery: {
getThreadShellById: () =>
Effect.succeed(
Option.some(makeDefaultOrchestrationThreadShell({ id: threadId, session: null })),
),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const dispatchResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.archive",
commandId: CommandId.make("cmd-thread-archive-no-session"),
threadId,
}),
),
);
assert.equal(dispatchResult.sequence, 1);
assert.deepEqual(effects, ["dispatch:thread.archive", `terminal.close:${threadId}`]);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
["thread.archive"],
);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"archives without dispatching session stop when the thread session is already stopped",
() =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-archive-stopped-session");
const effects: string[] = [];
const dispatchedCommands: Array<OrchestrationCommand> = [];
const now = new Date().toISOString();
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
effects.push(`terminal.close:${input.threadId}`);
}),
},
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
effects.push(`dispatch:${command.type}`);
return { sequence: dispatchedCommands.length };
}),
},
projectionSnapshotQuery: {
getThreadShellById: () =>
Effect.succeed(
Option.some(
makeDefaultOrchestrationThreadShell({
id: threadId,
updatedAt: now,
session: {
threadId,
status: "stopped",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
}),
),
),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const dispatchResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.archive",
commandId: CommandId.make("cmd-thread-archive-stopped-session"),
threadId,
}),
),
);
assert.equal(dispatchResult.sequence, 1);
assert.deepEqual(effects, ["dispatch:thread.archive", `terminal.close:${threadId}`]);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
["thread.archive"],
);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("archives and still closes terminals when session stop fails", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-archive-stop-failure");
const effects: string[] = [];
const dispatchedCommands: Array<OrchestrationCommand> = [];
const now = new Date().toISOString();
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
effects.push(`terminal.close:${input.threadId}`);
}),
},
orchestrationEngine: {
dispatch: (command) => {
dispatchedCommands.push(command);
effects.push(`dispatch:${command.type}`);
if (command.type === "thread.session.stop") {
return Effect.fail(
new OrchestrationListenerCallbackError({
listener: "domain-event",
detail: "simulated archive stop failure",
}),
);
}
return Effect.succeed({ sequence: dispatchedCommands.length });
},
},
projectionSnapshotQuery: {
getThreadShellById: () =>
Effect.succeed(
Option.some(
makeDefaultOrchestrationThreadShell({
id: threadId,
updatedAt: now,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
}),
),
),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const dispatchResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.archive",
commandId: CommandId.make("cmd-thread-archive-stop-failure"),
threadId,
}),
),
);
assert.equal(dispatchResult.sequence, 1);
assert.deepEqual(effects, [
"dispatch:thread.archive",
"dispatch:thread.session.stop",
`terminal.close:${threadId}`,
]);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
["thread.archive", "thread.session.stop"],
);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("archives and still closes terminals when session stop defects", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-archive-stop-defect");
const effects: string[] = [];
const dispatchedCommands: Array<OrchestrationCommand> = [];
const now = new Date().toISOString();
yield* buildAppUnderTest({
layers: {
terminalManager: {
close: (input) =>
Effect.sync(() => {
effects.push(`terminal.close:${input.threadId}`);
}),
},
orchestrationEngine: {
dispatch: (command) => {
dispatchedCommands.push(command);
effects.push(`dispatch:${command.type}`);
if (command.type === "thread.session.stop") {
return Effect.die(new Error("simulated archive stop defect"));
}
return Effect.succeed({ sequence: dispatchedCommands.length });
},
},
projectionSnapshotQuery: {
getThreadShellById: () =>
Effect.succeed(
Option.some(
makeDefaultOrchestrationThreadShell({
id: threadId,
updatedAt: now,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
}),
),
),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const dispatchResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.archive",
commandId: CommandId.make("cmd-thread-archive-stop-defect"),
threadId,
}),
),
);
assert.equal(dispatchResult.sequence, 1);
assert.deepEqual(effects, [
"dispatch:thread.archive",
"dispatch:thread.session.stop",
`terminal.close:${threadId}`,
]);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
["thread.archive", "thread.session.stop"],
);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+16 -7
View File
@@ -23,6 +23,7 @@ import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
import { GitCoreLive } from "./git/Layers/GitCore";
@@ -134,6 +135,10 @@ const CheckpointingLayerLive = Layer.empty.pipe(
Layer.provideMerge(CheckpointStoreLive),
);
const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
const ProviderLayerLive = Layer.unwrap(
Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
@@ -143,9 +148,6 @@ const ProviderLayerLive = Layer.unwrap(
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
});
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
const codexAdapterLayer = makeCodexAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
@@ -155,11 +157,14 @@ const ProviderLayerLive = Layer.unwrap(
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
Layer.provide(codexAdapterLayer),
Layer.provide(claudeAdapterLayer),
Layer.provideMerge(providerSessionDirectoryLayer),
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
);
return makeProviderServiceLive(
canonicalEventLogger ? { canonicalEventLogger } : undefined,
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
).pipe(
Layer.provide(adapterRegistryLayer),
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
);
}),
);
@@ -194,12 +199,16 @@ const AuthLayerLive = ServerAuthLive.pipe(
Layer.provide(ServerSecretStoreLive),
);
const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
Layer.provideMerge(ProviderLayerLive),
Layer.provideMerge(OrchestrationLayerLive),
);
const RuntimeDependenciesLive = ReactorLayerLive.pipe(
// Core Services
Layer.provideMerge(CheckpointingLayerLive),
Layer.provideMerge(GitLayerLive),
Layer.provideMerge(OrchestrationLayerLive),
Layer.provideMerge(ProviderLayerLive),
Layer.provideMerge(ProviderRuntimeLayerLive),
Layer.provideMerge(TerminalLayerLive),
Layer.provideMerge(PersistenceLayerLive),
Layer.provideMerge(KeybindingsLive),
+6 -1
View File
@@ -32,6 +32,7 @@ import { ServerSettingsService } from "./serverSettings";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
import { ServerAuth } from "./auth/Services/ServerAuth";
import { ProviderSessionReaper } from "./provider/Services/ProviderSessionReaper";
import {
formatHeadlessServeOutput,
formatHostForUrl,
@@ -281,6 +282,7 @@ export const makeServerRuntimeStartup = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const keybindings = yield* Keybindings;
const orchestrationReactor = yield* OrchestrationReactor;
const providerSessionReaper = yield* ProviderSessionReaper;
const lifecycleEvents = yield* ServerLifecycleEvents;
const serverSettings = yield* ServerSettingsService;
const serverEnvironment = yield* ServerEnvironment;
@@ -325,7 +327,10 @@ export const makeServerRuntimeStartup = Effect.gen(function* () {
yield* Effect.logDebug("startup phase: starting orchestration reactors");
yield* runStartupPhase(
"reactors.start",
orchestrationReactor.start().pipe(Scope.provide(reactorScope)),
Effect.gen(function* () {
yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
}),
);
const welcomeBase = yield* resolveWelcomeBase;
+35
View File
@@ -92,6 +92,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
enabled: true,
binaryPath: "/usr/local/bin/claude",
customModels: ["claude-custom"],
launchArgs: "",
});
assert.deepEqual(next.textGenerationModelSelection, {
provider: "codex",
@@ -141,6 +142,35 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("drops stale text generation options when resetting model selection", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
yield* serverSettings.updateSettings({
textGenerationModelSelection: {
provider: "codex",
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
options: {
reasoningEffort: "high",
fastMode: true,
},
},
});
const next = yield* serverSettings.updateSettings({
textGenerationModelSelection: {
provider: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.provider,
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
},
});
assert.deepEqual(next.textGenerationModelSelection, {
provider: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.provider,
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("trims provider path settings when updates are applied", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
@@ -167,6 +197,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
enabled: true,
binaryPath: "/opt/homebrew/bin/claude",
customModels: [],
launchArgs: "",
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
@@ -176,12 +207,14 @@ it.layer(NodeServices.layer)("server settings", (it) => {
const serverSettings = yield* ServerSettingsService;
const next = yield* serverSettings.updateSettings({
addProjectBaseDirectory: " ~/Development ",
observability: {
otlpTracesUrl: " http://localhost:4318/v1/traces ",
otlpMetricsUrl: " http://localhost:4318/v1/metrics ",
},
});
assert.equal(next.addProjectBaseDirectory, "~/Development");
assert.deepEqual(next.observability, {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
@@ -215,6 +248,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
const serverConfig = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const next = yield* serverSettings.updateSettings({
addProjectBaseDirectory: "~/Development",
observability: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
@@ -230,6 +264,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
assert.deepEqual(JSON.parse(raw), {
addProjectBaseDirectory: "~/Development",
observability: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
+18 -2
View File
@@ -42,6 +42,7 @@ import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
export interface ServerSettingsShape {
/** Start the settings runtime and attach file watching. */
@@ -80,7 +81,20 @@ export class ServerSettingsService extends Context.Service<
getSettings: Ref.get(currentSettingsRef),
updateSettings: (patch) =>
Ref.get(currentSettingsRef).pipe(
Effect.map((currentSettings) => deepMerge(currentSettings, patch)),
Effect.flatMap((currentSettings) =>
Schema.decodeEffect(ServerSettings)(
applyServerSettingsPatch(currentSettings, patch),
).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
),
),
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
),
streamChanges: Stream.empty,
@@ -314,7 +328,9 @@ const makeServerSettings = Effect.gen(function* () {
writeSemaphore.withPermits(1)(
Effect.gen(function* () {
const current = yield* getSettingsFromCache;
const next = yield* Schema.decodeEffect(ServerSettings)(deepMerge(current, patch)).pipe(
const next = yield* Schema.decodeEffect(ServerSettings)(
applyServerSettingsPatch(current, patch),
).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
@@ -68,6 +68,11 @@ const searchWorkspaceEntries = (input: { cwd: string; query: string; limit: numb
return yield* workspaceEntries.search(input);
});
const appendSeparator = (input: string) =>
input.endsWith("/") || input.endsWith("\\")
? input
: `${input}${process.platform === "win32" ? "\\" : "/"}`;
it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
afterEach(() => {
vi.restoreAllMocks();
@@ -275,4 +280,85 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
}),
);
});
describe("browse", () => {
it.effect("returns matching directories and excludes files", () =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries;
const path = yield* Path.Path;
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-prefix-" });
yield* writeTextFile(cwd, "alphabet.txt", "ignore me");
yield* writeTextFile(cwd, "alpha/index.ts", "export {};\n");
yield* writeTextFile(cwd, "alpine/index.ts", "export {};\n");
const result = yield* workspaceEntries.browse({
partialPath: path.join(cwd, "alp"),
});
expect(result).toEqual({
parentPath: cwd,
entries: [
{ name: "alpha", fullPath: path.join(cwd, "alpha") },
{ name: "alpine", fullPath: path.join(cwd, "alpine") },
],
});
}),
);
it.effect("shows dot directories in directory mode and hidden-prefix mode", () =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries;
const path = yield* Path.Path;
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-hidden-" });
yield* writeTextFile(cwd, ".config/settings.json", "{}");
yield* writeTextFile(cwd, "config/settings.json", "{}");
const directoryResult = yield* workspaceEntries.browse({
partialPath: appendSeparator(cwd),
});
const hiddenPrefixResult = yield* workspaceEntries.browse({
partialPath: `${appendSeparator(cwd)}.c`,
});
expect(directoryResult.entries.map((entry) => entry.name)).toEqual([".config", "config"]);
expect(hiddenPrefixResult).toEqual({
parentPath: cwd,
entries: [{ name: ".config", fullPath: path.join(cwd, ".config") }],
});
}),
);
it.effect("supports relative paths when cwd is provided", () =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries;
const path = yield* Path.Path;
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-relative-" });
yield* writeTextFile(cwd, "packages/pkg.json", "{}");
const result = yield* workspaceEntries.browse({
cwd,
partialPath: "./pack",
});
expect(result).toEqual({
parentPath: cwd,
entries: [{ name: "packages", fullPath: path.join(cwd, "packages") }],
});
}),
);
it.effect("rejects relative paths without cwd", () =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries;
const error = yield* workspaceEntries
.browse({
partialPath: "./src",
})
.pipe(Effect.flip);
expect(error.detail).toBe("Relative filesystem browse paths require a current project.");
}),
);
});
});
@@ -1,9 +1,11 @@
import * as OS from "node:os";
import fsPromises from "node:fs/promises";
import type { Dirent } from "node:fs";
import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect";
import { type ProjectEntry } from "@t3tools/contracts";
import { type FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
import {
insertRankedSearchResult,
normalizeSearchQuery,
@@ -14,6 +16,7 @@ import {
import { GitCore } from "../../git/Services/GitCore.ts";
import {
WorkspaceEntries,
WorkspaceEntriesBrowseError,
WorkspaceEntriesError,
type WorkspaceEntriesShape,
} from "../Services/WorkspaceEntries.ts";
@@ -52,6 +55,16 @@ function toPosixPath(input: string): string {
return input.replaceAll("\\", "/");
}
function expandHomePath(input: string, path: Path.Path): string {
if (input === "~") {
return OS.homedir();
}
if (input.startsWith("~/") || input.startsWith("~\\")) {
return path.join(OS.homedir(), input.slice(2));
}
return input;
}
function parentPathOf(input: string): string | undefined {
const separatorIndex = input.lastIndexOf("/");
if (separatorIndex === -1) {
@@ -129,6 +142,36 @@ function directoryAncestorsOf(relativePath: string): string[] {
return directories;
}
const resolveBrowseTarget = (
input: FilesystemBrowseInput,
pathService: Path.Path,
): Effect.Effect<string, WorkspaceEntriesBrowseError> =>
Effect.gen(function* () {
if (process.platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
return yield* new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.resolveBrowseTarget",
detail: "Windows-style paths are only supported on Windows.",
});
}
if (!isExplicitRelativePath(input.partialPath)) {
return pathService.resolve(expandHomePath(input.partialPath, pathService));
}
if (!input.cwd) {
return yield* new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.resolveBrowseTarget",
detail: "Relative filesystem browse paths require a current project.",
});
}
return pathService.resolve(expandHomePath(input.cwd, pathService), input.partialPath);
});
export const makeWorkspaceEntries = Effect.gen(function* () {
const path = yield* Path.Path;
const gitOption = yield* Effect.serviceOption(GitCore);
@@ -379,6 +422,46 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
},
);
const browse: WorkspaceEntriesShape["browse"] = Effect.fn("WorkspaceEntries.browse")(
function* (input) {
const resolvedInputPath = yield* resolveBrowseTarget(input, path);
const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
const dirents = yield* Effect.tryPromise({
try: () => fsPromises.readdir(parentPath, { withFileTypes: true }),
catch: (cause) =>
new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.browse.readDirectory",
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
cause,
}),
});
const showHidden = endsWithSeparator || prefix.startsWith(".");
const lowerPrefix = prefix.toLowerCase();
return {
parentPath,
entries: dirents
.filter(
(dirent) =>
dirent.isDirectory() &&
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !dirent.name.startsWith(".")),
)
.map((dirent) => ({
name: dirent.name,
fullPath: path.join(parentPath, dirent.name),
}))
.toSorted((left, right) => left.name.localeCompare(right.name)),
};
},
);
const search: WorkspaceEntriesShape["search"] = Effect.fn("WorkspaceEntries.search")(
function* (input) {
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
@@ -415,6 +498,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
);
return {
browse,
invalidate,
search,
} satisfies WorkspaceEntriesShape;
@@ -58,6 +58,24 @@ it.layer(TestLayer)("WorkspacePathsLive", (it) => {
}),
);
it.effect("creates missing directories when createIfMissing is enabled", () =>
Effect.gen(function* () {
const workspacePaths = yield* WorkspacePaths;
const fileSystem = yield* FileSystem.FileSystem;
const cwd = yield* makeTempDir();
const path = yield* Path.Path;
const missingPath = path.join(cwd, "nested", "new-project");
const resolved = yield* workspacePaths.normalizeWorkspaceRoot(missingPath, {
createIfMissing: true,
});
const stat = yield* fileSystem.stat(resolved);
expect(resolved).toBe(missingPath);
expect(stat.type).toBe("Directory");
}),
);
it.effect("rejects file paths", () =>
Effect.gen(function* () {
const workspacePaths = yield* WorkspacePaths;
@@ -4,6 +4,7 @@ import { Effect, FileSystem, Layer, Path } from "effect";
import {
WorkspacePaths,
WorkspacePathOutsideRootError,
WorkspaceRootCreateFailedError,
WorkspaceRootNotDirectoryError,
WorkspaceRootNotExistsError,
type WorkspacePathsShape,
@@ -29,11 +30,25 @@ export const makeWorkspacePaths = Effect.gen(function* () {
const normalizeWorkspaceRoot: WorkspacePathsShape["normalizeWorkspaceRoot"] = Effect.fn(
"WorkspacePaths.normalizeWorkspaceRoot",
)(function* (workspaceRoot) {
)(function* (workspaceRoot, options) {
const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));
const workspaceStat = yield* fileSystem
let workspaceStat = yield* fileSystem
.stat(normalizedWorkspaceRoot)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!workspaceStat && options?.createIfMissing) {
yield* fileSystem.makeDirectory(normalizedWorkspaceRoot, { recursive: true }).pipe(
Effect.mapError(
() =>
new WorkspaceRootCreateFailedError({
workspaceRoot,
normalizedWorkspaceRoot,
}),
),
);
workspaceStat = yield* fileSystem
.stat(normalizedWorkspaceRoot)
.pipe(Effect.catch(() => Effect.succeed(null)));
}
if (!workspaceStat) {
return yield* new WorkspaceRootNotExistsError({
workspaceRoot,
@@ -9,7 +9,12 @@
import { Schema, Context } from "effect";
import type { Effect } from "effect";
import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "@t3tools/contracts";
import type {
FilesystemBrowseInput,
FilesystemBrowseResult,
ProjectSearchEntriesInput,
ProjectSearchEntriesResult,
} from "@t3tools/contracts";
export class WorkspaceEntriesError extends Schema.TaggedErrorClass<WorkspaceEntriesError>()(
"WorkspaceEntriesError",
@@ -21,11 +26,29 @@ export class WorkspaceEntriesError extends Schema.TaggedErrorClass<WorkspaceEntr
},
) {}
export class WorkspaceEntriesBrowseError extends Schema.TaggedErrorClass<WorkspaceEntriesBrowseError>()(
"WorkspaceEntriesBrowseError",
{
cwd: Schema.optional(Schema.String),
partialPath: Schema.String,
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
/**
* WorkspaceEntriesShape - Service API for workspace entry search and cache
* invalidation.
*/
export interface WorkspaceEntriesShape {
/**
* Browse matching directories for the provided partial path.
*/
readonly browse: (
input: FilesystemBrowseInput,
) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
/**
* Search indexed workspace entries for files and directories matching the
* provided query.
@@ -21,6 +21,18 @@ export class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass<Workspa
}
}
export class WorkspaceRootCreateFailedError extends Schema.TaggedErrorClass<WorkspaceRootCreateFailedError>()(
"WorkspaceRootCreateFailedError",
{
workspaceRoot: Schema.String,
normalizedWorkspaceRoot: Schema.String,
},
) {
override get message(): string {
return `Failed to create workspace root: ${this.normalizedWorkspaceRoot}`;
}
}
export class WorkspaceRootNotDirectoryError extends Schema.TaggedErrorClass<WorkspaceRootNotDirectoryError>()(
"WorkspaceRootNotDirectoryError",
{
@@ -47,6 +59,7 @@ export class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass<Works
export const WorkspacePathsError = Schema.Union([
WorkspaceRootNotExistsError,
WorkspaceRootCreateFailedError,
WorkspaceRootNotDirectoryError,
WorkspacePathOutsideRootError,
]);
@@ -61,7 +74,11 @@ export interface WorkspacePathsShape {
*/
readonly normalizeWorkspaceRoot: (
workspaceRoot: string,
) => Effect.Effect<string, WorkspaceRootNotExistsError | WorkspaceRootNotDirectoryError>;
options?: { readonly createIfMissing?: boolean },
) => Effect.Effect<
string,
WorkspaceRootNotExistsError | WorkspaceRootCreateFailedError | WorkspaceRootNotDirectoryError
>;
/**
* Resolve a relative path within a validated workspace root.
+52
View File
@@ -17,6 +17,7 @@ import {
ProjectSearchEntriesError,
ProjectWriteFileError,
OrchestrationReplayEventsError,
FilesystemBrowseError,
ThreadId,
type TerminalEvent,
WS_METHODS,
@@ -549,8 +550,45 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
ORCHESTRATION_WS_METHODS.dispatchCommand,
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
const shouldStopSessionAfterArchive =
normalizedCommand.type === "thread.archive"
? yield* projectionSnapshotQuery
.getThreadShellById(normalizedCommand.threadId)
.pipe(
Effect.map(
Option.match({
onNone: () => false,
onSome: (thread) =>
thread.session !== null && thread.session.status !== "stopped",
}),
),
Effect.catch(() => Effect.succeed(false)),
)
: false;
const result = yield* dispatchNormalizedCommand(normalizedCommand);
if (normalizedCommand.type === "thread.archive") {
if (shouldStopSessionAfterArchive) {
yield* Effect.gen(function* () {
const stopCommand = yield* normalizeDispatchCommand({
type: "thread.session.stop",
commandId: CommandId.make(
`session-stop-for-archive:${normalizedCommand.commandId}`,
),
threadId: normalizedCommand.threadId,
createdAt: new Date().toISOString(),
});
yield* dispatchNormalizedCommand(stopCommand);
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("failed to stop provider session during archive", {
threadId: normalizedCommand.threadId,
cause,
}),
),
);
}
yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to close thread terminals after archive", {
@@ -768,6 +806,20 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
"rpc.aggregate": "workspace",
}),
[WS_METHODS.filesystemBrowse]: (input) =>
observeRpcEffect(
WS_METHODS.filesystemBrowse,
workspaceEntries.browse(input).pipe(
Effect.mapError(
(cause) =>
new FilesystemBrowseError({
message: cause.detail,
cause,
}),
),
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.subscribeGitStatus]: (input) =>
observeRpcStream(
WS_METHODS.subscribeGitStatus,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.17",
"version": "0.0.20",
"private": true,
"type": "module",
"scripts": {
+37
View File
@@ -0,0 +1,37 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const originalWindow = globalThis.window;
afterEach(() => {
vi.resetModules();
if (originalWindow === undefined) {
Reflect.deleteProperty(globalThis, "window");
return;
}
globalThis.window = originalWindow;
});
describe("branding", () => {
it("uses injected desktop branding when available", async () => {
Object.defineProperty(globalThis, "window", {
configurable: true,
value: {
desktopBridge: {
getAppBranding: () => ({
baseName: "T3 Code",
stageLabel: "Nightly",
displayName: "T3 Code (Nightly)",
}),
},
},
});
const branding = await import("./branding");
expect(branding.APP_BASE_NAME).toBe("T3 Code");
expect(branding.APP_STAGE_LABEL).toBe("Nightly");
expect(branding.APP_DISPLAY_NAME).toBe("T3 Code (Nightly)");
});
});
+17 -3
View File
@@ -1,4 +1,18 @@
export const APP_BASE_NAME = "T3 Code";
export const APP_STAGE_LABEL = import.meta.env.DEV ? "Dev" : "Alpha";
export const APP_DISPLAY_NAME = `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
import type { DesktopAppBranding } from "@t3tools/contracts";
function readInjectedDesktopAppBranding(): DesktopAppBranding | null {
if (typeof window === "undefined") {
return null;
}
return window.desktopBridge?.getAppBranding?.() ?? null;
}
const injectedDesktopAppBranding = readInjectedDesktopAppBranding();
export const APP_BASE_NAME = injectedDesktopAppBranding?.baseName ?? "T3 Code";
export const APP_STAGE_LABEL =
injectedDesktopAppBranding?.stageLabel ?? (import.meta.env.DEV ? "Dev" : "Alpha");
export const APP_DISPLAY_NAME =
injectedDesktopAppBranding?.displayName ?? `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0";
+21 -2
View File
@@ -1,13 +1,32 @@
import { create } from "zustand";
interface CommandPaletteOpenIntent {
kind: "add-project";
requestId: number;
}
interface CommandPaletteStore {
open: boolean;
openIntent: CommandPaletteOpenIntent | null;
setOpen: (open: boolean) => void;
toggleOpen: () => void;
openAddProject: () => void;
clearOpenIntent: () => void;
}
export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
open: false,
setOpen: (open) => set({ open }),
toggleOpen: () => set((state) => ({ open: !state.open })),
openIntent: null,
setOpen: (open) => set({ open, ...(open ? {} : { openIntent: null }) }),
toggleOpen: () =>
set((state) => ({ open: !state.open, ...(state.open ? { openIntent: null } : {}) })),
openAddProject: () =>
set((state) => ({
open: true,
openIntent: {
kind: "add-project",
requestId: (state.openIntent?.requestId ?? 0) + 1,
},
})),
clearOpenIntent: () => set({ openIntent: null }),
}));
@@ -63,7 +63,7 @@ describe("ChatMarkdown", () => {
);
try {
const link = page.getByRole("link", { name: "PermissionRule.ts:1" });
const link = page.getByRole("link", { name: "PermissionRule.ts · L1" });
await expect.element(link).toBeInTheDocument();
await expect.element(link).toHaveAttribute("href", `${filePath}#L1`);
@@ -76,4 +76,66 @@ describe("ChatMarkdown", () => {
await screen.unmount();
}
});
it("shows column information inline when present", async () => {
const filePath =
"/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
const screen = await render(
<ChatMarkdown text={`[PermissionRule.ts](file://${filePath}#L1C7)`} cwd="/repo/project" />,
);
try {
const link = page.getByRole("link", { name: "PermissionRule.ts · L1:C7" });
await expect.element(link).toBeInTheDocument();
await expect.element(link).toHaveAttribute("href", `${filePath}#L1C7`);
await link.click();
await vi.waitFor(() => {
expect(openInPreferredEditorMock).toHaveBeenCalledWith(
expect.anything(),
`${filePath}:1:7`,
);
});
} finally {
await screen.unmount();
}
});
it("disambiguates duplicate file basenames inline", async () => {
const firstPath = "/Users/yashsingh/p/t3code/apps/web/src/components/chat/MessagesTimeline.tsx";
const secondPath = "/Users/yashsingh/p/t3code/apps/web/src/components/MessagesTimeline.tsx";
const screen = await render(
<ChatMarkdown
text={`See [MessagesTimeline.tsx](file://${firstPath}) and [MessagesTimeline.tsx](file://${secondPath}).`}
cwd="/repo/project"
/>,
);
try {
await expect
.element(page.getByRole("link", { name: "MessagesTimeline.tsx · components/chat" }))
.toBeInTheDocument();
await expect
.element(page.getByRole("link", { name: "MessagesTimeline.tsx · src/components" }))
.toBeInTheDocument();
} finally {
await screen.unmount();
}
});
it("keeps normal web links unchanged", async () => {
const screen = await render(
<ChatMarkdown text="[OpenAI](https://openai.com/docs)" cwd="/repo/project" />,
);
try {
const link = page.getByRole("link", { name: "OpenAI" });
await expect.element(link).toBeInTheDocument();
await expect.element(link).toHaveAttribute("href", "https://openai.com/docs");
await expect.element(link).toHaveAttribute("target", "_blank");
} finally {
await screen.unmount();
}
});
});
+283 -17
View File
@@ -3,6 +3,7 @@ import { CheckIcon, CopyIcon } from "lucide-react";
import React, {
Children,
Suspense,
type MouseEvent as ReactMouseEvent,
isValidElement,
use,
useCallback,
@@ -17,13 +18,17 @@ import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import { defaultUrlTransform } from "react-markdown";
import remarkGfm from "remark-gfm";
import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { toastManager } from "./ui/toast";
import { openInPreferredEditor } from "../editorPreferences";
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { useTheme } from "../hooks/useTheme";
import { resolveMarkdownFileLinkTarget, rewriteMarkdownFileUriHref } from "../markdown-links";
import { resolveMarkdownFileLinkMeta, rewriteMarkdownFileUriHref } from "../markdown-links";
import { readLocalApi } from "../localApi";
import { cn } from "../lib/utils";
class CodeHighlightErrorBoundary extends React.Component<
{ fallback: ReactNode; children: ReactNode },
@@ -236,34 +241,289 @@ function SuspenseShikiCodeBlock({
);
}
interface MarkdownFileLinkProps {
href: string;
targetPath: string;
displayPath: string;
filePath: string;
label: string;
theme: "light" | "dark";
className?: string | undefined;
}
const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
const MARKDOWN_FILE_LINK_CLASS_NAME =
"chat-markdown-file-link relative top-[2px] max-w-full no-underline";
const MARKDOWN_FILE_LINK_ICON_CLASS_NAME = "chat-markdown-file-link-icon size-3.5 shrink-0";
const MARKDOWN_FILE_LINK_LABEL_CLASS_NAME = "chat-markdown-file-link-label truncate";
function pathParentSegments(path: string): string[] {
const normalized = path.replaceAll("\\", "/");
const segments = normalized.split("/").filter((segment) => segment.length > 0);
return segments.slice(0, -1);
}
function buildFileLinkParentSuffixByPath(filePaths: ReadonlyArray<string>): Map<string, string> {
const groups = new Map<string, Set<string>>();
for (const filePath of filePaths) {
const pathSegments = filePath
.replaceAll("\\", "/")
.split("/")
.filter((segment) => segment.length > 0);
const basename = pathSegments[pathSegments.length - 1];
if (!basename) continue;
const group = groups.get(basename) ?? new Set<string>();
group.add(filePath);
groups.set(basename, group);
}
const suffixByPath = new Map<string, string>();
for (const group of groups.values()) {
const uniquePaths = [...group];
if (uniquePaths.length < 2) continue;
const parentSegmentsByPath = new Map(
uniquePaths.map((filePath) => [filePath, pathParentSegments(filePath)]),
);
const minUniqueDepthByPath = new Map<string, number>();
for (const filePath of uniquePaths) {
const segments = parentSegmentsByPath.get(filePath) ?? [];
let resolvedDepth = segments.length;
for (let depth = 1; depth <= segments.length; depth += 1) {
const candidate = segments.slice(-depth).join("/");
const collision = uniquePaths.some((otherPath) => {
if (otherPath === filePath) return false;
const otherSegments = parentSegmentsByPath.get(otherPath) ?? [];
return otherSegments.slice(-depth).join("/") === candidate;
});
if (!collision) {
resolvedDepth = depth;
break;
}
}
minUniqueDepthByPath.set(filePath, resolvedDepth);
}
for (const filePath of uniquePaths) {
const segments = parentSegmentsByPath.get(filePath) ?? [];
if (segments.length === 0) continue;
const minUniqueDepth = minUniqueDepthByPath.get(filePath) ?? 1;
const suffixDepth = Math.min(segments.length, Math.max(minUniqueDepth, 2));
suffixByPath.set(filePath, segments.slice(-suffixDepth).join("/"));
}
}
return suffixByPath;
}
function extractMarkdownLinkHrefs(text: string): string[] {
const hrefs: string[] = [];
for (const match of text.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
const href = match[1]?.trim();
if (!href) continue;
hrefs.push(href);
}
return hrefs;
}
function normalizeMarkdownLinkHrefKey(href: string): string {
return rewriteMarkdownFileUriHref(href.trim()) ?? href.trim();
}
const MarkdownFileLink = memo(function MarkdownFileLink({
href,
targetPath,
displayPath,
filePath,
label,
theme,
className,
}: MarkdownFileLinkProps) {
const handleOpen = useCallback(() => {
const api = readLocalApi();
if (!api) {
toastManager.add({
type: "error",
title: "Open in editor is unavailable",
});
return;
}
void openInPreferredEditor(api, targetPath).catch((error) => {
toastManager.add({
type: "error",
title: "Unable to open file",
description: error instanceof Error ? error.message : "An error occurred.",
});
});
}, [targetPath]);
const handleCopy = useCallback((value: string, title: string) => {
if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
toastManager.add({
type: "error",
title: `Failed to copy ${title.toLowerCase()}`,
description: "Clipboard API unavailable.",
});
return;
}
void navigator.clipboard.writeText(value).then(
() => {
toastManager.add({
type: "success",
title: `${title} copied`,
description: value,
});
},
(error) => {
toastManager.add({
type: "error",
title: `Failed to copy ${title.toLowerCase()}`,
description: error instanceof Error ? error.message : "An error occurred.",
});
},
);
}, []);
const handleContextMenu = useCallback(
async (event: ReactMouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
event.stopPropagation();
const api = readLocalApi();
if (!api) return;
const clicked = await api.contextMenu.show(
[
{ id: "open", label: "Open in editor" },
{ id: "copy-relative", label: "Copy relative path" },
{ id: "copy-full", label: "Copy full path" },
] as const,
{ x: event.clientX, y: event.clientY },
);
if (clicked === "open") {
handleOpen();
return;
}
if (clicked === "copy-relative") {
handleCopy(displayPath, "Relative path");
return;
}
if (clicked === "copy-full") {
handleCopy(targetPath, "Full path");
}
},
[displayPath, handleCopy, handleOpen, targetPath],
);
return (
<Tooltip>
<TooltipTrigger
render={
<a
href={href}
className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, className)}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
handleOpen();
}}
onContextMenu={handleContextMenu}
>
<VscodeEntryIcon
pathValue={filePath}
kind="file"
theme={theme}
className={cn(MARKDOWN_FILE_LINK_ICON_CLASS_NAME, "text-current")}
/>
<span className={MARKDOWN_FILE_LINK_LABEL_CLASS_NAME}>{label}</span>
</a>
}
/>
<TooltipPopup
side="top"
className="max-w-[min(40rem,calc(100vw-2rem))] font-mono text-[11px] leading-tight"
>
<div className="markdown-file-link-tooltip-scroll overflow-x-auto whitespace-nowrap">
{displayPath}
</div>
</TooltipPopup>
</Tooltip>
);
}, areMarkdownFileLinkPropsEqual);
function areMarkdownFileLinkPropsEqual(
previous: Readonly<MarkdownFileLinkProps>,
next: Readonly<MarkdownFileLinkProps>,
): boolean {
return (
previous.href === next.href &&
previous.targetPath === next.targetPath &&
previous.displayPath === next.displayPath &&
previous.filePath === next.filePath &&
previous.label === next.label &&
previous.theme === next.theme &&
previous.className === next.className
);
}
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const markdownFileLinkMetaByHref = useMemo(() => {
const metaByHref = new Map<
string,
NonNullable<ReturnType<typeof resolveMarkdownFileLinkMeta>>
>();
for (const href of extractMarkdownLinkHrefs(text)) {
const normalizedHref = normalizeMarkdownLinkHrefKey(href);
if (metaByHref.has(normalizedHref)) continue;
const meta = resolveMarkdownFileLinkMeta(normalizedHref, cwd);
if (meta) {
metaByHref.set(normalizedHref, meta);
}
}
return metaByHref;
}, [cwd, text]);
const fileLinkParentSuffixByPath = useMemo(() => {
const filePaths = [...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath);
return buildFileLinkParentSuffixByPath(filePaths);
}, [markdownFileLinkMetaByHref]);
const markdownUrlTransform = useCallback((href: string) => {
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
}, []);
const markdownComponents = useMemo<Components>(
() => ({
a({ node: _node, href, ...props }) {
const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
if (!targetPath) {
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
if (!fileLinkMeta) {
return <a {...props} href={href} target="_blank" rel="noopener noreferrer" />;
}
const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath);
const labelParts = [fileLinkMeta.basename];
if (typeof parentSuffix === "string" && parentSuffix.length > 0) {
labelParts.push(parentSuffix);
}
if (fileLinkMeta.line) {
labelParts.push(
`L${fileLinkMeta.line}${fileLinkMeta.column ? `:C${fileLinkMeta.column}` : ""}`,
);
}
return (
<a
{...props}
href={href}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
const api = readLocalApi();
if (api) {
void openInPreferredEditor(api, targetPath);
} else {
console.warn("Native API not found. Unable to open file in editor.");
}
}}
<MarkdownFileLink
href={href ?? fileLinkMeta.targetPath}
targetPath={fileLinkMeta.targetPath}
displayPath={fileLinkMeta.displayPath}
filePath={fileLinkMeta.filePath}
label={labelParts.join(" · ")}
theme={resolvedTheme}
className={props.className}
/>
);
},
@@ -289,7 +549,13 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
);
},
}),
[cwd, diffThemeName, isStreaming],
[
diffThemeName,
fileLinkParentSuffixByPath,
isStreaming,
markdownFileLinkMetaByHref,
resolvedTheme,
],
);
return (
+840 -11
View File
@@ -5,6 +5,7 @@ import {
EventId,
ORCHESTRATION_WS_METHODS,
EnvironmentId,
type EnvironmentApi,
type MessageId,
type OrchestrationReadModel,
type ProjectId,
@@ -16,12 +17,7 @@ import {
OrchestrationSessionStatus,
DEFAULT_SERVER_SETTINGS,
} from "@t3tools/contracts";
import {
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
@@ -31,6 +27,16 @@ import { render } from "vitest-browser-react";
import { useCommandPaletteStore } from "../commandPaletteStore";
import { useComposerDraftStore, DraftId } from "../composerDraftStore";
import {
__resetEnvironmentApiOverridesForTests,
__setEnvironmentApiOverrideForTests,
} from "../environmentApi";
import {
resetSavedEnvironmentRegistryStoreForTests,
resetSavedEnvironmentRuntimeStoreForTests,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
} from "../environments/runtime";
import {
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
removeInlineTerminalContextPlaceholder,
@@ -41,6 +47,7 @@ import { __resetLocalApiForTests } from "../localApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getRouter } from "../router";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import { selectBootstrapCompleteForActiveEnvironment, useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { useUiStateStore } from "../uiStateStore";
@@ -62,14 +69,27 @@ const ARCHIVED_SECONDARY_THREAD_ID = "thread-secondary-project-archived" as Thre
const PROJECT_ID = "project-1" as ProjectId;
const SECOND_PROJECT_ID = "project-2" as ProjectId;
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const REMOTE_ENVIRONMENT_ID = EnvironmentId.make("environment-remote");
const THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, THREAD_ID);
const THREAD_KEY = scopedThreadKey(THREAD_REF);
const UUID_ROUTE_RE = /^\/draft\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const PROJECT_DRAFT_KEY = `${LOCAL_ENVIRONMENT_ID}:${PROJECT_ID}`;
const PROJECT_KEY = scopedProjectKey(scopeProjectRef(LOCAL_ENVIRONMENT_ID, PROJECT_ID));
const PROJECT_LOGICAL_KEY = deriveLogicalProjectKeyFromSettings(
{
environmentId: LOCAL_ENVIRONMENT_ID,
id: PROJECT_ID,
cwd: "/repo/project",
repositoryIdentity: null,
},
{
sidebarProjectGroupingMode: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingOverrides,
},
);
const NOW_ISO = "2026-03-04T12:00:00.000Z";
const BASE_TIME_MS = Date.parse(NOW_ISO);
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'></svg>";
const ADD_PROJECT_SUBMENU_PLACEHOLDER = "Enter path (e.g. ~/projects/my-app)";
interface TestFixture {
snapshot: OrchestrationReadModel;
@@ -172,6 +192,32 @@ function createBaseServerConfig(): ServerConfig {
};
}
function createMockEnvironmentApi(input: {
browse: EnvironmentApi["filesystem"]["browse"];
dispatchCommand: EnvironmentApi["orchestration"]["dispatchCommand"];
}): EnvironmentApi {
return {
terminal: {} as EnvironmentApi["terminal"],
projects: {} as EnvironmentApi["projects"],
filesystem: {
browse: input.browse,
},
git: {} as EnvironmentApi["git"],
orchestration: {
dispatchCommand: input.dispatchCommand,
getTurnDiff: (() => {
throw new Error("Not implemented in browser test.");
}) as EnvironmentApi["orchestration"]["getTurnDiff"],
getFullThreadDiff: (() => {
throw new Error("Not implemented in browser test.");
}) as EnvironmentApi["orchestration"]["getFullThreadDiff"],
subscribeShell: (() => () => undefined) as EnvironmentApi["orchestration"]["subscribeShell"],
subscribeThread: (() => () =>
undefined) as EnvironmentApi["orchestration"]["subscribeThread"],
},
};
}
function createUserMessage(options: {
id: MessageId;
text: string;
@@ -1383,6 +1429,44 @@ async function waitForCommandPaletteShortcutLabel(): Promise<void> {
);
}
async function waitForCommandPaletteInput(placeholder: string): Promise<HTMLInputElement> {
return waitForElement(
() => document.querySelector(`input[placeholder="${placeholder}"]`) as HTMLInputElement | null,
`Command palette input with placeholder "${placeholder}" did not render.`,
);
}
function getCommandPaletteLegendEntries(): string[] {
const footer = document.querySelector('[data-slot="command-footer"]');
if (!footer) {
return [];
}
return Array.from(footer.querySelectorAll('[data-slot="kbd-group"]'))
.map((group) =>
Array.from(group.children)
.map((child) => child.textContent?.trim() ?? "")
.filter((value) => value.length > 0)
.join(" "),
)
.filter((value) => value.length > 0);
}
async function dispatchInputKey(
input: HTMLInputElement,
init: Pick<KeyboardEventInit, "key" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey">,
): Promise<void> {
input.focus();
input.dispatchEvent(
new KeyboardEvent("keydown", {
bubbles: true,
cancelable: true,
...init,
}),
);
await waitForLayout();
}
async function mountChatView(options: {
viewport: ViewportSpec;
snapshot: OrchestrationReadModel;
@@ -1524,6 +1608,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
document.body.innerHTML = "";
wsRequests.length = 0;
customWsRpcResolver = null;
__resetEnvironmentApiOverridesForTests();
resetSavedEnvironmentRegistryStoreForTests();
resetSavedEnvironmentRuntimeStoreForTests();
Reflect.deleteProperty(window, "desktopBridge");
useComposerDraftStore.setState({
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
@@ -1533,6 +1621,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
useCommandPaletteStore.setState({
open: false,
openIntent: null,
});
useStore.setState({
activeEnvironmentId: null,
@@ -1556,12 +1645,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
customWsRpcResolver = null;
document.body.innerHTML = "";
});
it("re-expands the bootstrap project using its scoped key", async () => {
it("re-expands the bootstrap project using its logical key", async () => {
useUiStateStore.setState({
projectExpandedById: {
[PROJECT_KEY]: false,
[PROJECT_LOGICAL_KEY]: false,
},
projectOrder: [PROJECT_KEY],
projectOrder: [PROJECT_LOGICAL_KEY],
threadLastVisitedAtById: {},
});
@@ -1576,7 +1665,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
await vi.waitFor(
() => {
expect(useUiStateStore.getState().projectExpandedById[PROJECT_KEY]).toBe(true);
expect(useUiStateStore.getState().projectExpandedById[PROJECT_LOGICAL_KEY]).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
@@ -4079,6 +4168,746 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("adds a project from browse mode with Enter when no directory is highlighted", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-add-project-enter" as MessageId,
targetText: "command palette add project enter",
}),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
keybindings: [
{
command: "commandPalette.toggle",
shortcut: {
key: "k",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
],
};
},
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Development/") {
return {
parentPath: "~/Development/",
entries: [
{ name: "alpha", fullPath: "~/Development/alpha" },
{ name: "beta", fullPath: "~/Development/beta" },
],
};
}
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
await waitForCommandPaletteShortcutLabel();
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Add project", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/");
await expect.element(palette.getByText("alpha", { exact: true })).toBeInTheDocument();
await expect
.element(palette.getByRole("button", { name: "Add (Enter)" }))
.toBeInTheDocument();
await dispatchInputKey(browseInput, { key: "Enter" });
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) =>
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
request.type === "project.create",
) as
| {
_tag: string;
type?: string;
workspaceRoot?: string;
title?: string;
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "project.create",
workspaceRoot: "~/Development",
title: "Development",
});
},
{ timeout: 8_000, interval: 16 },
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread after adding a project with Enter.",
);
} finally {
await mounted.cleanup();
}
});
it("opens add project browse mode from the sidebar add button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-sidebar-add-project-trigger" as MessageId,
targetText: "sidebar add project trigger",
}),
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
await page.getByTestId("sidebar-add-project-trigger").click();
const palette = page.getByTestId("command-palette");
await expect.element(palette).toBeInTheDocument();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await expect.element(browseInput).toHaveValue("~/");
await vi.waitFor(
() => {
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.filesystemBrowse && request.partialPath === "~/",
),
).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("starts add project browse mode from the configured base directory", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-sidebar-add-project-custom-base-dir" as MessageId,
targetText: "sidebar add project custom base directory",
}),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
settings: {
...nextFixture.serverConfig.settings,
addProjectBaseDirectory: "~/Development",
},
};
},
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Development/") {
return {
parentPath: "~/Development/",
entries: [{ name: "codething", fullPath: "~/Development/codething" }],
};
}
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
await page.getByTestId("sidebar-add-project-trigger").click();
const palette = page.getByTestId("command-palette");
await expect.element(palette).toBeInTheDocument();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await expect.element(browseInput).toHaveValue("~/Development/");
await vi.waitFor(
() => {
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.filesystemBrowse &&
request.partialPath === "~/Development/",
),
).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("shows create-folder affordances for missing project paths", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-create-missing-project" as MessageId,
targetText: "command palette create missing project",
}),
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Desktop/") {
return {
parentPath: "~/Desktop/",
entries: [{ name: "existing", fullPath: "~/Desktop/existing" }],
};
}
return {
parentPath: "~/",
entries: [{ name: "Desktop", fullPath: "~/Desktop" }],
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
const palette = page.getByTestId("command-palette");
await page.getByTestId("sidebar-add-project-trigger").click();
await expect.element(palette).toBeInTheDocument();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Desktop/fresh-project");
await expect
.element(palette.getByRole("button", { name: "Create & Add (Enter)" }))
.toBeInTheDocument();
await expect.element(palette.getByText("Will create this folder")).not.toBeInTheDocument();
await dispatchInputKey(browseInput, { key: "Enter" });
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) =>
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
request.type === "project.create",
) as
| {
_tag: string;
type?: string;
workspaceRoot?: string;
title?: string;
createWorkspaceRootIfMissing?: boolean;
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "project.create",
workspaceRoot: "~/Desktop/fresh-project",
title: "fresh-project",
createWorkspaceRootIfMissing: true,
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("does not show create affordances for an existing directory with a trailing slash", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-existing-trailing-directory" as MessageId,
targetText: "command palette existing trailing directory",
}),
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Development/codex/") {
return {
parentPath: "~/Development/codex/",
entries: [{ name: "Codex.app", fullPath: "~/Development/codex/Codex.app" }],
};
}
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
const palette = page.getByTestId("command-palette");
await page.getByTestId("sidebar-add-project-trigger").click();
await expect.element(palette).toBeInTheDocument();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/codex/");
await vi.waitFor(
() => {
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.filesystemBrowse &&
request.partialPath === "~/Development/codex/",
),
).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
await expect
.element(palette.getByRole("button", { name: "Add (Enter)" }))
.toBeInTheDocument();
await expect
.element(palette.getByRole("button", { name: "Create & Add (Enter)" }))
.not.toBeInTheDocument();
await dispatchInputKey(browseInput, { key: "Enter" });
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) =>
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
request.type === "project.create",
) as
| {
_tag: string;
type?: string;
workspaceRoot?: string;
title?: string;
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "project.create",
workspaceRoot: "~/Development/codex",
title: "codex",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("selects an environment before browsing when multiple environments are available", async () => {
const remoteBrowseMock = vi.fn(async ({ partialPath }: { partialPath: string }) => {
if (partialPath === "~/workspaces/") {
return {
parentPath: "~/workspaces/",
entries: [{ name: "codething", fullPath: "~/workspaces/codething" }],
};
}
return {
parentPath: "~/",
entries: [{ name: "workspaces", fullPath: "~/workspaces" }],
};
});
const remoteDispatchMock = vi.fn(async () => ({
sequence: fixture.snapshot.snapshotSequence + 1,
}));
__setEnvironmentApiOverrideForTests(
REMOTE_ENVIRONMENT_ID,
createMockEnvironmentApi({
browse: remoteBrowseMock,
dispatchCommand: remoteDispatchMock,
}),
);
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-add-project-multi-env" as MessageId,
targetText: "command palette add project multi env",
}),
});
try {
await waitForServerConfigToApply();
useSavedEnvironmentRegistryStore.getState().upsert({
environmentId: REMOTE_ENVIRONMENT_ID,
label: "Staging",
httpBaseUrl: "https://staging.example.test",
wsBaseUrl: "wss://staging.example.test/ws",
createdAt: NOW_ISO,
lastConnectedAt: NOW_ISO,
});
useSavedEnvironmentRuntimeStore.getState().patch(REMOTE_ENVIRONMENT_ID, {
connectionState: "connected",
authState: "authenticated",
descriptor: {
...fixture.serverConfig.environment,
environmentId: REMOTE_ENVIRONMENT_ID,
label: "Staging",
},
serverConfig: {
...fixture.serverConfig,
environment: {
...fixture.serverConfig.environment,
environmentId: REMOTE_ENVIRONMENT_ID,
label: "Staging",
},
settings: {
...fixture.serverConfig.settings,
addProjectBaseDirectory: "~/workspaces",
},
},
connectedAt: NOW_ISO,
});
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Add project", { exact: true }).click();
await expect.element(palette.getByText("Environments", { exact: true })).toBeInTheDocument();
await expect
.element(palette.getByText("This device", { exact: true }).first())
.toBeInTheDocument();
await palette.getByText("Staging", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await expect.element(browseInput).toHaveValue("~/workspaces/");
await vi.waitFor(
() => {
expect(remoteBrowseMock).toHaveBeenCalledWith({ partialPath: "~/workspaces/" });
},
{ timeout: 8_000, interval: 16 },
);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/workspaces/");
await vi.waitFor(
() => {
expect(remoteBrowseMock).toHaveBeenCalledWith({ partialPath: "~/workspaces/" });
},
{ timeout: 8_000, interval: 16 },
);
await expect.element(palette.getByText("codething", { exact: true })).toBeInTheDocument();
await expect
.element(palette.getByRole("button", { name: "Add (Enter)" }))
.toBeInTheDocument();
await dispatchInputKey(browseInput, { key: "Enter" });
await vi.waitFor(
() => {
expect(remoteDispatchMock).toHaveBeenCalledWith(
expect.objectContaining({
type: "project.create",
workspaceRoot: "~/workspaces",
title: "workspaces",
}),
);
},
{ timeout: 8_000, interval: 16 },
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread after adding a remote project.",
);
} finally {
await mounted.cleanup();
}
});
it("picks a local project from the native file manager", async () => {
const pickFolder = vi.fn().mockResolvedValue("/Users/julius/Projects/finder-picked");
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-add-project-file-manager" as MessageId,
targetText: "command palette add project file manager",
}),
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Applications/") {
return {
parentPath: "~/Applications/",
entries: [{ name: "Utilities", fullPath: "~/Applications/Utilities" }],
};
}
return {
parentPath: "~/",
entries: [{ name: "Applications", fullPath: "~/Applications" }],
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
window.desktopBridge = {
pickFolder,
setTheme: vi.fn().mockResolvedValue(undefined),
} as unknown as NonNullable<typeof window.desktopBridge>;
await page.getByTestId("sidebar-add-project-trigger").click();
const palette = page.getByTestId("command-palette");
await expect.element(palette).toBeInTheDocument();
const browseInput = palette.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await browseInput.fill("~/Applications/access");
const fileManagerLabel = isMacPlatform(navigator.platform)
? "Open in Finder"
: navigator.platform.toLowerCase().startsWith("win")
? "Open in Explorer"
: "Open in Files";
await palette.getByRole("button", { name: fileManagerLabel }).click();
await vi.waitFor(
() => {
expect(pickFolder).toHaveBeenCalledWith({ initialPath: "~/Applications" });
},
{ timeout: 8_000, interval: 16 },
);
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) =>
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
request.type === "project.create",
) as
| {
_tag: string;
type?: string;
workspaceRoot?: string;
title?: string;
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "project.create",
workspaceRoot: "/Users/julius/Projects/finder-picked",
title: "finder-picked",
});
},
{ timeout: 8_000, interval: 16 },
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread after adding a project from the native file manager.",
);
} finally {
await mounted.cleanup();
}
});
it("adds a project from browse mode with Mod+Enter when a directory is highlighted", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-add-project-mod-enter" as MessageId,
targetText: "command palette add project mod enter",
}),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
keybindings: [
{
command: "commandPalette.toggle",
shortcut: {
key: "k",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
],
};
},
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
if (body.partialPath === "~/Development/") {
return {
parentPath: "~/Development/",
entries: [
{ name: "alpha", fullPath: "~/Development/alpha" },
{ name: "beta", fullPath: "~/Development/beta" },
],
};
}
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await waitForServerConfigToApply();
await waitForCommandPaletteShortcutLabel();
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Add project", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/");
await expect.element(palette.getByText("alpha", { exact: true })).toBeInTheDocument();
await dispatchInputKey(browseInput, { key: "ArrowDown" });
const addButtonLabel = isMacPlatform(navigator.platform)
? "Add (\u2318 Enter)"
: "Add (Ctrl Enter)";
await vi.waitFor(
() => {
const legendEntries = getCommandPaletteLegendEntries();
expect(legendEntries).toContain("Enter Select");
},
{ timeout: 8_000, interval: 16 },
);
await expect
.element(palette.getByRole("button", { name: addButtonLabel }))
.toBeInTheDocument();
await dispatchInputKey(browseInput, {
key: "Enter",
metaKey: isMacPlatform(navigator.platform),
ctrlKey: !isMacPlatform(navigator.platform),
});
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) =>
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
request.type === "project.create",
) as
| {
_tag: string;
type?: string;
workspaceRoot?: string;
title?: string;
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "project.create",
workspaceRoot: "~/Development",
title: "Development",
});
},
{ timeout: 8_000, interval: 16 },
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread after adding a project with Mod+Enter.",
);
} finally {
await mounted.cleanup();
}
});
it("keeps project-context thread matches available when searching by project name", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
+44 -13
View File
@@ -1,7 +1,7 @@
import {
type ApprovalRequestId,
DEFAULT_MODEL_BY_PROVIDER,
type ClaudeCodeEffort,
type ClaudeAgentEffort,
type EnvironmentId,
type MessageId,
type ModelSelection,
@@ -92,6 +92,8 @@ import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useCommandPaletteStore } from "../commandPaletteStore";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import PlanSidebar from "./PlanSidebar";
@@ -111,7 +113,7 @@ import { getProviderModelCapabilities, resolveSelectableProvider } from "../prov
import { useSettings } from "../hooks/useSettings";
import { resolveAppModelSelection } from "../modelSelection";
import { isTerminalFocused } from "../lib/terminalFocus";
import { deriveLogicalProjectKey } from "../logicalProject";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import {
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
@@ -171,6 +173,7 @@ import {
} from "~/rpc/serverState";
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import { retainThreadDetailSubscription } from "../environments/runtime/service";
import { RightPanelSheet } from "./RightPanelSheet";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
@@ -303,7 +306,7 @@ function formatOutgoingPrompt(params: {
}): string {
const caps = getProviderModelCapabilities(params.models, params.model, params.provider);
if (params.effort && caps.promptInjectedEffortLevels.includes(params.effort)) {
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null);
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeAgentEffort | null);
}
return params.text;
}
@@ -675,6 +678,7 @@ export default function ChatView(props: ChatViewProps) {
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
useState<Record<string, number>>({});
const [planSidebarOpen, setPlanSidebarOpen] = useState(false);
const shouldUsePlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
// When set, the thread-change reset effect will open the sidebar instead of closing it.
@@ -843,10 +847,16 @@ export default function ChatView(props: ChatViewProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId);
const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const logicalProjectEnvironments = useMemo(() => {
if (!activeProject) return [];
const logicalKey = deriveLogicalProjectKey(activeProject);
const memberProjects = allProjects.filter((p) => deriveLogicalProjectKey(p) === logicalKey);
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
const memberProjects = allProjects.filter(
(p) => deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) === logicalKey,
);
const seen = new Set<string>();
const envs: Array<{
environmentId: EnvironmentId;
@@ -882,6 +892,7 @@ export default function ChatView(props: ChatViewProps) {
}, [
activeProject,
allProjects,
projectGroupingSettings,
primaryEnvironmentId,
savedEnvironmentRegistry,
savedEnvironmentRuntimeById,
@@ -911,7 +922,10 @@ export default function ChatView(props: ChatViewProps) {
throw new Error("No active project is available for this pull request.");
}
const activeProjectRef = scopeProjectRef(activeProject.environmentId, activeProject.id);
const logicalProjectKey = deriveLogicalProjectKey(activeProject);
const logicalProjectKey = deriveLogicalProjectKeyFromSettings(
activeProject,
projectGroupingSettings,
);
const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey);
if (storedDraftSession) {
setDraftThreadContext(storedDraftSession.draftId, input);
@@ -972,6 +986,7 @@ export default function ChatView(props: ChatViewProps) {
getDraftSessionByLogicalProjectKey,
isServerThread,
navigate,
projectGroupingSettings,
routeKind,
setDraftThreadContext,
setLogicalProjectDraftThreadId,
@@ -1897,6 +1912,11 @@ export default function ChatView(props: ChatViewProps) {
return !open;
});
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
const closePlanSidebar = useCallback(() => {
setPlanSidebarOpen(false);
planSidebarDismissedForTurnRef.current =
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
const persistThreadSettingsForNextTurn = useCallback(
async (input: {
@@ -3394,7 +3414,7 @@ export default function ChatView(props: ChatViewProps) {
{/* end chat column */}
{/* Plan sidebar */}
{planSidebarOpen ? (
{planSidebarOpen && !shouldUsePlanSidebarSheet ? (
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
@@ -3403,12 +3423,8 @@ export default function ChatView(props: ChatViewProps) {
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
onClose={() => {
setPlanSidebarOpen(false);
// Track that the user explicitly dismissed for this turn so auto-open won't fight them.
planSidebarDismissedForTurnRef.current =
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
}}
mode="sidebar"
onClose={closePlanSidebar}
/>
) : null}
</div>
@@ -3430,6 +3446,21 @@ export default function ChatView(props: ChatViewProps) {
onAddTerminalContext={addTerminalContextToDraft}
/>
))}
{shouldUsePlanSidebarSheet ? (
<RightPanelSheet open={planSidebarOpen} onClose={closePlanSidebar}>
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
label={planSidebarLabel}
environmentId={environmentId}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
mode="sheet"
onClose={closePlanSidebar}
/>
</RightPanelSheet>
) : null}
{expandedImage && (
<ExpandedImageDialog preview={expandedImage} onClose={closeExpandedImage} />
@@ -4,6 +4,7 @@ import type { Thread } from "../types";
import {
buildThreadActionItems,
filterCommandPaletteGroups,
getBrowsePrefetchPaths,
type CommandPaletteGroup,
} from "./CommandPalette.logic";
@@ -164,3 +165,28 @@ describe("buildThreadActionItems", () => {
expect(items.map((item) => item.value)).toEqual(["thread:thread-active"]);
});
});
describe("getBrowsePrefetchPaths", () => {
it("prefetches the parent path and an exact typed child path", () => {
expect(
getBrowsePrefetchPaths({
browseQuery: "~/Downloads",
canBrowseUp: true,
exactEntry: {
name: "Downloads",
fullPath: "/Users/test/Downloads",
},
}),
).toEqual(["~/", "~/Downloads/"]);
});
it("does not prefetch a child path when the user only has a highlighted browse row", () => {
expect(
getBrowsePrefetchPaths({
browseQuery: "~/Do",
canBrowseUp: true,
exactEntry: null,
}),
).toEqual(["~/"]);
});
});
@@ -1,6 +1,7 @@
import { type KeybindingCommand } from "@t3tools/contracts";
import { type KeybindingCommand, type FilesystemBrowseEntry } from "@t3tools/contracts";
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import { type ReactNode } from "react";
import { appendBrowsePathSegment, getBrowseParentPath } from "../lib/projectPaths";
import { sortThreads } from "../lib/threadSort";
import { formatRelativeTimeLabel } from "../timestampFormat";
import { type Project, type SidebarThreadSummary, type Thread } from "../types";
@@ -45,7 +46,52 @@ export interface CommandPaletteView {
readonly initialQuery?: string;
}
export type CommandPaletteMode = "root" | "submenu";
export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
export function filterBrowseEntries(input: {
browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
browseFilterQuery: string;
}): {
filteredEntries: FilesystemBrowseEntry[];
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(".")),
);
const exactEntry =
input.browseFilterQuery.length > 0
? (filteredEntries.find((entry) => entry.name === input.browseFilterQuery) ?? null)
: null;
return { filteredEntries, exactEntry };
}
export function getBrowsePrefetchPaths(input: {
browseQuery: string;
canBrowseUp: boolean;
exactEntry: FilesystemBrowseEntry | null;
}): string[] {
const paths: string[] = [];
if (input.canBrowseUp) {
const parentPath = getBrowseParentPath(input.browseQuery);
if (parentPath !== null) {
paths.push(parentPath);
}
}
if (input.exactEntry) {
paths.push(appendBrowsePathSegment(input.browseQuery, input.exactEntry.name));
}
return paths;
}
export function normalizeSearchText(value: string): string {
return value.trim().toLowerCase().replace(/\s+/g, " ");
@@ -230,10 +276,56 @@ export function filterCommandPaletteGroups(input: {
});
}
export function buildBrowseGroups(input: {
browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
browseQuery: string;
canBrowseUp: boolean;
upIcon: ReactNode;
directoryIcon: ReactNode;
browseUp: () => void;
browseTo: (name: string) => void;
}): CommandPaletteGroup[] {
const items: CommandPaletteActionItem[] = [];
if (input.canBrowseUp) {
items.push({
kind: "action",
value: "browse:up",
searchTerms: [input.browseQuery, ".."],
title: "..",
icon: input.upIcon,
keepOpen: true,
run: async () => {
input.browseUp();
},
});
}
for (const entry of input.browseEntries) {
items.push({
kind: "action",
value: `browse:${entry.fullPath}`,
searchTerms: [input.browseQuery, entry.fullPath, entry.name],
title: entry.name,
icon: input.directoryIcon,
keepOpen: true,
run: async () => {
input.browseTo(entry.name);
},
});
}
return [{ value: "directories", label: "Directories", items }];
}
export function getCommandPaletteMode(input: {
currentView: CommandPaletteView | null;
isBrowsing: boolean;
}): CommandPaletteMode {
return input.currentView ? "submenu" : "root";
if (input.currentView) {
return input.isBrowsing ? "submenu-browse" : "submenu";
}
return input.isBrowsing ? "root-browse" : "root";
}
export function buildRootGroups(input: {
@@ -258,7 +350,11 @@ export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): str
switch (mode) {
case "root":
return "Search commands, projects, and threads...";
case "root-browse":
return "Enter project path (e.g. ~/projects/my-app)";
case "submenu":
return "Search...";
case "submenu-browse":
return "Enter path (e.g. ~/projects/my-app)";
}
}
+688 -39
View File
@@ -1,17 +1,27 @@
"use client";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import type { ProjectId } from "@t3tools/contracts";
import {
DEFAULT_MODEL_BY_PROVIDER,
type EnvironmentId,
type FilesystemBrowseResult,
type ProjectId,
} from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
import {
ArrowDownIcon,
ArrowLeftIcon,
ArrowUpIcon,
CornerLeftUpIcon,
FolderIcon,
FolderPlusIcon,
MessageSquareIcon,
SettingsIcon,
SquarePenIcon,
} from "lucide-react";
import {
useCallback,
useDeferredValue,
useEffect,
useMemo,
@@ -22,15 +32,37 @@ import {
} from "react";
import { useShallow } from "zustand/react/shallow";
import { useCommandPaletteStore } from "../commandPaletteStore";
import { readEnvironmentApi } from "../environmentApi";
import { readPrimaryEnvironmentDescriptor, usePrimaryEnvironmentId } from "../environments/primary";
import {
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
} from "../environments/runtime";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useSettings } from "../hooks/useSettings";
import { readLocalApi } from "../localApi";
import {
startNewThreadInProjectFromContext,
startNewThreadFromContext,
} from "../lib/chatThreadActions";
import {
appendBrowsePathSegment,
canNavigateUp,
ensureBrowseDirectoryPath,
findProjectByPath,
getBrowseDirectoryPath,
getBrowseLeafPathSegment,
getBrowseParentPath,
hasTrailingPathSeparator,
inferProjectTitleFromPath,
isExplicitRelativeProjectPath,
isFilesystemBrowseQuery,
isUnsupportedWindowsProjectPath,
resolveProjectPathForDispatch,
} from "../lib/projectPaths";
import { isTerminalFocused } from "../lib/terminalFocus";
import { getLatestThreadForProject } from "../lib/threadSort";
import { cn } from "../lib/utils";
import { cn, isMacPlatform, isWindowsPlatform, newCommandId, newProjectId } from "../lib/utils";
import {
selectProjectsAcrossEnvironments,
selectSidebarThreadsAcrossEnvironments,
@@ -40,18 +72,22 @@ import { selectThreadTerminalState, useTerminalStateStore } from "../terminalSta
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
import {
ADDON_ICON_CLASS,
buildBrowseGroups,
buildProjectActionItems,
buildRootGroups,
buildThreadActionItems,
type CommandPaletteActionItem,
type CommandPaletteSubmenuItem,
type CommandPaletteView,
filterBrowseEntries,
filterCommandPaletteGroups,
getBrowsePrefetchPaths,
getCommandPaletteInputPlaceholder,
getCommandPaletteMode,
ITEM_ICON_CLASS,
RECENT_THREAD_LIMIT,
} from "./CommandPalette.logic";
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
import { CommandPaletteResults } from "./CommandPaletteResults";
import { ProjectFavicon } from "./ProjectFavicon";
import { useServerKeybindings } from "../rpc/serverState";
@@ -64,11 +100,44 @@ import {
CommandInput,
CommandPanel,
} from "./ui/command";
import { Button } from "./ui/button";
import { Kbd, KbdGroup } from "./ui/kbd";
import { toastManager } from "./ui/toast";
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
import type { ChatComposerHandle } from "./chat/ChatComposer";
const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
const BROWSE_STALE_TIME_MS = 30_000;
function getLocalFileManagerName(platform: string): string {
if (isMacPlatform(platform)) {
return "Finder";
}
if (isWindowsPlatform(platform)) {
return "Explorer";
}
return "Files";
}
function getEnvironmentBrowsePlatform(os: string | null | undefined): string {
if (os === "windows") {
return "Win32";
}
if (os === "darwin") {
return "MacIntel";
}
if (os === "linux") {
return "Linux";
}
return typeof navigator === "undefined" ? "" : navigator.platform;
}
interface AddProjectEnvironmentOption {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly isPrimary: boolean;
}
export function CommandPalette({ children }: { children: ReactNode }) {
const open = useCommandPaletteStore((store) => store.open);
const setOpen = useCommandPaletteStore((store) => store.setOpen);
@@ -136,10 +205,14 @@ function CommandPaletteDialog() {
function OpenCommandPaletteDialog() {
const navigate = useNavigate();
const setOpen = useCommandPaletteStore((store) => store.setOpen);
const openIntent = useCommandPaletteStore((store) => store.openIntent);
const clearOpenIntent = useCommandPaletteStore((store) => store.clearOpenIntent);
const composerHandleRef = useComposerHandleContext();
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
const isActionsOnly = deferredQuery.startsWith(">");
const queryClient = useQueryClient();
const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);
const settings = useSettings();
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
useHandleNewThread();
@@ -148,15 +221,193 @@ function OpenCommandPaletteDialog() {
const keybindings = useServerKeybindings();
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
const currentView = viewStack.at(-1) ?? null;
const paletteMode = getCommandPaletteMode({ currentView });
const [browseGeneration, setBrowseGeneration] = useState(0);
const [addProjectEnvironmentId, setAddProjectEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const primaryEnvironmentLabel = readPrimaryEnvironmentDescriptor()?.label ?? null;
const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((state) => state.byId);
const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((state) => state.byId);
const addProjectEnvironmentOptions = useMemo(() => {
const options: AddProjectEnvironmentOption[] = [];
const seenEnvironmentIds = new Set<EnvironmentId>();
if (primaryEnvironmentId) {
seenEnvironmentIds.add(primaryEnvironmentId);
options.push({
environmentId: primaryEnvironmentId,
label: resolveEnvironmentOptionLabel({
isPrimary: true,
environmentId: primaryEnvironmentId,
runtimeLabel: primaryEnvironmentLabel,
}),
isPrimary: true,
});
}
for (const record of Object.values(savedEnvironmentRegistry)) {
if (seenEnvironmentIds.has(record.environmentId)) {
continue;
}
const runtimeState = savedEnvironmentRuntimeById[record.environmentId];
options.push({
environmentId: record.environmentId,
label: resolveEnvironmentOptionLabel({
isPrimary: false,
environmentId: record.environmentId,
runtimeLabel: runtimeState?.descriptor?.label ?? null,
savedLabel: record.label,
}),
isPrimary: false,
});
}
options.sort((left, right) => {
if (left.isPrimary !== right.isPrimary) {
return left.isPrimary ? -1 : 1;
}
return left.label.localeCompare(right.label);
});
return options;
}, [
primaryEnvironmentId,
primaryEnvironmentLabel,
savedEnvironmentRegistry,
savedEnvironmentRuntimeById,
]);
const defaultAddProjectEnvironmentId = addProjectEnvironmentOptions[0]?.environmentId ?? null;
const browseEnvironmentId = addProjectEnvironmentId ?? defaultAddProjectEnvironmentId;
const browseEnvironmentPlatform = useMemo(() => {
const os =
browseEnvironmentId && primaryEnvironmentId && browseEnvironmentId === primaryEnvironmentId
? (readPrimaryEnvironmentDescriptor()?.platform.os ?? null)
: browseEnvironmentId
? (savedEnvironmentRuntimeById[browseEnvironmentId]?.descriptor?.platform.os ??
savedEnvironmentRuntimeById[browseEnvironmentId]?.serverConfig?.environment.platform
.os ??
null)
: null;
return getEnvironmentBrowsePlatform(os);
}, [browseEnvironmentId, primaryEnvironmentId, savedEnvironmentRuntimeById]);
const isBrowsing = isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
const paletteMode = getCommandPaletteMode({ currentView, isBrowsing });
const getAddProjectInitialQueryForEnvironment = useCallback(
(environmentId: EnvironmentId | null): string => {
const environmentSettings =
environmentId && primaryEnvironmentId && environmentId === primaryEnvironmentId
? settings
: environmentId
? savedEnvironmentRuntimeById[environmentId]?.serverConfig?.settings
: null;
const baseDirectory = environmentSettings?.addProjectBaseDirectory?.trim() ?? "";
if (baseDirectory.length === 0) {
return "~/";
}
return ensureBrowseDirectoryPath(baseDirectory);
},
[primaryEnvironmentId, savedEnvironmentRuntimeById, settings],
);
const projectCwdById = useMemo(
() => new Map<ProjectId, string>(projects.map((project) => [project.id, project.cwd])),
[projects],
);
const projectTitleById = useMemo(
() => new Map<ProjectId, string>(projects.map((project) => [project.id, project.name])),
[projects],
);
const activeThreadId = activeThread?.id;
const currentProjectEnvironmentId =
activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null;
const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null;
const currentProjectCwd = currentProjectId
? (projectCwdById.get(currentProjectId) ?? null)
: null;
const currentProjectCwdForBrowse =
browseEnvironmentId && currentProjectEnvironmentId === browseEnvironmentId
? currentProjectCwd
: null;
const relativePathNeedsActiveProject =
isExplicitRelativeProjectPath(query.trim()) && currentProjectCwdForBrowse === null;
const browseDirectoryPath = isBrowsing ? getBrowseDirectoryPath(query) : "";
const browseFilterQuery =
isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : "";
const fetchBrowseResult = useCallback(
async (partialPath: string): Promise<FilesystemBrowseResult | null> => {
if (!browseEnvironmentId) return null;
const api = readEnvironmentApi(browseEnvironmentId);
if (!api) return null;
return api.filesystem.browse({
partialPath,
...(currentProjectCwdForBrowse ? { cwd: currentProjectCwdForBrowse } : {}),
});
},
[browseEnvironmentId, currentProjectCwdForBrowse],
);
const { data: browseResult, isPending: isBrowsePending } = useQuery({
queryKey: [
"filesystemBrowse",
browseEnvironmentId,
browseDirectoryPath,
currentProjectCwdForBrowse,
],
queryFn: () => fetchBrowseResult(browseDirectoryPath),
staleTime: BROWSE_STALE_TIME_MS,
enabled:
isBrowsing &&
browseDirectoryPath.length > 0 &&
browseEnvironmentId !== null &&
!relativePathNeedsActiveProject,
});
const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES;
const { filteredEntries: filteredBrowseEntries, exactEntry: exactBrowseEntry } = useMemo(
() => filterBrowseEntries({ browseEntries, browseFilterQuery }),
[browseEntries, browseFilterQuery],
);
const prefetchBrowsePath = useCallback(
(partialPath: string) => {
void queryClient.prefetchQuery({
queryKey: [
"filesystemBrowse",
browseEnvironmentId,
partialPath,
currentProjectCwdForBrowse,
],
queryFn: () => fetchBrowseResult(partialPath),
staleTime: BROWSE_STALE_TIME_MS,
});
},
[browseEnvironmentId, currentProjectCwdForBrowse, fetchBrowseResult, queryClient],
);
const browsePrefetchPaths = useMemo(
() =>
getBrowsePrefetchPaths({
browseQuery: query,
canBrowseUp: canNavigateUp(query),
exactEntry: exactBrowseEntry,
}),
[exactBrowseEntry, query],
);
// Prefetch the parent and only an exact typed child so browse navigation
// stays warm without turning pointer hover into a directory read.
useEffect(() => {
if (!isBrowsing || filteredBrowseEntries.length === 0) return;
for (const partialPath of browsePrefetchPaths) {
prefetchBrowsePath(partialPath);
}
}, [filteredBrowseEntries.length, browsePrefetchPaths, isBrowsing, prefetchBrowsePath]);
const openProjectFromSearch = useMemo(
() => async (project: (typeof projects)[number]) => {
@@ -259,30 +510,117 @@ function OpenCommandPaletteDialog() {
);
const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
function pushView(item: CommandPaletteSubmenuItem): void {
function pushPaletteView(view: CommandPaletteView): void {
setViewStack((previousViews) => [
...previousViews,
{
addonIcon: item.addonIcon,
groups: item.groups,
...(item.initialQuery ? { initialQuery: item.initialQuery } : {}),
addonIcon: view.addonIcon,
groups: view.groups,
...(view.initialQuery ? { initialQuery: view.initialQuery } : {}),
},
]);
setQuery(item.initialQuery ?? "");
setHighlightedItemValue(null);
setQuery(view.initialQuery ?? "");
}
function pushView(item: CommandPaletteSubmenuItem): void {
pushPaletteView({
addonIcon: item.addonIcon,
groups: item.groups,
...(item.initialQuery ? { initialQuery: item.initialQuery } : {}),
});
}
function popView(): void {
if (viewStack.length <= 1) {
setAddProjectEnvironmentId(null);
}
setViewStack((previousViews) => previousViews.slice(0, -1));
setHighlightedItemValue(null);
setQuery("");
}
function handleQueryChange(nextQuery: string): void {
setHighlightedItemValue(null);
setQuery(nextQuery);
if (nextQuery === "" && currentView?.initialQuery) {
popView();
}
}
const startAddProjectBrowse = useCallback(
(environmentId: EnvironmentId): void => {
setAddProjectEnvironmentId(environmentId);
pushPaletteView({
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: [],
initialQuery: getAddProjectInitialQueryForEnvironment(environmentId),
});
},
[getAddProjectInitialQueryForEnvironment],
);
const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map(
(option) => ({
kind: "action",
value: `action:add-project:environment:${option.environmentId}`,
searchTerms: [option.label, option.environmentId, option.isPrimary ? "this device" : ""],
title: option.label,
description: option.isPrimary ? "This device" : option.environmentId,
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
startAddProjectBrowse(option.environmentId);
},
}),
);
const addProjectEnvironmentGroups = useMemo<CommandPaletteView["groups"]>(
() => [
{
value: "environments",
label: "Environments",
items: addProjectEnvironmentItems,
},
],
[addProjectEnvironmentItems],
);
const openAddProjectFlow = useCallback(() => {
if (addProjectEnvironmentOptions.length > 1) {
pushPaletteView({
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: addProjectEnvironmentGroups,
});
return;
}
const environmentId = defaultAddProjectEnvironmentId;
if (!environmentId) {
toastManager.add({
type: "error",
title: "Unable to browse projects",
description: "No environment is available.",
});
return;
}
startAddProjectBrowse(environmentId);
}, [
addProjectEnvironmentGroups,
addProjectEnvironmentOptions.length,
defaultAddProjectEnvironmentId,
startAddProjectBrowse,
]);
useEffect(() => {
if (openIntent?.kind !== "add-project") {
return;
}
clearOpenIntent();
openAddProjectFlow();
}, [clearOpenIntent, openAddProjectFlow, openIntent]);
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
if (projects.length > 0) {
@@ -325,6 +663,30 @@ function OpenCommandPaletteDialog() {
});
}
if (addProjectEnvironmentOptions.length > 1) {
actionItems.push({
kind: "submenu",
value: "action:add-project",
searchTerms: ["add project", "folder", "directory", "browse", "environment"],
title: "Add project",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: addProjectEnvironmentGroups,
});
} else {
actionItems.push({
kind: "action",
value: "action:add-project",
searchTerms: ["add project", "folder", "directory", "browse"],
title: "Add project",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
openAddProjectFlow();
},
});
}
actionItems.push({
kind: "action",
value: "action:settings",
@@ -339,7 +701,7 @@ function OpenCommandPaletteDialog() {
const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
const activeGroups = currentView ? currentView.groups : rootGroups;
const displayedGroups = filterCommandPaletteGroups({
const filteredGroups = filterCommandPaletteGroups({
activeGroups,
query: deferredQuery,
isInSubmenu: currentView !== null,
@@ -347,10 +709,206 @@ function OpenCommandPaletteDialog() {
threadSearchItems: allThreadItems,
});
const handleAddProject = useCallback(
async (rawCwd: string) => {
if (!browseEnvironmentId) return;
const api = readEnvironmentApi(browseEnvironmentId);
if (!api) return;
if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) {
toastManager.add({
type: "error",
title: "Failed to add project",
description: "Windows-style paths are only supported on Windows.",
});
return;
}
if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) {
toastManager.add({
type: "error",
title: "Failed to add project",
description: "Relative paths require an active project.",
});
return;
}
const cwd = resolveProjectPathForDispatch(rawCwd, currentProjectCwdForBrowse);
if (cwd.length === 0) return;
const existing = findProjectByPath(
projects.filter((project) => project.environmentId === browseEnvironmentId),
cwd,
);
if (existing) {
const latestThread = getLatestThreadForProject(
threads.filter((thread) => thread.environmentId === existing.environmentId),
existing.id,
settings.sidebarThreadSortOrder,
);
if (latestThread) {
await navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(
scopeThreadRef(latestThread.environmentId, latestThread.id),
),
});
} else {
await handleNewThread(scopeProjectRef(existing.environmentId, existing.id), {
envMode: settings.defaultThreadEnvMode,
}).catch(() => undefined);
}
setOpen(false);
return;
}
try {
const projectId = newProjectId();
await api.orchestration.dispatchCommand({
type: "project.create",
commandId: newCommandId(),
projectId,
title: inferProjectTitleFromPath(cwd),
workspaceRoot: cwd,
createWorkspaceRootIfMissing: true,
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
createdAt: new Date().toISOString(),
});
await handleNewThread(scopeProjectRef(browseEnvironmentId, projectId), {
envMode: settings.defaultThreadEnvMode,
}).catch(() => undefined);
setOpen(false);
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to add project",
description: error instanceof Error ? error.message : "An error occurred.",
});
}
},
[
browseEnvironmentId,
browseEnvironmentPlatform,
currentProjectCwdForBrowse,
handleNewThread,
navigate,
projects,
setOpen,
settings.defaultThreadEnvMode,
settings.sidebarThreadSortOrder,
threads,
],
);
function browseTo(name: string): void {
const nextQuery = appendBrowsePathSegment(query, name);
setHighlightedItemValue(null);
setQuery(nextQuery);
setBrowseGeneration((generation) => generation + 1);
}
function browseUp(): void {
const parentPath = getBrowseParentPath(query);
if (parentPath === null) {
return;
}
setHighlightedItemValue(null);
setQuery(parentPath);
setBrowseGeneration((generation) => generation + 1);
}
// Resolve the add-project path from browse data when available. When the
// query has a trailing separator (e.g. "~/projects/foo/"), parentPath is the
// directory itself. Otherwise the user typed a partial leaf name, so we need
// the exact browse entry's fullPath or fall back to the raw query.
const resolvedAddProjectPath = hasTrailingPathSeparator(query)
? (browseResult?.parentPath ?? query.trim())
: (exactBrowseEntry?.fullPath ?? query.trim());
const canBrowseUp =
isBrowsing && !relativePathNeedsActiveProject && canNavigateUp(browseDirectoryPath);
const browseGroups = buildBrowseGroups({
browseEntries: filteredBrowseEntries,
browseQuery: query,
canBrowseUp,
upIcon: <CornerLeftUpIcon className={ITEM_ICON_CLASS} />,
directoryIcon: <FolderIcon className={ITEM_ICON_CLASS} />,
browseUp,
browseTo,
});
let displayedGroups = filteredGroups;
if (isBrowsing) {
displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups;
}
const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
const isSubmenu = paletteMode === "submenu";
const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject;
const willCreateProjectPath =
canSubmitBrowsePath &&
!isBrowsePending &&
query.trim().length > 0 &&
!hasHighlightedBrowseItem &&
(hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null);
const useMetaForMod = isMacPlatform(navigator.platform);
const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl";
const submitActionLabel = willCreateProjectPath ? "Create & Add" : "Add";
const addShortcutLabel = hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter";
const fileManagerName = getLocalFileManagerName(navigator.platform);
const canOpenProjectFromFileManager =
isBrowsing &&
browseEnvironmentId !== null &&
primaryEnvironmentId !== null &&
browseEnvironmentId === primaryEnvironmentId &&
typeof window !== "undefined" &&
window.desktopBridge !== undefined;
const fileManagerInitialPath = useMemo(() => {
if (!canOpenProjectFromFileManager) {
return undefined;
}
const trimmedQuery = query.trim();
if (trimmedQuery.length === 0) {
return undefined;
}
const initialPath = hasTrailingPathSeparator(query)
? (browseResult?.parentPath ?? trimmedQuery)
: browseDirectoryPath || trimmedQuery;
const resolvedPath = resolveProjectPathForDispatch(initialPath, currentProjectCwdForBrowse);
return resolvedPath.length > 0 ? resolvedPath : undefined;
}, [
browseDirectoryPath,
browseResult?.parentPath,
canOpenProjectFromFileManager,
currentProjectCwdForBrowse,
query,
]);
function isPrimaryModifierPressed(event: KeyboardEvent<HTMLInputElement>): boolean {
return useMetaForMod ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
}
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
const shouldSubmitBrowsePath =
canSubmitBrowsePath &&
event.key === "Enter" &&
(!hasHighlightedBrowseItem || isPrimaryModifierPressed(event));
if (shouldSubmitBrowsePath) {
event.preventDefault();
void handleAddProject(resolvedAddProjectPath);
return;
}
if (event.key === "Backspace" && query === "" && isSubmenu) {
event.preventDefault();
popView();
@@ -376,6 +934,38 @@ function OpenCommandPaletteDialog() {
});
}
const handleOpenProjectFromFileManager = useCallback(async () => {
if (!canOpenProjectFromFileManager || isPickingProjectFolder) {
return;
}
const api = readLocalApi();
if (!api) {
return;
}
setIsPickingProjectFolder(true);
let pickedPath: string | null = null;
try {
pickedPath = await api.dialogs.pickFolder(
fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : undefined,
);
} catch {
// Ignore picker failures and leave the palette open.
setIsPickingProjectFolder(false);
return;
}
setIsPickingProjectFolder(false);
if (!pickedPath) {
return;
}
await handleAddProject(pickedPath);
}, [
canOpenProjectFromFileManager,
fileManagerInitialPath,
handleAddProject,
isPickingProjectFolder,
]);
return (
<CommandDialogPopup
aria-label="Command palette"
@@ -387,42 +977,86 @@ function OpenCommandPaletteDialog() {
}}
>
<Command
key={viewStack.length}
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}`}
aria-label="Command palette"
autoHighlight="always"
autoHighlight={isBrowsing ? false : "always"}
mode="none"
onItemHighlighted={(value) => {
setHighlightedItemValue(typeof value === "string" ? value : null);
}}
onValueChange={handleQueryChange}
value={query}
>
<CommandInput
placeholder={inputPlaceholder}
wrapperClassName={
isSubmenu
? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto [&_[data-slot=autocomplete-start-addon]]:cursor-pointer"
: undefined
}
{...(isSubmenu
? {
startAddon: (
<button
type="button"
className="flex cursor-pointer items-center"
aria-label="Back"
onClick={popView}
>
<ArrowLeftIcon />
</button>
),
}
: {})}
onKeyDown={handleKeyDown}
/>
<div className="relative">
<CommandInput
className={isBrowsing ? (willCreateProjectPath ? "pe-36" : "pe-16") : undefined}
placeholder={inputPlaceholder}
wrapperClassName={
isSubmenu ? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto" : undefined
}
{...(isSubmenu
? {
startAddon: (
<button
type="button"
className="flex cursor-pointer items-center"
aria-label="Back"
onClick={popView}
>
<ArrowLeftIcon />
</button>
),
}
: isBrowsing && !isSubmenu
? {
startAddon: <FolderPlusIcon />,
}
: {})}
onKeyDown={handleKeyDown}
/>
{isBrowsing ? (
<Button
variant="outline"
size="xs"
tabIndex={-1}
className={cn(
"absolute end-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
)}
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
disabled={relativePathNeedsActiveProject}
onMouseDown={(event) => {
event.preventDefault();
}}
onClick={() => {
if (relativePathNeedsActiveProject) {
return;
}
void handleAddProject(resolvedAddProjectPath);
}}
title={`${submitActionLabel} (${addShortcutLabel})`}
>
<span>{submitActionLabel}</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
</KbdGroup>
</Button>
) : null}
</div>
<CommandPanel className="max-h-[min(28rem,70vh)]">
<CommandPaletteResults
groups={displayedGroups}
highlightedItemValue={highlightedItemValue}
isActionsOnly={isActionsOnly}
keybindings={keybindings}
onExecuteItem={executeItem}
{...(relativePathNeedsActiveProject
? { emptyStateMessage: "Relative paths require an active project." }
: willCreateProjectPath
? {
emptyStateMessage: "Press Enter to create this folder and add it as a project.",
}
: {})}
/>
</CommandPanel>
<CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
@@ -436,10 +1070,12 @@ function OpenCommandPaletteDialog() {
</Kbd>
<span className={cn("text-muted-foreground/80")}>Navigate</span>
</KbdGroup>
<KbdGroup className="items-center gap-1.5">
<Kbd>Enter</Kbd>
<span className={cn("text-muted-foreground/80")}>Select</span>
</KbdGroup>
{!canSubmitBrowsePath || hasHighlightedBrowseItem ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Enter</Kbd>
<span className={cn("text-muted-foreground/80")}>Select</span>
</KbdGroup>
) : null}
{isSubmenu ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Backspace</Kbd>
@@ -451,6 +1087,19 @@ function OpenCommandPaletteDialog() {
<span className={cn("text-muted-foreground/80")}>Close</span>
</KbdGroup>
</div>
{canOpenProjectFromFileManager ? (
<Button
variant="ghost"
size="xs"
className="h-auto px-2 text-xs text-muted-foreground/80 hover:bg-transparent hover:text-foreground"
disabled={isPickingProjectFolder}
onClick={() => {
void handleOpenProjectFromFileManager();
}}
>
{`Open in ${fileManagerName}`}
</Button>
) : null}
</CommandFooter>
</Command>
</CommandDialogPopup>
@@ -14,10 +14,12 @@ import {
CommandList,
CommandShortcut,
} from "./ui/command";
import { cn } from "~/lib/utils";
interface CommandPaletteResultsProps {
emptyStateMessage?: string;
groups: ReadonlyArray<CommandPaletteGroup>;
highlightedItemValue?: string | null;
isActionsOnly: boolean;
keybindings: ResolvedKeybindingsConfig;
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
@@ -46,6 +48,7 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
item={item}
key={item.value}
keybindings={props.keybindings}
isActive={props.highlightedItemValue === item.value}
onExecuteItem={props.onExecuteItem}
/>
)}
@@ -58,6 +61,7 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
function CommandPaletteResultRow(props: {
item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
isActive: boolean;
keybindings: ResolvedKeybindingsConfig;
onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
}) {
@@ -68,7 +72,10 @@ function CommandPaletteResultRow(props: {
return (
<CommandItem
value={props.item.value}
className="cursor-pointer gap-2"
className={cn(
"cursor-pointer gap-2 hover:bg-transparent hover:text-inherit data-highlighted:bg-transparent data-highlighted:text-inherit data-selected:bg-transparent data-selected:text-inherit [&[data-highlighted][data-selected]]:bg-transparent [&[data-highlighted][data-selected]]:text-inherit",
props.isActive && "bg-accent! text-accent-foreground!",
)}
onMouseDown={(event) => {
event.preventDefault();
}}
@@ -32,11 +32,8 @@ import {
type ElementNode,
type LexicalNode,
type SerializedLexicalNode,
TextNode,
type EditorConfig,
type EditorState,
type NodeKey,
type SerializedTextNode,
type Spread,
} from "lexical";
import {
@@ -103,7 +100,7 @@ type SerializedComposerMentionNode = Spread<
type: "composer-mention";
version: 1;
},
SerializedTextNode
SerializedLexicalNode
>;
type SerializedComposerSkillNode = Spread<
@@ -132,7 +129,40 @@ const ComposerTerminalContextActionsContext = createContext<{
onRemoveTerminalContext: () => {},
});
class ComposerMentionNode extends TextNode {
function ComposerMentionDecorator(props: { path: string }) {
const theme = resolvedThemeFromDocument();
const chip = (
<span
className={COMPOSER_INLINE_CHIP_CLASS_NAME}
contentEditable={false}
spellCheck={false}
data-composer-mention-chip="true"
>
<img
alt=""
aria-hidden="true"
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
loading="lazy"
src={getVscodeIconUrlForEntry(props.path, inferEntryKindFromPath(props.path), theme)}
/>
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{basenameOfPath(props.path)}</span>
</span>
);
return (
<Tooltip>
<TooltipTrigger render={chip} />
<TooltipPopup
side="top"
className="max-w-[30rem] whitespace-normal leading-tight wrap-anywhere"
>
{props.path}
</TooltipPopup>
</Tooltip>
);
}
class ComposerMentionNode extends DecoratorNode<ReactElement> {
__path: string;
static override getType(): string {
@@ -144,12 +174,12 @@ class ComposerMentionNode extends TextNode {
}
static override importJSON(serializedNode: SerializedComposerMentionNode): ComposerMentionNode {
return $createComposerMentionNode(serializedNode.path);
return $createComposerMentionNode(serializedNode.path).updateFromJSON(serializedNode);
}
constructor(path: string, key?: NodeKey) {
super(key);
const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
super(`@${normalizedPath}`, key);
this.__path = normalizedPath;
}
@@ -162,41 +192,26 @@ class ComposerMentionNode extends TextNode {
};
}
override createDOM(_config: EditorConfig): HTMLElement {
override createDOM(): HTMLElement {
const dom = document.createElement("span");
dom.className = COMPOSER_INLINE_CHIP_CLASS_NAME;
dom.contentEditable = "false";
dom.setAttribute("spellcheck", "false");
renderMentionChipDom(dom, this.__path);
dom.className = "inline-flex align-middle leading-none";
return dom;
}
override updateDOM(
prevNode: ComposerMentionNode,
dom: HTMLElement,
_config: EditorConfig,
): boolean {
dom.contentEditable = "false";
if (prevNode.__text !== this.__text || prevNode.__path !== this.__path) {
renderMentionChipDom(dom, this.__path);
}
override updateDOM(): false {
return false;
}
override canInsertTextBefore(): false {
return false;
override getTextContent(): string {
return `@${this.__path}`;
}
override canInsertTextAfter(): false {
return false;
}
override isTextEntity(): true {
override isInline(): true {
return true;
}
override isToken(): true {
return true;
override decorate(): ReactElement {
return <ComposerMentionDecorator path={this.__path} />;
}
}
@@ -434,26 +449,6 @@ function resolvedThemeFromDocument(): "light" | "dark" {
return document.documentElement.classList.contains("dark") ? "dark" : "light";
}
function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
container.textContent = "";
container.style.setProperty("user-select", "none");
container.style.setProperty("-webkit-user-select", "none");
const theme = resolvedThemeFromDocument();
const icon = document.createElement("img");
icon.alt = "";
icon.ariaHidden = "true";
icon.className = COMPOSER_INLINE_CHIP_ICON_CLASS_NAME;
icon.loading = "lazy";
icon.src = getVscodeIconUrlForEntry(pathValue, inferEntryKindFromPath(pathValue), theme);
const label = document.createElement("span");
label.className = COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME;
label.textContent = basenameOfPath(pathValue);
container.append(icon, label);
}
function terminalContextSignature(contexts: ReadonlyArray<TerminalContextDraft>): string {
return contexts
.map((context) =>
@@ -595,12 +590,9 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
}
if ($isTextNode(node)) {
if (node instanceof ComposerMentionNode) {
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
}
return offset + Math.min(pointOffset, node.getTextContentSize());
}
if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) {
if (isComposerInlineTokenNode(node)) {
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
}
@@ -642,12 +634,9 @@ function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: numbe
}
if ($isTextNode(node)) {
if (node instanceof ComposerMentionNode) {
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
}
return offset + Math.min(pointOffset, node.getTextContentSize());
}
if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) {
if (isComposerInlineTokenNode(node)) {
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
}
@@ -673,10 +662,7 @@ function findSelectionPointAtOffset(
node: LexicalNode,
remainingRef: { value: number },
): { key: string; offset: number; type: "text" | "element" } | null {
if (node instanceof ComposerMentionNode || node instanceof ComposerSkillNode) {
return findSelectionPointForInlineToken(node, remainingRef);
}
if (node instanceof ComposerTerminalContextNode) {
if (isComposerInlineTokenNode(node)) {
return findSelectionPointForInlineToken(node, remainingRef);
}
@@ -98,7 +98,7 @@ function createBaseServerConfig(): ServerConfig {
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
providers: {
codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
claudeAgent: { enabled: true, binaryPath: "", customModels: [], launchArgs: "" },
},
},
};
+10 -1
View File
@@ -59,6 +59,7 @@ interface PlanSidebarProps {
markdownCwd: string | undefined;
workspaceRoot: string | undefined;
timestampFormat: TimestampFormat;
mode?: "sheet" | "sidebar";
onClose: () => void;
}
@@ -70,6 +71,7 @@ const PlanSidebar = memo(function PlanSidebar({
markdownCwd,
workspaceRoot,
timestampFormat,
mode = "sidebar",
onClose,
}: PlanSidebarProps) {
const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false);
@@ -123,7 +125,14 @@ const PlanSidebar = memo(function PlanSidebar({
}, [environmentId, planMarkdown, workspaceRoot]);
return (
<div className="flex h-full w-[340px] shrink-0 flex-col border-l border-border/70 bg-card/50">
<div
className={cn(
"flex min-h-0 flex-col bg-card/50",
mode === "sidebar"
? "h-full w-[340px] shrink-0 border-l border-border/70"
: "h-full w-full",
)}
>
{/* Header */}
<div className="flex h-12 shrink-0 items-center justify-between border-b border-border/60 px-3">
<div className="flex items-center gap-2">
@@ -0,0 +1,30 @@
import { type ReactNode } from "react";
import { RIGHT_PANEL_SHEET_CLASS_NAME } from "../rightPanelLayout";
import { Sheet, SheetPopup } from "./ui/sheet";
export function RightPanelSheet(props: {
children: ReactNode;
open: boolean;
onClose: () => void;
}) {
return (
<Sheet
open={props.open}
onOpenChange={(open) => {
if (!open) {
props.onClose();
}
}}
>
<SheetPopup
side="right"
showCloseButton={false}
keepMounted
className={RIGHT_PANEL_SHEET_CLASS_NAME}
>
{props.children}
</SheetPopup>
</Sheet>
);
}
File diff suppressed because it is too large. Load diff
@@ -28,7 +28,11 @@ import {
resolveWrappedTerminalLinkRange,
wrappedTerminalLinkRangeIntersectsBufferLine,
} from "../terminal-links";
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
import {
isTerminalClearShortcut,
terminalDeleteShortcutData,
terminalNavigationShortcutData,
} from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -407,6 +411,14 @@ export function TerminalViewport({
return false;
}
const deleteData = terminalDeleteShortcutData(event);
if (deleteData !== null) {
event.preventDefault();
event.stopPropagation();
void sendTerminalInput(deleteData, "Failed to delete terminal input");
return false;
}
if (!isTerminalClearShortcut(event)) return true;
event.preventDefault();
event.stopPropagation();
@@ -0,0 +1,189 @@
import { EnvironmentId, MessageId } from "@t3tools/contracts";
import { createRef } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { beforeAll, describe, expect, it, vi } from "vitest";
import type { LegendListRef } from "@legendapp/list/react";
vi.mock("@legendapp/list/react", async () => {
const React = await import("react");
const LegendList = React.forwardRef(function MockLegendList(
props: {
data: Array<{ id: string }>;
keyExtractor: (item: { id: string }) => string;
renderItem: (args: { item: { id: string } }) => React.ReactNode;
ListHeaderComponent?: React.ReactNode;
ListFooterComponent?: React.ReactNode;
},
_ref: React.ForwardedRef<LegendListRef>,
) {
return (
<div data-testid="legend-list">
{props.ListHeaderComponent}
{props.data.map((item) => (
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
))}
{props.ListFooterComponent}
</div>
);
});
return { LegendList };
});
function matchMedia() {
return {
matches: false,
addEventListener: () => {},
removeEventListener: () => {},
};
}
beforeAll(() => {
const classList = {
add: () => {},
remove: () => {},
toggle: () => {},
contains: () => false,
};
vi.stubGlobal("localStorage", {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
clear: () => {},
});
vi.stubGlobal("window", {
matchMedia,
addEventListener: () => {},
removeEventListener: () => {},
requestAnimationFrame: (callback: FrameRequestCallback) => {
callback(0);
return 0;
},
cancelAnimationFrame: () => {},
desktopBridge: undefined,
});
vi.stubGlobal("document", {
documentElement: {
classList,
offsetHeight: 0,
},
});
});
const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
function buildProps() {
return {
isWorking: false,
activeTurnInProgress: false,
activeTurnId: null,
activeTurnStartedAt: null,
listRef: createRef<LegendListRef | null>(),
completionDividerBeforeEntryId: null,
completionSummary: null,
turnDiffSummaryByAssistantMessageId: new Map(),
routeThreadKey: "environment-local:thread-1",
onOpenTurnDiff: () => {},
revertTurnCountByUserMessageId: new Map(),
onRevertUserMessage: () => {},
isRevertingCheckpoint: false,
onImageExpand: () => {},
activeThreadEnvironmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
markdownCwd: undefined,
resolvedTheme: "light" as const,
timestampFormat: "locale" as const,
workspaceRoot: undefined,
onIsAtEndChange: () => {},
};
}
describe("MessagesTimeline", () => {
it("renders inline terminal labels with the composer chip UI", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-1",
kind: "message",
createdAt: "2026-03-17T19:12:28.000Z",
message: {
id: MessageId.make("message-2"),
role: "user",
text: [
"yoo what's @terminal-1:1-5 mean",
"",
"<terminal_context>",
"- Terminal 1 lines 1-5:",
" 1 | julius@mac effect-http-ws-cli % bun i",
" 2 | bun install v1.3.9 (cf6cdbbb)",
"</terminal_context>",
].join("\n"),
createdAt: "2026-03-17T19:12:28.000Z",
streaming: false,
},
},
]}
/>,
);
expect(markup).toContain("Terminal 1 lines 1-5");
expect(markup).toContain("lucide-terminal");
expect(markup).toContain("yoo what&#x27;s ");
}, 20_000);
it("renders context compaction entries in the normal work log", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-1",
kind: "work",
createdAt: "2026-03-17T19:12:28.000Z",
entry: {
id: "work-1",
createdAt: "2026-03-17T19:12:28.000Z",
label: "Context compacted",
tone: "info",
},
},
]}
/>,
);
expect(markup).toContain("Context compacted");
expect(markup).toContain("Work log");
});
it("formats changed file paths from the workspace root", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-1",
kind: "work",
createdAt: "2026-03-17T19:12:28.000Z",
entry: {
id: "work-1",
createdAt: "2026-03-17T19:12:28.000Z",
label: "Updated files",
tone: "tool",
changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
},
},
]}
workspaceRoot="C:/Users/mike/dev-stuff/t3code"
/>,
);
expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
});
});
@@ -60,6 +60,7 @@ import {
formatInlineTerminalContextLabel,
textContainsInlineTerminalContextLabels,
} from "./userMessageTerminalContexts";
import { formatWorkspaceRelativePath } from "../../filePathDisplay";
// ---------------------------------------------------------------------------
// Context — shared state consumed by every row component via useContext.
@@ -528,6 +529,7 @@ const WorkGroupSection = memo(function WorkGroupSection({
}: {
groupedEntries: Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"];
}) {
const { workspaceRoot } = use(TimelineRowCtx);
const [isExpanded, setIsExpanded] = useState(false);
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
@@ -559,7 +561,11 @@ const WorkGroupSection = memo(function WorkGroupSection({
)}
<div className="space-y-0.5">
{visibleEntries.map((workEntry) => (
<SimpleWorkEntryRow key={`work-row:${workEntry.id}`} workEntry={workEntry} />
<SimpleWorkEntryRow
key={`work-row:${workEntry.id}`}
workEntry={workEntry}
workspaceRoot={workspaceRoot}
/>
))}
</div>
</div>
@@ -861,15 +867,17 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
function workEntryPreview(
workEntry: Pick<TimelineWorkEntry, "detail" | "command" | "changedFiles">,
workspaceRoot: string | undefined,
) {
if (workEntry.command) return workEntry.command;
if (workEntry.detail) return workEntry.detail;
if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
const [firstPath] = workEntry.changedFiles ?? [];
if (!firstPath) return null;
const displayPath = formatWorkspaceRelativePath(firstPath, workspaceRoot);
return workEntry.changedFiles!.length === 1
? firstPath
: `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
? displayPath
: `${displayPath} +${workEntry.changedFiles!.length - 1} more`;
}
function workEntryRawCommand(
@@ -924,12 +932,13 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
workEntry: TimelineWorkEntry;
workspaceRoot: string | undefined;
}) {
const { workEntry } = props;
const { workEntry, workspaceRoot } = props;
const iconConfig = workToneIcon(workEntry.tone);
const EntryIcon = workEntryIcon(workEntry);
const heading = toolWorkEntryHeading(workEntry);
const preview = workEntryPreview(workEntry);
const preview = workEntryPreview(workEntry, workspaceRoot);
const rawCommand = workEntryRawCommand(workEntry);
const displayText = preview ? `${heading} - ${preview}` : heading;
const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
@@ -988,15 +997,18 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
</div>
{hasChangedFiles && !previewIsChangedFiles && (
<div className="mt-1 flex flex-wrap gap-1 pl-6">
{workEntry.changedFiles?.slice(0, 4).map((filePath) => (
<span
key={`${workEntry.id}:${filePath}`}
className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
title={filePath}
>
{filePath}
</span>
))}
{workEntry.changedFiles?.slice(0, 4).map((filePath) => {
const displayPath = formatWorkspaceRelativePath(filePath, workspaceRoot);
return (
<span
key={`${workEntry.id}:${filePath}`}
className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
title={displayPath}
>
{displayPath}
</span>
);
})}
{(workEntry.changedFiles?.length ?? 0) > 4 && (
<span className="px-1 text-[10px] text-muted-foreground/55">
+{(workEntry.changedFiles?.length ?? 0) - 4}
@@ -17,6 +17,7 @@ import {
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
@@ -7,6 +7,7 @@ import {
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
type DesktopBridge,
type DesktopUpdateChannel,
type DesktopUpdateState,
type LocalApi,
type ServerConfig,
@@ -258,10 +259,12 @@ function makeClientSession(input: {
const createDesktopBridgeStub = (overrides?: {
readonly serverExposureState?: Awaited<ReturnType<DesktopBridge["getServerExposureState"]>>;
readonly setServerExposureMode?: DesktopBridge["setServerExposureMode"];
readonly setUpdateChannel?: DesktopBridge["setUpdateChannel"];
}): DesktopBridge => {
const idleUpdateState: DesktopUpdateState = {
enabled: false,
status: "idle",
channel: "latest",
currentVersion: "0.0.0-test",
hostArch: "arm64",
appArch: "arm64",
@@ -276,6 +279,7 @@ const createDesktopBridgeStub = (overrides?: {
};
return {
getAppBranding: vi.fn().mockReturnValue(null),
getLocalEnvironmentBootstrap: () => ({
label: "Local environment",
httpBaseUrl: "http://127.0.0.1:3773",
@@ -310,6 +314,12 @@ const createDesktopBridgeStub = (overrides?: {
openExternal: vi.fn().mockResolvedValue(true),
onMenuAction: () => () => {},
getUpdateState: vi.fn().mockResolvedValue(idleUpdateState),
setUpdateChannel:
overrides?.setUpdateChannel ??
vi.fn().mockImplementation(async (channel: DesktopUpdateChannel) => ({
...idleUpdateState,
channel,
})),
checkForUpdate: vi.fn().mockResolvedValue({ checked: false, state: idleUpdateState }),
downloadUpdate: vi
.fn()
@@ -12,6 +12,7 @@ import { useQueryClient } from "@tanstack/react-query";
import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";
import {
PROVIDER_DISPLAY_NAMES,
type DesktopUpdateChannel,
type ScopedThreadRef,
type ProviderKind,
type ServerProvider,
@@ -232,8 +233,42 @@ function AboutVersionTitle() {
function AboutVersionSection() {
const queryClient = useQueryClient();
const updateStateQuery = useDesktopUpdateState();
const [isChangingUpdateChannel, setIsChangingUpdateChannel] = useState(false);
const updateState = updateStateQuery.data ?? null;
const hasDesktopBridge = typeof window !== "undefined" && Boolean(window.desktopBridge);
const selectedUpdateChannel = updateState?.channel ?? "latest";
const handleUpdateChannelChange = useCallback(
(channel: DesktopUpdateChannel) => {
const bridge = window.desktopBridge;
if (
!bridge ||
typeof bridge.setUpdateChannel !== "function" ||
channel === selectedUpdateChannel
) {
return;
}
setIsChangingUpdateChannel(true);
void bridge
.setUpdateChannel(channel)
.then((state) => {
setDesktopUpdateStateQueryData(queryClient, state);
})
.catch((error: unknown) => {
toastManager.add({
type: "error",
title: "Could not change update track",
description: error instanceof Error ? error.message : "Update track change failed.",
});
})
.finally(() => {
setIsChangingUpdateChannel(false);
});
},
[queryClient, selectedUpdateChannel],
);
const handleButtonClick = useCallback(() => {
const bridge = window.desktopBridge;
@@ -323,27 +358,59 @@ function AboutVersionSection() {
: "Current version of the application.";
return (
<SettingsRow
title={<AboutVersionTitle />}
description={description}
control={
<Tooltip>
<TooltipTrigger
render={
<Button
size="xs"
variant={action === "install" ? "default" : "outline"}
disabled={buttonDisabled}
onClick={handleButtonClick}
>
{buttonLabel}
</Button>
}
/>
{buttonTooltip ? <TooltipPopup>{buttonTooltip}</TooltipPopup> : null}
</Tooltip>
}
/>
<>
<SettingsRow
title={<AboutVersionTitle />}
description={description}
control={
<Tooltip>
<TooltipTrigger
render={
<Button
size="xs"
variant={action === "install" ? "default" : "outline"}
disabled={buttonDisabled}
onClick={handleButtonClick}
>
{buttonLabel}
</Button>
}
/>
{buttonTooltip ? <TooltipPopup>{buttonTooltip}</TooltipPopup> : null}
</Tooltip>
}
/>
<SettingsRow
title="Update track"
description="Stable follows full releases. Nightly follows the nightly desktop channel and can switch back to stable immediately."
control={
<Select
value={selectedUpdateChannel}
onValueChange={(value) => {
handleUpdateChannelChange(value as DesktopUpdateChannel);
}}
>
<SelectTrigger
className="w-full sm:w-40"
aria-label="Update track"
disabled={!hasDesktopBridge || isChangingUpdateChannel}
>
<SelectValue>
{selectedUpdateChannel === "nightly" ? "Nightly" : "Stable"}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="latest">
Stable
</SelectItem>
<SelectItem hideIndicator value="nightly">
Nightly
</SelectItem>
</SelectPopup>
</Select>
}
/>
</>
);
}
@@ -377,6 +444,9 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
? ["New thread mode"]
: []),
...(settings.addProjectBaseDirectory !== DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory
? ["Add project base directory"]
: []),
...(settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive
? ["Archive confirmation"]
: []),
@@ -391,6 +461,7 @@ export function useSettingsRestore(onRestored?: () => void) {
isGitWritingModelDirty,
settings.confirmThreadArchive,
settings.confirmThreadDelete,
settings.addProjectBaseDirectory,
settings.defaultThreadEnvMode,
settings.diffWordWrap,
settings.enableAssistantStreaming,
@@ -440,7 +511,8 @@ export function GeneralSettingsPanel() {
claudeAgent: Boolean(
settings.providers.claudeAgent.binaryPath !==
DEFAULT_UNIFIED_SETTINGS.providers.claudeAgent.binaryPath ||
settings.providers.claudeAgent.customModels.length > 0,
settings.providers.claudeAgent.customModels.length > 0 ||
settings.providers.claudeAgent.launchArgs !== "",
),
});
const [customModelInputByProvider, setCustomModelInputByProvider] = useState<
@@ -852,6 +924,34 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
title="Add project starts in"
description='Leave empty to use "~/" when the Add Project browser opens.'
resetAction={
settings.addProjectBaseDirectory !==
DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory ? (
<SettingResetButton
label="add project base directory"
onClick={() =>
updateSettings({
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
})
}
/>
) : null
}
control={
<Input
className="w-full sm:w-72"
value={settings.addProjectBaseDirectory}
onChange={(event) => updateSettings({ addProjectBaseDirectory: event.target.value })}
placeholder="~/"
spellCheck={false}
aria-label="Add project base directory"
/>
}
/>
<SettingsRow
title="Archive confirmation"
description="Require a second click on the inline archive action before a thread is archived."
@@ -1179,6 +1279,37 @@ export function GeneralSettingsPanel() {
</div>
) : null}
{providerCard.provider === "claudeAgent" ? (
<div className="border-t border-border/60 px-4 py-3 sm:px-5">
<label htmlFor="provider-install-claudeAgent-launch-args" className="block">
<span className="text-xs font-medium text-foreground">
Launch arguments
</span>
<Input
id="provider-install-claudeAgent-launch-args"
className="mt-1.5"
value={settings.providers.claudeAgent.launchArgs}
onChange={(event) =>
updateSettings({
providers: {
...settings.providers,
claudeAgent: {
...settings.providers.claudeAgent,
launchArgs: event.target.value,
},
},
})
}
placeholder="e.g. --chrome"
spellCheck={false}
/>
<span className="mt-1 block text-xs text-muted-foreground">
Additional CLI arguments passed to Claude Code on session start.
</span>
</label>
</div>
) : null}
<div className="border-t border-border/60 px-4 py-3 sm:px-5">
<div className="text-xs font-medium text-foreground">Models</div>
<div className="mt-1 text-xs text-muted-foreground">
+12 -24
View File
@@ -1,7 +1,6 @@
import {
CODEX_REASONING_EFFORT_OPTIONS,
type ClaudeCodeEffort,
type CodexReasoningEffort,
ClaudeAgentEffort,
CodexReasoningEffort,
DEFAULT_MODEL_BY_PROVIDER,
type EnvironmentId,
ModelSelection,
@@ -105,7 +104,7 @@ const PersistedComposerThreadDraftState = Schema.Struct({
type PersistedComposerThreadDraftState = typeof PersistedComposerThreadDraftState.Type;
const LegacyCodexFields = Schema.Struct({
effort: Schema.optionalKey(Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS)),
effort: Schema.optionalKey(CodexReasoningEffort),
codexFastMode: Schema.optionalKey(Schema.Boolean),
serviceTier: Schema.optionalKey(Schema.String),
});
@@ -546,19 +545,13 @@ function normalizeProviderModelOptions(
? (candidate.claudeAgent as Record<string, unknown>)
: null;
const codexReasoningEffort: CodexReasoningEffort | undefined =
codexCandidate?.reasoningEffort === "low" ||
codexCandidate?.reasoningEffort === "medium" ||
codexCandidate?.reasoningEffort === "high" ||
codexCandidate?.reasoningEffort === "xhigh"
? codexCandidate.reasoningEffort
: provider === "codex" &&
(legacy?.effort === "low" ||
legacy?.effort === "medium" ||
legacy?.effort === "high" ||
legacy?.effort === "xhigh")
const codexReasoningEffort = Schema.is(CodexReasoningEffort)(codexCandidate?.reasoningEffort)
? codexCandidate.reasoningEffort
: provider === "codex"
? Schema.is(CodexReasoningEffort)(legacy?.effort)
? legacy.effort
: undefined;
: undefined
: undefined;
const codexFastMode =
codexCandidate?.fastMode === true
? true
@@ -582,14 +575,9 @@ function normalizeProviderModelOptions(
: claudeCandidate?.thinking === false
? false
: undefined;
const claudeEffort: ClaudeCodeEffort | undefined =
claudeCandidate?.effort === "low" ||
claudeCandidate?.effort === "medium" ||
claudeCandidate?.effort === "high" ||
claudeCandidate?.effort === "max" ||
claudeCandidate?.effort === "ultrathink"
? claudeCandidate.effort
: undefined;
const claudeEffort = Schema.is(ClaudeAgentEffort)(claudeCandidate?.effort)
? claudeCandidate.effort
: undefined;
const claudeFastMode =
claudeCandidate?.fastMode === true
? true
+221
View File
@@ -0,0 +1,221 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { showContextMenuFallback } from "./contextMenuFallback";
type FakeListener = (event: FakeDomEvent) => void;
class FakeDomEvent {
defaultPrevented = false;
constructor(
readonly type: string,
init: Record<string, unknown> = {},
) {
Object.assign(this, init);
}
preventDefault() {
this.defaultPrevented = true;
}
}
class FakeElement {
children: FakeElement[] = [];
parent: FakeElement | null = null;
style: Record<string, string> & { cssText?: string } = {};
dataset: Record<string, string> = {};
className = "";
disabled = false;
type = "";
private textValue = "";
private readonly listeners = new Map<string, FakeListener[]>();
constructor(readonly tagName: string) {}
appendChild(child: FakeElement) {
child.parent = this;
this.children.push(child);
return child;
}
remove() {
if (!this.parent) {
return;
}
const index = this.parent.children.indexOf(this);
if (index >= 0) {
this.parent.children.splice(index, 1);
}
this.parent = null;
}
addEventListener(type: string, listener: FakeListener) {
const existing = this.listeners.get(type) ?? [];
existing.push(listener);
this.listeners.set(type, existing);
}
dispatchEvent(event: FakeDomEvent) {
for (const listener of this.listeners.get(event.type) ?? []) {
listener(event);
}
return true;
}
set textContent(value: string) {
this.textValue = value;
}
get textContent() {
return `${this.textValue}${this.children.map((child) => child.textContent).join("")}`;
}
querySelectorAll(tagName: string): FakeElement[] {
const matches: FakeElement[] = [];
if (this.tagName === tagName) {
matches.push(this);
}
for (const child of this.children) {
matches.push(...child.querySelectorAll(tagName));
}
return matches;
}
getBoundingClientRect() {
const left = Number.parseInt(this.style.left ?? "0", 10) || 0;
const top = Number.parseInt(this.style.top ?? "0", 10) || 0;
const width = this.tagName === "div" ? 180 : 140;
const height = this.tagName === "div" ? 120 : 28;
return {
left,
top,
width,
height,
right: left + width,
bottom: top + height,
};
}
}
class FakeBody extends FakeElement {
private html = "";
constructor() {
super("body");
}
set innerHTML(value: string) {
this.html = value;
this.children = [];
}
get innerHTML() {
return this.html;
}
}
class FakeDocument {
body = new FakeBody();
private readonly listeners = new Map<string, FakeListener[]>();
createElement(tagName: string) {
return new FakeElement(tagName);
}
addEventListener(type: string, listener: FakeListener) {
const existing = this.listeners.get(type) ?? [];
existing.push(listener);
this.listeners.set(type, existing);
}
removeEventListener(type: string, listener: FakeListener) {
const existing = this.listeners.get(type);
if (!existing) {
return;
}
const index = existing.indexOf(listener);
if (index >= 0) {
existing.splice(index, 1);
}
}
querySelectorAll(tagName: string) {
return this.body.querySelectorAll(tagName);
}
}
function findButton(label: string): FakeElement | undefined {
return (document as unknown as FakeDocument)
.querySelectorAll("button")
.find((button) => button.textContent.includes(label));
}
beforeEach(() => {
vi.stubGlobal("document", new FakeDocument());
vi.stubGlobal("window", {
innerWidth: 1280,
innerHeight: 800,
});
vi.stubGlobal("requestAnimationFrame", (callback: (time: number) => void) => {
callback(0);
return 0;
});
vi.stubGlobal(
"MouseEvent",
class extends FakeDomEvent {
constructor(type: string, init: Record<string, unknown> = {}) {
super(type, init);
}
},
);
vi.stubGlobal(
"KeyboardEvent",
class extends FakeDomEvent {
constructor(type: string, init: Record<string, unknown> = {}) {
super(type, init);
}
},
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("showContextMenuFallback", () => {
it("resolves a clicked flat menu item", async () => {
const selectionPromise = showContextMenuFallback([
{ id: "rename", label: "Rename" },
{ id: "delete", label: "Delete", destructive: true },
]);
const renameButton = findButton("Rename");
expect(renameButton).toBeTruthy();
renameButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await expect(selectionPromise).resolves.toBe("rename");
});
it("opens nested submenus and resolves the clicked leaf id", async () => {
const selectionPromise = showContextMenuFallback([
{
id: "rename:submenu",
label: "Rename project",
children: [
{ id: "rename:project-a", label: "/tmp/project-a" },
{ id: "rename:project-b", label: "/tmp/project-b" },
],
},
]);
const parentButton = findButton("Rename project");
expect(parentButton).toBeTruthy();
parentButton?.dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
const childButton = findButton("/tmp/project-b");
expect(childButton).toBeTruthy();
childButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await expect(selectionPromise).resolves.toBe("rename:project-b");
});
});
+116 -48
View File
@@ -1,9 +1,22 @@
import type { ContextMenuItem } from "@t3tools/contracts";
function clampMenuPosition(menu: HTMLDivElement, preferredLeft: number, preferredTop: number) {
const rect = menu.getBoundingClientRect();
const left = Math.min(
Math.max(4, preferredLeft),
Math.max(4, window.innerWidth - rect.width - 4),
);
const top = Math.min(
Math.max(4, preferredTop),
Math.max(4, window.innerHeight - rect.height - 4),
);
menu.style.left = `${left}px`;
menu.style.top = `${top}px`;
}
/**
* Imperative DOM-based context menu for non-Electron environments.
* Shows a positioned dropdown and returns a promise that resolves
* with the clicked item id, or null if dismissed.
* Supports nested submenus and resolves with the clicked leaf item id.
*/
export function showContextMenuFallback<T extends string>(
items: readonly ContextMenuItem<T>[],
@@ -13,62 +26,117 @@ export function showContextMenuFallback<T extends string>(
const overlay = document.createElement("div");
overlay.style.cssText = "position:fixed;inset:0;z-index:9999";
const menu = document.createElement("div");
menu.className =
"fixed z-[10000] min-w-[140px] rounded-md border border-border bg-popover py-1 shadow-xl animate-in fade-in zoom-in-95";
const menuStack: HTMLDivElement[] = [];
const x = position?.x ?? 0;
const y = position?.y ?? 0;
menu.style.top = `${y}px`;
menu.style.left = `${x}px`;
function cleanup(result: T | null) {
const cleanup = (result: T | null) => {
document.removeEventListener("keydown", onKeyDown);
overlay.remove();
menu.remove();
for (const menu of menuStack) {
menu.remove();
}
resolve(result);
}
};
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
e.preventDefault();
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
cleanup(null);
}
}
};
const closeMenusFromLevel = (level: number) => {
while (menuStack.length > level) {
menuStack.pop()?.remove();
}
};
const openMenu = (
entries: readonly ContextMenuItem<T>[],
preferredLeft: number,
preferredTop: number,
level: number,
) => {
closeMenusFromLevel(level);
const menu = document.createElement("div");
menu.className =
"fixed z-[10000] min-w-[160px] rounded-md border border-border bg-popover py-1 shadow-xl animate-in fade-in zoom-in-95";
menu.style.left = `${preferredLeft}px`;
menu.style.top = `${preferredTop}px`;
menu.dataset.level = String(level);
for (const item of entries) {
const button = document.createElement("button");
button.type = "button";
const hasChildren = Array.isArray(item.children) && item.children.length > 0;
const isLeafDestructive =
!hasChildren && (item.destructive === true || item.id === ("delete" as T));
const isDisabled = item.disabled === true;
button.disabled = isDisabled;
button.className = isDisabled
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed"
: isLeafDestructive
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
const label = document.createElement("span");
label.className = "min-w-0 flex-1 truncate";
label.textContent = item.label;
button.appendChild(label);
if (hasChildren) {
const chevron = document.createElement("span");
chevron.className = "shrink-0 text-muted-foreground/70";
chevron.textContent = "›";
button.appendChild(chevron);
}
if (!isDisabled) {
if (hasChildren) {
button.addEventListener("mouseenter", () => {
const rect = button.getBoundingClientRect();
const nextLeft = rect.right + 4;
const nextTop = rect.top;
openMenu(item.children!, nextLeft, nextTop, level + 1);
const childMenu = menuStack[level + 1];
if (!childMenu) {
return;
}
const childRect = childMenu.getBoundingClientRect();
if (childRect.right > window.innerWidth) {
clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
}
});
button.addEventListener("click", (event) => {
event.preventDefault();
});
} else {
button.addEventListener("mouseenter", () => {
closeMenusFromLevel(level + 1);
});
button.addEventListener("click", () => cleanup(item.id));
}
}
menu.appendChild(button);
}
menu.addEventListener("mouseenter", () => {
closeMenusFromLevel(level + 1);
});
document.body.appendChild(menu);
menuStack[level] = menu;
requestAnimationFrame(() => {
clampMenuPosition(menu, preferredLeft, preferredTop);
});
};
overlay.addEventListener("mousedown", () => cleanup(null));
document.addEventListener("keydown", onKeyDown);
for (const item of items) {
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = item.label;
const isDestructiveAction = item.destructive === true || item.id === "delete";
const isDisabled = item.disabled === true;
btn.disabled = isDisabled;
btn.className = isDisabled
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed"
: isDestructiveAction
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
if (!isDisabled) {
btn.addEventListener("click", () => cleanup(item.id));
}
menu.appendChild(btn);
}
document.body.appendChild(overlay);
document.body.appendChild(menu);
// Adjust if menu overflows viewport
requestAnimationFrame(() => {
const rect = menu.getBoundingClientRect();
if (rect.right > window.innerWidth) {
menu.style.left = `${window.innerWidth - rect.width - 4}px`;
}
if (rect.bottom > window.innerHeight) {
menu.style.top = `${window.innerHeight - rect.height - 4}px`;
}
});
openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
});
}
+21
View File
@@ -3,6 +3,8 @@ import type { EnvironmentId, EnvironmentApi } from "@t3tools/contracts";
import type { WsRpcClient } from "./rpc/wsRpcClient";
import { readEnvironmentConnection } from "./environments/runtime";
const environmentApiOverridesForTests = new Map<EnvironmentId, EnvironmentApi>();
export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
return {
terminal: {
@@ -18,6 +20,9 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
searchEntries: rpcClient.projects.searchEntries,
writeFile: rpcClient.projects.writeFile,
},
filesystem: {
browse: rpcClient.filesystem.browse,
},
git: {
pull: rpcClient.git.pull,
refreshStatus: rpcClient.git.refreshStatus,
@@ -52,6 +57,11 @@ export function readEnvironmentApi(environmentId: EnvironmentId): EnvironmentApi
return undefined;
}
const overriddenApi = environmentApiOverridesForTests.get(environmentId);
if (overriddenApi) {
return overriddenApi;
}
const connection = readEnvironmentConnection(environmentId);
return connection ? createEnvironmentApi(connection.client) : undefined;
}
@@ -63,3 +73,14 @@ export function ensureEnvironmentApi(environmentId: EnvironmentId): EnvironmentA
}
return api;
}
export function __setEnvironmentApiOverrideForTests(
environmentId: EnvironmentId,
api: EnvironmentApi,
): void {
environmentApiOverridesForTests.set(environmentId, api);
}
export function __resetEnvironmentApiOverridesForTests(): void {
environmentApiOverridesForTests.clear();
}
+165 -4
View File
@@ -10,7 +10,12 @@ import {
type AppState,
type EnvironmentState,
} from "./store";
import { deriveLogicalProjectKey } from "./logicalProject";
import {
deriveLogicalProjectKey,
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKey,
resolveProjectGroupingMode,
} from "./logicalProject";
import type { Project, SidebarThreadSummary } from "./types";
import { DEFAULT_INTERACTION_MODE } from "./types";
@@ -31,6 +36,10 @@ const threadL1 = ThreadId.make("thread-local-only-1");
const threadRO1 = ThreadId.make("thread-remote-only-1");
const SHARED_REPO_CANONICAL_KEY = "github.com/example/shared-repo";
const DEFAULT_GROUPING_SETTINGS = {
sidebarProjectGroupingMode: "repository" as const,
sidebarProjectGroupingOverrides: {},
};
// ── Factory Helpers ──────────────────────────────────────────────────
@@ -238,9 +247,7 @@ describe("environment grouping", () => {
environmentId: primaryEnvId,
name: "local-only",
});
const key = deriveLogicalProjectKey(project);
expect(key).toContain(primaryEnvId);
expect(key).toContain(localOnlyProjectId);
expect(deriveLogicalProjectKey(project)).toBe(derivePhysicalProjectKey(project));
});
it("groups projects from different environments that share the same canonical key", () => {
@@ -273,6 +280,134 @@ describe("environment grouping", () => {
expect(deriveLogicalProjectKey(primary)).toBe(deriveLogicalProjectKey(remote));
});
it("groups repo root and nested projects from the same repository by default", () => {
const rootProject = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "shared-repo",
cwd: "/workspace/repo",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
const nestedProject = makeProject({
id: localOnlyProjectId,
environmentId: primaryEnvId,
name: "web",
cwd: "/workspace/repo/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(deriveLogicalProjectKey(rootProject)).toBe(SHARED_REPO_CANONICAL_KEY);
expect(deriveLogicalProjectKey(nestedProject)).toBe(SHARED_REPO_CANONICAL_KEY);
});
it("uses repository path grouping when requested", () => {
const rootProject = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "shared-repo",
cwd: "/workspace/repo",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
const nestedProject = makeProject({
id: localOnlyProjectId,
environmentId: primaryEnvId,
name: "web",
cwd: "/workspace/repo/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(
deriveLogicalProjectKey(rootProject, {
groupingMode: "repository_path",
}),
).toBe(SHARED_REPO_CANONICAL_KEY);
expect(
deriveLogicalProjectKey(nestedProject, {
groupingMode: "repository_path",
}),
).toBe(`${SHARED_REPO_CANONICAL_KEY}::apps/web`);
});
it("groups matching nested project paths across environments when repo roots differ", () => {
const primary = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "web",
cwd: "/workspace/repo/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
const remote = makeProject({
id: sharedProjectRemoteId,
environmentId: remoteEnvId,
name: "web",
cwd: "/srv/checkout/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/srv/checkout",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(
deriveLogicalProjectKey(primary, {
groupingMode: "repository_path",
}),
).toBe(`${SHARED_REPO_CANONICAL_KEY}::apps/web`);
expect(
deriveLogicalProjectKey(primary, {
groupingMode: "repository_path",
}),
).toBe(
deriveLogicalProjectKey(remote, {
groupingMode: "repository_path",
}),
);
});
it("does NOT group projects without shared canonical key", () => {
const local = makeProject({
id: localOnlyProjectId,
@@ -286,6 +421,32 @@ describe("environment grouping", () => {
});
expect(deriveLogicalProjectKey(local)).not.toBe(deriveLogicalProjectKey(remote));
});
it("uses per-project overrides from settings", () => {
const project = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "shared-repo",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(resolveProjectGroupingMode(project, DEFAULT_GROUPING_SETTINGS)).toBe("repository");
expect(
deriveLogicalProjectKeyFromSettings(project, {
...DEFAULT_GROUPING_SETTINGS,
sidebarProjectGroupingOverrides: {
[derivePhysicalProjectKey(project)]: "separate",
},
}),
).toBe(derivePhysicalProjectKey(project));
});
});
describe("selectProjectsAcrossEnvironments", () => {
+3 -4
View File
@@ -13,9 +13,7 @@ import { Throttler } from "@tanstack/react-pacer";
import {
createKnownEnvironment,
getKnownEnvironmentWsBaseUrl,
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
@@ -62,6 +60,7 @@ import { useTerminalStateStore } from "~/terminalStateStore";
import { useUiStateStore } from "~/uiStateStore";
import { WsTransport } from "../../rpc/wsTransport";
import { createWsRpcClient, type WsRpcClient } from "../../rpc/wsRpcClient";
import { derivePhysicalProjectKey } from "../../logicalProject";
type EnvironmentServiceState = {
readonly queryClient: QueryClient;
@@ -470,7 +469,7 @@ function syncProjectUiFromStore() {
const projects = selectProjectsAcrossEnvironments(useStore.getState());
useUiStateStore.getState().syncProjects(
projects.map((project) => ({
key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
key: derivePhysicalProjectKey(project),
cwd: project.cwd,
})),
);
@@ -543,7 +542,7 @@ function applyRecoveredEventBatch(
const projects = selectProjectsAcrossEnvironments(useStore.getState());
useUiStateStore.getState().syncProjects(
projects.map((project) => ({
key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
key: derivePhysicalProjectKey(project),
cwd: project.cwd,
})),
);
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import { formatWorkspaceRelativePath } from "./filePathDisplay";
describe("formatWorkspaceRelativePath", () => {
it("formats absolute workspace paths from the workspace root", () => {
expect(
formatWorkspaceRelativePath(
"C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts:501",
"C:/Users/mike/dev-stuff/t3code",
),
).toBe("t3code/apps/web/src/session-logic.ts:501");
});
it("prefixes relative paths with the workspace root label", () => {
expect(
formatWorkspaceRelativePath(
"apps/web/src/session-logic.ts:501",
"C:/Users/mike/dev-stuff/t3code",
),
).toBe("t3code/apps/web/src/session-logic.ts:501");
});
it("keeps paths already rooted at the workspace label stable", () => {
expect(
formatWorkspaceRelativePath(
"t3code/apps/web/src/session-logic.ts:501",
"C:/Users/mike/dev-stuff/t3code",
),
).toBe("t3code/apps/web/src/session-logic.ts:501");
});
it("preserves columns when present", () => {
expect(
formatWorkspaceRelativePath(
"/C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts:501:9",
"C:/Users/mike/dev-stuff/t3code",
),
).toBe("t3code/apps/web/src/session-logic.ts:501:9");
});
});
+57
View File
@@ -0,0 +1,57 @@
import { splitPathAndPosition } from "./terminal-links";
function normalizePathSeparators(path: string): string {
return path.replaceAll("\\", "/");
}
function canonicalizeWindowsDrivePath(path: string): string {
return /^\/[A-Za-z]:\//.test(path) ? path.slice(1) : path;
}
function trimTrailingPathSeparators(path: string): string {
return path.replace(/[\\/]+$/, "");
}
function basenameOfPath(path: string): string {
const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
}
function stripRelativePrefixes(path: string): string {
return path.replace(/^\.\/+/, "").replace(/^\/+/, "");
}
export function formatWorkspaceRelativePath(
pathWithPosition: string,
workspaceRoot: string | undefined,
): string {
const { path, line, column } = splitPathAndPosition(pathWithPosition);
const normalizedPath = canonicalizeWindowsDrivePath(normalizePathSeparators(path));
let displayPath = normalizedPath;
if (workspaceRoot) {
const normalizedWorkspaceRoot = canonicalizeWindowsDrivePath(
normalizePathSeparators(trimTrailingPathSeparators(workspaceRoot)),
);
const workspaceLabel = basenameOfPath(normalizedWorkspaceRoot);
const pathForCompare = normalizedPath.toLowerCase();
const workspaceForCompare = normalizedWorkspaceRoot.toLowerCase();
const workspaceWithSeparator = `${workspaceForCompare}/`;
const workspaceLabelWithSeparator = `${workspaceLabel.toLowerCase()}/`;
if (pathForCompare === workspaceForCompare) {
displayPath = workspaceLabel;
} else if (pathForCompare.startsWith(workspaceWithSeparator)) {
const relativeSuffix = normalizedPath.slice(normalizedWorkspaceRoot.length + 1);
displayPath = `${workspaceLabel}/${relativeSuffix}`;
} else if (!normalizedPath.startsWith("/")) {
const relativePath = stripRelativePrefixes(normalizedPath);
displayPath = pathForCompare.startsWith(workspaceLabelWithSeparator)
? normalizedPath
: `${workspaceLabel}/${relativePath}`;
}
}
if (!line) return displayPath;
return `${displayPath}:${line}${column ? `:${column}` : ""}`;
}
+8 -3
View File
@@ -10,14 +10,19 @@ import {
} from "../composerDraftStore";
import { newDraftId, newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import { deriveLogicalProjectKey } from "../logicalProject";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import { selectProjectsAcrossEnvironments, useStore } from "../store";
import { createThreadSelectorByRef } from "../storeSelectors";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { useUiStateStore } from "../uiStateStore";
import { useSettings } from "./useSettings";
function useNewThreadState() {
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const router = useRouter();
const getCurrentRouteTarget = useCallback(() => {
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
@@ -48,7 +53,7 @@ function useNewThreadState() {
candidate.environmentId === projectRef.environmentId,
);
const logicalProjectKey = project
? deriveLogicalProjectKey(project)
? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)
: scopedProjectKey(projectRef);
const hasBranchOption = options?.branch !== undefined;
const hasWorktreePathOption = options?.worktreePath !== undefined;
@@ -129,7 +134,7 @@ function useNewThreadState() {
});
})();
},
[getCurrentRouteTarget, router, projects],
[getCurrentRouteTarget, projectGroupingSettings, router, projects],
);
}
+3 -3
View File
@@ -19,7 +19,7 @@ import {
} from "@t3tools/contracts/settings";
import { ensureLocalApi } from "~/localApi";
import { Struct } from "effect";
import { deepMerge } from "@t3tools/shared/Struct";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
@@ -64,7 +64,7 @@ async function hydrateClientSettings(): Promise<void> {
try {
const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
if (persistedSettings) {
replaceClientSettingsSnapshot(persistedSettings);
replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
}
} catch (error) {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
@@ -154,7 +154,7 @@ export function useUpdateSettings() {
if (Object.keys(serverPatch).length > 0) {
const currentServerConfig = getServerConfig();
if (currentServerConfig) {
applySettingsUpdated(deepMerge(currentServerConfig.settings, serverPatch));
applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));
}
// Fire-and-forget RPC — push will reconcile on success
void ensureLocalApi().server.updateSettings(serverPatch);
+59
View File
@@ -324,6 +324,47 @@ label:has(> select#reasoning-effort) select {
font-size: 0.75rem;
}
.chat-markdown-file-link {
display: inline-flex;
align-items: center;
gap: 0.28rem;
border: 1px solid color-mix(in srgb, var(--border) 92%, transparent);
border-radius: 0.375rem;
background: color-mix(in srgb, var(--muted) 88%, var(--background));
padding: 0.08rem 0.34rem;
color: var(--foreground);
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 0.75rem;
line-height: 1.15;
vertical-align: text-bottom;
transition:
background-color 120ms ease,
border-color 120ms ease,
color 120ms ease,
opacity 120ms ease;
}
.chat-markdown-file-link:hover {
opacity: 1;
color: var(--foreground);
border-color: color-mix(in srgb, var(--border) 65%, var(--foreground));
background: color-mix(in srgb, var(--muted) 72%, var(--background));
}
.chat-markdown-file-link:focus-visible {
outline: none;
box-shadow: 0 0 0 1px color-mix(in srgb, var(--ring) 70%, transparent);
}
.chat-markdown-file-link-icon {
opacity: 0.72;
}
.chat-markdown-file-link-label {
color: color-mix(in srgb, var(--foreground) 88%, transparent);
line-height: 1.1;
}
.chat-markdown pre {
max-width: 100%;
overflow-x: auto;
@@ -340,6 +381,24 @@ label:has(> select#reasoning-effort) select {
font-size: 0.75rem;
}
.markdown-file-link-tooltip-scroll {
scrollbar-width: thin;
scrollbar-color: color-mix(in srgb, var(--border) 78%, transparent) transparent;
}
.markdown-file-link-tooltip-scroll::-webkit-scrollbar {
height: 6px;
}
.markdown-file-link-tooltip-scroll::-webkit-scrollbar-track {
background: transparent;
}
.markdown-file-link-tooltip-scroll::-webkit-scrollbar-thumb {
border-radius: 999px;
background: color-mix(in srgb, var(--border) 78%, transparent);
}
.chat-markdown .chat-markdown-codeblock {
--chat-markdown-codeblock-copy-button-space: 1.5rem;
position: relative;
+29
View File
@@ -20,6 +20,7 @@ import {
resolveShortcutCommand,
shouldShowThreadJumpHints,
shortcutLabelForCommand,
terminalDeleteShortcutData,
terminalNavigationShortcutData,
threadJumpCommandForIndex,
threadJumpIndexFromCommand,
@@ -560,6 +561,34 @@ describe("isTerminalClearShortcut", () => {
});
});
describe("terminalDeleteShortcutData", () => {
it("maps Cmd+Backspace on macOS to delete-to-line-start", () => {
assert.strictEqual(
terminalDeleteShortcutData(event({ key: "Backspace", metaKey: true }), "MacIntel"),
"\u0015",
);
});
it("ignores non-macOS platforms and modified variants", () => {
assert.isNull(terminalDeleteShortcutData(event({ key: "Backspace", metaKey: true }), "Linux"));
assert.isNull(
terminalDeleteShortcutData(
event({ key: "Backspace", metaKey: true, altKey: true }),
"MacIntel",
),
);
});
it("ignores non-keydown events", () => {
assert.isNull(
terminalDeleteShortcutData(
event({ type: "keyup", key: "Backspace", metaKey: true }),
"MacIntel",
),
);
});
});
describe("terminalNavigationShortcutData", () => {
it("maps Option+Arrow on macOS to word movement", () => {
assert.strictEqual(
+23
View File
@@ -37,6 +37,7 @@ const TERMINAL_WORD_BACKWARD = "\u001bb";
const TERMINAL_WORD_FORWARD = "\u001bf";
const TERMINAL_LINE_START = "\u0001";
const TERMINAL_LINE_END = "\u0005";
const TERMINAL_DELETE_TO_LINE_START = "\u0015";
const EVENT_CODE_KEY_ALIASES: Readonly<Record<string, readonly string[]>> = {
BracketLeft: ["["],
BracketRight: ["]"],
@@ -370,6 +371,28 @@ export function isTerminalClearShortcut(
);
}
export function terminalDeleteShortcutData(
event: ShortcutEventLike,
platform = navigator.platform,
): string | null {
if (event.type !== undefined && event.type !== "keydown") {
return null;
}
if (!isMacPlatform(platform)) {
return null;
}
const key = normalizeEventKey(event.key);
if (key !== "backspace") {
return null;
}
return event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
? TERMINAL_DELETE_TO_LINE_START
: null;
}
export function terminalNavigationShortcutData(
event: ShortcutEventLike,
platform = navigator.platform,
@@ -10,6 +10,7 @@ import {
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
channel: "latest",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
+117
View File
@@ -0,0 +1,117 @@
import { describe, expect, it } from "vitest";
import {
appendBrowsePathSegment,
canNavigateUp,
getBrowseDirectoryPath,
findProjectByPath,
getBrowseLeafPathSegment,
getBrowseParentPath,
hasTrailingPathSeparator,
inferProjectTitleFromPath,
isExplicitRelativeProjectPath,
isFilesystemBrowseQuery,
normalizeProjectPathForComparison,
normalizeProjectPathForDispatch,
isUnsupportedWindowsProjectPath,
resolveProjectPathForDispatch,
} from "./projectPaths";
describe("projectPaths", () => {
it("normalizes trailing separators for dispatch and comparison", () => {
expect(normalizeProjectPathForDispatch(" /repo/app/ ")).toBe("/repo/app");
expect(normalizeProjectPathForComparison("/repo/app/")).toBe("/repo/app");
});
it("normalizes windows-style paths for comparison", () => {
expect(normalizeProjectPathForComparison("C:/Work/Repo/")).toBe("c:\\work\\repo");
expect(normalizeProjectPathForComparison("C:\\Work\\Repo\\")).toBe("c:\\work\\repo");
});
it("finds existing projects even when the input formatting differs", () => {
const existing = findProjectByPath(
[
{ id: "project-1", cwd: "/repo/app" },
{ id: "project-2", cwd: "C:\\Work\\Repo" },
],
"C:/Work/Repo/",
);
expect(existing?.id).toBe("project-2");
});
it("infers project titles from normalized paths", () => {
expect(inferProjectTitleFromPath("/repo/app/")).toBe("app");
expect(inferProjectTitleFromPath("C:\\Work\\Repo\\")).toBe("Repo");
expect(inferProjectTitleFromPath("/home/user\\project/")).toBe("user\\project");
});
it("detects browse queries across supported path styles", () => {
expect(isFilesystemBrowseQuery(".")).toBe(false);
expect(isFilesystemBrowseQuery("..")).toBe(false);
expect(isFilesystemBrowseQuery("./")).toBe(true);
expect(isFilesystemBrowseQuery("../")).toBe(true);
expect(isFilesystemBrowseQuery("~/projects")).toBe(true);
expect(isFilesystemBrowseQuery("..\\docs")).toBe(true);
expect(isFilesystemBrowseQuery("notes")).toBe(false);
});
it("only treats windows-style paths as browse queries on windows", () => {
expect(isFilesystemBrowseQuery("C:\\Work\\Repo\\", "MacIntel")).toBe(false);
expect(isFilesystemBrowseQuery("C:\\Work\\Repo\\", "Win32")).toBe(true);
expect(isUnsupportedWindowsProjectPath("C:\\Work\\Repo\\", "MacIntel")).toBe(true);
expect(isUnsupportedWindowsProjectPath("C:\\Work\\Repo\\", "Win32")).toBe(false);
});
it("detects explicit relative project paths", () => {
expect(isExplicitRelativeProjectPath(".")).toBe(true);
expect(isExplicitRelativeProjectPath("..")).toBe(true);
expect(isExplicitRelativeProjectPath("./docs")).toBe(true);
expect(isExplicitRelativeProjectPath("..\\docs")).toBe(true);
expect(isExplicitRelativeProjectPath("/repo/docs")).toBe(false);
});
it("resolves explicit relative paths against the current project", () => {
expect(resolveProjectPathForDispatch(".", "/repo/app")).toBe("/repo/app");
expect(resolveProjectPathForDispatch("..", "/repo/app")).toBe("/repo");
expect(resolveProjectPathForDispatch("./docs", "/repo/app")).toBe("/repo/app/docs");
expect(resolveProjectPathForDispatch("../docs", "/repo/app")).toBe("/repo/docs");
expect(resolveProjectPathForDispatch("./Repo", "C:\\Work")).toBe("C:\\Work\\Repo");
expect(resolveProjectPathForDispatch("./docs", "/home/user\\project")).toBe(
"/home/user\\project/docs",
);
});
it("navigates browse paths with matching separators", () => {
expect(appendBrowsePathSegment("/repo/", "src")).toBe("/repo/src/");
expect(appendBrowsePathSegment("C:\\Work\\", "Repo")).toBe("C:\\Work\\Repo\\");
expect(appendBrowsePathSegment("/home/user\\project/", "docs")).toBe(
"/home/user\\project/docs/",
);
expect(getBrowseParentPath("/repo/src/")).toBe("/repo/");
expect(getBrowseParentPath("C:\\Work\\Repo\\")).toBe("C:\\Work\\");
expect(getBrowseParentPath("\\\\server\\share\\")).toBeNull();
expect(getBrowseParentPath("\\\\server\\share\\repo\\")).toBe("\\\\server\\share\\");
expect(getBrowseParentPath("C:\\")).toBeNull();
expect(getBrowseParentPath("/home/user\\project/docs/")).toBe("/home/user\\project/");
});
it("detects browse path boundaries", () => {
expect(hasTrailingPathSeparator("/repo/src/")).toBe(true);
expect(hasTrailingPathSeparator("/repo/src")).toBe(false);
expect(getBrowseDirectoryPath("/repo/src")).toBe("/repo/");
expect(getBrowseDirectoryPath("/repo/src/")).toBe("/repo/src/");
expect(getBrowseLeafPathSegment("/repo/src")).toBe("src");
expect(getBrowseLeafPathSegment("C:\\Work\\Repo\\Docs")).toBe("Docs");
expect(getBrowseDirectoryPath("/home/user\\project/docs")).toBe("/home/user\\project/");
expect(getBrowseLeafPathSegment("/home/user\\project/docs")).toBe("docs");
});
it("only allows browse-up after entering a directory", () => {
expect(canNavigateUp("~/repo")).toBe(false);
expect(canNavigateUp("~/a")).toBe(false);
expect(canNavigateUp("~/repo/")).toBe(true);
expect(canNavigateUp("\\\\server\\share\\")).toBe(false);
expect(canNavigateUp("\\\\server\\share\\repo\\")).toBe(true);
});
});
+259
View File
@@ -0,0 +1,259 @@
import {
isExplicitRelativePath,
isUncPath,
isWindowsAbsolutePath,
isWindowsDrivePath,
} from "@t3tools/shared/path";
import { isWindowsPlatform } from "./utils";
function isRootPath(value: string): boolean {
return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]?$/.test(value);
}
function getAbsolutePathKind(value: string): "unix" | "windows" | null {
if (isWindowsDrivePath(value) || isUncPath(value)) {
return "windows";
}
if (value.startsWith("/")) {
return "unix";
}
return null;
}
function trimTrailingPathSeparators(value: string): string {
if (value.length === 0 || isRootPath(value)) {
return value;
}
const trimmed =
getAbsolutePathKind(value) === "unix"
? value.replace(/\/+$/g, "")
: value.replace(/[\\/]+$/g, "");
if (trimmed.length === 0) {
return value;
}
return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed;
}
function preferredPathSeparator(value: string): "/" | "\\" {
const absolutePathKind = getAbsolutePathKind(value);
if (absolutePathKind === "windows") {
return "\\";
}
if (absolutePathKind === "unix") {
return "/";
}
return value.includes("\\") ? "\\" : "/";
}
export function hasTrailingPathSeparator(value: string): boolean {
return (getAbsolutePathKind(value) === "unix" ? /\/$/ : /[\\/]$/).test(value);
}
export { isExplicitRelativePath as isExplicitRelativeProjectPath };
function splitPathSegments(value: string, separator: "/" | "\\"): string[] {
return value.split(separator === "/" ? /\/+/ : /[\\/]+/).filter(Boolean);
}
function getLastPathSeparatorIndex(value: string): number {
if (getAbsolutePathKind(value) === "unix") {
return value.lastIndexOf("/");
}
return Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
}
function splitAbsolutePath(value: string): {
root: string;
separator: "/" | "\\";
segments: string[];
} | null {
if (isWindowsDrivePath(value)) {
const root = `${value.slice(0, 2)}\\`;
const segments = splitPathSegments(value.slice(root.length), "\\");
return { root, separator: "\\", segments };
}
if (isUncPath(value)) {
const segments = splitPathSegments(value, "\\");
const [server, share, ...rest] = segments;
if (!server || !share) {
return null;
}
return {
root: `\\\\${server}\\${share}\\`,
separator: "\\",
segments: rest,
};
}
if (value.startsWith("/")) {
return {
root: "/",
separator: "/",
segments: splitPathSegments(value.slice(1), "/"),
};
}
return null;
}
export function isFilesystemBrowseQuery(
value: string,
platform = typeof navigator === "undefined" ? "" : navigator.platform,
): boolean {
const allowWindowsPaths = isWindowsPlatform(platform);
return (
value.startsWith("./") ||
value.startsWith("../") ||
value.startsWith(".\\") ||
value.startsWith("..\\") ||
value.startsWith("/") ||
value.startsWith("~/") ||
(allowWindowsPaths && isWindowsAbsolutePath(value))
);
}
export function isUnsupportedWindowsProjectPath(value: string, platform: string): boolean {
return isWindowsAbsolutePath(value) && !isWindowsPlatform(platform);
}
export function normalizeProjectPathForDispatch(value: string): string {
return trimTrailingPathSeparators(value.trim());
}
export function resolveProjectPathForDispatch(value: string, cwd?: string | null): string {
const trimmedValue = value.trim();
if (!isExplicitRelativePath(trimmedValue) || !cwd) {
return normalizeProjectPathForDispatch(trimmedValue);
}
const absoluteBase = splitAbsolutePath(normalizeProjectPathForDispatch(cwd));
if (!absoluteBase) {
return normalizeProjectPathForDispatch(trimmedValue);
}
const nextSegments = [...absoluteBase.segments];
for (const segment of trimmedValue.split(/[\\/]+/)) {
if (segment.length === 0 || segment === ".") {
continue;
}
if (segment === "..") {
nextSegments.pop();
continue;
}
nextSegments.push(segment);
}
const joinedPath = nextSegments.join(absoluteBase.separator);
if (joinedPath.length === 0) {
return normalizeProjectPathForDispatch(absoluteBase.root);
}
return normalizeProjectPathForDispatch(`${absoluteBase.root}${joinedPath}`);
}
export function normalizeProjectPathForComparison(value: string): string {
const normalized = normalizeProjectPathForDispatch(value);
if (isWindowsDrivePath(normalized) || normalized.startsWith("\\\\")) {
return normalized.replaceAll("/", "\\").toLowerCase();
}
return normalized;
}
export function findProjectByPath<T extends { cwd: string }>(
projects: ReadonlyArray<T>,
candidatePath: string,
): T | undefined {
const normalizedCandidate = normalizeProjectPathForComparison(candidatePath);
if (normalizedCandidate.length === 0) {
return undefined;
}
return projects.find(
(project) => normalizeProjectPathForComparison(project.cwd) === normalizedCandidate,
);
}
export function inferProjectTitleFromPath(value: string): string {
const normalized = normalizeProjectPathForDispatch(value);
const absolutePath = splitAbsolutePath(normalized);
if (absolutePath) {
return absolutePath.segments.findLast(Boolean) ?? normalized;
}
const segments = normalized.split(/[/\\]/);
return segments.findLast(Boolean) ?? normalized;
}
export function appendBrowsePathSegment(currentPath: string, segment: string): string {
const separator = preferredPathSeparator(currentPath);
return `${getBrowseDirectoryPath(currentPath)}${segment}${separator}`;
}
export function getBrowseLeafPathSegment(currentPath: string): string {
const lastSeparatorIndex = getLastPathSeparatorIndex(currentPath);
return currentPath.slice(lastSeparatorIndex + 1);
}
export function getBrowseDirectoryPath(currentPath: string): string {
if (hasTrailingPathSeparator(currentPath)) {
return currentPath;
}
const lastSeparatorIndex = getLastPathSeparatorIndex(currentPath);
if (lastSeparatorIndex < 0) {
return currentPath;
}
return currentPath.slice(0, lastSeparatorIndex + 1);
}
export function ensureBrowseDirectoryPath(currentPath: string): string {
const trimmed = currentPath.trim();
if (trimmed.length === 0) {
return trimmed;
}
if (hasTrailingPathSeparator(trimmed)) {
return trimmed;
}
return `${trimmed}${preferredPathSeparator(trimmed)}`;
}
export function getBrowseParentPath(currentPath: string): string | null {
const trimmed = trimTrailingPathSeparators(currentPath);
const absolutePath = splitAbsolutePath(trimmed);
if (absolutePath) {
if (absolutePath.segments.length === 0) {
return null;
}
if (absolutePath.segments.length === 1) {
return absolutePath.root;
}
const parentSegments = absolutePath.segments.slice(0, -1).join(absolutePath.separator);
return `${absolutePath.root}${parentSegments}${absolutePath.separator}`;
}
const separator = preferredPathSeparator(currentPath);
const lastSeparatorIndex = getLastPathSeparatorIndex(trimmed);
if (lastSeparatorIndex < 0) {
return null;
}
if (lastSeparatorIndex === 2 && /^[a-zA-Z]:/.test(trimmed)) {
return `${trimmed.slice(0, 2)}${separator}`;
}
return trimmed.slice(0, lastSeparatorIndex + 1);
}
export function canNavigateUp(currentPath: string): boolean {
return hasTrailingPathSeparator(currentPath) && getBrowseParentPath(currentPath) !== null;
}
+64 -34
View File
@@ -51,6 +51,9 @@ const rpcClientMock = {
searchEntries: vi.fn(),
writeFile: vi.fn(),
},
filesystem: {
browse: vi.fn(),
},
shell: {
openInEditor: vi.fn(),
},
@@ -157,6 +160,7 @@ function createLocalStorageStub(): Storage {
function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
return {
getAppBranding: () => null,
getLocalEnvironmentBootstrap: () => null,
getClientSettings: async () => null,
setClientSettings: async () => undefined,
@@ -184,6 +188,9 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridg
getUpdateState: async () => {
throw new Error("getUpdateState not implemented in test");
},
setUpdateChannel: async () => {
throw new Error("setUpdateChannel not implemented in test");
},
checkForUpdate: async () => {
throw new Error("checkForUpdate not implemented in test");
},
@@ -415,6 +422,25 @@ describe("wsApi", () => {
});
});
it("forwards filesystem browse requests to the RPC client", async () => {
rpcClientMock.filesystem.browse.mockResolvedValue({
parentPath: "/tmp/project/",
entries: [],
});
const { createEnvironmentApi } = await import("./environmentApi");
const api = createEnvironmentApi(rpcClientMock as never);
await api.filesystem.browse({
partialPath: "/tmp/project/",
cwd: "/tmp/project",
});
expect(rpcClientMock.filesystem.browse).toHaveBeenCalledWith({
partialPath: "/tmp/project/",
cwd: "/tmp/project",
});
});
it("forwards full-thread diff requests to the orchestration RPC", async () => {
rpcClientMock.orchestration.getFullThreadDiff.mockResolvedValue({ diff: "patch" });
const { createEnvironmentApi } = await import("./environmentApi");
@@ -477,6 +503,19 @@ describe("wsApi", () => {
expect(showContextMenu).toHaveBeenCalledWith(items, undefined);
});
it("forwards folder picker options to the desktop bridge", async () => {
const pickFolder = vi.fn().mockResolvedValue("/tmp/project");
getWindowForTest().desktopBridge = makeDesktopBridge({ pickFolder });
const { createLocalApi } = await import("./localApi");
const api = createLocalApi(rpcClientMock as never);
await expect(api.dialogs.pickFolder({ initialPath: "/tmp/workspace" })).resolves.toBe(
"/tmp/project",
);
expect(pickFolder).toHaveBeenCalledWith({ initialPath: "/tmp/workspace" });
});
it("falls back to the browser context menu helper when the desktop bridge is missing", async () => {
showContextMenuFallbackMock.mockResolvedValue("rename");
const { createLocalApi } = await import("./localApi");
@@ -489,13 +528,20 @@ describe("wsApi", () => {
});
it("reads and writes persistence through the desktop bridge when available", async () => {
const getClientSettings = vi.fn().mockResolvedValue({
const clientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
sidebarProjectGroupingMode: "repository_path" as const,
sidebarProjectGroupingOverrides: {
"environment-local:/tmp/project": "separate" as const,
},
sidebarProjectSortOrder: "manual" as const,
sidebarThreadSortOrder: "created_at" as const,
timestampFormat: "24-hour" as const,
};
const getClientSettings = vi.fn().mockResolvedValue({
...clientSettings,
});
const setClientSettings = vi.fn().mockResolvedValue(undefined);
const getSavedEnvironmentRegistry = vi.fn().mockResolvedValue([]);
@@ -517,14 +563,7 @@ describe("wsApi", () => {
const api = createLocalApi(rpcClientMock as never);
await api.persistence.getClientSettings();
await api.persistence.setClientSettings({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
await api.persistence.setClientSettings(clientSettings);
await api.persistence.getSavedEnvironmentRegistry();
await api.persistence.setSavedEnvironmentRegistry([]);
await api.persistence.getSavedEnvironmentSecret(EnvironmentId.make("environment-local"));
@@ -535,14 +574,7 @@ describe("wsApi", () => {
await api.persistence.removeSavedEnvironmentSecret(EnvironmentId.make("environment-local"));
expect(getClientSettings).toHaveBeenCalledWith();
expect(setClientSettings).toHaveBeenCalledWith({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
expect(setClientSettings).toHaveBeenCalledWith(clientSettings);
expect(getSavedEnvironmentRegistry).toHaveBeenCalledWith();
expect(setSavedEnvironmentRegistry).toHaveBeenCalledWith([]);
expect(getSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local");
@@ -553,15 +585,20 @@ describe("wsApi", () => {
it("falls back to browser storage for persistence when the desktop bridge is missing", async () => {
const { createLocalApi } = await import("./localApi");
const api = createLocalApi(rpcClientMock as never);
await api.persistence.setClientSettings({
const clientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
sidebarProjectGroupingMode: "repository_path" as const,
sidebarProjectGroupingOverrides: {
"environment-local:/tmp/project": "separate" as const,
},
sidebarProjectSortOrder: "manual" as const,
sidebarThreadSortOrder: "created_at" as const,
timestampFormat: "24-hour" as const,
};
await api.persistence.setClientSettings(clientSettings);
await api.persistence.setSavedEnvironmentRegistry([
{
environmentId: EnvironmentId.make("environment-local"),
@@ -577,14 +614,7 @@ describe("wsApi", () => {
"bearer-token",
);
await expect(api.persistence.getClientSettings()).resolves.toEqual({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
await expect(api.persistence.getClientSettings()).resolves.toEqual(clientSettings);
await expect(api.persistence.getSavedEnvironmentRegistry()).resolves.toEqual([
{
environmentId: EnvironmentId.make("environment-local"),
+2 -2
View File
@@ -29,9 +29,9 @@ let cachedApi: LocalApi | undefined;
export function createLocalApi(rpcClient: WsRpcClient): LocalApi {
return {
dialogs: {
pickFolder: async () => {
pickFolder: async (options) => {
if (!window.desktopBridge) return null;
return window.desktopBridge.pickFolder();
return window.desktopBridge.pickFolder(options);
},
confirm: async (message) => {
if (window.desktopBridge) {
+144 -6
View File
@@ -1,19 +1,157 @@
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime";
import type { ScopedProjectRef } from "@t3tools/contracts";
import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
import { normalizeProjectPathForComparison } from "./lib/projectPaths";
import type { Project } from "./types";
export function deriveLogicalProjectKey(
project: Pick<Project, "environmentId" | "id" | "repositoryIdentity">,
export interface ProjectGroupingSettings {
sidebarProjectGroupingMode: SidebarProjectGroupingMode;
sidebarProjectGroupingOverrides: Record<string, SidebarProjectGroupingMode>;
}
export type ProjectGroupingMode = SidebarProjectGroupingMode;
function uniqueNonEmptyValues(values: ReadonlyArray<string | null | undefined>): string[] {
const seen = new Set<string>();
const unique: string[] = [];
for (const value of values) {
const trimmed = value?.trim();
if (!trimmed || seen.has(trimmed)) {
continue;
}
seen.add(trimmed);
unique.push(trimmed);
}
return unique;
}
function deriveRepositoryRelativeProjectPath(
project: Pick<Project, "cwd" | "repositoryIdentity">,
): string | null {
const rootPath = project.repositoryIdentity?.rootPath?.trim();
if (!rootPath) {
return null;
}
const normalizedProjectPath = normalizeProjectPathForComparison(project.cwd);
const normalizedRootPath = normalizeProjectPathForComparison(rootPath);
if (normalizedProjectPath.length === 0 || normalizedRootPath.length === 0) {
return null;
}
if (normalizedProjectPath === normalizedRootPath) {
return "";
}
const separator = normalizedRootPath.includes("\\") ? "\\" : "/";
const rootPrefix = `${normalizedRootPath}${separator}`;
if (!normalizedProjectPath.startsWith(rootPrefix)) {
return null;
}
return normalizedProjectPath.slice(rootPrefix.length).replaceAll("\\", "/");
}
export function derivePhysicalProjectKeyFromPath(environmentId: string, cwd: string): string {
return `${environmentId}:${normalizeProjectPathForComparison(cwd)}`;
}
export function derivePhysicalProjectKey(project: Pick<Project, "environmentId" | "cwd">): string {
return derivePhysicalProjectKeyFromPath(project.environmentId, project.cwd);
}
export function deriveProjectGroupingOverrideKey(
project: Pick<Project, "environmentId" | "cwd">,
): string {
return derivePhysicalProjectKey(project);
}
export function resolveProjectGroupingMode(
project: Pick<Project, "environmentId" | "cwd">,
settings: ProjectGroupingSettings,
): SidebarProjectGroupingMode {
return (
project.repositoryIdentity?.canonicalKey ??
settings.sidebarProjectGroupingOverrides?.[deriveProjectGroupingOverrideKey(project)] ??
settings.sidebarProjectGroupingMode
);
}
function deriveRepositoryScopedKey(
project: Pick<Project, "cwd" | "repositoryIdentity">,
groupingMode: SidebarProjectGroupingMode,
): string | null {
const canonicalKey = project.repositoryIdentity?.canonicalKey;
if (!canonicalKey) {
return null;
}
if (groupingMode === "repository") {
return canonicalKey;
}
const relativeProjectPath = deriveRepositoryRelativeProjectPath(project);
if (relativeProjectPath === null) {
return canonicalKey;
}
return relativeProjectPath.length === 0
? canonicalKey
: `${canonicalKey}::${relativeProjectPath}`;
}
export function deriveLogicalProjectKey(
project: Pick<Project, "environmentId" | "id" | "cwd" | "repositoryIdentity">,
options?: {
groupingMode?: SidebarProjectGroupingMode;
},
): string {
const groupingMode = options?.groupingMode ?? "repository";
if (groupingMode === "separate") {
return derivePhysicalProjectKey(project);
}
return (
deriveRepositoryScopedKey(project, groupingMode) ??
derivePhysicalProjectKey(project) ??
scopedProjectKey(scopeProjectRef(project.environmentId, project.id))
);
}
export function deriveLogicalProjectKeyFromSettings(
project: Pick<Project, "environmentId" | "id" | "cwd" | "repositoryIdentity">,
settings: ProjectGroupingSettings,
): string {
return deriveLogicalProjectKey(project, {
groupingMode: resolveProjectGroupingMode(project, settings),
});
}
export function deriveLogicalProjectKeyFromRef(
projectRef: ScopedProjectRef,
project: Pick<Project, "repositoryIdentity"> | null | undefined,
project: Pick<Project, "environmentId" | "id" | "cwd" | "repositoryIdentity"> | null | undefined,
options?: {
groupingMode?: SidebarProjectGroupingMode;
},
): string {
return project?.repositoryIdentity?.canonicalKey ?? scopedProjectKey(projectRef);
return project ? deriveLogicalProjectKey(project, options) : scopedProjectKey(projectRef);
}
export function deriveProjectGroupLabel(input: {
representative: Pick<Project, "name" | "repositoryIdentity">;
members: ReadonlyArray<Pick<Project, "name" | "repositoryIdentity">>;
}): string {
const sharedDisplayNames = uniqueNonEmptyValues(
input.members.map((member) => member.repositoryIdentity?.displayName),
);
if (sharedDisplayNames.length === 1) {
return sharedDisplayNames[0]!;
}
const sharedRepositoryNames = uniqueNonEmptyValues(
input.members.map((member) => member.repositoryIdentity?.name),
);
if (sharedRepositoryNames.length === 1) {
return sharedRepositoryNames[0]!;
}
return input.representative.name;
}
+28 -1
View File
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vitest";
import { resolveMarkdownFileLinkTarget, rewriteMarkdownFileUriHref } from "./markdown-links";
import {
resolveMarkdownFileLinkMeta,
resolveMarkdownFileLinkTarget,
rewriteMarkdownFileUriHref,
} from "./markdown-links";
describe("rewriteMarkdownFileUriHref", () => {
it("rewrites file uri hrefs into direct path hrefs", () => {
@@ -57,6 +61,29 @@ describe("resolveMarkdownFileLinkTarget", () => {
);
});
it("formats tooltip display paths relative to the cwd when possible", () => {
expect(
resolveMarkdownFileLinkMeta(
"file:///C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts#L501",
"C:/Users/mike/dev-stuff/t3code",
),
).toMatchObject({
displayPath: "t3code/apps/web/src/session-logic.ts:501",
});
});
it("formats tooltip display paths relative to the cwd for slash-prefixed windows paths", () => {
expect(
resolveMarkdownFileLinkMeta(
"/C:/Users/mike/dev-stuff/t3code/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx",
"C:/Users/mike/dev-stuff/t3code",
),
).toMatchObject({
displayPath:
"t3code/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx",
});
});
it("does not treat app routes as file links", () => {
expect(resolveMarkdownFileLinkTarget("/chat/settings")).toBeNull();
});
+39 -1
View File
@@ -1,4 +1,5 @@
import { resolvePathLinkTarget } from "./terminal-links";
import { formatWorkspaceRelativePath } from "./filePathDisplay";
import { resolvePathLinkTarget, splitPathAndPosition } from "./terminal-links";
const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
@@ -21,6 +22,15 @@ const POSIX_FILE_ROOT_PREFIXES = [
"/root/",
] as const;
export interface MarkdownFileLinkMeta {
filePath: string;
targetPath: string;
displayPath: string;
basename: string;
line?: number;
column?: number;
}
function safeDecode(value: string): string {
try {
return decodeURIComponent(value);
@@ -143,3 +153,31 @@ export function resolveMarkdownFileLinkTarget(
if (!cwd) return null;
return resolvePathLinkTarget(pathWithPosition, cwd);
}
function basenameOfPath(path: string): string {
const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
}
export function resolveMarkdownFileLinkMeta(
href: string | undefined,
cwd?: string,
): MarkdownFileLinkMeta | null {
const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
if (!targetPath) return null;
const { path, line, column } = splitPathAndPosition(targetPath);
const parsedLine = line ? Number.parseInt(line, 10) : Number.NaN;
const parsedColumn = column ? Number.parseInt(column, 10) : Number.NaN;
const lineNumber = Number.isFinite(parsedLine) ? parsedLine : undefined;
const columnNumber = Number.isFinite(parsedColumn) ? parsedColumn : undefined;
return {
filePath: path,
targetPath,
displayPath: formatWorkspaceRelativePath(targetPath, cwd),
basename: basenameOfPath(path),
...(lineNumber !== undefined ? { line: lineNumber } : {}),
...(columnNumber !== undefined ? { column: columnNumber } : {}),
};
}
+2
View File
@@ -0,0 +1,2 @@
export const RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
export const RIGHT_PANEL_SHEET_CLASS_NAME = "w-[min(88vw,820px)] max-w-[820px] p-0";
+23 -7
View File
@@ -22,6 +22,11 @@ import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { readLocalApi } from "../localApi";
import { useSettings } from "../hooks/useSettings";
import {
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKeyFromPath,
} from "../logicalProject";
import {
getServerConfigUpdatedNotification,
ServerConfigUpdatedNotification,
@@ -204,6 +209,10 @@ function EventRouter() {
const setActiveEnvironmentId = useStore((store) => store.setActiveEnvironmentId);
const navigate = useNavigate();
const pathname = useLocation({ select: (loc) => loc.pathname });
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const readPathname = useEffectEvent(() => pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
@@ -224,14 +233,21 @@ function EventRouter() {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return;
}
useUiStateStore
.getState()
.setProjectExpanded(
scopedProjectKey(
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
),
true,
const bootstrapEnvironmentState =
useStore.getState().environmentStateById[payload.environment.environmentId];
const bootstrapProject =
bootstrapEnvironmentState?.projectById[payload.bootstrapProjectId] ?? null;
const bootstrapProjectKey =
(bootstrapProject
? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
: null) ??
(serverConfig?.cwd
? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
: null) ??
scopedProjectKey(
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
);
useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
if (readPathname() !== "/") {
return;
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more