Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
150e171a88 | ||
|
|
39f07869d9 | ||
|
|
afc0c78f0b | ||
|
|
dadda0d490 | ||
|
|
fb9274117c | ||
|
|
88dc6c94aa | ||
|
|
585031572f | ||
|
|
cd732a2b2e | ||
|
|
875e6edcf2 | ||
|
|
e1a8ee189a | ||
|
|
e64ad4b2c7 | ||
|
|
0e146e22fb | ||
|
|
700579bb3f | ||
|
|
ad79b5a4a3 | ||
|
|
4bc43a0e2b | ||
|
|
44e409f9c6 | ||
|
|
d3d0a08237 | ||
|
|
9b0fe5efd0 | ||
|
|
0df68cc73e | ||
|
|
61e1babcc7 | ||
|
|
06912c3222 | ||
|
|
8416ecdb53 |
No files matched your search
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Browser Test, Build
|
||||
name: Lint, Typecheck, Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -34,14 +34,6 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
@@ -54,14 +46,6 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: |
|
||||
cd apps/web
|
||||
bunx playwright install --with-deps chromium
|
||||
|
||||
- name: Browser test
|
||||
run: bun run --cwd apps/web test:browser
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: bun run build:desktop
|
||||
|
||||
|
||||
@@ -1,350 +0,0 @@
|
||||
name: Release Desktop
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Release version (for example 1.2.3 or v1.2.3)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- 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"
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- label: macOS arm64
|
||||
runner: macos-14
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
- label: macOS x64
|
||||
runner: macos-15-intel
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
- label: Linux x64
|
||||
runner: ubuntu-24.04
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
- label: Windows x64
|
||||
runner: windows-2022
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
CSC_LINK: ${{ secrets.CSC_LINK }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
|
||||
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
|
||||
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
|
||||
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
|
||||
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
|
||||
run: |
|
||||
args=(
|
||||
--platform "${{ matrix.platform }}"
|
||||
--target "${{ matrix.target }}"
|
||||
--arch "${{ matrix.arch }}"
|
||||
--build-version "${{ needs.preflight.outputs.version }}"
|
||||
--verbose
|
||||
)
|
||||
|
||||
has_all() {
|
||||
for value in "$@"; do
|
||||
if [[ -z "$value" ]]; then
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" ]]; then
|
||||
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
|
||||
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
|
||||
printf '%s' "$APPLE_API_KEY" > "$key_path"
|
||||
export APPLE_API_KEY="$key_path"
|
||||
echo "macOS signing enabled."
|
||||
args+=(--signed)
|
||||
else
|
||||
echo "macOS signing disabled (missing one or more Apple signing secrets)."
|
||||
fi
|
||||
elif [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
if has_all \
|
||||
"$AZURE_TENANT_ID" \
|
||||
"$AZURE_CLIENT_ID" \
|
||||
"$AZURE_CLIENT_SECRET" \
|
||||
"$AZURE_TRUSTED_SIGNING_ENDPOINT" \
|
||||
"$AZURE_TRUSTED_SIGNING_ACCOUNT_NAME" \
|
||||
"$AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME" \
|
||||
"$AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"; then
|
||||
echo "Windows signing enabled (Azure Trusted Signing)."
|
||||
args+=(--signed)
|
||||
else
|
||||
echo "Windows signing disabled (missing one or more Azure Trusted Signing secrets)."
|
||||
fi
|
||||
else
|
||||
echo "Signing disabled for ${{ matrix.platform }}."
|
||||
fi
|
||||
|
||||
bun run dist:desktop:artifact -- "${args[@]}"
|
||||
|
||||
- name: Collect release assets
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p release-publish
|
||||
|
||||
shopt -s nullglob
|
||||
for pattern in \
|
||||
"release/*.dmg" \
|
||||
"release/*.zip" \
|
||||
"release/*.AppImage" \
|
||||
"release/*.exe" \
|
||||
"release/*.blockmap" \
|
||||
"release/latest*.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
|
||||
fi
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Build CLI package
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: desktop-*
|
||||
merge-multiple: true
|
||||
path: release-assets
|
||||
|
||||
- name: Publish release
|
||||
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 }}
|
||||
generate_release_notes: true
|
||||
make_latest: true
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/latest*.yml
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
run: |
|
||||
node --input-type=module -e '
|
||||
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const files = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
"apps/web/package.json",
|
||||
"packages/contracts/package.json",
|
||||
];
|
||||
|
||||
let changed = false;
|
||||
for (const file of files) {
|
||||
const packageJson = JSON.parse(readFileSync(file, "utf8"));
|
||||
if (packageJson.version !== process.env.RELEASE_VERSION) {
|
||||
packageJson.version = process.env.RELEASE_VERSION;
|
||||
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
console.log("All package.json versions already match release version.");
|
||||
}
|
||||
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `changed=${changed}\n`);
|
||||
'
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bun install
|
||||
|
||||
- name: Commit and push version bump
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
|
||||
run: |
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
echo "No version changes to commit."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
git push origin HEAD:main
|
||||
+1
-4
@@ -11,7 +11,4 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.t3
|
||||
@@ -1,9 +1,5 @@
|
||||
# CLAUDE.md
|
||||
|
||||
## Task Completion Requirements
|
||||
|
||||
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
|
||||
@@ -18,16 +14,11 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon
|
||||
|
||||
If a tradeoff is required, choose correctness and robustness over short-term convenience.
|
||||
|
||||
## Maintainability
|
||||
|
||||
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
|
||||
|
||||
## Package Roles
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
|
||||
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
|
||||
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
|
||||
## Codex App Server (Important)
|
||||
|
||||
|
||||
@@ -75,11 +75,8 @@ npx t3
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
|
||||
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
|
||||
@@ -89,12 +86,6 @@ npx t3
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
|
||||
- Windows `--signed` uses Azure Trusted Signing and expects:
|
||||
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
|
||||
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
### Running multiple dev instances
|
||||
|
||||
@@ -131,6 +122,3 @@ Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI
|
||||
## CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
|
||||
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
|
||||
- See `docs/release.md` for full release/signing setup checklist.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
@@ -14,17 +14,15 @@
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
"electron": "40.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"@types/node": "^22.10.2",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
"wait-on": "^8.0.2"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
|
||||
@@ -1,171 +1,43 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import electronmon from "electronmon";
|
||||
import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
|
||||
await waitOn({
|
||||
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||
resources: [
|
||||
`tcp:${port}`,
|
||||
"file:dist-electron/main.js",
|
||||
"file:dist-electron/preload.js",
|
||||
"file:../server/dist/index.mjs",
|
||||
],
|
||||
});
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const monitor = await electronmon({
|
||||
cwd: desktopDir,
|
||||
args: ["dist-electron/main.js"],
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
electronPath: resolveElectronPath(),
|
||||
});
|
||||
|
||||
let shuttingDown = false;
|
||||
let restartTimer = null;
|
||||
let currentApp = null;
|
||||
let restartQueue = Promise.resolve();
|
||||
const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function startApp() {
|
||||
if (shuttingDown || currentApp !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const app = spawn(
|
||||
resolveElectronPath(),
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
currentApp = app;
|
||||
|
||||
app.once("error", () => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
if (!shuttingDown) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
|
||||
app.once("exit", () => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
if (!shuttingDown && !expectedExits.has(app)) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stopApp() {
|
||||
const app = currentApp;
|
||||
if (!app) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentApp = null;
|
||||
expectedExits.add(app);
|
||||
|
||||
await new Promise((resolve) => {
|
||||
let settled = false;
|
||||
|
||||
const finish = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
resolve();
|
||||
};
|
||||
|
||||
app.once("exit", finish);
|
||||
app.kill("SIGTERM");
|
||||
killChildTreeByPid(app.pid, "TERM");
|
||||
|
||||
setTimeout(() => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
app.kill("SIGKILL");
|
||||
killChildTreeByPid(app.pid, "KILL");
|
||||
finish();
|
||||
}, forcedShutdownTimeoutMs).unref();
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleRestart() {
|
||||
if (shuttingDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
}
|
||||
|
||||
restartTimer = setTimeout(() => {
|
||||
restartTimer = null;
|
||||
restartQueue = restartQueue
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
await stopApp();
|
||||
if (!shuttingDown) {
|
||||
startApp();
|
||||
}
|
||||
});
|
||||
}, restartDebounceMs);
|
||||
}
|
||||
|
||||
function startWatchers() {
|
||||
for (const { directory, files } of watchedDirectories) {
|
||||
const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {
|
||||
if (typeof filename !== "string" || !files.has(filename)) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleRestart();
|
||||
});
|
||||
|
||||
watchers.push(watcher);
|
||||
}
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
|
||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
@@ -173,29 +45,20 @@ async function shutdown(exitCode) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
try {
|
||||
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
|
||||
} catch {
|
||||
// Best effort only; fallback process kill below handles stubborn children.
|
||||
}
|
||||
|
||||
for (const watcher of watchers) {
|
||||
watcher.close();
|
||||
}
|
||||
|
||||
await stopApp();
|
||||
killChildTree("TERM");
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, childTreeGracePeriodMs);
|
||||
});
|
||||
killChildTree("KILL");
|
||||
setTimeout(() => {
|
||||
killChildTree("KILL");
|
||||
}, 1_200).unref();
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
startWatchers();
|
||||
cleanupStaleDevApps();
|
||||
startApp();
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void shutdown(130);
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import * as ChildProcess from "node:child_process";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
+78
-748
File diff suppressed because it is too large.
Load diff
@@ -6,17 +6,13 @@ const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
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_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => wsUrl,
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
showContextMenu: (items) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
@@ -29,18 +25,4 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||
onUpdateState: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
|
||||
if (typeof state !== "object" || state === null) return;
|
||||
listener(state as Parameters<typeof listener>[0]);
|
||||
};
|
||||
|
||||
ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
} satisfies DesktopBridge);
|
||||
@@ -1,74 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-"));
|
||||
tempRoots.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempRoots.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("RotatingFileSink", () => {
|
||||
it("rotates when writes exceed max bytes", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "desktop-main.log");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 10,
|
||||
maxFiles: 3,
|
||||
});
|
||||
|
||||
sink.write("12345");
|
||||
sink.write("67890");
|
||||
sink.write("abc");
|
||||
|
||||
expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc");
|
||||
expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890");
|
||||
});
|
||||
|
||||
it("retains only maxFiles backups", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "server-child.log");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 4,
|
||||
maxFiles: 2,
|
||||
});
|
||||
|
||||
sink.write("aaaa");
|
||||
sink.write("bbbb");
|
||||
sink.write("cccc");
|
||||
sink.write("dddd");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false);
|
||||
});
|
||||
|
||||
it("prunes stale backups above maxFiles on startup", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "desktop-main.log");
|
||||
fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first");
|
||||
fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale");
|
||||
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 16,
|
||||
maxFiles: 2,
|
||||
});
|
||||
sink.write("hello");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,130 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
reduceDesktopUpdateStateOnCheckStart,
|
||||
reduceDesktopUpdateStateOnDownloadComplete,
|
||||
reduceDesktopUpdateStateOnDownloadFailure,
|
||||
reduceDesktopUpdateStateOnDownloadProgress,
|
||||
reduceDesktopUpdateStateOnDownloadStart,
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
|
||||
describe("updateMachine", () => {
|
||||
it("clears transient errors when a check starts", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
message: "network",
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("checking");
|
||||
expect(state.message).toBeNull();
|
||||
expect(state.errorContext).toBeNull();
|
||||
expect(state.canRetry).toBe(false);
|
||||
});
|
||||
|
||||
it("records a check failure without exposing an action", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
"network unavailable",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("error");
|
||||
expect(state.errorContext).toBe("check");
|
||||
expect(state.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves available version on download failure for retry", () => {
|
||||
const state = reduceDesktopUpdateStateOnDownloadFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
downloadPercent: 43,
|
||||
},
|
||||
"checksum mismatch",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("available");
|
||||
expect(state.availableVersion).toBe("1.1.0");
|
||||
expect(state.errorContext).toBe("download");
|
||||
expect(state.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("transitions to downloaded and then preserves install retry state", () => {
|
||||
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
},
|
||||
"1.1.0",
|
||||
);
|
||||
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
|
||||
|
||||
expect(downloaded.status).toBe("downloaded");
|
||||
expect(downloaded.downloadedVersion).toBe("1.1.0");
|
||||
expect(failedInstall.status).toBe("downloaded");
|
||||
expect(failedInstall.errorContext).toBe("install");
|
||||
expect(failedInstall.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("clears stale download state when no update is available", () => {
|
||||
const state = reduceDesktopUpdateStateOnNoUpdate(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
availableVersion: "1.1.0",
|
||||
downloadedVersion: "1.1.0",
|
||||
message: "old failure",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("up-to-date");
|
||||
expect(state.availableVersion).toBeNull();
|
||||
expect(state.downloadedVersion).toBeNull();
|
||||
expect(state.message).toBeNull();
|
||||
expect(state.errorContext).toBeNull();
|
||||
});
|
||||
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
"1.1.0",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
expect(progress.errorContext).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
|
||||
|
||||
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState {
|
||||
return {
|
||||
enabled: false,
|
||||
status: "disabled",
|
||||
currentVersion,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnCheckStart(
|
||||
state: DesktopUpdateState,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "checking",
|
||||
checkedAt,
|
||||
message: null,
|
||||
downloadPercent: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnCheckFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "error",
|
||||
message,
|
||||
checkedAt,
|
||||
downloadPercent: null,
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "available",
|
||||
availableVersion: version,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnNoUpdate(
|
||||
state: DesktopUpdateState,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "up-to-date",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadStart(
|
||||
state: DesktopUpdateState,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloading",
|
||||
downloadPercent: 0,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: nextStatusAfterDownloadFailure(state),
|
||||
message,
|
||||
downloadPercent: null,
|
||||
errorContext: "download",
|
||||
canRetry: getCanRetryAfterDownloadFailure(state),
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadProgress(
|
||||
state: DesktopUpdateState,
|
||||
percent: number,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloading",
|
||||
downloadPercent: percent,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadComplete(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloaded",
|
||||
availableVersion: version,
|
||||
downloadedVersion: version,
|
||||
downloadPercent: 100,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnInstallFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloaded",
|
||||
message,
|
||||
errorContext: "install",
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
getCanRetryAfterDownloadFailure,
|
||||
getAutoUpdateDisabledReason,
|
||||
nextStatusAfterDownloadFailure,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
currentVersion: "1.0.0",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
|
||||
describe("shouldBroadcastDownloadProgress", () => {
|
||||
it("broadcasts the first downloading progress update", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: null },
|
||||
1,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("skips progress updates within the same 10% bucket", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 11.2 },
|
||||
18.7,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("broadcasts progress updates when a new 10% bucket is reached", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 19.9 },
|
||||
20.1,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("broadcasts progress updates when a retry resets the download percentage", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 50.4 },
|
||||
0.2,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAutoUpdateDisabledReason", () => {
|
||||
it("reports development builds as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: true,
|
||||
isPackaged: false,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
}),
|
||||
).toContain("packaged production builds");
|
||||
});
|
||||
|
||||
it("reports env-disabled auto updates", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: true,
|
||||
}),
|
||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||
});
|
||||
|
||||
it("reports linux non-AppImage builds as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "linux",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
}),
|
||||
).toContain("AppImage");
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextStatusAfterDownloadFailure", () => {
|
||||
it("returns available when an update version is still known", () => {
|
||||
expect(
|
||||
nextStatusAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
}),
|
||||
).toBe("available");
|
||||
});
|
||||
|
||||
it("returns error when no update version can be retried", () => {
|
||||
expect(
|
||||
nextStatusAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: null,
|
||||
}),
|
||||
).toBe("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCanRetryAfterDownloadFailure", () => {
|
||||
it("returns true when an available version is still present", () => {
|
||||
expect(
|
||||
getCanRetryAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when no version is available to retry", () => {
|
||||
expect(
|
||||
getCanRetryAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
export function shouldBroadcastDownloadProgress(
|
||||
currentState: DesktopUpdateState,
|
||||
nextPercent: number,
|
||||
): boolean {
|
||||
if (currentState.status !== "downloading") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const currentPercent = currentState.downloadPercent;
|
||||
if (currentPercent === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const previousStep = Math.floor(currentPercent / 10);
|
||||
const nextStep = Math.floor(nextPercent / 10);
|
||||
return nextStep !== previousStep || nextPercent === 100;
|
||||
}
|
||||
|
||||
export function nextStatusAfterDownloadFailure(
|
||||
currentState: DesktopUpdateState,
|
||||
): DesktopUpdateState["status"] {
|
||||
return currentState.availableVersion ? "available" : "error";
|
||||
}
|
||||
|
||||
export function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean {
|
||||
return currentState.availableVersion !== null;
|
||||
}
|
||||
|
||||
export function getAutoUpdateDisabledReason(args: {
|
||||
isDevelopment: boolean;
|
||||
isPackaged: boolean;
|
||||
platform: NodeJS.Platform;
|
||||
appImage?: string | undefined;
|
||||
disabledByEnv: boolean;
|
||||
}): string | null {
|
||||
if (args.isDevelopment || !args.isPackaged) {
|
||||
return "Automatic updates are only available in packaged production builds.";
|
||||
}
|
||||
if (args.disabledByEnv) {
|
||||
return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
|
||||
}
|
||||
if (args.platform === "linux" && !args.appImage) {
|
||||
return "Automatic updates on Linux require running the AppImage build.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
+10
-18
@@ -1,11 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
"directory": "apps/server"
|
||||
},
|
||||
"version": "0.1.0",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
},
|
||||
@@ -13,9 +8,10 @@
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "./dist/index.mjs",
|
||||
"scripts": {
|
||||
"dev": "bun run src/index.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
|
||||
"build": "tsdown && node scripts/bundle-client.ts",
|
||||
"start": "node dist/index.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
@@ -31,19 +27,15 @@
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.13 || ^23.4 || >=24.10"
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Copies the built web app into dist/client/ so the published npm package
|
||||
* includes the web UI. This runs as a post-build step.
|
||||
*/
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
|
||||
const target = path.resolve(import.meta.dirname, "../dist/client");
|
||||
|
||||
if (!fs.existsSync(webDist)) {
|
||||
console.log(
|
||||
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.cpSync(webDist, target, { recursive: true });
|
||||
console.log("✓ Bundled web app into dist/client");
|
||||
@@ -1,172 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
|
||||
);
|
||||
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(command);
|
||||
const exitCode = yield* child.exitCode;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new CliError({
|
||||
message: `Command exited with non-zero exit code (${exitCode})`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// build subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const buildCmd = Command.make(
|
||||
"build",
|
||||
{
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
})`bun tsdown`,
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
const clientTarget = path.join(serverDir, "dist/client");
|
||||
|
||||
if (yield* fs.exists(webDist)) {
|
||||
yield* fs.copy(webDist, clientTarget);
|
||||
yield* Effect.log("[cli] Bundled web app into dist/client");
|
||||
} else {
|
||||
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
|
||||
}
|
||||
}),
|
||||
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// publish subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const publishCmd = Command.make(
|
||||
"publish",
|
||||
{
|
||||
tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
|
||||
access: Flag.string("access").pipe(Flag.withDefault("public")),
|
||||
appVersion: Flag.string("app-version").pipe(Flag.optional),
|
||||
provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
|
||||
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
const packageJsonPath = path.join(serverDir, "package.json");
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
|
||||
// Build package.json for publish
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
type: serverPackageJson.type,
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||
};
|
||||
|
||||
// Resolve catalog: entries in production dependencies
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
|
||||
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
yield* Effect.log("[cli] Resolved package.json for publish");
|
||||
}),
|
||||
// Use: npm publish
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["publish", "--access", config.access, "--tag", config.tag];
|
||||
if (config.provenance) args.push("--provenance");
|
||||
if (config.dryRun) args.push("--dry-run");
|
||||
|
||||
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
|
||||
yield* runCommand(
|
||||
ChildProcess.make("npm", [...args], {
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Release: restore
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
yield* fs.rename(backupPath, packageJsonPath);
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
).pipe(Command.withDescription("Publish the server package to npm."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// root command
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const cli = Command.make("cli").pipe(
|
||||
Command.withDescription("T3 server build & publish CLI."),
|
||||
Command.withSubcommands([buildCmd, publishCmd]),
|
||||
);
|
||||
|
||||
Command.run(cli, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
|
||||
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
import readline from "node:readline";
|
||||
@@ -104,23 +104,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
||||
"does not exist",
|
||||
];
|
||||
|
||||
/**
|
||||
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
}
|
||||
child.kill();
|
||||
}
|
||||
|
||||
export function normalizeCodexModelSlug(
|
||||
model: string | undefined | null,
|
||||
preferredId?: string,
|
||||
@@ -202,7 +185,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
@@ -493,7 +475,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
context.output.close();
|
||||
|
||||
if (!context.child.killed) {
|
||||
killChildTree(context.child);
|
||||
context.child.kill();
|
||||
}
|
||||
|
||||
this.updateSession(context, {
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
/**
|
||||
* ServerConfig - Runtime configuration services.
|
||||
* ServerConfig and NetService - Runtime configuration services.
|
||||
*
|
||||
* Defines process-level server configuration and networking helpers used by
|
||||
* startup and runtime layers.
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
import * as Net from "node:net";
|
||||
import { Data, Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
|
||||
@@ -59,6 +60,68 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
);
|
||||
}
|
||||
|
||||
// Helpers
|
||||
|
||||
export class NetError extends Data.TaggedError("NetError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
/**
|
||||
* NetServiceShape - Networking helper operations used during startup.
|
||||
*/
|
||||
export interface NetServiceShape {
|
||||
/**
|
||||
* Resolve an available listening port, preferring the provided port first.
|
||||
*
|
||||
* Falls back to an ephemeral OS-assigned port when the preferred port is in use.
|
||||
*/
|
||||
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* NetService - Service tag for startup networking helpers.
|
||||
*/
|
||||
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
|
||||
"t3/config/NetService",
|
||||
) {
|
||||
static readonly layer = Layer.succeed(NetService, {
|
||||
findAvailablePort: (preferred) =>
|
||||
Effect.callback<number, NetError>((resume) => {
|
||||
let fallbackServer: Net.Server | null = null;
|
||||
const server = Net.createServer();
|
||||
server.listen(preferred, () => {
|
||||
server.close(() => resume(Effect.succeed(preferred)));
|
||||
});
|
||||
server.on("error", () => {
|
||||
const fallback = Net.createServer();
|
||||
fallback.listen(0, () => {
|
||||
const addr = fallback.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
fallback.close(() => {
|
||||
resume(
|
||||
port > 0
|
||||
? Effect.succeed(port)
|
||||
: Effect.fail(new NetError({ message: "Could not find an available port." })),
|
||||
);
|
||||
});
|
||||
});
|
||||
fallback.on("error", (cause) => {
|
||||
resume(
|
||||
Effect.fail(new NetError({ message: "Failed to find an available port", cause })),
|
||||
);
|
||||
});
|
||||
fallbackServer = fallback;
|
||||
});
|
||||
|
||||
return Effect.sync(() => {
|
||||
server.close();
|
||||
fallbackServer?.close();
|
||||
});
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export const resolveStaticDir = Effect.fn(function* () {
|
||||
const { join, resolve } = yield* Path.Path;
|
||||
const { exists } = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -189,7 +189,7 @@ function withFakeCodexEnv<A, E, R>(
|
||||
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
||||
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
||||
it.effect("generates and sanitizes commit messages", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
@@ -197,7 +197,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
" Add important change to the system with too much detail and a trailing period.\nsecondary line",
|
||||
body: "\n- added migration\n- updated tests\n",
|
||||
}),
|
||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
@@ -212,34 +211,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||
expect(generated.subject.endsWith(".")).toBe(false);
|
||||
expect(generated.body).toBe("- added migration\n- updated tests");
|
||||
expect(generated.branch).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates commit message with branch when includeBranch is true", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
subject: "Add important change",
|
||||
body: "",
|
||||
branch: "fix/important-system-change",
|
||||
}),
|
||||
stdinMustContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
includeBranch: true,
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add important change");
|
||||
expect(generated.branch).toBe("feature/fix/important-system-change");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -3,8 +3,6 @@ import { randomUUID } from "node:crypto";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
@@ -21,17 +19,6 @@ const CODEX_MODEL = "gpt-5.3-codex";
|
||||
const CODEX_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
|
||||
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
|
||||
const document = Schema.toJsonSchemaDocument(schema);
|
||||
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||
return {
|
||||
...document.schema,
|
||||
$defs: document.definitions,
|
||||
};
|
||||
}
|
||||
return document.schema;
|
||||
}
|
||||
|
||||
function normalizeCodexError(
|
||||
operation: string,
|
||||
error: unknown,
|
||||
@@ -95,6 +82,24 @@ function sanitizePrTitle(raw: string): string {
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
function sanitizeBranchName(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/['"`]/g, "")
|
||||
.replace(/^[./\s_-]+|[./\s_-]+$/g, "");
|
||||
|
||||
const branchFragment = normalized
|
||||
.replace(/[^a-z0-9/_-]+/g, "-")
|
||||
.replace(/\/+/g, "/")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^[./_-]+|[./_-]+$/g, "")
|
||||
.slice(0, 64)
|
||||
.replace(/[./_-]+$/g, "");
|
||||
|
||||
return branchFragment.length > 0 ? branchFragment : "update";
|
||||
}
|
||||
|
||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -199,7 +204,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
|
||||
JSON.stringify(Schema.toJsonSchemaDocument(outputSchemaJson).schema),
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
@@ -224,7 +229,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||
},
|
||||
@@ -313,19 +317,12 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||
const wantsBranch = input.includeBranch === true;
|
||||
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
wantsBranch
|
||||
? "Return a JSON object with keys: subject, body, branch."
|
||||
: "Return a JSON object with keys: subject, body.",
|
||||
"Return a JSON object with keys: subject, body.",
|
||||
"Rules:",
|
||||
"- subject must be imperative, <= 72 chars, and no trailing period",
|
||||
"- body can be empty string or short bullet points",
|
||||
...(wantsBranch
|
||||
? ["- branch must be a short semantic git branch fragment for this change"]
|
||||
: []),
|
||||
"- capture the primary user-visible or developer-visible change",
|
||||
"",
|
||||
`Branch: ${input.branch ?? "(detached)"}`,
|
||||
@@ -337,31 +334,20 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
limitSection(input.stagedPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
const outputSchemaJson = wantsBranch
|
||||
? Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
branch: Schema.String,
|
||||
})
|
||||
: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
});
|
||||
|
||||
return runCodexJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
outputSchemaJson: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
({
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
}) satisfies CommitMessageGenerationResult,
|
||||
),
|
||||
);
|
||||
@@ -411,10 +397,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
|
||||
return Effect.gen(function* () {
|
||||
const { imagePaths } = yield* materializeImageAttachments(
|
||||
"generateBranchName",
|
||||
input.attachments,
|
||||
);
|
||||
const { imagePaths } = yield* materializeImageAttachments("generateBranchName", input.attachments);
|
||||
const attachmentLines = (input.attachments ?? []).map(
|
||||
(attachment) =>
|
||||
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||
@@ -452,7 +435,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
branch: sanitizeBranchName(generated.branch),
|
||||
} satisfies BranchNameGenerationResult;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -110,7 +110,6 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
|
||||
createBranch: (input) => core.createBranch(input),
|
||||
checkoutBranch: (input) => core.checkoutBranch(input),
|
||||
initRepo: (input) => core.initRepo(input),
|
||||
listLocalBranchNames: (cwd) => core.listLocalBranchNames(cwd),
|
||||
} satisfies GitCoreShape;
|
||||
});
|
||||
|
||||
@@ -275,18 +274,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not include detached HEAD pseudo-refs as branches", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
yield* git(tmp, ["checkout", "--detach", "HEAD"]);
|
||||
|
||||
const result = yield* listGitBranches({ cwd: tmp });
|
||||
expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);
|
||||
expect(result.branches.some((branch) => branch.current)).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -391,82 +378,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists local branches first and remote branches last", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
yield* createGitBranch({ cwd: tmp, branch: "feature/local-only" });
|
||||
|
||||
const remoteOnlyBranch = "feature/remote-only";
|
||||
yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
|
||||
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
|
||||
yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
|
||||
|
||||
const result = yield* listGitBranches({ cwd: tmp });
|
||||
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
|
||||
|
||||
expect(firstRemoteIndex).toBeGreaterThan(0);
|
||||
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.branches.some(
|
||||
(branch) => branch.name === "origin/feature/remote-only" && branch.isRemote,
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remoteName = "my-org/upstream";
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
yield* git(tmp, ["remote", "add", remoteName, remote]);
|
||||
yield* git(tmp, ["push", "-u", remoteName, defaultBranch]);
|
||||
|
||||
const remoteOnlyBranch = "feature/remote-with-remote-name";
|
||||
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
|
||||
yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
|
||||
|
||||
const result = yield* listGitBranches({ cwd: tmp });
|
||||
const remoteBranch = result.branches.find(
|
||||
(branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`,
|
||||
);
|
||||
|
||||
expect(remoteBranch).toBeDefined();
|
||||
expect(remoteBranch?.isRemote).toBe(true);
|
||||
expect(remoteBranch?.remoteName).toBe(remoteName);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkoutGitBranch ──
|
||||
@@ -689,87 +600,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"does not silently checkout a local branch when a remote ref no longer exists",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
yield* createGitBranch({ cwd: source, branch: "feature" });
|
||||
|
||||
const checkoutResult = yield* Effect.result(
|
||||
checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
|
||||
);
|
||||
expect(checkoutResult._tag).toBe("Failure");
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const remoteName = "my-org/upstream";
|
||||
const featureBranch = "feature";
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", remoteName, remote]);
|
||||
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
|
||||
|
||||
yield* git(source, ["checkout", "-b", featureBranch]);
|
||||
yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n");
|
||||
yield* git(source, ["add", "feature.txt"]);
|
||||
yield* git(source, ["commit", "-m", "feature commit"]);
|
||||
yield* git(source, ["push", "-u", remoteName, featureBranch]);
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
yield* git(source, ["branch", "-D", featureBranch]);
|
||||
|
||||
yield* checkoutGitBranch({ cwd: source, branch: `${remoteName}/${featureBranch}` });
|
||||
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"falls back to detached checkout when --track would conflict with an existing local branch",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
// Keep local branch but remove tracking so `--track origin/<branch>`
|
||||
// would attempt to create an already-existing local branch.
|
||||
yield* git(source, ["branch", "--unset-upstream"]);
|
||||
|
||||
yield* checkoutGitBranch({ cwd: source, branch: `origin/${defaultBranch}` });
|
||||
|
||||
const core = yield* GitCore;
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(status.branch).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when checkout would overwrite uncommitted changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -1273,135 +1103,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("computes ahead count against base branch when no upstream is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const core = yield* GitCore;
|
||||
|
||||
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
|
||||
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
|
||||
yield* writeTextFile(path.join(tmp, "feature.txt"), "ahead of base\n");
|
||||
yield* git(tmp, ["add", "feature.txt"]);
|
||||
yield* git(tmp, ["commit", "-m", "feature commit"]);
|
||||
|
||||
const details = yield* core.statusDetails(tmp);
|
||||
expect(details.branch).toBe("feature/no-upstream-ahead");
|
||||
expect(details.hasUpstream).toBe(false);
|
||||
expect(details.aheadCount).toBe(1);
|
||||
expect(details.behindCount).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"computes ahead count against origin/default when local default branch is missing",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(source, ["checkout", "-b", "feature/remote-base-only"]);
|
||||
yield* writeTextFile(
|
||||
path.join(source, "feature.txt"),
|
||||
`ahead of origin/${initialBranch}\n`,
|
||||
);
|
||||
yield* git(source, ["add", "feature.txt"]);
|
||||
yield* git(source, ["commit", "-m", "feature commit"]);
|
||||
yield* git(source, ["branch", "-D", initialBranch]);
|
||||
|
||||
const core = yield* GitCore;
|
||||
const details = yield* core.statusDetails(source);
|
||||
expect(details.branch).toBe("feature/remote-base-only");
|
||||
expect(details.hasUpstream).toBe(false);
|
||||
expect(details.aheadCount).toBe(1);
|
||||
expect(details.behindCount).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips push when no upstream is configured and branch is not ahead of base", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const core = yield* GitCore;
|
||||
|
||||
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
|
||||
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
|
||||
|
||||
const pushed = yield* core.pushCurrentBranch(tmp, null);
|
||||
expect(pushed.status).toBe("skipped_up_to_date");
|
||||
expect(pushed.branch).toBe("feature/no-upstream-no-ahead");
|
||||
expect(pushed.setUpstream).toBeUndefined();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes with upstream setup when no comparable base branch exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
yield* git(tmp, ["init", "--initial-branch=trunk"]);
|
||||
yield* git(tmp, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(tmp, ["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(path.join(tmp, "README.md"), "hello\n");
|
||||
yield* git(tmp, ["add", "README.md"]);
|
||||
yield* git(tmp, ["commit", "-m", "initial"]);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["checkout", "-b", "feature/no-base"]);
|
||||
|
||||
const core = yield* GitCore;
|
||||
const pushed = yield* core.pushCurrentBranch(tmp, null);
|
||||
expect(pushed.status).toBe("pushed");
|
||||
expect(pushed.setUpstream).toBe(true);
|
||||
expect(pushed.upstreamBranch).toBe("origin/feature/no-base");
|
||||
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
|
||||
"origin/feature/no-base",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"pushes with upstream setup when comparable base exists but remote branch is missing",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const initialBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
|
||||
|
||||
yield* writeTextFile(path.join(tmp, "default-ahead.txt"), "ahead on default\n");
|
||||
yield* git(tmp, ["add", "default-ahead.txt"]);
|
||||
yield* git(tmp, ["commit", "-m", "default ahead"]);
|
||||
|
||||
const featureBranch = "feature/publish-no-upstream";
|
||||
yield* git(tmp, ["checkout", "-b", featureBranch]);
|
||||
|
||||
const core = yield* GitCore;
|
||||
const pushed = yield* core.pushCurrentBranch(tmp, null);
|
||||
expect(pushed.status).toBe("pushed");
|
||||
expect(pushed.setUpstream).toBe(true);
|
||||
expect(pushed.upstreamBranch).toBe(`origin/${featureBranch}`);
|
||||
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
|
||||
`origin/${featureBranch}`,
|
||||
);
|
||||
expect(yield* git(tmp, ["ls-remote", "--heads", "origin", featureBranch])).toContain(
|
||||
featureBranch,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("includes command context when worktree removal fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -1583,54 +1284,5 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(didFailRecency).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to empty remote branch data when remote lookups fail", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
|
||||
const realGitService = yield* GitService;
|
||||
let didFailRemoteBranches = false;
|
||||
let didFailRemoteNames = false;
|
||||
const core = yield* makeIsolatedGitCore({
|
||||
execute: (input) => {
|
||||
if (input.args.join(" ") === "branch --no-color --remotes") {
|
||||
didFailRemoteBranches = true;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: "git.test.listBranchesRemoteBranches",
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "remote unavailable",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.args.join(" ") === "remote") {
|
||||
didFailRemoteNames = true;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: "git.test.listBranchesRemoteNames",
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "remote unavailable",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return realGitService.execute(input);
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* core.listBranches({ cwd: tmp });
|
||||
|
||||
expect(result.isRepo).toBe(true);
|
||||
expect(result.branches.length).toBeGreaterThan(0);
|
||||
expect(result.branches.every((branch) => !branch.isRemote)).toBe(true);
|
||||
expect(didFailRemoteBranches).toBe(true);
|
||||
expect(didFailRemoteNames).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,6 @@ import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
cwd: string;
|
||||
@@ -77,98 +76,10 @@ function parsePorcelainPath(line: string): string | null {
|
||||
return filePath.length > 0 ? filePath : null;
|
||||
}
|
||||
|
||||
function parseBranchLine(line: string): { name: string; current: boolean } | null {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
const name = trimmed.replace(/^[*+]\s+/, "");
|
||||
// Exclude symbolic refs like: "origin/HEAD -> origin/main".
|
||||
// Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)".
|
||||
if (name.includes(" -> ") || name.startsWith("(")) return null;
|
||||
|
||||
return {
|
||||
name,
|
||||
current: trimmed.startsWith("* "),
|
||||
};
|
||||
}
|
||||
|
||||
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.toSorted((a, b) => b.length - a.length);
|
||||
}
|
||||
|
||||
function parseRemoteRefWithRemoteNames(
|
||||
branchName: string,
|
||||
remoteNames: ReadonlyArray<string>,
|
||||
): { remoteRef: string; remoteName: string; localBranch: string } | null {
|
||||
const trimmedBranchName = branchName.trim();
|
||||
if (trimmedBranchName.length === 0) return null;
|
||||
|
||||
for (const remoteName of remoteNames) {
|
||||
const remotePrefix = `${remoteName}/`;
|
||||
if (!trimmedBranchName.startsWith(remotePrefix)) {
|
||||
continue;
|
||||
}
|
||||
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
|
||||
if (localBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
remoteRef: trimmedBranchName,
|
||||
remoteName,
|
||||
localBranch,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
|
||||
for (const line of stdout.split("\n")) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
|
||||
const branchName = branchNameRaw?.trim() ?? "";
|
||||
const upstreamBranch = upstreamBranchRaw.trim();
|
||||
if (branchName.length === 0 || upstreamBranch.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (upstreamBranch === upstreamRef) {
|
||||
return branchName;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {
|
||||
const separatorIndex = branchName.indexOf("/");
|
||||
if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {
|
||||
return null;
|
||||
}
|
||||
const localBranch = branchName.slice(separatorIndex + 1).trim();
|
||||
return localBranch.length > 0 ? localBranch : null;
|
||||
}
|
||||
|
||||
function commandLabel(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function parseDefaultBranchFromRemoteHeadRef(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
const prefix = "refs/remotes/origin/";
|
||||
if (!trimmed.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
const branch = trimmed.slice(prefix.length).trim();
|
||||
return branch.length > 0 ? branch : null;
|
||||
}
|
||||
|
||||
function createGitCommandError(
|
||||
operation: string,
|
||||
cwd: string,
|
||||
@@ -385,117 +296,12 @@ const makeGitCore = Effect.gen(function* () {
|
||||
yield* fetchUpstreamRef(cwd, upstream);
|
||||
});
|
||||
|
||||
const resolveDefaultBranchName = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||
executeGit(
|
||||
"GitCore.resolveDefaultBranchName",
|
||||
cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{ allowNonZeroExit: true },
|
||||
).pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
return parseDefaultBranchFromRemoteHeadRef(result.stdout);
|
||||
}),
|
||||
);
|
||||
|
||||
const remoteBranchExists = (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit(
|
||||
"GitCore.remoteBranchExists",
|
||||
cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0));
|
||||
|
||||
const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], {
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(Effect.map((result) => result.code === 0));
|
||||
|
||||
const resolveBaseBranchForNoUpstream = (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
): Effect.Effect<string | null, GitCommandError> =>
|
||||
Effect.gen(function* () {
|
||||
const configuredBaseBranch = yield* runGitStdout(
|
||||
"GitCore.resolveBaseBranchForNoUpstream.config",
|
||||
cwd,
|
||||
["config", "--get", `branch.${branch}.gh-merge-base`],
|
||||
true,
|
||||
).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
|
||||
const defaultBranch = yield* resolveDefaultBranchName(cwd);
|
||||
const candidates = [
|
||||
configuredBaseBranch.length > 0 ? configuredBaseBranch : null,
|
||||
defaultBranch,
|
||||
...DEFAULT_BASE_BRANCH_CANDIDATES,
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedCandidate = candidate.startsWith("origin/")
|
||||
? candidate.slice("origin/".length)
|
||||
: candidate;
|
||||
if (normalizedCandidate.length === 0 || normalizedCandidate === branch) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (yield* branchExists(cwd, normalizedCandidate)) {
|
||||
return normalizedCandidate;
|
||||
}
|
||||
|
||||
if (yield* remoteBranchExists(cwd, normalizedCandidate)) {
|
||||
return `origin/${normalizedCandidate}`;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
const computeAheadCountAgainstBase = (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
): Effect.Effect<number, GitCommandError> =>
|
||||
Effect.gen(function* () {
|
||||
const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch);
|
||||
if (!baseBranch) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = yield* executeGit(
|
||||
"GitCore.computeAheadCountAgainstBase",
|
||||
cwd,
|
||||
["rev-list", "--count", `${baseBranch}..HEAD`],
|
||||
{ allowNonZeroExit: true },
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(result.stdout.trim(), 10);
|
||||
return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
|
||||
});
|
||||
|
||||
const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
|
||||
Effect.gen(function* () {
|
||||
const branchRecency = yield* executeGit(
|
||||
"GitCore.readBranchRecency",
|
||||
cwd,
|
||||
[
|
||||
"for-each-ref",
|
||||
"--format=%(refname:short)%09%(committerdate:unix)",
|
||||
"refs/heads",
|
||||
"refs/remotes",
|
||||
],
|
||||
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 15_000,
|
||||
allowNonZeroExit: true,
|
||||
@@ -574,14 +380,6 @@ const makeGitCore = Effect.gen(function* () {
|
||||
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
|
||||
}
|
||||
}
|
||||
|
||||
if (!upstreamRef && branch) {
|
||||
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(0)),
|
||||
);
|
||||
behindCount = 0;
|
||||
}
|
||||
|
||||
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
|
||||
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
|
||||
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
|
||||
@@ -691,40 +489,12 @@ const makeGitCore = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
|
||||
if (hasNoLocalDelta) {
|
||||
if (details.hasUpstream) {
|
||||
return {
|
||||
status: "skipped_up_to_date" as const,
|
||||
branch,
|
||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
if (comparableBaseBranch) {
|
||||
const hasOriginRemote = yield* originRemoteExists(cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
if (!hasOriginRemote) {
|
||||
return {
|
||||
status: "skipped_up_to_date" as const,
|
||||
branch,
|
||||
};
|
||||
}
|
||||
|
||||
const hasRemoteBranch = yield* remoteBranchExists(cwd, branch).pipe(
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
if (hasRemoteBranch) {
|
||||
return {
|
||||
status: "skipped_up_to_date" as const,
|
||||
branch,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
|
||||
return {
|
||||
status: "skipped_up_to_date" as const,
|
||||
branch,
|
||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (!details.hasUpstream) {
|
||||
@@ -831,7 +601,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||
);
|
||||
const localBranchResult = yield* executeGit(
|
||||
const result = yield* executeGit(
|
||||
"GitCore.listBranches.branchNoColor",
|
||||
input.cwd,
|
||||
["branch", "--no-color"],
|
||||
@@ -841,8 +611,8 @@ const makeGitCore = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
if (localBranchResult.code !== 0) {
|
||||
const stderr = localBranchResult.stderr.trim();
|
||||
if (result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return { branches: [], isRepo: false };
|
||||
}
|
||||
@@ -854,79 +624,31 @@ const makeGitCore = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
const remoteBranchResultEffect = executeGit(
|
||||
"GitCore.listBranches.remoteBranches",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--remotes"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
`GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`,
|
||||
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
|
||||
),
|
||||
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.listBranches.defaultRef",
|
||||
input.cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitCore.listBranches.worktreeList",
|
||||
input.cwd,
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const remoteNamesResultEffect = executeGit(
|
||||
"GitCore.listBranches.remoteNames",
|
||||
input.cwd,
|
||||
["remote"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
`GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`,
|
||||
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
|
||||
),
|
||||
);
|
||||
|
||||
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.listBranches.defaultRef",
|
||||
input.cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitCore.listBranches.worktreeList",
|
||||
input.cwd,
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
remoteBranchResultEffect,
|
||||
remoteNamesResultEffect,
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const remoteNames =
|
||||
remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
|
||||
);
|
||||
}
|
||||
if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
|
||||
);
|
||||
}
|
||||
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0
|
||||
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
@@ -951,17 +673,19 @@ const makeGitCore = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
const localBranches = localBranchResult.stdout
|
||||
const branches = result.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => ({
|
||||
name: branch.name,
|
||||
current: branch.current,
|
||||
isRemote: false,
|
||||
isDefault: branch.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(branch.name) ?? null,
|
||||
}))
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const name = line.replace(/^[*+]\s+/, "");
|
||||
return {
|
||||
name,
|
||||
current: line.startsWith("* "),
|
||||
isDefault: name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(name) ?? null,
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
@@ -973,43 +697,6 @@ const makeGitCore = Effect.gen(function* () {
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const remoteBranches =
|
||||
remoteBranchResult.code === 0
|
||||
? remoteBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => {
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames);
|
||||
const remoteBranch: {
|
||||
name: string;
|
||||
current: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
isDefault: boolean;
|
||||
worktreePath: string | null;
|
||||
} = {
|
||||
name: branch.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
remoteBranch.remoteName = parsedRemoteRef.remoteName;
|
||||
}
|
||||
return remoteBranch;
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
: [];
|
||||
|
||||
const branches = [...localBranches, ...remoteBranches];
|
||||
|
||||
return { branches, isRepo: true };
|
||||
});
|
||||
|
||||
@@ -1089,79 +776,13 @@ const makeGitCore = Effect.gen(function* () {
|
||||
|
||||
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const [localInputExists, remoteExists] = yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.checkoutBranch.localInputExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0)),
|
||||
executeGit(
|
||||
"GitCore.checkoutBranch.remoteExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const localTrackingBranch = remoteExists
|
||||
? yield* executeGit(
|
||||
"GitCore.checkoutBranch.localTrackingBranch",
|
||||
input.cwd,
|
||||
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) =>
|
||||
result.code === 0
|
||||
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
|
||||
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
|
||||
const localTrackedBranchTargetExists =
|
||||
remoteExists && localTrackedBranchCandidate
|
||||
? yield* executeGit(
|
||||
"GitCore.checkoutBranch.localTrackedBranchTargetExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0))
|
||||
: false;
|
||||
|
||||
const checkoutArgs = localInputExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch
|
||||
? ["checkout", "--track", input.branch]
|
||||
: remoteExists && localTrackingBranch
|
||||
? ["checkout", localTrackingBranch]
|
||||
: ["checkout", input.branch];
|
||||
|
||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
|
||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
|
||||
// Refresh upstream refs in the background so checkout remains responsive.
|
||||
yield* Effect.forkScoped(
|
||||
yield* Effect.forkDetach(
|
||||
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
|
||||
);
|
||||
});
|
||||
@@ -1172,20 +793,6 @@ const makeGitCore = Effect.gen(function* () {
|
||||
fallbackErrorMessage: "git init failed",
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) =>
|
||||
runGitStdout("GitCore.listLocalBranchNames", cwd, [
|
||||
"branch",
|
||||
"--list",
|
||||
"--format=%(refname:short)",
|
||||
]).pipe(
|
||||
Effect.map((stdout) =>
|
||||
stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
status,
|
||||
statusDetails,
|
||||
@@ -1202,7 +809,6 @@ const makeGitCore = Effect.gen(function* () {
|
||||
createBranch,
|
||||
checkoutBranch,
|
||||
initRepo,
|
||||
listLocalBranchNames,
|
||||
} satisfies GitCoreShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -32,11 +32,7 @@ interface FakeGitTextGeneration {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch?: boolean;
|
||||
}) => Effect.Effect<
|
||||
{ subject: string; body: string; branch?: string | undefined },
|
||||
TextGenerationError
|
||||
>;
|
||||
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
@@ -108,13 +104,10 @@ function createBareRemote(): Effect.Effect<
|
||||
|
||||
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
|
||||
const implementation: FakeGitTextGeneration = {
|
||||
generateCommitMessage: (input) =>
|
||||
generateCommitMessage: () =>
|
||||
Effect.succeed({
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
...(input.includeBranch
|
||||
? { branch: "feature/implement-stacked-git-actions" }
|
||||
: {}),
|
||||
}),
|
||||
generatePrContent: () =>
|
||||
Effect.succeed({
|
||||
@@ -290,7 +283,6 @@ function runStackedAction(
|
||||
cwd: string;
|
||||
action: "commit" | "commit_push" | "commit_push_pr";
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
},
|
||||
) {
|
||||
return manager.runStackedAction(input);
|
||||
@@ -483,7 +475,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
@@ -504,13 +495,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) =>
|
||||
generateCommitMessage: () =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "this should not be used",
|
||||
body: "",
|
||||
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
@@ -521,7 +511,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||
expect(generatedCount).toBe(0);
|
||||
@@ -538,101 +527,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nfeature-branch\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
...(input.includeBranch
|
||||
? { branch: "feature/implement-stacked-git-actions" }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
featureBranch: true,
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("created");
|
||||
expect(result.branch.name).toBe("feature/implement-stacked-git-actions");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(
|
||||
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toBe("feature/implement-stacked-git-actions");
|
||||
|
||||
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", "HEAD"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
expect(mergeBase).toBe(mainSha);
|
||||
expect(generatedCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("featureBranch uses custom commit message and derives branch name", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom-feature\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "unused",
|
||||
body: "",
|
||||
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
featureBranch: true,
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("created");
|
||||
expect(result.branch.name).toBe("feature/feat-custom-summary-line");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||
expect(generatedCount).toBe(0);
|
||||
|
||||
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", result.branch.name!]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
expect(mergeBase).toBe(mainSha);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips commit when there are no uncommitted changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -644,32 +538,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("featureBranch returns error when worktree is clean", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const errorMessage = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
featureBranch: true,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
|
||||
expect(errorMessage).toContain("no changes to commit");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("commits and pushes with upstream auto-setup when needed", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -685,7 +559,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
@@ -697,57 +570,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
"[]",
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 77,
|
||||
title: "Add no-upstream PR flow",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/no-upstream-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(
|
||||
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toBe("origin/feature/no-upstream-pr");
|
||||
expect(
|
||||
ghCalls.some((call) =>
|
||||
call.includes("pr create --base main --head feature/no-upstream-pr"),
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips push when branch is already up to date", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -763,7 +585,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_up_to_date");
|
||||
}),
|
||||
@@ -798,7 +619,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("opened_existing");
|
||||
expect(result.pr.number).toBe(42);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
||||
@@ -839,7 +659,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(88);
|
||||
expect(
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { GitManagerError } from "../Errors.ts";
|
||||
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
|
||||
@@ -86,14 +85,9 @@ function limitContext(value: string, maxChars: number): string {
|
||||
return `${value.slice(0, maxChars)}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
function sanitizeCommitMessage(generated: {
|
||||
function sanitizeCommitMessage(generated: { subject: string; body: string }): {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
}): {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
} {
|
||||
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const subject = rawSubject.replace(/[.]+$/g, "").trim();
|
||||
@@ -101,25 +95,9 @@ function sanitizeCommitMessage(generated: {
|
||||
return {
|
||||
subject: safeSubject,
|
||||
body: generated.body.trim(),
|
||||
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
interface CommitAndBranchSuggestion {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
commitMessage: string;
|
||||
}
|
||||
|
||||
function formatCommitMessage(subject: string, body: string): string {
|
||||
const trimmedBody = body.trim();
|
||||
if (trimmedBody.length === 0) {
|
||||
return subject;
|
||||
}
|
||||
return `${subject}\n\n${trimmedBody}`;
|
||||
}
|
||||
|
||||
function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
|
||||
const normalized = raw.replace(/\r\n/g, "\n").trim();
|
||||
if (normalized.length === 0) {
|
||||
@@ -275,72 +253,30 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
return "main";
|
||||
});
|
||||
|
||||
const resolveCommitAndBranchSuggestion = (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
commitMessage?: string;
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
}) =>
|
||||
const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd);
|
||||
const context = yield* gitCore.prepareCommitContext(cwd);
|
||||
if (!context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
|
||||
if (customCommit) {
|
||||
return {
|
||||
subject: customCommit.subject,
|
||||
body: customCommit.body,
|
||||
...(input.includeBranch
|
||||
? { branch: sanitizeFeatureBranchName(customCommit.subject) }
|
||||
: {}),
|
||||
commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
|
||||
};
|
||||
}
|
||||
|
||||
const generated = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: input.cwd,
|
||||
branch: input.branch,
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
|
||||
return {
|
||||
subject: generated.subject,
|
||||
body: generated.body,
|
||||
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
|
||||
commitMessage: formatCommitMessage(generated.subject, generated.body),
|
||||
};
|
||||
});
|
||||
|
||||
const runCommitStep = (
|
||||
cwd: string,
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
preResolvedSuggestion ??
|
||||
(yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
}));
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
}
|
||||
|
||||
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
|
||||
let generated = parseCustomCommitMessage(commitMessage ?? "");
|
||||
if (!generated) {
|
||||
generated = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd,
|
||||
branch,
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
}
|
||||
|
||||
const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
|
||||
return {
|
||||
status: "created" as const,
|
||||
commitSha,
|
||||
subject: suggestion.subject,
|
||||
subject: generated.subject,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -445,88 +381,34 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
includeBranch: true,
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* gitManagerError(
|
||||
"runFeatureBranchStep",
|
||||
"Cannot create a feature branch because there are no changes to commit.",
|
||||
);
|
||||
}
|
||||
|
||||
const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
|
||||
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
|
||||
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
|
||||
|
||||
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
|
||||
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
|
||||
|
||||
return {
|
||||
branchStep: { status: "created" as const, name: resolvedBranch },
|
||||
resolvedCommitMessage: suggestion.commitMessage,
|
||||
resolvedCommitSuggestion: suggestion,
|
||||
};
|
||||
});
|
||||
|
||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
|
||||
function* (input) {
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
|
||||
const initialStatus = yield* gitCore.statusDetails(input.cwd);
|
||||
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
|
||||
if (wantsPush && !initialStatus.branch) {
|
||||
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
||||
}
|
||||
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
|
||||
if (wantsPr && !initialStatus.branch) {
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Cannot create a pull request from detached HEAD.",
|
||||
);
|
||||
}
|
||||
|
||||
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
|
||||
if (input.featureBranch) {
|
||||
const result = yield* runFeatureBranchStep(
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
|
||||
} else {
|
||||
branchStep = { status: "skipped_not_requested" as const };
|
||||
}
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
|
||||
const commit = yield* runCommitStep(
|
||||
input.cwd,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
);
|
||||
const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
|
||||
|
||||
const push = wantsPush
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, currentBranch)
|
||||
? yield* runPrStep(input.cwd, initialStatus.branch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return {
|
||||
action: input.action,
|
||||
branch: branchStep,
|
||||
commit,
|
||||
push,
|
||||
pr,
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* @module GitCore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCreateBranchInput,
|
||||
@@ -111,7 +111,7 @@ export interface GitCoreShape {
|
||||
) => Effect.Effect<string | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local + remote branches and branch metadata.
|
||||
* List local branches and branch metadata.
|
||||
*/
|
||||
readonly listBranches: (
|
||||
input: GitListBranchesInput,
|
||||
@@ -149,19 +149,12 @@ export interface GitCoreShape {
|
||||
/**
|
||||
* Checkout an existing branch and refresh its upstream metadata in background.
|
||||
*/
|
||||
readonly checkoutBranch: (
|
||||
input: GitCheckoutInput,
|
||||
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
|
||||
readonly checkoutBranch: (input: GitCheckoutInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Initialize a repository in the provided directory.
|
||||
*/
|
||||
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local branch names (short format).
|
||||
*/
|
||||
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,7 +29,6 @@ export interface GitManagerShape {
|
||||
|
||||
/**
|
||||
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
|
||||
* When `featureBranch` is set, creates and checks out a feature branch first.
|
||||
*/
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
|
||||
@@ -17,15 +17,11 @@ export interface CommitMessageGenerationInput {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
subject: string;
|
||||
body: string;
|
||||
/** Only present when `includeBranch` was set on the input. */
|
||||
branch?: string | undefined;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationInput {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { OpenLive } from "./open";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
import { ServerLive } from "./wsServer";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { NetService } from "./config";
|
||||
|
||||
const RuntimeLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(CliConfig.layer),
|
||||
|
||||
@@ -6,10 +6,9 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { beforeEach } from "vitest";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { NetService, ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
|
||||
@@ -34,9 +33,6 @@ const testLayer = Layer.mergeAll(
|
||||
resolveStaticDir: Effect.undefined,
|
||||
} satisfies CliConfigShape),
|
||||
Layer.succeed(NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
reserveLoopbackPort: () => Effect.succeed(0),
|
||||
findAvailablePort,
|
||||
}),
|
||||
Layer.succeed(Server, {
|
||||
|
||||
@@ -8,10 +8,10 @@
|
||||
*/
|
||||
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
NetService,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
type RuntimeMode,
|
||||
@@ -21,7 +21,6 @@ import { fixPath, resolveStateDir } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
|
||||
import { Server } from "./wsServer";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
@@ -198,7 +197,6 @@ const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderHealthLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
@@ -1,51 +1,24 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
import { launchDetached, resolveEditorLaunch } from "./open";
|
||||
import { Effect } from "effect";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
|
||||
describe("resolveEditorLaunch", () => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
it.effect("returns cursor command for cursor editor", () =>
|
||||
Effect.gen(function* () {
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
assert.deepEqual(launch, {
|
||||
command: "cursor",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses --goto when editor supports line/column suffixes", () =>
|
||||
it.effect("uses --goto when cursor target includes line/column suffixes", () =>
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
@@ -64,24 +37,6 @@ describe("resolveEditorLaunch", () => {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -138,85 +93,3 @@ describe("launchDetached", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("isCommandAvailable", () => {
|
||||
function withTempDir(run: (dir: string) => void): void {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-"));
|
||||
try {
|
||||
run(dir);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
it("resolves win32 commands with PATHEXT", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "code.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
|
||||
it("returns false when a command is not on PATH", () => {
|
||||
const env = {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
|
||||
});
|
||||
|
||||
it("does not treat bare files without executable extension as available on win32", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "npm"), "echo nope\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
|
||||
});
|
||||
});
|
||||
|
||||
it("appends PATHEXT for commands with non-executable extensions on win32", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "my.tool.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
|
||||
it("uses platform-specific PATH delimiter for platform overrides", () => {
|
||||
withTempDir((firstDir) => {
|
||||
withTempDir((secondDir) => {
|
||||
fs.writeFileSync(path.join(secondDir, "code.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: `${firstDir};${secondDir}`,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAvailableEditors", () => {
|
||||
it("returns only editors whose launch commands are available", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
|
||||
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
+28
-169
@@ -7,8 +7,6 @@
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
@@ -32,147 +30,10 @@ interface EditorLaunch {
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface CommandAvailabilityOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "open";
|
||||
case "win32":
|
||||
return "explorer";
|
||||
default:
|
||||
return "xdg-open";
|
||||
}
|
||||
}
|
||||
|
||||
function stripWrappingQuotes(value: string): string {
|
||||
return value.replace(/^"+|"+$/g, "");
|
||||
}
|
||||
|
||||
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
|
||||
return env.PATH ?? env.Path ?? env.path ?? "";
|
||||
}
|
||||
|
||||
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
|
||||
const rawValue = env.PATHEXT;
|
||||
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
|
||||
if (!rawValue) return fallback;
|
||||
|
||||
const parsed = rawValue
|
||||
.split(";")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
|
||||
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
|
||||
}
|
||||
|
||||
function resolveCommandCandidates(
|
||||
command: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> {
|
||||
if (platform !== "win32") return [command];
|
||||
const extension = extname(command);
|
||||
const normalizedExtension = extension.toUpperCase();
|
||||
|
||||
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
|
||||
const commandWithoutExtension = command.slice(0, -extension.length);
|
||||
return Array.from(
|
||||
new Set([
|
||||
command,
|
||||
`${commandWithoutExtension}${normalizedExtension}`,
|
||||
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
const candidates: string[] = [];
|
||||
for (const extension of windowsPathExtensions) {
|
||||
candidates.push(`${command}${extension}`);
|
||||
candidates.push(`${command}${extension.toLowerCase()}`);
|
||||
}
|
||||
return Array.from(new Set(candidates));
|
||||
}
|
||||
|
||||
function isExecutableFile(
|
||||
filePath: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): boolean {
|
||||
try {
|
||||
const stat = statSync(filePath);
|
||||
if (!stat.isFile()) return false;
|
||||
if (platform === "win32") {
|
||||
const extension = extname(filePath);
|
||||
if (extension.length === 0) return false;
|
||||
return windowsPathExtensions.includes(extension.toUpperCase());
|
||||
}
|
||||
accessSync(filePath, constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePathDelimiter(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? ";" : ":";
|
||||
}
|
||||
|
||||
export function isCommandAvailable(
|
||||
command: string,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): boolean {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
|
||||
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
|
||||
|
||||
if (command.includes("/") || command.includes("\\")) {
|
||||
return commandCandidates.some((candidate) =>
|
||||
isExecutableFile(candidate, platform, windowsPathExtensions),
|
||||
);
|
||||
}
|
||||
|
||||
const pathValue = resolvePathEnvironmentVariable(env);
|
||||
if (pathValue.length === 0) return false;
|
||||
const pathEntries = pathValue
|
||||
.split(resolvePathDelimiter(platform))
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of commandCandidates) {
|
||||
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
const command = editor.command ?? fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
return editorId === "cursor" && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -220,41 +81,39 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return { command: "open", args: [input.cwd] };
|
||||
case "win32":
|
||||
return { command: "explorer", args: [input.cwd] };
|
||||
default:
|
||||
return { command: "xdg-open", args: [input.cwd] };
|
||||
}
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(
|
||||
new OpenError({ message: "failed to spawn detached process", cause: error }),
|
||||
),
|
||||
);
|
||||
}
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
|
||||
@@ -415,7 +415,8 @@ const make = Effect.gen(function* () {
|
||||
: event.threadId !== undefined
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
: null;
|
||||
const providerThreadId = providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
||||
const providerThreadId =
|
||||
providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
||||
const status =
|
||||
event.type === "turn.started"
|
||||
? "running"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export interface ProcessRunOptions {
|
||||
cwd?: string | undefined;
|
||||
@@ -37,21 +37,11 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
|
||||
function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
if (process.platform !== "win32") return false;
|
||||
if (code === 9009) return true;
|
||||
return /is not recognized as an internal or external command/i.test(stderr);
|
||||
}
|
||||
|
||||
function normalizeExitError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
result: ProcessRunResult,
|
||||
): Error {
|
||||
if (isWindowsCommandNotFound(result.code, result.stderr)) {
|
||||
return new Error(`Command not found: ${command}`);
|
||||
}
|
||||
|
||||
const reason = result.timedOut
|
||||
? "timed out"
|
||||
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
|
||||
@@ -80,23 +70,6 @@ function normalizeBufferError(
|
||||
|
||||
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
}
|
||||
child.kill(signal);
|
||||
}
|
||||
|
||||
function appendChunkWithinLimit(
|
||||
target: string,
|
||||
currentBytes: number,
|
||||
@@ -139,7 +112,6 @@ export async function runProcess(
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: "pipe",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
@@ -154,9 +126,9 @@ export async function runProcess(
|
||||
|
||||
const timeoutTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
killChild(child, "SIGTERM");
|
||||
child.kill("SIGTERM");
|
||||
forceKillTimer = setTimeout(() => {
|
||||
killChild(child, "SIGKILL");
|
||||
child.kill("SIGKILL");
|
||||
}, 1_000);
|
||||
}, timeoutMs);
|
||||
|
||||
@@ -171,7 +143,7 @@ export async function runProcess(
|
||||
};
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
killChild(child, "SIGTERM");
|
||||
child.kill("SIGTERM");
|
||||
finalize(() => {
|
||||
reject(error);
|
||||
});
|
||||
|
||||
@@ -152,16 +152,4 @@ describe("tryHandleProjectFaviconRequest", () => {
|
||||
expect(response.body).toBe("<svg>brand-obj-order</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("serves a fallback favicon when no icon exists", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-fallback-");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toContain('data-fallback="project-favicon"');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -9,8 +9,6 @@ const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||
".ico": "image/x-icon",
|
||||
};
|
||||
|
||||
const FALLBACK_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg",
|
||||
@@ -87,14 +85,6 @@ function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
|
||||
});
|
||||
}
|
||||
|
||||
function serveFallbackFavicon(res: http.ServerResponse): void {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "image/svg+xml",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
});
|
||||
res.end(FALLBACK_FAVICON_SVG);
|
||||
}
|
||||
|
||||
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
|
||||
if (url.pathname !== "/api/project-favicon") {
|
||||
return false;
|
||||
@@ -128,7 +118,8 @@ export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerRespons
|
||||
|
||||
const trySourceFiles = (index: number): void => {
|
||||
if (index >= ICON_SOURCE_FILES.length) {
|
||||
serveFallbackFavicon(res);
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("No favicon found");
|
||||
return;
|
||||
}
|
||||
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
|
||||
|
||||
@@ -15,7 +15,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { afterAll, assert, it, vi } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
|
||||
import { Effect, Fiber, Layer, Option, Stream } from "effect";
|
||||
import { Effect, Fiber, Layer, Stream } from "effect";
|
||||
|
||||
import {
|
||||
CodexAppServerManager,
|
||||
@@ -24,7 +24,6 @@ import {
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
@@ -122,21 +121,10 @@ class FakeCodexManager extends CodexAppServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
getThreadId: () => Effect.succeed(Option.none()),
|
||||
remove: () => Effect.void,
|
||||
listSessionIds: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
const validationManager = new FakeCodexManager();
|
||||
const validationLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: validationManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
@@ -171,7 +159,6 @@ sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
|
||||
const sessionErrorLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
@@ -208,7 +195,6 @@ const lifecycleManager = new FakeCodexManager();
|
||||
const lifecycleLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Option, Queue, Schema, Stream } from "effect";
|
||||
import { Effect, FileSystem, Layer, Queue, Schema, Stream } from "effect";
|
||||
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
@@ -28,11 +28,10 @@ import {
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
|
||||
@@ -40,7 +39,6 @@ export interface CodexAdapterLiveOptions {
|
||||
readonly manager?: CodexAppServerManager;
|
||||
readonly makeManager?: () => CodexAppServerManager;
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||
}
|
||||
|
||||
function toMessage(cause: unknown, fallback: string): string {
|
||||
@@ -432,14 +430,10 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
options?.nativeEventLogPath !== undefined
|
||||
? makeEventNdjsonLogger(options.nativeEventLogPath)
|
||||
: undefined;
|
||||
|
||||
const manager = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
@@ -495,17 +489,17 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* toRequestError(
|
||||
input.sessionId,
|
||||
"turn/start",
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
return yield* Effect.fail(
|
||||
toRequestError(
|
||||
input.sessionId,
|
||||
"turn/start",
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
),
|
||||
);
|
||||
}
|
||||
const bytes = yield* fileSystem
|
||||
.readFile(attachmentPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
|
||||
);
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
|
||||
);
|
||||
return {
|
||||
type: "image" as const,
|
||||
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
|
||||
@@ -587,29 +581,14 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
const writeNativeEvent = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
const orchestrationThreadId = yield* Effect.catch(
|
||||
directory.getThreadId(event.sessionId).pipe(
|
||||
Effect.map((threadIdOption) =>
|
||||
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||
),
|
||||
),
|
||||
() => Effect.succeed(null),
|
||||
);
|
||||
yield* nativeEventLogger.write(event, orchestrationThreadId);
|
||||
Effect.sync(() => {
|
||||
const listener = (event: ProviderEvent) => {
|
||||
nativeEventLogger?.write({
|
||||
observedAt: new Date().toISOString(),
|
||||
event,
|
||||
});
|
||||
|
||||
const services = yield* Effect.services<never>();
|
||||
const listener = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeNativeEvent(event);
|
||||
yield* Queue.offerAll(runtimeEventQueue, mapToRuntimeEvents(event));
|
||||
}).pipe(Effect.runPromiseWith(services));
|
||||
Queue.offerAllUnsafe(runtimeEventQueue, mapToRuntimeEvents(event));
|
||||
};
|
||||
manager.on("event", listener);
|
||||
return listener;
|
||||
}),
|
||||
|
||||
@@ -2,165 +2,36 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
function parseLogLine(line: string) {
|
||||
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
|
||||
assert.notEqual(match, null);
|
||||
if (!match) {
|
||||
throw new Error(`invalid log line: ${line}`);
|
||||
}
|
||||
const observedAt = match[1];
|
||||
const stream = match[2];
|
||||
const payload = match[3];
|
||||
if (!observedAt || !stream || payload === undefined) {
|
||||
throw new Error(`invalid log line: ${line}`);
|
||||
}
|
||||
return {
|
||||
observedAt,
|
||||
stream,
|
||||
payload,
|
||||
};
|
||||
}
|
||||
|
||||
describe("EventNdjsonLogger", () => {
|
||||
it.effect("writes effect-style lines to thread-scoped files", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = path.join(tempDir, "provider-native.ndjson");
|
||||
it("writes NDJSON records to disk", () => {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||
const filePath = path.join(tempDir, "provider-native.ndjson");
|
||||
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* logger.write(
|
||||
{ threadId: "provider-thread-1", id: "evt-1" },
|
||||
ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
yield* logger.write(
|
||||
{ type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" },
|
||||
ThreadId.makeUnsafe("thread-2"),
|
||||
);
|
||||
yield* logger.close();
|
||||
|
||||
const threadOnePath = path.join(tempDir, "thread-1.log");
|
||||
const threadTwoPath = path.join(tempDir, "thread-2.log");
|
||||
assert.equal(fs.existsSync(threadOnePath), true);
|
||||
assert.equal(fs.existsSync(threadTwoPath), true);
|
||||
|
||||
const first = parseLogLine(fs.readFileSync(threadOnePath, "utf8").trim());
|
||||
const second = parseLogLine(fs.readFileSync(threadTwoPath, "utf8").trim());
|
||||
|
||||
assert.equal(Number.isNaN(Date.parse(first.observedAt)), false);
|
||||
assert.equal(first.stream, "NTIVE");
|
||||
assert.equal(first.payload, '{"threadId":"provider-thread-1","id":"evt-1"}');
|
||||
|
||||
assert.equal(Number.isNaN(Date.parse(second.observedAt)), false);
|
||||
assert.equal(second.stream, "NTIVE");
|
||||
assert.equal(
|
||||
second.payload,
|
||||
'{"type":"turn.completed","threadId":"provider-thread-2","id":"evt-2"}',
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
try {
|
||||
const logger = makeEventNdjsonLogger(filePath);
|
||||
expect(logger).toBeDefined();
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"falls back to a global segment when orchestration thread id is missing or invalid",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = path.join(tempDir, "provider-canonical.ndjson");
|
||||
logger.write({ type: "native", payload: { id: "evt-1" } });
|
||||
logger.write({ type: "canonical", payload: { id: "evt-2" } });
|
||||
logger.close();
|
||||
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "orchestration" });
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
const raw = fs.readFileSync(filePath, "utf8").trim();
|
||||
const lines = raw.split("\n");
|
||||
expect(lines.length).toBe(2);
|
||||
|
||||
yield* logger.write({ id: "evt-no-thread" }, null);
|
||||
yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
|
||||
yield* logger.close();
|
||||
|
||||
const globalPath = path.join(tempDir, "_global.log");
|
||||
assert.equal(fs.existsSync(globalPath), true);
|
||||
const lines = fs
|
||||
.readFileSync(globalPath, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => parseLogLine(line));
|
||||
assert.equal(lines.length, 2);
|
||||
assert.equal(Number.isNaN(Date.parse(lines[0]?.observedAt ?? "")), false);
|
||||
assert.equal(Number.isNaN(Date.parse(lines[1]?.observedAt ?? "")), false);
|
||||
assert.equal(lines[0]?.stream, "CANON");
|
||||
assert.equal(lines[0]?.payload, '{"id":"evt-no-thread"}');
|
||||
assert.equal(lines[1]?.stream, "CANON");
|
||||
assert.equal(lines[1]?.payload, '{"id":"evt-invalid-thread"}');
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rotates per-thread files when max size is exceeded", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = path.join(tempDir, "provider-native.ndjson");
|
||||
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, {
|
||||
stream: "native",
|
||||
maxBytes: 120,
|
||||
maxFiles: 2,
|
||||
});
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
yield* logger.write(
|
||||
{
|
||||
threadId: "provider-thread-rotate",
|
||||
id: `evt-${index}`,
|
||||
payload: "x".repeat(40),
|
||||
},
|
||||
ThreadId.makeUnsafe("thread-rotate"),
|
||||
);
|
||||
}
|
||||
yield* logger.close();
|
||||
|
||||
const fileStem = "thread-rotate.log";
|
||||
const matchingFiles = fs
|
||||
.readdirSync(tempDir)
|
||||
.filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
|
||||
.toSorted();
|
||||
|
||||
assert.equal(
|
||||
matchingFiles.some((entry) => entry === `${fileStem}.1`),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
matchingFiles.some((entry) => entry === `${fileStem}.3`),
|
||||
false,
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
const first = JSON.parse(lines[0] ?? "{}");
|
||||
const second = JSON.parse(lines[1] ?? "{}");
|
||||
expect(first).toEqual({ type: "native", payload: { id: "evt-1" } });
|
||||
expect(second).toEqual({ type: "canonical", payload: { id: "evt-2" } });
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,257 +1,66 @@
|
||||
/**
|
||||
* Provider event logger helper.
|
||||
* Provider event NDJSON logger helper.
|
||||
*
|
||||
* Best-effort writer for observability logs. Each record is formatted as a
|
||||
* single effect-style text line in a thread-scoped file. Failures are
|
||||
* downgraded to warnings so provider runtime behavior is unaffected.
|
||||
* Best-effort writer for observability logs. Failures are downgraded to warnings
|
||||
* so provider runtime behavior is unaffected.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { Effect, Exit, Logger, Scope } from "effect";
|
||||
import { createLogger } from "../../logger.ts";
|
||||
|
||||
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
|
||||
|
||||
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DEFAULT_MAX_FILES = 10;
|
||||
const DEFAULT_BATCH_WINDOW_MS = 200;
|
||||
const GLOBAL_THREAD_SEGMENT = "_global";
|
||||
const LOG_SCOPE = "provider-observability";
|
||||
|
||||
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
|
||||
const logger = createLogger("provider-observability");
|
||||
|
||||
export interface EventNdjsonLogger {
|
||||
readonly filePath: string;
|
||||
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
|
||||
close: () => Effect.Effect<void>;
|
||||
write: (record: unknown) => void;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
export interface EventNdjsonLoggerOptions {
|
||||
readonly stream: EventNdjsonStream;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
readonly batchWindowMs?: number;
|
||||
}
|
||||
|
||||
interface ThreadWriter {
|
||||
writeMessage: (message: string) => Effect.Effect<void>;
|
||||
close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
|
||||
return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
|
||||
}
|
||||
|
||||
function resolveThreadSegment(raw: string | null | undefined): string {
|
||||
const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
|
||||
return normalized ?? GLOBAL_THREAD_SEGMENT;
|
||||
}
|
||||
|
||||
function formatLoggerMessage(message: unknown): string {
|
||||
if (Array.isArray(message)) {
|
||||
return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
|
||||
}
|
||||
return typeof message === "string" ? message : String(message);
|
||||
}
|
||||
|
||||
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
|
||||
return Logger.make(
|
||||
({ date, message }) =>
|
||||
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
function resolveStreamLabel(stream: EventNdjsonStream): string {
|
||||
switch (stream) {
|
||||
case "native":
|
||||
return "NTIVE";
|
||||
case "canonical":
|
||||
case "orchestration":
|
||||
default:
|
||||
return "CANON";
|
||||
function stringifyRecord(record: unknown): string | undefined {
|
||||
try {
|
||||
return JSON.stringify(record);
|
||||
} catch (error) {
|
||||
logger.warn("failed to serialize provider event log record", { error });
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function toLogMessage(event: unknown): Effect.Effect<string | undefined> {
|
||||
return Effect.gen(function* () {
|
||||
const serialized = yield* Effect.sync(() => {
|
||||
try {
|
||||
return { ok: true as const, value: JSON.stringify(event) };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
export function makeEventNdjsonLogger(filePath: string): EventNdjsonLogger | undefined {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.appendFileSync(filePath, "", { encoding: "utf8", flag: "a" });
|
||||
} catch (error) {
|
||||
logger.warn("failed to create provider event log directory", { filePath, error });
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!serialized.ok) {
|
||||
yield* logWarning("failed to serialize provider event log record", {
|
||||
error: serialized.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (typeof serialized.value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return serialized.value;
|
||||
});
|
||||
}
|
||||
|
||||
function makeThreadWriter(input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly streamLabel: string;
|
||||
}): Effect.Effect<ThreadWriter | undefined> {
|
||||
return Effect.gen(function* () {
|
||||
const sinkResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
return {
|
||||
ok: true as const,
|
||||
sink: new RotatingFileSink({
|
||||
filePath: input.filePath,
|
||||
maxBytes: input.maxBytes,
|
||||
maxFiles: input.maxFiles,
|
||||
throwOnError: true,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!sinkResult.ok) {
|
||||
yield* logWarning("failed to initialize provider thread log file", {
|
||||
filePath: input.filePath,
|
||||
error: sinkResult.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sink = sinkResult.sink;
|
||||
const scope = yield* Scope.make();
|
||||
const lineLogger = makeLineLogger(input.streamLabel);
|
||||
const batchedLogger = yield* Logger.batched(lineLogger, {
|
||||
window: input.batchWindowMs,
|
||||
flush: (messages) =>
|
||||
Effect.gen(function* () {
|
||||
const flushResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
for (const message of messages) {
|
||||
sink.write(message);
|
||||
}
|
||||
return { ok: true as const };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!flushResult.ok) {
|
||||
yield* logWarning("provider event log batch flush failed", {
|
||||
filePath: input.filePath,
|
||||
error: flushResult.error,
|
||||
});
|
||||
}
|
||||
}),
|
||||
}).pipe(Effect.provideService(Scope.Scope, scope));
|
||||
|
||||
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
|
||||
|
||||
return {
|
||||
writeMessage(message: string) {
|
||||
return Effect.log(message).pipe(Effect.provide(loggerLayer));
|
||||
},
|
||||
close() {
|
||||
return Scope.close(scope, Exit.void);
|
||||
},
|
||||
} satisfies ThreadWriter;
|
||||
});
|
||||
}
|
||||
|
||||
export function makeEventNdjsonLogger(
|
||||
filePath: string,
|
||||
options: EventNdjsonLoggerOptions,
|
||||
): Effect.Effect<EventNdjsonLogger | undefined> {
|
||||
return Effect.gen(function* () {
|
||||
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
|
||||
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
|
||||
const streamLabel = resolveStreamLabel(options.stream);
|
||||
|
||||
const directoryReady = yield* Effect.sync(() => {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
return true;
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
if (directoryReady !== true) {
|
||||
yield* logWarning("failed to create provider event log directory", {
|
||||
filePath,
|
||||
error: directoryReady.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const threadWriters = new Map<string, ThreadWriter>();
|
||||
const failedSegments = new Set<string>();
|
||||
|
||||
const resolveThreadWriter = (threadSegment: string): Effect.Effect<ThreadWriter | undefined> =>
|
||||
Effect.gen(function* () {
|
||||
if (failedSegments.has(threadSegment)) {
|
||||
return undefined;
|
||||
}
|
||||
const existing = threadWriters.get(threadSegment);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const writer = yield* makeThreadWriter({
|
||||
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
|
||||
maxBytes,
|
||||
maxFiles,
|
||||
batchWindowMs,
|
||||
streamLabel,
|
||||
});
|
||||
if (!writer) {
|
||||
failedSegments.add(threadSegment);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
threadWriters.set(threadSegment, writer);
|
||||
return writer;
|
||||
});
|
||||
try {
|
||||
let broken = false;
|
||||
|
||||
return {
|
||||
filePath,
|
||||
write(event: unknown, threadId: ThreadId | null) {
|
||||
return Effect.gen(function* () {
|
||||
const threadSegment = resolveThreadSegment(threadId);
|
||||
const message = yield* toLogMessage(event);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const writer = yield* resolveThreadWriter(threadSegment);
|
||||
if (!writer) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writer.writeMessage(message);
|
||||
});
|
||||
write(record: unknown) {
|
||||
if (broken) {
|
||||
return;
|
||||
}
|
||||
const serialized = stringifyRecord(record);
|
||||
if (!serialized) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
fs.appendFileSync(filePath, `${serialized}\n`, { encoding: "utf8", flag: "a" });
|
||||
} catch (error) {
|
||||
broken = true;
|
||||
logger.warn("provider event log write failed", { filePath, error });
|
||||
}
|
||||
},
|
||||
close() {
|
||||
return Effect.gen(function* () {
|
||||
for (const writer of threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
threadWriters.clear();
|
||||
});
|
||||
// no-op for sync append logger
|
||||
},
|
||||
} satisfies EventNdjsonLogger;
|
||||
});
|
||||
};
|
||||
} catch (error) {
|
||||
logger.warn("failed to create provider event log file", { filePath, error });
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer, Sink, Stream } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderHealth";
|
||||
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout)),
|
||||
stderr: Stream.make(encoder.encode(result.stderr)),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function mockSpawnerLayer(
|
||||
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const cmd = command as unknown as { args: ReadonlyArray<string> };
|
||||
return Effect.succeed(mockHandle(handler(cmd.args)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function failingSpawnerLayer(description: string) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tests ───────────────────────────────────────────────────────────
|
||||
|
||||
it.effect("returns ready when codex is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"returns unauthenticated when login status output includes 'not logged in'",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns warning when login status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// ── Pure function tests ─────────────────────────────────────────────
|
||||
|
||||
it("parseAuthStatusFromOutput: exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("parseAuthStatusFromOutput: JSON with authenticated=false is unauthenticated", () => {
|
||||
const parsed = parseAuthStatusFromOutput({
|
||||
stdout: '[{"authenticated":false}]\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
});
|
||||
|
||||
it("parseAuthStatusFromOutput: JSON without auth marker is warning", () => {
|
||||
const parsed = parseAuthStatusFromOutput({
|
||||
stdout: '[{"ok":true}]\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
});
|
||||
@@ -1,303 +0,0 @@
|
||||
/**
|
||||
* ProviderHealthLive - Startup-time provider health checks.
|
||||
*
|
||||
* Performs one-time provider readiness probes when the server starts and
|
||||
* keeps the resulting snapshot in memory for `server.getConfig`.
|
||||
*
|
||||
* Uses effect's ChildProcessSpawner to run CLI probes natively.
|
||||
*
|
||||
* @module ProviderHealthLive
|
||||
*/
|
||||
import type {
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderStatus,
|
||||
ServerProviderStatusState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
const CODEX_PROVIDER = "codex" as const;
|
||||
|
||||
// ── Pure helpers ────────────────────────────────────────────────────
|
||||
|
||||
export interface CommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number;
|
||||
}
|
||||
|
||||
function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function isCommandMissingCause(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const lower = error.message.toLowerCase();
|
||||
return (
|
||||
lower.includes("command not found: codex") ||
|
||||
lower.includes("spawn codex enoent") ||
|
||||
lower.includes("enoent") ||
|
||||
lower.includes("notfound")
|
||||
);
|
||||
}
|
||||
|
||||
function detailFromResult(
|
||||
result: CommandResult & { readonly timedOut?: boolean },
|
||||
): string | undefined {
|
||||
if (result.timedOut) return "Timed out while running command.";
|
||||
const stderr = nonEmptyTrimmed(result.stderr);
|
||||
if (stderr) return stderr;
|
||||
const stdout = nonEmptyTrimmed(result.stdout);
|
||||
if (stdout) return stdout;
|
||||
if (result.code !== 0) {
|
||||
return `Command exited with code ${result.code}.`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function extractAuthBoolean(value: unknown): boolean | undefined {
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
const nested = extractAuthBoolean(entry);
|
||||
if (nested !== undefined) return nested;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
|
||||
const record = value as Record<string, unknown>;
|
||||
for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
|
||||
if (typeof record[key] === "boolean") return record[key];
|
||||
}
|
||||
for (const key of ["auth", "status", "session", "account"] as const) {
|
||||
const nested = extractAuthBoolean(record[key]);
|
||||
if (nested !== undefined) return nested;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: ServerProviderStatusState;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
|
||||
if (
|
||||
lowerOutput.includes("unknown command") ||
|
||||
lowerOutput.includes("unrecognized command") ||
|
||||
lowerOutput.includes("unexpected argument")
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
lowerOutput.includes("not logged in") ||
|
||||
lowerOutput.includes("login required") ||
|
||||
lowerOutput.includes("authentication required") ||
|
||||
lowerOutput.includes("run `codex login`") ||
|
||||
lowerOutput.includes("run codex login")
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsedAuth = (() => {
|
||||
const trimmed = result.stdout.trim();
|
||||
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
try {
|
||||
return {
|
||||
attemptedJsonParse: true as const,
|
||||
auth: extractAuthBoolean(JSON.parse(trimmed)),
|
||||
};
|
||||
} catch {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Codex authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Could not verify Codex authentication status. ${detail}`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
// ── Effect-native command execution ─────────────────────────────────
|
||||
|
||||
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
|
||||
Stream.runFold(
|
||||
stream,
|
||||
() => "",
|
||||
(acc, chunk) => acc + new TextDecoder().decode(chunk),
|
||||
);
|
||||
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("codex", [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
const child = yield* spawner.spawn(command);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
// ── Health check ────────────────────────────────────────────────────
|
||||
|
||||
export const checkCodexProviderStatus: Effect.Effect<
|
||||
ServerProviderStatus,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
// Probe 1: `codex --version` — is the CLI reachable?
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Codex CLI is installed but failed to run. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Codex authentication status: ${error.message}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: parsed.authStatus,
|
||||
checkedAt,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
|
||||
// ── Layer ───────────────────────────────────────────────────────────
|
||||
|
||||
export const ProviderHealthLive = Layer.effect(
|
||||
ProviderHealth,
|
||||
Effect.gen(function* () {
|
||||
const codexStatus = yield* checkCodexProviderStatus;
|
||||
return {
|
||||
getStatuses: Effect.succeed([codexStatus]),
|
||||
} satisfies ProviderHealthShape;
|
||||
}),
|
||||
);
|
||||
@@ -30,11 +30,10 @@ import {
|
||||
ProviderSessionDirectory,
|
||||
type ProviderSessionBinding,
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
export interface ProviderServiceLiveOptions {
|
||||
readonly canonicalEventLogPath?: string;
|
||||
readonly canonicalEventLogger?: EventNdjsonLogger;
|
||||
}
|
||||
|
||||
const ProviderRollbackConversationInput = Schema.Struct({
|
||||
@@ -109,12 +108,9 @@ function readPersistedCwd(
|
||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const canonicalEventLogger =
|
||||
options?.canonicalEventLogger ??
|
||||
(options?.canonicalEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
|
||||
stream: "canonical",
|
||||
})
|
||||
: undefined);
|
||||
options?.canonicalEventLogPath !== undefined
|
||||
? makeEventNdjsonLogger(options.canonicalEventLogPath)
|
||||
: undefined;
|
||||
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
@@ -144,20 +140,12 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
canonicalizeRuntimeEventSession(event).pipe(
|
||||
Effect.tap((canonicalEvent) =>
|
||||
canonicalEventLogger
|
||||
? Effect.flatMap(
|
||||
Effect.catch(
|
||||
directory.getThreadId(canonicalEvent.sessionId).pipe(
|
||||
Effect.map((threadIdOption) =>
|
||||
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||
),
|
||||
),
|
||||
() => Effect.succeed<ThreadId | null>(null),
|
||||
),
|
||||
(orchestrationThreadId) =>
|
||||
canonicalEventLogger.write(canonicalEvent, orchestrationThreadId),
|
||||
)
|
||||
: Effect.void,
|
||||
Effect.sync(() => {
|
||||
canonicalEventLogger?.write({
|
||||
observedAt: new Date().toISOString(),
|
||||
event: canonicalEvent,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
|
||||
Effect.asVoid,
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* ProviderHealth - Provider readiness snapshot service.
|
||||
*
|
||||
* Owns startup-time provider health checks (install/auth reachability) and
|
||||
* exposes the cached results to transport layers.
|
||||
*
|
||||
* @module ProviderHealth
|
||||
*/
|
||||
import type { ServerProviderStatus } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ProviderHealthShape {
|
||||
/**
|
||||
* Read provider health statuses computed at server startup.
|
||||
*/
|
||||
readonly getStatuses: Effect.Effect<ReadonlyArray<ServerProviderStatus>>;
|
||||
}
|
||||
|
||||
export class ProviderHealth extends ServiceMap.Service<ProviderHealth, ProviderHealthShape>()(
|
||||
"t3/provider/Services/ProviderHealth",
|
||||
) {}
|
||||
@@ -23,7 +23,6 @@ import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRe
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
|
||||
import { ProviderService } from "./provider/Services/ProviderService";
|
||||
import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";
|
||||
|
||||
import { TerminalManagerLive } from "./terminal/Layers/Manager";
|
||||
import { KeybindingsLive } from "./keybindings";
|
||||
@@ -42,27 +41,17 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
const providerLogsDir = path.join(stateDir, "logs", "provider");
|
||||
const providerEventLogPath = path.join(providerLogsDir, "events.log");
|
||||
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "native",
|
||||
});
|
||||
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "canonical",
|
||||
const providerLogsDir = path.join(stateDir, "logs", "providers");
|
||||
const codexAdapterLayer = makeCodexAdapterLive({
|
||||
nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"),
|
||||
});
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(Layer.provide(codexAdapterLayer));
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const codexAdapterLayer = makeCodexAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
canonicalEventLogger ? { canonicalEventLogger } : undefined,
|
||||
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
||||
return makeProviderServiceLive({
|
||||
canonicalEventLogPath: path.join(providerLogsDir, "provider-canonical.ndjson"),
|
||||
}).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
||||
}).pipe(Layer.unwrap);
|
||||
}
|
||||
|
||||
@@ -105,11 +94,7 @@ export function makeServerRuntimeServicesLayer() {
|
||||
);
|
||||
|
||||
const terminalLayer = TerminalManagerLive.pipe(
|
||||
Layer.provide(
|
||||
typeof Bun !== "undefined" && process.platform !== "win32"
|
||||
? BunPtyAdapterLive
|
||||
: NodePtyAdapterLive,
|
||||
),
|
||||
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
|
||||
);
|
||||
|
||||
const gitManagerLayer = GitManagerLive.pipe(
|
||||
|
||||
@@ -13,7 +13,6 @@ import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serve
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
EDITORS,
|
||||
EventId,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
@@ -25,7 +24,6 @@ import {
|
||||
WS_METHODS,
|
||||
type WebSocketResponse,
|
||||
type ProviderRuntimeEvent,
|
||||
type ServerProviderStatus,
|
||||
type KeybindingsConfig,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type WsPush,
|
||||
@@ -44,7 +42,6 @@ import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/
|
||||
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
||||
import { SqlClient, SqlError } from "effect/unstable/sql";
|
||||
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
||||
import { ProviderHealth, type ProviderHealthShape } from "./provider/Services/ProviderHealth";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||
import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
@@ -71,20 +68,6 @@ const defaultOpenService: OpenShape = {
|
||||
openInEditor: () => Effect.void,
|
||||
};
|
||||
|
||||
const defaultProviderStatuses: ReadonlyArray<ServerProviderStatus> = [
|
||||
{
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
available: true,
|
||||
authStatus: "authenticated",
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
|
||||
const defaultProviderHealthService: ProviderHealthShape = {
|
||||
getStatuses: Effect.succeed(defaultProviderStatuses),
|
||||
};
|
||||
|
||||
class MockTerminalManager implements TerminalManagerShape {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||
@@ -357,15 +340,6 @@ function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsCon
|
||||
}
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
|
||||
const VALID_EDITOR_IDS = new Set(EDITORS.map((editor) => editor.id));
|
||||
|
||||
function expectAvailableEditors(value: unknown): void {
|
||||
expect(Array.isArray(value)).toBe(true);
|
||||
for (const editorId of value as unknown[]) {
|
||||
expect(typeof editorId).toBe("string");
|
||||
expect(VALID_EDITOR_IDS.has(editorId as (typeof EDITORS)[number]["id"])).toBe(true);
|
||||
}
|
||||
}
|
||||
|
||||
describe("WebSocket Server", () => {
|
||||
let server: Http.Server | null = null;
|
||||
@@ -393,7 +367,6 @@ describe("WebSocket Server", () => {
|
||||
stateDir?: string;
|
||||
staticDir?: string;
|
||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||
providerHealth?: ProviderHealthShape;
|
||||
open?: OpenShape;
|
||||
gitManager?: GitManagerShape;
|
||||
gitCore?: Pick<
|
||||
@@ -411,10 +384,6 @@ describe("WebSocket Server", () => {
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
|
||||
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
|
||||
const providerHealthLayer = Layer.succeed(
|
||||
ProviderHealth,
|
||||
options.providerHealth ?? defaultProviderHealthService,
|
||||
);
|
||||
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
|
||||
const serverConfigLayer = Layer.succeed(ServerConfig, {
|
||||
mode: "web",
|
||||
@@ -449,7 +418,6 @@ describe("WebSocket Server", () => {
|
||||
);
|
||||
const dependenciesLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeLayer),
|
||||
Layer.provideMerge(providerHealthLayer),
|
||||
Layer.provideMerge(openLayer),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -758,10 +726,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
|
||||
it("bootstraps default keybindings file when missing", async () => {
|
||||
@@ -784,10 +749,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
|
||||
const persistedConfig = JSON.parse(
|
||||
fs.readFileSync(keybindingsPath, "utf8"),
|
||||
@@ -820,10 +782,7 @@ describe("WebSocket Server", () => {
|
||||
message: expect.stringContaining("expected JSON array"),
|
||||
},
|
||||
],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
|
||||
});
|
||||
|
||||
@@ -855,8 +814,6 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: string;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
issues: Array<{ kind: string; index?: number; message: string }>;
|
||||
providers: ReadonlyArray<ServerProviderStatus>;
|
||||
availableEditors: unknown;
|
||||
};
|
||||
expect(result.cwd).toBe("/my/workspace");
|
||||
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
|
||||
@@ -875,8 +832,6 @@ describe("WebSocket Server", () => {
|
||||
expect(result.keybindings).toHaveLength(DEFAULT_RESOLVED_KEYBINDINGS.length);
|
||||
expect(result.keybindings.some((entry) => entry.command === "terminal.toggle")).toBe(true);
|
||||
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
|
||||
expect(result.providers).toEqual(defaultProviderStatuses);
|
||||
expectAvailableEditors(result.availableEditors);
|
||||
});
|
||||
|
||||
it("pushes server.configUpdated issues when keybindings file changes", async () => {
|
||||
@@ -904,7 +859,6 @@ describe("WebSocket Server", () => {
|
||||
);
|
||||
expect(malformedPush.data).toEqual({
|
||||
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
|
||||
providers: defaultProviderStatuses,
|
||||
});
|
||||
|
||||
fs.writeFileSync(keybindingsPath, "[]", "utf8");
|
||||
@@ -915,7 +869,7 @@ describe("WebSocket Server", () => {
|
||||
Array.isArray((push.data as { issues?: unknown[] }).issues) &&
|
||||
(push.data as { issues: unknown[] }).issues.length === 0,
|
||||
);
|
||||
expect(successPush.data).toEqual({ issues: [], providers: defaultProviderStatuses });
|
||||
expect(successPush.data).toEqual({ issues: [] });
|
||||
});
|
||||
|
||||
it("routes shell.openInEditor through the injected open service", async () => {
|
||||
@@ -975,10 +929,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: compileKeybindings(persistedConfig),
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
|
||||
it("upserts keybinding rules and updates cached server config", async () => {
|
||||
@@ -1023,12 +974,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: compileKeybindings(persistedConfig),
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
});
|
||||
expectAvailableEditors(
|
||||
(configResponse.result as { availableEditors: unknown }).availableEditors,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns error for unknown methods", async () => {
|
||||
|
||||
@@ -52,10 +52,9 @@ import { OrchestrationEngineService } from "./orchestration/Services/Orchestrati
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
|
||||
import { ProviderService } from "./provider/Services/ProviderService";
|
||||
import { ProviderHealth } from "./provider/Services/ProviderHealth";
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
|
||||
import { clamp } from "effect/Number";
|
||||
import { Open, resolveAvailableEditors } from "./open";
|
||||
import { Open } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
@@ -64,11 +63,7 @@ import {
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths";
|
||||
import {
|
||||
createAttachmentId,
|
||||
resolveAttachmentPath,
|
||||
resolveAttachmentPathById,
|
||||
} from "./attachmentStore.ts";
|
||||
import { createAttachmentId, resolveAttachmentPath, resolveAttachmentPathById } from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
|
||||
/**
|
||||
@@ -155,8 +150,7 @@ export type ServerCoreRuntimeServices =
|
||||
| ProjectionSnapshotQuery
|
||||
| CheckpointDiffQuery
|
||||
| OrchestrationReactor
|
||||
| ProviderService
|
||||
| ProviderHealth;
|
||||
| ProviderService;
|
||||
|
||||
export type ServerRuntimeServices =
|
||||
| ServerCoreRuntimeServices
|
||||
@@ -195,12 +189,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
logWebSocketEvents,
|
||||
autoBootstrapProjectFromCwd,
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
|
||||
const gitManager = yield* GitManager;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
const providerHealth = yield* ProviderHealth;
|
||||
const git = yield* GitCore;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -215,8 +207,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
),
|
||||
);
|
||||
|
||||
const providerStatuses = yield* providerHealth.getStatuses;
|
||||
|
||||
const clients = yield* Ref.make(new Set<WebSocket>());
|
||||
const logger = createLogger("ws");
|
||||
|
||||
@@ -542,10 +532,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
broadcastPush({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: {
|
||||
issues: event.issues,
|
||||
providers: providerStatuses,
|
||||
},
|
||||
data: event,
|
||||
}),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
|
||||
@@ -698,7 +685,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
case WS_METHODS.gitCheckout: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* Effect.scoped(git.checkoutBranch(body));
|
||||
return yield* git.checkoutBranch(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitInit: {
|
||||
@@ -743,8 +730,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
keybindingsConfigPath,
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
providers: providerStatuses,
|
||||
availableEditors,
|
||||
};
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding: {
|
||||
|
||||
@@ -21,5 +21,5 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
|
||||
"include": ["src", "tsdown.config.ts", "scripts", "integration"]
|
||||
}
|
||||
@@ -3,13 +3,10 @@ import { defineConfig } from "tsdown";
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm", "cjs"],
|
||||
checks: {
|
||||
legacyCjs: false,
|
||||
},
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
inlineOnly: false,
|
||||
banner: {
|
||||
js: "#!/usr/bin/env node\n",
|
||||
|
||||
+5
-17
@@ -1,24 +1,19 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"prepare": "effect-language-service patch",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:browser": "vitest run --config vitest.browser.config.ts",
|
||||
"test:browser:install": "playwright install --with-deps chromium"
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
@@ -27,14 +22,12 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"lexical": "^0.41.0",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"zustand": "^5.0.11"
|
||||
"tailwind-merge": "^3.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
@@ -43,14 +36,9 @@
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"msw": "^2.12.10",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "^8.0.0-beta.12",
|
||||
"vitest": "catalog:",
|
||||
"vitest-browser-react": "^2.0.5"
|
||||
"typescript": "^5.7.3",
|
||||
"vite": "^8.0.0-beta.12"
|
||||
}
|
||||
}
|
||||
@@ -1,349 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* tslint:disable */
|
||||
|
||||
/**
|
||||
* Mock Service Worker.
|
||||
* @see https://github.com/mswjs/msw
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.12.10'
|
||||
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
addEventListener('install', function () {
|
||||
self.skipWaiting()
|
||||
})
|
||||
|
||||
addEventListener('activate', function (event) {
|
||||
event.waitUntil(self.clients.claim())
|
||||
})
|
||||
|
||||
addEventListener('message', async function (event) {
|
||||
const clientId = Reflect.get(event.source || {}, 'id')
|
||||
|
||||
if (!clientId || !self.clients) {
|
||||
return
|
||||
}
|
||||
|
||||
const client = await self.clients.get(clientId)
|
||||
|
||||
if (!client) {
|
||||
return
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
switch (event.data) {
|
||||
case 'KEEPALIVE_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'KEEPALIVE_RESPONSE',
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'INTEGRITY_CHECK_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'INTEGRITY_CHECK_RESPONSE',
|
||||
payload: {
|
||||
packageVersion: PACKAGE_VERSION,
|
||||
checksum: INTEGRITY_CHECKSUM,
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'MOCK_ACTIVATE': {
|
||||
activeClientIds.add(clientId)
|
||||
|
||||
sendToClient(client, {
|
||||
type: 'MOCKING_ENABLED',
|
||||
payload: {
|
||||
client: {
|
||||
id: client.id,
|
||||
frameType: client.frameType,
|
||||
},
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'CLIENT_CLOSED': {
|
||||
activeClientIds.delete(clientId)
|
||||
|
||||
const remainingClients = allClients.filter((client) => {
|
||||
return client.id !== clientId
|
||||
})
|
||||
|
||||
// Unregister itself when there are no more clients
|
||||
if (remainingClients.length === 0) {
|
||||
self.registration.unregister()
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
addEventListener('fetch', function (event) {
|
||||
const requestInterceptedAt = Date.now()
|
||||
|
||||
// Bypass navigation requests.
|
||||
if (event.request.mode === 'navigate') {
|
||||
return
|
||||
}
|
||||
|
||||
// Opening the DevTools triggers the "only-if-cached" request
|
||||
// that cannot be handled by the worker. Bypass such requests.
|
||||
if (
|
||||
event.request.cache === 'only-if-cached' &&
|
||||
event.request.mode !== 'same-origin'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Bypass all requests when there are no active clients.
|
||||
// Prevents the self-unregistered worked from handling requests
|
||||
// after it's been terminated (still remains active until the next reload).
|
||||
if (activeClientIds.size === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const requestId = crypto.randomUUID()
|
||||
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
|
||||
})
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
*/
|
||||
async function handleRequest(event, requestId, requestInterceptedAt) {
|
||||
const client = await resolveMainClient(event)
|
||||
const requestCloneForEvents = event.request.clone()
|
||||
const response = await getResponse(
|
||||
event,
|
||||
client,
|
||||
requestId,
|
||||
requestInterceptedAt,
|
||||
)
|
||||
|
||||
// Send back the response clone for the "response:*" life-cycle events.
|
||||
// Ensure MSW is active and ready to handle the message, otherwise
|
||||
// this message will pend indefinitely.
|
||||
if (client && activeClientIds.has(client.id)) {
|
||||
const serializedRequest = await serializeRequest(requestCloneForEvents)
|
||||
|
||||
// Clone the response so both the client and the library could consume it.
|
||||
const responseClone = response.clone()
|
||||
|
||||
sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'RESPONSE',
|
||||
payload: {
|
||||
isMockedResponse: IS_MOCKED_RESPONSE in response,
|
||||
request: {
|
||||
id: requestId,
|
||||
...serializedRequest,
|
||||
},
|
||||
response: {
|
||||
type: responseClone.type,
|
||||
status: responseClone.status,
|
||||
statusText: responseClone.statusText,
|
||||
headers: Object.fromEntries(responseClone.headers.entries()),
|
||||
body: responseClone.body,
|
||||
},
|
||||
},
|
||||
},
|
||||
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
|
||||
)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the main client for the given event.
|
||||
* Client that issues a request doesn't necessarily equal the client
|
||||
* that registered the worker. It's with the latter the worker should
|
||||
* communicate with during the response resolving phase.
|
||||
* @param {FetchEvent} event
|
||||
* @returns {Promise<Client | undefined>}
|
||||
*/
|
||||
async function resolveMainClient(event) {
|
||||
const client = await self.clients.get(event.clientId)
|
||||
|
||||
if (activeClientIds.has(event.clientId)) {
|
||||
return client
|
||||
}
|
||||
|
||||
if (client?.frameType === 'top-level') {
|
||||
return client
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
return allClients
|
||||
.filter((client) => {
|
||||
// Get only those clients that are currently visible.
|
||||
return client.visibilityState === 'visible'
|
||||
})
|
||||
.find((client) => {
|
||||
// Find the client ID that's recorded in the
|
||||
// set of clients that have registered the worker.
|
||||
return activeClientIds.has(client.id)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {Client | undefined} client
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
async function getResponse(event, client, requestId, requestInterceptedAt) {
|
||||
// Clone the request because it might've been already used
|
||||
// (i.e. its body has been read and sent to the client).
|
||||
const requestClone = event.request.clone()
|
||||
|
||||
function passthrough() {
|
||||
// Cast the request headers to a new Headers instance
|
||||
// so the headers can be manipulated with.
|
||||
const headers = new Headers(requestClone.headers)
|
||||
|
||||
// Remove the "accept" header value that marked this request as passthrough.
|
||||
// This prevents request alteration and also keeps it compliant with the
|
||||
// user-defined CORS policies.
|
||||
const acceptHeader = headers.get('accept')
|
||||
if (acceptHeader) {
|
||||
const values = acceptHeader.split(',').map((value) => value.trim())
|
||||
const filteredValues = values.filter(
|
||||
(value) => value !== 'msw/passthrough',
|
||||
)
|
||||
|
||||
if (filteredValues.length > 0) {
|
||||
headers.set('accept', filteredValues.join(', '))
|
||||
} else {
|
||||
headers.delete('accept')
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(requestClone, { headers })
|
||||
}
|
||||
|
||||
// Bypass mocking when the client is not active.
|
||||
if (!client) {
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Bypass initial page load requests (i.e. static assets).
|
||||
// The absence of the immediate/parent client in the map of the active clients
|
||||
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
||||
// and is not ready to handle requests.
|
||||
if (!activeClientIds.has(client.id)) {
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Notify the client that a request has been intercepted.
|
||||
const serializedRequest = await serializeRequest(event.request)
|
||||
const clientMessage = await sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'REQUEST',
|
||||
payload: {
|
||||
id: requestId,
|
||||
interceptedAt: requestInterceptedAt,
|
||||
...serializedRequest,
|
||||
},
|
||||
},
|
||||
[serializedRequest.body],
|
||||
)
|
||||
|
||||
switch (clientMessage.type) {
|
||||
case 'MOCK_RESPONSE': {
|
||||
return respondWithMock(clientMessage.data)
|
||||
}
|
||||
|
||||
case 'PASSTHROUGH': {
|
||||
return passthrough()
|
||||
}
|
||||
}
|
||||
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Client} client
|
||||
* @param {any} message
|
||||
* @param {Array<Transferable>} transferrables
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
function sendToClient(client, message, transferrables = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const channel = new MessageChannel()
|
||||
|
||||
channel.port1.onmessage = (event) => {
|
||||
if (event.data && event.data.error) {
|
||||
return reject(event.data.error)
|
||||
}
|
||||
|
||||
resolve(event.data)
|
||||
}
|
||||
|
||||
client.postMessage(message, [
|
||||
channel.port2,
|
||||
...transferrables.filter(Boolean),
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Response} response
|
||||
* @returns {Response}
|
||||
*/
|
||||
function respondWithMock(response) {
|
||||
// Setting response status code to 0 is a no-op.
|
||||
// However, when responding with a "Response.error()", the produced Response
|
||||
// instance will have status code set to 0. Since it's not possible to create
|
||||
// a Response instance with status code 0, handle that use-case separately.
|
||||
if (response.status === 0) {
|
||||
return Response.error()
|
||||
}
|
||||
|
||||
const mockedResponse = new Response(response.body, response)
|
||||
|
||||
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
|
||||
value: true,
|
||||
enumerable: true,
|
||||
})
|
||||
|
||||
return mockedResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Request} request
|
||||
*/
|
||||
async function serializeRequest(request) {
|
||||
return {
|
||||
url: request.url,
|
||||
mode: request.mode,
|
||||
method: request.method,
|
||||
headers: Object.fromEntries(request.headers.entries()),
|
||||
cache: request.cache,
|
||||
credentials: request.credentials,
|
||||
destination: request.destination,
|
||||
integrity: request.integrity,
|
||||
redirect: request.redirect,
|
||||
referrer: request.referrer,
|
||||
referrerPolicy: request.referrerPolicy,
|
||||
body: await request.arrayBuffer(),
|
||||
keepalive: request.keepalive,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAppModelOptions, getSlashModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
@@ -40,17 +40,3 @@ describe("getAppModelOptions", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSlashModelOptions", () => {
|
||||
it("includes saved custom model slugs for /model command suggestions", () => {
|
||||
const options = getSlashModelOptions(["custom/internal-model"], "", "gpt-5.3-codex");
|
||||
|
||||
expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);
|
||||
});
|
||||
|
||||
it("filters slash-model suggestions across built-in and custom model names", () => {
|
||||
const options = getSlashModelOptions(["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
|
||||
});
|
||||
});
|
||||
@@ -105,24 +105,6 @@ export function getAppModelOptions(
|
||||
return options;
|
||||
}
|
||||
|
||||
export function getSlashModelOptions(
|
||||
customModels: readonly string[],
|
||||
query: string,
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const options = getAppModelOptions(customModels, selectedModel);
|
||||
if (!normalizedQuery) {
|
||||
return options;
|
||||
}
|
||||
|
||||
return options.filter((option) => {
|
||||
const searchSlug = option.slug.toLowerCase();
|
||||
const searchName = option.name.toLowerCase();
|
||||
return searchSlug.includes(normalizedQuery) || searchName.includes(normalizedQuery);
|
||||
});
|
||||
}
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
|
||||
@@ -1,196 +1,59 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { ThreadId, type GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveBranchToolbarValue,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
|
||||
describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: null,
|
||||
currentWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
effectiveEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("local");
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("deriveSyncedLocalBranch", () => {
|
||||
it("syncs to git current branch in local mode", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: threadId,
|
||||
activeWorktreePath: null,
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBe("main");
|
||||
});
|
||||
|
||||
it("keeps new-worktree mode when selecting a base branch before worktree creation", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: null,
|
||||
currentWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
it("does not sync when creating a new worktree", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: threadId,
|
||||
activeWorktreePath: null,
|
||||
envMode: "worktree",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("uses worktree mode when selecting a branch already attached to a worktree", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
currentWorktreePath: null,
|
||||
effectiveEnvMode: "local",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBranchToolbarValue", () => {
|
||||
it("defaults new-worktree mode to current git branch when no explicit base branch is set", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "worktree",
|
||||
activeWorktreePath: null,
|
||||
activeThreadBranch: null,
|
||||
currentGitBranch: "main",
|
||||
}),
|
||||
).toBe("main");
|
||||
});
|
||||
|
||||
it("keeps an explicitly selected worktree base branch", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "worktree",
|
||||
activeWorktreePath: null,
|
||||
activeThreadBranch: "feature/base",
|
||||
currentGitBranch: "main",
|
||||
}),
|
||||
).toBe("feature/base");
|
||||
});
|
||||
|
||||
it("shows the actual checked-out branch when not selecting a new worktree base", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "local",
|
||||
activeWorktreePath: null,
|
||||
activeThreadBranch: "feature/base",
|
||||
currentGitBranch: "main",
|
||||
}),
|
||||
).toBe("main");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
it("strips the remote prefix from a remote ref", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
|
||||
});
|
||||
|
||||
it("supports remote names that contain slashes", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe(
|
||||
"upstream/feature/demo",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns the original name when ref is malformed", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/")).toBe("origin/");
|
||||
expect(deriveLocalBranchNameFromRemoteRef("/feature/demo")).toBe("/feature/demo");
|
||||
});
|
||||
});
|
||||
|
||||
describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
it("hides remote refs when the matching local branch exists", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "origin/feature/demo",
|
||||
isRemote: true,
|
||||
remoteName: "origin",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "origin/feature/remote-only",
|
||||
isRemote: true,
|
||||
remoteName: "origin",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/demo",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps all entries when no local match exists for a remote ref", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/local",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "origin/feature/remote-only",
|
||||
isRemote: true,
|
||||
remoteName: "origin",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/local",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("dedupes remote refs for remotes whose names contain slashes", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "my-org/upstream/feature/demo",
|
||||
isRemote: true,
|
||||
remoteName: "my-org/upstream",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/demo",
|
||||
]);
|
||||
});
|
||||
|
||||
it("dedupes remote refs when git tracks with first-slash local naming", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "upstream/feature",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "my-org/upstream/feature",
|
||||
isRemote: true,
|
||||
remoteName: "my-org/upstream",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"upstream/feature",
|
||||
]);
|
||||
it("does not sync when thread already targets a worktree path", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: threadId,
|
||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,90 +1,28 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import type { GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export type EnvMode = "local" | "worktree";
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
activeWorktreePath: string | null;
|
||||
hasServerThread: boolean;
|
||||
draftThreadEnvMode: EnvMode | undefined;
|
||||
}): EnvMode {
|
||||
const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input;
|
||||
return activeWorktreePath || (!hasServerThread && draftThreadEnvMode === "worktree")
|
||||
? "worktree"
|
||||
: "local";
|
||||
}
|
||||
|
||||
export function resolveDraftEnvModeAfterBranchChange(input: {
|
||||
nextWorktreePath: string | null;
|
||||
currentWorktreePath: string | null;
|
||||
effectiveEnvMode: EnvMode;
|
||||
}): EnvMode {
|
||||
const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
|
||||
if (nextWorktreePath) {
|
||||
return "worktree";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
|
||||
return "worktree";
|
||||
}
|
||||
return "local";
|
||||
}
|
||||
|
||||
export function resolveBranchToolbarValue(input: {
|
||||
envMode: EnvMode;
|
||||
interface DeriveSyncedLocalBranchInput {
|
||||
activeThreadId: ThreadId | undefined;
|
||||
activeWorktreePath: string | null;
|
||||
envMode: "local" | "worktree";
|
||||
activeThreadBranch: string | null;
|
||||
currentGitBranch: string | null;
|
||||
}): string | null {
|
||||
const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
|
||||
if (envMode === "worktree" && !activeWorktreePath) {
|
||||
return activeThreadBranch ?? currentGitBranch;
|
||||
}
|
||||
return currentGitBranch ?? activeThreadBranch;
|
||||
queryBranches: ReadonlyArray<GitBranch> | undefined;
|
||||
}
|
||||
|
||||
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
|
||||
const firstSeparatorIndex = branchName.indexOf("/");
|
||||
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
|
||||
return branchName;
|
||||
}
|
||||
return branchName.slice(firstSeparatorIndex + 1);
|
||||
}
|
||||
|
||||
function deriveLocalBranchNameCandidatesFromRemoteRef(
|
||||
branchName: string,
|
||||
remoteName?: string,
|
||||
): ReadonlyArray<string> {
|
||||
const candidates = new Set<string>();
|
||||
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
|
||||
if (firstSlashCandidate.length > 0) {
|
||||
candidates.add(firstSlashCandidate);
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
}: DeriveSyncedLocalBranchInput): string | null {
|
||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (remoteName) {
|
||||
const remotePrefix = `${remoteName}/`;
|
||||
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
|
||||
candidates.add(branchName.slice(remotePrefix.length));
|
||||
}
|
||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
export function dedupeRemoteBranchesWithLocalMatches(
|
||||
branches: ReadonlyArray<GitBranch>,
|
||||
): ReadonlyArray<GitBranch> {
|
||||
const localBranchNames = new Set(
|
||||
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
|
||||
);
|
||||
|
||||
return branches.filter((branch) => {
|
||||
if (!branch.isRemote) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
|
||||
branch.name,
|
||||
branch.remoteName,
|
||||
);
|
||||
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
|
||||
});
|
||||
return currentBranch.name;
|
||||
}
|
||||
@@ -1,105 +1,212 @@
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { useCallback } from "react";
|
||||
import type { GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { newCommandId } from "../lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useStore } from "../store";
|
||||
import {
|
||||
EnvMode,
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveEffectiveEnvMode,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
gitBranchesQueryOptions,
|
||||
gitCheckoutMutationOptions,
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxEmpty,
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxPopup,
|
||||
ComboboxTrigger,
|
||||
} from "./ui/combobox";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
|
||||
interface BranchToolbarProps {
|
||||
threadId: ThreadId;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
envMode: "local" | "worktree";
|
||||
onEnvModeChange: (mode: "local" | "worktree") => void;
|
||||
envLocked: boolean;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
|
||||
export default function BranchToolbar({
|
||||
threadId,
|
||||
envMode,
|
||||
onEnvModeChange,
|
||||
envLocked,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarProps) {
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const { state, dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const serverThread = threads.find((thread) => thread.id === threadId);
|
||||
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
|
||||
const activeProject = projects.find((project) => project.id === activeProjectId);
|
||||
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
|
||||
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
|
||||
const activeThread = state.threads.find((thread) => thread.id === threadId);
|
||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||
const activeThreadId = activeThread?.id;
|
||||
const activeThreadBranch = activeThread?.branch ?? null;
|
||||
const activeWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
|
||||
const hasServerThread = serverThread !== undefined;
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
|
||||
const setThreadBranch = useCallback(
|
||||
(branch: string | null, worktreePath: string | null) => {
|
||||
if (!activeThreadId) return;
|
||||
const api = readNativeApi();
|
||||
// If the effective cwd is about to change, stop the running session so the
|
||||
// next message creates a new one with the correct cwd.
|
||||
const sessionId = serverThread?.session?.sessionId;
|
||||
if (sessionId && worktreePath !== activeWorktreePath && api) {
|
||||
void api.orchestration
|
||||
.dispatchCommand({
|
||||
type: "thread.session.stop",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
if (api && hasServerThread) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
branch,
|
||||
worktreePath,
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
setThreadBranchAction(activeThreadId, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: worktreePath,
|
||||
currentWorktreePath: activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
});
|
||||
setDraftThreadContext(threadId, {
|
||||
branch,
|
||||
worktreePath,
|
||||
envMode: nextDraftEnvMode,
|
||||
});
|
||||
},
|
||||
[
|
||||
activeThreadId,
|
||||
serverThread?.session?.sessionId,
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
setThreadBranchAction,
|
||||
setDraftThreadContext,
|
||||
threadId,
|
||||
effectiveEnvMode,
|
||||
],
|
||||
// ── Queries ───────────────────────────────────────────────────────────
|
||||
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||
|
||||
const branches = branchesQuery.data?.branches ?? [];
|
||||
const branchNames = branches.map((branch) => branch.name);
|
||||
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
|
||||
const trimmedBranchQuery = branchQuery.trim();
|
||||
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0;
|
||||
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
|
||||
const createBranchItemValue = canCreateBranch
|
||||
? `__create_new_branch__:${trimmedBranchQuery}`
|
||||
: null;
|
||||
const branchPickerItems =
|
||||
createBranchItemValue && !hasExactBranchMatch
|
||||
? [...branchNames, createBranchItemValue]
|
||||
: branchNames;
|
||||
// ── Mutations ─────────────────────────────────────────────────────────
|
||||
|
||||
const checkoutMutation = useMutation(gitCheckoutMutationOptions({ cwd: branchCwd, queryClient }));
|
||||
|
||||
const createBranchMutation = useMutation(
|
||||
gitCreateBranchAndCheckoutMutationOptions({ cwd: branchCwd, queryClient }),
|
||||
);
|
||||
|
||||
if (!activeThreadId || !activeProject) return null;
|
||||
// ── Effects ───────────────────────────────────────────────────────────
|
||||
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
const api = readNativeApi();
|
||||
|
||||
if (api) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
setBranchQuery("");
|
||||
}, [isBranchMenuOpen]);
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
const setThreadError = (error: string | null) => {
|
||||
if (!activeThreadId) return;
|
||||
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
|
||||
};
|
||||
|
||||
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
|
||||
if (!activeThreadId) return;
|
||||
const api = readNativeApi();
|
||||
// If the effective cwd is about to change, stop the running session so the
|
||||
// next message creates a new one with the correct cwd.
|
||||
const sessionId = activeThread?.session?.sessionId;
|
||||
if (sessionId && worktreePath !== activeWorktreePath && api) {
|
||||
void api.orchestration
|
||||
.dispatchCommand({
|
||||
type: "thread.session.stop",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
if (api) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
branch,
|
||||
worktreePath,
|
||||
});
|
||||
}
|
||||
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
|
||||
};
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !branchCwd) return;
|
||||
|
||||
// For new worktree mode, selecting a branch picks the base branch.
|
||||
if (envMode === "worktree" && !envLocked && !activeWorktreePath) {
|
||||
setThreadError(null);
|
||||
setThreadBranch(branch.name, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
// If the branch already lives in a worktree, redirect there instead of
|
||||
// trying to checkout (which git would reject with "already used by worktree").
|
||||
if (branch.worktreePath) {
|
||||
const isMainWorktree = branch.worktreePath === activeProject?.cwd;
|
||||
setThreadError(null);
|
||||
// Main worktree → switch back to local (project cwd, worktreePath=null).
|
||||
// Secondary worktree → point the thread at that worktree path.
|
||||
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
checkoutMutation.mutate(branch.name, {
|
||||
onSuccess: () => {
|
||||
setThreadError(null);
|
||||
setThreadBranch(branch.name, activeWorktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const createBranch = (rawName: string) => {
|
||||
const name = rawName.trim();
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return;
|
||||
createBranchMutation.mutate(name, {
|
||||
onSuccess: () => {
|
||||
setThreadError(null);
|
||||
setThreadBranch(name, activeWorktreePath);
|
||||
setBranchQuery("");
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
if (!activeThread || !activeProject) return null;
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
|
||||
@@ -114,23 +221,92 @@ export default function BranchToolbar({
|
||||
variant="ghost"
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
size="xs"
|
||||
onClick={() => onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")}
|
||||
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
|
||||
>
|
||||
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
|
||||
{envMode === "worktree" ? "New worktree" : "Local"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<BranchToolbarBranchSelector
|
||||
activeProjectCwd={activeProject.cwd}
|
||||
activeThreadBranch={activeThreadBranch}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
branchCwd={branchCwd}
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
envLocked={envLocked}
|
||||
onSetThreadBranch={setThreadBranch}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
<Combobox
|
||||
items={branchPickerItems}
|
||||
autoHighlight
|
||||
onOpenChange={(open) => setIsBranchMenuOpen(open)}
|
||||
open={isBranchMenuOpen}
|
||||
value={activeThread.branch}
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={branchesQuery.isLoading}
|
||||
>
|
||||
<span className="max-w-[240px] truncate">
|
||||
{activeThread.branch
|
||||
? envMode === "worktree" && !activeWorktreePath
|
||||
? `From ${activeThread.branch}`
|
||||
: activeThread.branch
|
||||
: "Select branch"}
|
||||
</span>
|
||||
<ChevronDownIcon />
|
||||
</ComboboxTrigger>
|
||||
<ComboboxPopup align="end" side="top" className="w-64">
|
||||
<div className="border-b p-1">
|
||||
<ComboboxInput
|
||||
className="[&_input]:font-sans rounded-md"
|
||||
inputClassName="ring-0"
|
||||
placeholder="Search branches..."
|
||||
showTrigger={false}
|
||||
size="sm"
|
||||
value={branchQuery}
|
||||
onChange={(event) => setBranchQuery(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
|
||||
<ComboboxList className="max-h-56">
|
||||
{(itemValue) => {
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) {
|
||||
return (
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
key={itemValue}
|
||||
value={itemValue}
|
||||
onClick={() => createBranch(trimmedBranchQuery)}
|
||||
>
|
||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
||||
</ComboboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
const branch = branchByName.get(itemValue);
|
||||
if (!branch) return null;
|
||||
|
||||
const hasSecondaryWorktree =
|
||||
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
|
||||
return (
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
key={itemValue}
|
||||
value={itemValue}
|
||||
className={
|
||||
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined
|
||||
}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<span className="truncate">{itemValue}</span>
|
||||
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/45">
|
||||
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</ComboboxItem>
|
||||
);
|
||||
}}
|
||||
</ComboboxList>
|
||||
</ComboboxPopup>
|
||||
</Combobox>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,408 +0,0 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useOptimistic,
|
||||
useRef,
|
||||
useState,
|
||||
useTransition,
|
||||
} from "react";
|
||||
|
||||
import { gitBranchesQueryOptions, gitQueryKeys, invalidateGitQueries } from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
EnvMode,
|
||||
resolveBranchToolbarValue,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxEmpty,
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxPopup,
|
||||
ComboboxTrigger,
|
||||
} from "./ui/combobox";
|
||||
import { toastManager } from "./ui/toast";
|
||||
|
||||
interface BranchToolbarBranchSelectorProps {
|
||||
activeProjectCwd: string;
|
||||
activeThreadBranch: string | null;
|
||||
activeWorktreePath: string | null;
|
||||
branchCwd: string | null;
|
||||
effectiveEnvMode: EnvMode;
|
||||
envLocked: boolean;
|
||||
onSetThreadBranch: (branch: string | null, worktreePath: string | null) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
|
||||
function toBranchActionErrorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "An error occurred.";
|
||||
}
|
||||
|
||||
function getBranchTriggerLabel(input: {
|
||||
activeWorktreePath: string | null;
|
||||
effectiveEnvMode: EnvMode;
|
||||
resolvedActiveBranch: string | null;
|
||||
}): string {
|
||||
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
|
||||
if (!resolvedActiveBranch) {
|
||||
return "Select branch";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
|
||||
return `From ${resolvedActiveBranch}`;
|
||||
}
|
||||
return resolvedActiveBranch;
|
||||
}
|
||||
|
||||
export function BranchToolbarBranchSelector({
|
||||
activeProjectCwd,
|
||||
activeThreadBranch,
|
||||
activeWorktreePath,
|
||||
branchCwd,
|
||||
effectiveEnvMode,
|
||||
envLocked,
|
||||
onSetThreadBranch,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||
const branches = useMemo(
|
||||
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
|
||||
[branchesQuery.data?.branches],
|
||||
);
|
||||
const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
|
||||
const canonicalActiveBranch = resolveBranchToolbarValue({
|
||||
envMode: effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
activeThreadBranch,
|
||||
currentGitBranch,
|
||||
});
|
||||
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
|
||||
const branchByName = useMemo(
|
||||
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
|
||||
[branches],
|
||||
);
|
||||
const trimmedBranchQuery = branchQuery.trim();
|
||||
const normalizedBranchQuery = trimmedBranchQuery.toLowerCase();
|
||||
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
|
||||
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
|
||||
const createBranchItemValue = canCreateBranch
|
||||
? `__create_new_branch__:${trimmedBranchQuery}`
|
||||
: null;
|
||||
const branchPickerItems = useMemo(
|
||||
() =>
|
||||
createBranchItemValue && !hasExactBranchMatch
|
||||
? [...branchNames, createBranchItemValue]
|
||||
: branchNames,
|
||||
[branchNames, createBranchItemValue, hasExactBranchMatch],
|
||||
);
|
||||
const filteredBranchPickerItems = useMemo(
|
||||
() =>
|
||||
normalizedBranchQuery.length === 0
|
||||
? branchPickerItems
|
||||
: branchPickerItems.filter((itemValue) => {
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) return true;
|
||||
return itemValue.toLowerCase().includes(normalizedBranchQuery);
|
||||
}),
|
||||
[branchPickerItems, createBranchItemValue, normalizedBranchQuery],
|
||||
);
|
||||
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
|
||||
canonicalActiveBranch,
|
||||
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
|
||||
);
|
||||
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||
|
||||
const runBranchAction = (action: () => Promise<void>) => {
|
||||
startBranchActionTransition(async () => {
|
||||
await action().catch(() => undefined);
|
||||
await invalidateGitQueries(queryClient).catch(() => undefined);
|
||||
});
|
||||
};
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !branchCwd || isBranchActionPending) return;
|
||||
|
||||
// In new-worktree mode, selecting a branch sets the base branch.
|
||||
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
|
||||
onSetThreadBranch(branch.name, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
// If the branch already lives in a worktree, point the thread there.
|
||||
if (branch.worktreePath) {
|
||||
const isMainWorktree = branch.worktreePath === activeProjectCwd;
|
||||
onSetThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedBranchName = branch.isRemote
|
||||
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
||||
: branch.name;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
|
||||
runBranchAction(async () => {
|
||||
setOptimisticBranch(selectedBranchName);
|
||||
try {
|
||||
await api.git.checkout({ cwd: branchCwd, branch: branch.name });
|
||||
await invalidateGitQueries(queryClient);
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let nextBranchName = selectedBranchName;
|
||||
if (branch.isRemote) {
|
||||
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||
if (status?.branch) {
|
||||
nextBranchName = status.branch;
|
||||
}
|
||||
}
|
||||
|
||||
setOptimisticBranch(nextBranchName);
|
||||
onSetThreadBranch(nextBranchName, activeWorktreePath);
|
||||
});
|
||||
};
|
||||
|
||||
const createBranch = (rawName: string) => {
|
||||
const name = rawName.trim();
|
||||
const api = readNativeApi();
|
||||
if (!api || !branchCwd || !name || isBranchActionPending) return;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
|
||||
runBranchAction(async () => {
|
||||
setOptimisticBranch(name);
|
||||
|
||||
try {
|
||||
await api.git.createBranch({ cwd: branchCwd, branch: name });
|
||||
try {
|
||||
await api.git.checkout({ cwd: branchCwd, branch: name });
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to create branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setOptimisticBranch(name);
|
||||
onSetThreadBranch(name, activeWorktreePath);
|
||||
setBranchQuery("");
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
effectiveEnvMode !== "worktree" ||
|
||||
activeWorktreePath ||
|
||||
activeThreadBranch ||
|
||||
!currentGitBranch
|
||||
) {
|
||||
return;
|
||||
}
|
||||
onSetThreadBranch(currentGitBranch, null);
|
||||
}, [
|
||||
activeThreadBranch,
|
||||
activeWorktreePath,
|
||||
currentGitBranch,
|
||||
effectiveEnvMode,
|
||||
onSetThreadBranch,
|
||||
]);
|
||||
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
setIsBranchMenuOpen(open);
|
||||
if (!open) {
|
||||
setBranchQuery("");
|
||||
return;
|
||||
}
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: gitQueryKeys.branches(branchCwd),
|
||||
});
|
||||
},
|
||||
[branchCwd, queryClient],
|
||||
);
|
||||
|
||||
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
|
||||
const branchListVirtualizer = useVirtualizer({
|
||||
count: filteredBranchPickerItems.length,
|
||||
estimateSize: () => 28,
|
||||
getScrollElement: () => branchListScrollElementRef.current,
|
||||
overscan: 12,
|
||||
enabled: isBranchMenuOpen,
|
||||
initialRect: {
|
||||
height: 224,
|
||||
width: 0,
|
||||
},
|
||||
});
|
||||
const virtualBranchRows = branchListVirtualizer.getVirtualItems();
|
||||
const setBranchListRef = useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
branchListScrollElementRef.current =
|
||||
(element?.parentElement as HTMLDivElement | null) ?? null;
|
||||
if (element) {
|
||||
branchListVirtualizer.measure();
|
||||
}
|
||||
},
|
||||
[branchListVirtualizer],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isBranchMenuOpen) return;
|
||||
queueMicrotask(() => {
|
||||
branchListVirtualizer.measure();
|
||||
});
|
||||
}, [branchListVirtualizer, filteredBranchPickerItems.length, isBranchMenuOpen]);
|
||||
|
||||
const triggerLabel = getBranchTriggerLabel({
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
resolvedActiveBranch,
|
||||
});
|
||||
|
||||
return (
|
||||
<Combobox
|
||||
items={branchPickerItems}
|
||||
filteredItems={filteredBranchPickerItems}
|
||||
autoHighlight
|
||||
virtualized
|
||||
onItemHighlighted={(_value, eventDetails) => {
|
||||
if (!isBranchMenuOpen || eventDetails.index < 0) return;
|
||||
branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" });
|
||||
}}
|
||||
onOpenChange={handleOpenChange}
|
||||
open={isBranchMenuOpen}
|
||||
value={resolvedActiveBranch}
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={branchesQuery.isLoading || isBranchActionPending}
|
||||
>
|
||||
<span className="max-w-[240px] truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon />
|
||||
</ComboboxTrigger>
|
||||
<ComboboxPopup align="end" side="top" className="w-64">
|
||||
<div className="border-b p-1">
|
||||
<ComboboxInput
|
||||
className="[&_input]:font-sans rounded-md"
|
||||
inputClassName="ring-0"
|
||||
placeholder="Search branches..."
|
||||
showTrigger={false}
|
||||
size="sm"
|
||||
value={branchQuery}
|
||||
onChange={(event) => setBranchQuery(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
|
||||
<ComboboxList ref={setBranchListRef} className="max-h-56">
|
||||
<div
|
||||
className="relative"
|
||||
style={{
|
||||
height: `${branchListVirtualizer.getTotalSize()}px`,
|
||||
}}
|
||||
>
|
||||
{virtualBranchRows.map((virtualRow) => {
|
||||
const itemValue = filteredBranchPickerItems[virtualRow.index];
|
||||
if (!itemValue) return null;
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) {
|
||||
return (
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
key={itemValue}
|
||||
index={virtualRow.index}
|
||||
value={itemValue}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
}}
|
||||
onClick={() => createBranch(trimmedBranchQuery)}
|
||||
>
|
||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
||||
</ComboboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
const branch = branchByName.get(itemValue);
|
||||
if (!branch) return null;
|
||||
|
||||
const hasSecondaryWorktree =
|
||||
branch.worktreePath && branch.worktreePath !== activeProjectCwd;
|
||||
const badge = branch.current
|
||||
? "current"
|
||||
: hasSecondaryWorktree
|
||||
? "worktree"
|
||||
: branch.isRemote
|
||||
? "remote"
|
||||
: branch.isDefault
|
||||
? "default"
|
||||
: null;
|
||||
return (
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
key={itemValue}
|
||||
index={virtualRow.index}
|
||||
value={itemValue}
|
||||
className={
|
||||
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
|
||||
}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
}}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<span className="truncate">{itemValue}</span>
|
||||
{badge && (
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
|
||||
)}
|
||||
</div>
|
||||
</ComboboxItem>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ComboboxList>
|
||||
</ComboboxPopup>
|
||||
</Combobox>
|
||||
);
|
||||
}
|
||||
@@ -1,713 +0,0 @@
|
||||
// Production CSS is part of the behavior under test because row height depends on it.
|
||||
import "../index.css";
|
||||
|
||||
import {
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type MessageId,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
type ProviderSessionId,
|
||||
type ServerConfig,
|
||||
type ThreadId,
|
||||
type WsWelcomePayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
import { HttpResponse, http, ws } from "msw";
|
||||
import { setupWorker } from "msw/browser";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
const THREAD_ID = "thread-browser-test" as ThreadId;
|
||||
const PROJECT_ID = "project-1" as ProjectId;
|
||||
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='300'></svg>";
|
||||
|
||||
interface WsRequestEnvelope {
|
||||
id: string;
|
||||
body: {
|
||||
_tag: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
interface TestFixture {
|
||||
snapshot: OrchestrationReadModel;
|
||||
serverConfig: ServerConfig;
|
||||
welcome: WsWelcomePayload;
|
||||
}
|
||||
|
||||
let fixture: TestFixture;
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
name: string;
|
||||
width: number;
|
||||
height: number;
|
||||
textTolerancePx: number;
|
||||
attachmentTolerancePx: number;
|
||||
}
|
||||
|
||||
const DEFAULT_VIEWPORT: ViewportSpec = {
|
||||
name: "desktop",
|
||||
width: 960,
|
||||
height: 1_100,
|
||||
textTolerancePx: 44,
|
||||
attachmentTolerancePx: 56,
|
||||
};
|
||||
const TEXT_VIEWPORT_MATRIX = [
|
||||
DEFAULT_VIEWPORT,
|
||||
{ name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 },
|
||||
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
|
||||
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
|
||||
] as const satisfies readonly ViewportSpec[];
|
||||
const ATTACHMENT_VIEWPORT_MATRIX = [
|
||||
DEFAULT_VIEWPORT,
|
||||
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
|
||||
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
|
||||
] as const satisfies readonly ViewportSpec[];
|
||||
|
||||
interface UserRowMeasurement {
|
||||
measuredRowHeightPx: number;
|
||||
timelineWidthMeasuredPx: number;
|
||||
renderedInVirtualizedRegion: boolean;
|
||||
}
|
||||
|
||||
interface MountedChatView {
|
||||
cleanup: () => Promise<void>;
|
||||
measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
|
||||
setViewport: (viewport: ViewportSpec) => Promise<void>;
|
||||
}
|
||||
|
||||
function isoAt(offsetSeconds: number): string {
|
||||
return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString();
|
||||
}
|
||||
|
||||
function createBaseServerConfig(): ServerConfig {
|
||||
return {
|
||||
cwd: "/repo/project",
|
||||
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
providers: [
|
||||
{
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
available: true,
|
||||
authStatus: "authenticated",
|
||||
checkedAt: NOW_ISO,
|
||||
},
|
||||
],
|
||||
availableEditors: [],
|
||||
};
|
||||
}
|
||||
|
||||
function createUserMessage(options: {
|
||||
id: MessageId;
|
||||
text: string;
|
||||
offsetSeconds: number;
|
||||
attachments?: Array<{
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
}>;
|
||||
}) {
|
||||
return {
|
||||
id: options.id,
|
||||
role: "user" as const,
|
||||
text: options.text,
|
||||
...(options.attachments ? { attachments: options.attachments } : {}),
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: isoAt(options.offsetSeconds),
|
||||
updatedAt: isoAt(options.offsetSeconds + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) {
|
||||
return {
|
||||
id: options.id,
|
||||
role: "assistant" as const,
|
||||
text: options.text,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: isoAt(options.offsetSeconds),
|
||||
updatedAt: isoAt(options.offsetSeconds + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function createSnapshotForTargetUser(options: {
|
||||
targetMessageId: MessageId;
|
||||
targetText: string;
|
||||
targetAttachmentCount?: number;
|
||||
}): OrchestrationReadModel {
|
||||
const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
|
||||
|
||||
for (let index = 0; index < 22; index += 1) {
|
||||
const isTarget = index === 3;
|
||||
const userId = `msg-user-${index}` as MessageId;
|
||||
const assistantId = `msg-assistant-${index}` as MessageId;
|
||||
const attachments =
|
||||
isTarget && (options.targetAttachmentCount ?? 0) > 0
|
||||
? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({
|
||||
type: "image" as const,
|
||||
id: `attachment-${attachmentIndex + 1}`,
|
||||
name: `attachment-${attachmentIndex + 1}.png`,
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 128,
|
||||
}))
|
||||
: undefined;
|
||||
|
||||
messages.push(
|
||||
createUserMessage({
|
||||
id: isTarget ? options.targetMessageId : userId,
|
||||
text: isTarget ? options.targetText : `filler user message ${index}`,
|
||||
offsetSeconds: messages.length * 3,
|
||||
...(attachments ? { attachments } : {}),
|
||||
}),
|
||||
);
|
||||
messages.push(
|
||||
createAssistantMessage({
|
||||
id: assistantId,
|
||||
text: `assistant filler ${index}`,
|
||||
offsetSeconds: messages.length * 3,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
snapshotSequence: 1,
|
||||
projects: [
|
||||
{
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModel: "gpt-5",
|
||||
scripts: [],
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Browser test thread",
|
||||
model: "gpt-5",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
deletedAt: null,
|
||||
messages,
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1" as ProviderSessionId,
|
||||
providerThreadId: null,
|
||||
approvalPolicy: "on-failure",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW_ISO,
|
||||
},
|
||||
},
|
||||
],
|
||||
updatedAt: NOW_ISO,
|
||||
};
|
||||
}
|
||||
|
||||
function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
|
||||
return {
|
||||
snapshot,
|
||||
serverConfig: createBaseServerConfig(),
|
||||
welcome: {
|
||||
cwd: "/repo/project",
|
||||
projectName: "Project",
|
||||
bootstrapProjectId: PROJECT_ID,
|
||||
bootstrapThreadId: THREAD_ID,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveWsRpc(tag: string): unknown {
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
}
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
if (tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.gitStatus) {
|
||||
return {
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.projectsSearchEntries) {
|
||||
return {
|
||||
entries: [],
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
const worker = setupWorker(
|
||||
wsLink.addEventListener("connection", ({ client }) => {
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: fixture.welcome,
|
||||
}),
|
||||
);
|
||||
client.addEventListener("message", (event) => {
|
||||
const rawData = event.data;
|
||||
if (typeof rawData !== "string") return;
|
||||
let request: WsRequestEnvelope;
|
||||
try {
|
||||
request = JSON.parse(rawData) as WsRequestEnvelope;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const method = request.body?._tag;
|
||||
if (typeof method !== "string") return;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
result: resolveWsRpc(method),
|
||||
}),
|
||||
);
|
||||
});
|
||||
}),
|
||||
http.get("*/attachments/:attachmentId", () =>
|
||||
HttpResponse.text(ATTACHMENT_SVG, {
|
||||
headers: {
|
||||
"Content-Type": "image/svg+xml",
|
||||
},
|
||||
}),
|
||||
),
|
||||
http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
|
||||
);
|
||||
|
||||
async function nextFrame(): Promise<void> {
|
||||
await new Promise<void>((resolve) => {
|
||||
window.requestAnimationFrame(() => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForLayout(): Promise<void> {
|
||||
await nextFrame();
|
||||
await nextFrame();
|
||||
await nextFrame();
|
||||
}
|
||||
|
||||
async function setViewport(viewport: ViewportSpec): Promise<void> {
|
||||
await page.viewport(viewport.width, viewport.height);
|
||||
await waitForLayout();
|
||||
}
|
||||
|
||||
async function waitForProductionStyles(): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).not.toBe(
|
||||
"",
|
||||
);
|
||||
expect(getComputedStyle(document.body).marginTop).toBe("0px");
|
||||
},
|
||||
{
|
||||
timeout: 4_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForElement<T extends Element>(
|
||||
query: () => T | null,
|
||||
errorMessage: string,
|
||||
): Promise<T> {
|
||||
let element: T | null = null;
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
element = query();
|
||||
expect(element, errorMessage).toBeTruthy();
|
||||
},
|
||||
{
|
||||
timeout: 8_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
if (!element) {
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
|
||||
const images = Array.from(scope.querySelectorAll("img"));
|
||||
if (images.length === 0) {
|
||||
return;
|
||||
}
|
||||
await Promise.all(
|
||||
images.map(
|
||||
(image) =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (image.complete) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
image.addEventListener("load", () => resolve(), { once: true });
|
||||
image.addEventListener("error", () => resolve(), { once: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
await waitForLayout();
|
||||
}
|
||||
|
||||
async function measureUserRow(options: {
|
||||
host: HTMLElement;
|
||||
targetMessageId: MessageId;
|
||||
}): Promise<UserRowMeasurement> {
|
||||
const { host, targetMessageId } = options;
|
||||
const rowSelector = `[data-message-id="${targetMessageId}"][data-message-role="user"]`;
|
||||
|
||||
const scrollContainer = await waitForElement(
|
||||
() => host.querySelector<HTMLDivElement>("div.overflow-y-auto.overscroll-y-contain"),
|
||||
"Unable to find ChatView message scroll container.",
|
||||
);
|
||||
|
||||
let row: HTMLElement | null = null;
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await waitForLayout();
|
||||
row = host.querySelector<HTMLElement>(rowSelector);
|
||||
expect(row, "Unable to locate targeted user message row.").toBeTruthy();
|
||||
},
|
||||
{
|
||||
timeout: 8_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
|
||||
await waitForImagesToLoad(row!);
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await nextFrame();
|
||||
|
||||
const timelineRoot =
|
||||
row!.closest<HTMLElement>('[data-timeline-root="true"]') ??
|
||||
host.querySelector<HTMLElement>('[data-timeline-root="true"]');
|
||||
if (!(timelineRoot instanceof HTMLElement)) {
|
||||
throw new Error("Unable to locate timeline root container.");
|
||||
}
|
||||
|
||||
let timelineWidthMeasuredPx = 0;
|
||||
let measuredRowHeightPx = 0;
|
||||
let renderedInVirtualizedRegion = false;
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await nextFrame();
|
||||
const measuredRow = host.querySelector<HTMLElement>(rowSelector);
|
||||
expect(measuredRow, "Unable to measure targeted user row height.").toBeTruthy();
|
||||
timelineWidthMeasuredPx = timelineRoot.getBoundingClientRect().width;
|
||||
measuredRowHeightPx = measuredRow!.getBoundingClientRect().height;
|
||||
renderedInVirtualizedRegion = measuredRow!.closest("[data-index]") instanceof HTMLElement;
|
||||
expect(timelineWidthMeasuredPx, "Unable to measure timeline width.").toBeGreaterThan(0);
|
||||
expect(measuredRowHeightPx, "Unable to measure targeted user row height.").toBeGreaterThan(0);
|
||||
},
|
||||
{
|
||||
timeout: 4_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
|
||||
return { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion };
|
||||
}
|
||||
|
||||
async function mountChatView(options: {
|
||||
viewport: ViewportSpec;
|
||||
snapshot: OrchestrationReadModel;
|
||||
}): Promise<MountedChatView> {
|
||||
fixture = buildFixture(options.snapshot);
|
||||
await setViewport(options.viewport);
|
||||
await waitForProductionStyles();
|
||||
|
||||
const host = document.createElement("div");
|
||||
host.style.position = "fixed";
|
||||
host.style.inset = "0";
|
||||
host.style.width = "100vw";
|
||||
host.style.height = "100vh";
|
||||
host.style.display = "grid";
|
||||
host.style.overflow = "hidden";
|
||||
document.body.append(host);
|
||||
|
||||
const router = getRouter(
|
||||
createMemoryHistory({
|
||||
initialEntries: [`/${THREAD_ID}`],
|
||||
}),
|
||||
);
|
||||
|
||||
const screen = await render(<RouterProvider router={router} />, {
|
||||
container: host,
|
||||
});
|
||||
|
||||
await waitForLayout();
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
|
||||
setViewport: async (viewport: ViewportSpec) => {
|
||||
await setViewport(viewport);
|
||||
await waitForProductionStyles();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function measureUserRowAtViewport(options: {
|
||||
snapshot: OrchestrationReadModel;
|
||||
targetMessageId: MessageId;
|
||||
viewport: ViewportSpec;
|
||||
}): Promise<UserRowMeasurement> {
|
||||
const mounted = await mountChatView({
|
||||
viewport: options.viewport,
|
||||
snapshot: options.snapshot,
|
||||
});
|
||||
|
||||
try {
|
||||
return await mounted.measureUserRow(options.targetMessageId);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
describe("ChatView timeline estimator parity (full app)", () => {
|
||||
beforeAll(async () => {
|
||||
fixture = buildFixture(
|
||||
createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-bootstrap" as MessageId,
|
||||
targetText: "bootstrap",
|
||||
}),
|
||||
);
|
||||
await worker.start({
|
||||
onUnhandledRequest: "bypass",
|
||||
quiet: true,
|
||||
serviceWorker: {
|
||||
url: "/mockServiceWorker.js",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await worker.stop();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await setViewport(DEFAULT_VIEWPORT);
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it.each(TEXT_VIEWPORT_MATRIX)(
|
||||
"keeps long user message estimate close at the $name viewport",
|
||||
async (viewport) => {
|
||||
const userText = "x".repeat(3_200);
|
||||
const targetMessageId = `msg-user-target-long-${viewport.name}` as MessageId;
|
||||
const mounted = await mountChatView({
|
||||
viewport,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
|
||||
await mounted.measureUserRow(targetMessageId);
|
||||
|
||||
expect(renderedInVirtualizedRegion).toBe(true);
|
||||
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.textTolerancePx,
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
|
||||
const userText = "x".repeat(3_200);
|
||||
const targetMessageId = "msg-user-target-resize" as MessageId;
|
||||
const mounted = await mountChatView({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[0],
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const measurements: Array<UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }> = [];
|
||||
|
||||
for (const viewport of TEXT_VIEWPORT_MATRIX) {
|
||||
await mounted.setViewport(viewport);
|
||||
const measurement = await mounted.measureUserRow(targetMessageId);
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: measurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(measurement.renderedInVirtualizedRegion).toBe(true);
|
||||
expect(Math.abs(measurement.measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.textTolerancePx,
|
||||
);
|
||||
measurements.push({ ...measurement, viewport, estimatedHeightPx });
|
||||
}
|
||||
|
||||
expect(new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx))).size).toBeGreaterThanOrEqual(3);
|
||||
|
||||
const byMeasuredWidth = measurements.toSorted(
|
||||
(left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,
|
||||
);
|
||||
const narrowest = byMeasuredWidth[0]!;
|
||||
const widest = byMeasuredWidth.at(-1)!;
|
||||
expect(narrowest.timelineWidthMeasuredPx).toBeLessThan(widest.timelineWidthMeasuredPx);
|
||||
expect(narrowest.measuredRowHeightPx).toBeGreaterThan(widest.measuredRowHeightPx);
|
||||
expect(narrowest.estimatedHeightPx).toBeGreaterThan(widest.estimatedHeightPx);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("tracks additional rendered wrapping when ChatView width narrows between desktop and mobile viewports", async () => {
|
||||
const userText = "x".repeat(2_400);
|
||||
const targetMessageId = "msg-user-target-wrap" as MessageId;
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
});
|
||||
const desktopMeasurement = await measureUserRowAtViewport({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[0],
|
||||
snapshot,
|
||||
targetMessageId,
|
||||
});
|
||||
const mobileMeasurement = await measureUserRowAtViewport({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[2],
|
||||
snapshot,
|
||||
targetMessageId,
|
||||
});
|
||||
|
||||
const estimatedDesktopPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: desktopMeasurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
const estimatedMobilePx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
const measuredDeltaPx = mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
|
||||
const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;
|
||||
expect(measuredDeltaPx).toBeGreaterThan(0);
|
||||
expect(estimatedDeltaPx).toBeGreaterThan(0);
|
||||
const ratio = estimatedDeltaPx / measuredDeltaPx;
|
||||
expect(ratio).toBeGreaterThan(0.65);
|
||||
expect(ratio).toBeLessThan(1.35);
|
||||
});
|
||||
|
||||
it.each(ATTACHMENT_VIEWPORT_MATRIX)(
|
||||
"keeps user attachment estimate close at the $name viewport",
|
||||
async (viewport) => {
|
||||
const targetMessageId = `msg-user-target-attachments-${viewport.name}` as MessageId;
|
||||
const userText = "message with image attachments";
|
||||
const mounted = await mountChatView({
|
||||
viewport,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
targetAttachmentCount: 3,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
|
||||
await mounted.measureUserRow(targetMessageId);
|
||||
|
||||
expect(renderedInVirtualizedRegion).toBe(true);
|
||||
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{
|
||||
role: "user",
|
||||
text: userText,
|
||||
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
|
||||
},
|
||||
{ timelineWidthPx: timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.attachmentTolerancePx,
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
+566
-1503
File diff suppressed because it is too large.
Load diff
@@ -1,811 +0,0 @@
|
||||
import {
|
||||
LexicalComposer,
|
||||
type InitialConfigType,
|
||||
} from "@lexical/react/LexicalComposer";
|
||||
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
|
||||
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
|
||||
import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
|
||||
import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
|
||||
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
|
||||
import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
|
||||
import {
|
||||
$applyNodeReplacement,
|
||||
$createRangeSelection,
|
||||
$getSelection,
|
||||
$setSelection,
|
||||
$isElementNode,
|
||||
$isLineBreakNode,
|
||||
$isRangeSelection,
|
||||
$isTextNode,
|
||||
$createLineBreakNode,
|
||||
$createParagraphNode,
|
||||
$createTextNode,
|
||||
KEY_ARROW_DOWN_COMMAND,
|
||||
KEY_ARROW_LEFT_COMMAND,
|
||||
KEY_ARROW_RIGHT_COMMAND,
|
||||
KEY_ARROW_UP_COMMAND,
|
||||
KEY_ENTER_COMMAND,
|
||||
KEY_TAB_COMMAND,
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
KEY_BACKSPACE_COMMAND,
|
||||
$getRoot,
|
||||
type ElementNode,
|
||||
type LexicalNode,
|
||||
TextNode,
|
||||
type EditorConfig,
|
||||
type EditorState,
|
||||
type NodeKey,
|
||||
type SerializedTextNode,
|
||||
type Spread,
|
||||
} from "lexical";
|
||||
import {
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ClipboardEventHandler,
|
||||
type Ref,
|
||||
} from "react";
|
||||
|
||||
import { isCollapsedCursorAdjacentToMention } from "~/composer-logic";
|
||||
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
|
||||
|
||||
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
|
||||
|
||||
type SerializedComposerMentionNode = Spread<
|
||||
{
|
||||
path: string;
|
||||
type: "composer-mention";
|
||||
version: 1;
|
||||
},
|
||||
SerializedTextNode
|
||||
>;
|
||||
|
||||
class ComposerMentionNode extends TextNode {
|
||||
__path: string;
|
||||
|
||||
static override getType(): string {
|
||||
return "composer-mention";
|
||||
}
|
||||
|
||||
static override clone(node: ComposerMentionNode): ComposerMentionNode {
|
||||
return new ComposerMentionNode(node.__path, node.__key);
|
||||
}
|
||||
|
||||
static override importJSON(serializedNode: SerializedComposerMentionNode): ComposerMentionNode {
|
||||
return $createComposerMentionNode(serializedNode.path);
|
||||
}
|
||||
|
||||
constructor(path: string, key?: NodeKey) {
|
||||
const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
|
||||
super(`@${normalizedPath}`, key);
|
||||
this.__path = normalizedPath;
|
||||
}
|
||||
|
||||
override exportJSON(): SerializedComposerMentionNode {
|
||||
return {
|
||||
...super.exportJSON(),
|
||||
path: this.__path,
|
||||
type: "composer-mention",
|
||||
version: 1,
|
||||
};
|
||||
}
|
||||
|
||||
override createDOM(_config: EditorConfig): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className =
|
||||
"inline-flex select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||
dom.contentEditable = "false";
|
||||
dom.setAttribute("spellcheck", "false");
|
||||
renderMentionChipDom(dom, this.__path);
|
||||
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);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
override canInsertTextBefore(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override canInsertTextAfter(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override isTextEntity(): true {
|
||||
return true;
|
||||
}
|
||||
|
||||
override isToken(): true {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function $createComposerMentionNode(path: string): ComposerMentionNode {
|
||||
return $applyNodeReplacement(new ComposerMentionNode(path));
|
||||
}
|
||||
|
||||
function inferMentionPathKind(pathValue: string): "file" | "directory" {
|
||||
const base = basenameOfPath(pathValue);
|
||||
if (base.startsWith(".") && !base.slice(1).includes(".")) {
|
||||
return "directory";
|
||||
}
|
||||
if (base.includes(".")) {
|
||||
return "file";
|
||||
}
|
||||
return "directory";
|
||||
}
|
||||
|
||||
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 = "size-3.5 shrink-0 opacity-85";
|
||||
icon.loading = "lazy";
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferMentionPathKind(pathValue), theme);
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = "truncate select-none leading-tight";
|
||||
label.textContent = basenameOfPath(pathValue);
|
||||
|
||||
container.append(icon, label);
|
||||
}
|
||||
|
||||
function clampCursor(value: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return value.length;
|
||||
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
|
||||
}
|
||||
|
||||
function getComposerNodeTextLength(node: LexicalNode): number {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return 1;
|
||||
}
|
||||
if ($isTextNode(node)) {
|
||||
return node.getTextContentSize();
|
||||
}
|
||||
if ($isLineBreakNode(node)) {
|
||||
return 1;
|
||||
}
|
||||
if ($isElementNode(node)) {
|
||||
return node.getChildren().reduce((total, child) => total + getComposerNodeTextLength(child), 0);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
|
||||
let offset = 0;
|
||||
let current: LexicalNode | null = node;
|
||||
|
||||
while (current) {
|
||||
const nextParent = current.getParent() as LexicalNode | null;
|
||||
if (!nextParent || !$isElementNode(nextParent)) {
|
||||
break;
|
||||
}
|
||||
const siblings = nextParent.getChildren();
|
||||
const index = current.getIndexWithinParent();
|
||||
for (let i = 0; i < index; i += 1) {
|
||||
const sibling = siblings[i];
|
||||
if (!sibling) continue;
|
||||
offset += getComposerNodeTextLength(sibling);
|
||||
}
|
||||
current = nextParent;
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return offset + (pointOffset > 0 ? 1 : 0);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
|
||||
if ($isLineBreakNode(node)) {
|
||||
return offset + Math.min(pointOffset, 1);
|
||||
}
|
||||
|
||||
if ($isElementNode(node)) {
|
||||
const children = node.getChildren();
|
||||
const clampedOffset = Math.max(0, Math.min(pointOffset, children.length));
|
||||
for (let i = 0; i < clampedOffset; i += 1) {
|
||||
const child = children[i];
|
||||
if (!child) continue;
|
||||
offset += getComposerNodeTextLength(child);
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
function findSelectionPointAtOffset(
|
||||
node: LexicalNode,
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "text" | "element" } | null {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
const parent = node.getParent();
|
||||
if (!parent || !$isElementNode(parent)) return null;
|
||||
const index = node.getIndexWithinParent();
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
if (remainingRef.value === 1) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index + 1,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
const size = node.getTextContentSize();
|
||||
if (remainingRef.value <= size) {
|
||||
return {
|
||||
key: node.getKey(),
|
||||
offset: remainingRef.value,
|
||||
type: "text",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= size;
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($isLineBreakNode(node)) {
|
||||
const parent = node.getParent();
|
||||
if (!parent) return null;
|
||||
const index = node.getIndexWithinParent();
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
if (remainingRef.value === 1) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index + 1,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($isElementNode(node)) {
|
||||
const children = node.getChildren();
|
||||
for (const child of children) {
|
||||
const point = findSelectionPointAtOffset(child, remainingRef);
|
||||
if (point) {
|
||||
return point;
|
||||
}
|
||||
}
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: node.getKey(),
|
||||
offset: children.length,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function $getComposerRootLength(): number {
|
||||
const root = $getRoot();
|
||||
const children = root.getChildren();
|
||||
return children.reduce((sum, child) => sum + getComposerNodeTextLength(child), 0);
|
||||
}
|
||||
|
||||
function $setSelectionAtComposerOffset(nextOffset: number): void {
|
||||
const root = $getRoot();
|
||||
const composerLength = $getComposerRootLength();
|
||||
const boundedOffset = Math.max(0, Math.min(nextOffset, composerLength));
|
||||
const remainingRef = { value: boundedOffset };
|
||||
const point =
|
||||
findSelectionPointAtOffset(root, remainingRef) ?? {
|
||||
key: root.getKey(),
|
||||
offset: root.getChildren().length,
|
||||
type: "element" as const,
|
||||
};
|
||||
const selection = $createRangeSelection();
|
||||
selection.anchor.set(point.key, point.offset, point.type);
|
||||
selection.focus.set(point.key, point.offset, point.type);
|
||||
$setSelection(selection);
|
||||
}
|
||||
|
||||
function $readSelectionOffsetFromEditorState(fallback: number): number {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
|
||||
return fallback;
|
||||
}
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
const offset = getAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset);
|
||||
const composerLength = $getComposerRootLength();
|
||||
return Math.max(0, Math.min(offset, composerLength));
|
||||
}
|
||||
|
||||
function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
|
||||
const lines = text.split("\n");
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
const line = lines[index] ?? "";
|
||||
if (line.length > 0) {
|
||||
parent.append($createTextNode(line));
|
||||
}
|
||||
if (index < lines.length - 1) {
|
||||
parent.append($createLineBreakNode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function $setComposerEditorPrompt(prompt: string): void {
|
||||
const root = $getRoot();
|
||||
root.clear();
|
||||
const paragraph = $createParagraphNode();
|
||||
root.append(paragraph);
|
||||
|
||||
const segments = splitPromptIntoComposerSegments(prompt);
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
paragraph.append($createComposerMentionNode(segment.path));
|
||||
continue;
|
||||
}
|
||||
$appendTextWithLineBreaks(paragraph, segment.text);
|
||||
}
|
||||
}
|
||||
|
||||
export interface ComposerPromptEditorHandle {
|
||||
focus: () => void;
|
||||
focusAt: (cursor: number) => void;
|
||||
focusAtEnd: () => void;
|
||||
readSnapshot: () => { value: string; cursor: number };
|
||||
}
|
||||
|
||||
interface ComposerPromptEditorProps {
|
||||
value: string;
|
||||
cursor: number;
|
||||
disabled: boolean;
|
||||
placeholder: string;
|
||||
className?: string;
|
||||
onChange: (nextValue: string, nextCursor: number, cursorAdjacentToMention: boolean) => void;
|
||||
onCommandKeyDown?: (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent,
|
||||
) => boolean;
|
||||
onPaste: ClipboardEventHandler<HTMLElement>;
|
||||
}
|
||||
|
||||
interface ComposerPromptEditorInnerProps extends ComposerPromptEditorProps {
|
||||
editorRef: Ref<ComposerPromptEditorHandle>;
|
||||
}
|
||||
|
||||
function ComposerCommandKeyPlugin(props: {
|
||||
onCommandKeyDown?: (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent,
|
||||
) => boolean;
|
||||
}) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
const handleCommand = (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent | null,
|
||||
): boolean => {
|
||||
if (!props.onCommandKeyDown || !event) {
|
||||
return false;
|
||||
}
|
||||
const handled = props.onCommandKeyDown(key, event);
|
||||
if (handled) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
return handled;
|
||||
};
|
||||
|
||||
const unregisterArrowDown = editor.registerCommand(
|
||||
KEY_ARROW_DOWN_COMMAND,
|
||||
(event) => handleCommand("ArrowDown", event),
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
const unregisterArrowUp = editor.registerCommand(
|
||||
KEY_ARROW_UP_COMMAND,
|
||||
(event) => handleCommand("ArrowUp", event),
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
const unregisterEnter = editor.registerCommand(
|
||||
KEY_ENTER_COMMAND,
|
||||
(event) => handleCommand("Enter", event),
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
const unregisterTab = editor.registerCommand(
|
||||
KEY_TAB_COMMAND,
|
||||
(event) => handleCommand("Tab", event),
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
|
||||
return () => {
|
||||
unregisterArrowDown();
|
||||
unregisterArrowUp();
|
||||
unregisterEnter();
|
||||
unregisterTab();
|
||||
};
|
||||
}, [editor, props]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionArrowPlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
const unregisterLeft = editor.registerCommand(
|
||||
KEY_ARROW_LEFT_COMMAND,
|
||||
(event) => {
|
||||
let nextOffset: number | null = null;
|
||||
editor.getEditorState().read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
const currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
if (currentOffset <= 0) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "left")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset - 1;
|
||||
});
|
||||
if (nextOffset === null) return false;
|
||||
const selectionOffset = nextOffset;
|
||||
event?.preventDefault();
|
||||
event?.stopPropagation();
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(selectionOffset);
|
||||
});
|
||||
return true;
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
const unregisterRight = editor.registerCommand(
|
||||
KEY_ARROW_RIGHT_COMMAND,
|
||||
(event) => {
|
||||
let nextOffset: number | null = null;
|
||||
editor.getEditorState().read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
const currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
const composerLength = $getComposerRootLength();
|
||||
if (currentOffset >= composerLength) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "right")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset + 1;
|
||||
});
|
||||
if (nextOffset === null) return false;
|
||||
const selectionOffset = nextOffset;
|
||||
event?.preventDefault();
|
||||
event?.stopPropagation();
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(selectionOffset);
|
||||
});
|
||||
return true;
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
return () => {
|
||||
unregisterLeft();
|
||||
unregisterRight();
|
||||
};
|
||||
}, [editor]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionSelectionNormalizePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerUpdateListener(({ editorState }) => {
|
||||
let afterOffset: number | null = null;
|
||||
editorState.read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
if (!(anchorNode instanceof ComposerMentionNode)) return;
|
||||
if (selection.anchor.offset === 0) return;
|
||||
const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
|
||||
afterOffset = beforeOffset + 1;
|
||||
});
|
||||
if (afterOffset !== null) {
|
||||
queueMicrotask(() => {
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(afterOffset!);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}, [editor]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionBackspacePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerCommand(
|
||||
KEY_BACKSPACE_COMMAND,
|
||||
(event) => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
const removeMentionNode = (candidate: unknown): boolean => {
|
||||
if (!(candidate instanceof ComposerMentionNode)) {
|
||||
return false;
|
||||
}
|
||||
const mentionStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||
candidate.remove();
|
||||
$setSelectionAtComposerOffset(mentionStart);
|
||||
event?.preventDefault();
|
||||
return true;
|
||||
};
|
||||
|
||||
if (removeMentionNode(anchorNode)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($isTextNode(anchorNode)) {
|
||||
if (selection.anchor.offset > 0) {
|
||||
return false;
|
||||
}
|
||||
if (removeMentionNode(anchorNode.getPreviousSibling())) {
|
||||
return true;
|
||||
}
|
||||
const parent = anchorNode.getParent();
|
||||
if ($isElementNode(parent)) {
|
||||
const index = anchorNode.getIndexWithinParent();
|
||||
if (index > 0 && removeMentionNode(parent.getChildAtIndex(index - 1))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($isElementNode(anchorNode)) {
|
||||
const childIndex = selection.anchor.offset - 1;
|
||||
if (childIndex >= 0 && removeMentionNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
}, [editor]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerPromptEditorInner({
|
||||
value,
|
||||
cursor,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
editorRef,
|
||||
}: ComposerPromptEditorInnerProps) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const onChangeRef = useRef(onChange);
|
||||
const snapshotRef = useRef({ value, cursor: clampCursor(value, cursor) });
|
||||
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
useEffect(() => {
|
||||
editor.setEditable(!disabled);
|
||||
}, [disabled, editor]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const normalizedCursor = clampCursor(value, cursor);
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (previousSnapshot.value !== value) {
|
||||
editor.update(() => {
|
||||
$setComposerEditorPrompt(value);
|
||||
});
|
||||
}
|
||||
|
||||
snapshotRef.current = { value, cursor: normalizedCursor };
|
||||
|
||||
const rootElement = editor.getRootElement();
|
||||
if (!rootElement || document.activeElement !== rootElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
});
|
||||
}, [cursor, editor, value]);
|
||||
|
||||
const focusAt = useCallback(
|
||||
(nextCursor: number) => {
|
||||
const rootElement = editor.getRootElement();
|
||||
if (!rootElement) return;
|
||||
const boundedCursor = clampCursor(snapshotRef.current.value, nextCursor);
|
||||
rootElement.focus();
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(boundedCursor);
|
||||
});
|
||||
snapshotRef.current = {
|
||||
value: snapshotRef.current.value,
|
||||
cursor: boundedCursor,
|
||||
};
|
||||
onChangeRef.current(snapshotRef.current.value, boundedCursor, false);
|
||||
},
|
||||
[editor],
|
||||
);
|
||||
|
||||
const readSnapshot = useCallback((): { value: string; cursor: number } => {
|
||||
let snapshot = snapshotRef.current;
|
||||
editor.getEditorState().read(() => {
|
||||
const nextValue = $getRoot().getTextContent();
|
||||
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
|
||||
const nextCursor = clampCursor(
|
||||
nextValue,
|
||||
$readSelectionOffsetFromEditorState(fallbackCursor),
|
||||
);
|
||||
snapshot = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
};
|
||||
});
|
||||
snapshotRef.current = snapshot;
|
||||
return snapshot;
|
||||
}, [editor]);
|
||||
|
||||
useImperativeHandle(
|
||||
editorRef,
|
||||
() => ({
|
||||
focus: () => {
|
||||
focusAt(snapshotRef.current.cursor);
|
||||
},
|
||||
focusAt: (nextCursor: number) => {
|
||||
focusAt(nextCursor);
|
||||
},
|
||||
focusAtEnd: () => {
|
||||
focusAt(snapshotRef.current.value.length);
|
||||
},
|
||||
readSnapshot,
|
||||
}),
|
||||
[focusAt, readSnapshot],
|
||||
);
|
||||
|
||||
const handleEditorChange = useCallback((editorState: EditorState) => {
|
||||
editorState.read(() => {
|
||||
const nextValue = $getRoot().getTextContent();
|
||||
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
|
||||
const nextCursor = clampCursor(nextValue, $readSelectionOffsetFromEditorState(fallbackCursor));
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {
|
||||
return;
|
||||
}
|
||||
snapshotRef.current = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
};
|
||||
const cursorAdjacentToMention =
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(nextValue, nextCursor, cursorAdjacentToMention);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<PlainTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className={cn(
|
||||
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
|
||||
className,
|
||||
)}
|
||||
aria-placeholder={placeholder}
|
||||
placeholder={<span />}
|
||||
onPaste={onPaste}
|
||||
/>
|
||||
}
|
||||
placeholder={
|
||||
<div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
|
||||
{placeholder}
|
||||
</div>
|
||||
}
|
||||
ErrorBoundary={LexicalErrorBoundary}
|
||||
/>
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerMentionArrowPlugin />
|
||||
<ComposerMentionSelectionNormalizePlugin />
|
||||
<ComposerMentionBackspacePlugin />
|
||||
<HistoryPlugin />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const ComposerPromptEditor = forwardRef<ComposerPromptEditorHandle, ComposerPromptEditorProps>(
|
||||
function ComposerPromptEditor(
|
||||
{ value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
|
||||
ref,
|
||||
) {
|
||||
const initialValueRef = useRef(value);
|
||||
const initialConfig = useMemo<InitialConfigType>(
|
||||
() => ({
|
||||
namespace: "t3tools-composer-editor",
|
||||
editable: true,
|
||||
nodes: [ComposerMentionNode],
|
||||
editorState: () => {
|
||||
$setComposerEditorPrompt(initialValueRef.current);
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>
|
||||
<ComposerPromptEditorInner
|
||||
value={value}
|
||||
cursor={cursor}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onChange={onChange}
|
||||
onPaste={onPaste}
|
||||
editorRef={ref}
|
||||
{...(onCommandKeyDown ? { onCommandKeyDown } : {})}
|
||||
{...(className ? { className } : {})}
|
||||
/>
|
||||
</LexicalComposer>
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -4,11 +4,9 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor, resolvePathLinkTarget } from "../terminal-links";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
@@ -60,29 +58,6 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
border-block-color: var(--border) !important;
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
|
||||
[data-diffs-header] {
|
||||
position: sticky !important;
|
||||
top: 0;
|
||||
z-index: 4;
|
||||
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||
border-bottom: 1px solid var(--border) !important;
|
||||
}
|
||||
|
||||
[data-title] {
|
||||
cursor: pointer;
|
||||
transition:
|
||||
color 120ms ease,
|
||||
text-decoration-color 120ms ease;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: transparent;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
[data-title]:hover {
|
||||
color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
|
||||
text-decoration-color: currentColor;
|
||||
}
|
||||
`;
|
||||
|
||||
type RenderablePatch =
|
||||
@@ -156,6 +131,7 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { state } = useStore();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
@@ -167,14 +143,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
});
|
||||
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = useStore((store) =>
|
||||
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
|
||||
);
|
||||
const activeProjectId = activeThread?.projectId ?? null;
|
||||
const activeProject = useStore((store) =>
|
||||
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
|
||||
);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
@@ -295,18 +264,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
target?.scrollIntoView({ block: "nearest" });
|
||||
}, [selectedFilePath, renderableFiles]);
|
||||
|
||||
const openDiffFileInEditor = useCallback(
|
||||
(filePath: string) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
|
||||
void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
|
||||
console.warn("Failed to open diff file in editor.", error);
|
||||
});
|
||||
},
|
||||
[activeCwd],
|
||||
);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!activeThread) return;
|
||||
void navigate({
|
||||
@@ -346,7 +303,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
if (!element) return;
|
||||
element.scrollBy({ left: offset, behavior: "smooth" });
|
||||
}, []);
|
||||
const onTurnStripWheel = useCallback((event: ReactWheelEvent<HTMLDivElement>) => {
|
||||
const onTurnStripWheel = useCallback((event: WheelEvent) => {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
if (element.scrollWidth <= element.clientWidth + 1) return;
|
||||
@@ -360,26 +317,24 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const element = turnStripRef.current;
|
||||
if (!element) return;
|
||||
|
||||
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
|
||||
updateTurnStripScrollState();
|
||||
const onScroll = () => updateTurnStripScrollState();
|
||||
|
||||
element.addEventListener("scroll", onScroll, { passive: true });
|
||||
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
|
||||
resizeObserver.observe(element);
|
||||
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
element.removeEventListener("scroll", onScroll);
|
||||
element.removeEventListener("wheel", onTurnStripWheel);
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [updateTurnStripScrollState]);
|
||||
}, [updateTurnStripScrollState, onTurnStripWheel]);
|
||||
|
||||
useEffect(() => {
|
||||
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
};
|
||||
updateTurnStripScrollState();
|
||||
}, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -428,11 +383,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
>
|
||||
<ChevronRightIcon className="size-3.5" />
|
||||
</button>
|
||||
<div
|
||||
ref={turnStripRef}
|
||||
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
|
||||
onWheel={onTurnStripWheel}
|
||||
>
|
||||
<div ref={turnStripRef} className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5">
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 rounded-md"
|
||||
@@ -557,7 +508,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : renderablePatch.kind === "files" ? (
|
||||
<Virtualizer
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto px-3 py-2"
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
@@ -571,17 +522,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div
|
||||
key={themedFileKey}
|
||||
data-diff-file-path={filePath}
|
||||
className="diff-render-file mb-2 rounded-md first:mt-2 last:mb-0"
|
||||
onClickCapture={(event) => {
|
||||
const nativeEvent = event.nativeEvent as MouseEvent;
|
||||
const composedPath = nativeEvent.composedPath?.() ?? [];
|
||||
const clickedHeader = composedPath.some((node) => {
|
||||
if (!(node instanceof Element)) return false;
|
||||
return node.hasAttribute("data-title");
|
||||
});
|
||||
if (!clickedHeader) return;
|
||||
openDiffFileInEditor(filePath);
|
||||
}}
|
||||
className="diff-render-file rounded-md"
|
||||
>
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
@@ -598,7 +539,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
})}
|
||||
</Virtualizer>
|
||||
) : (
|
||||
<div className="h-full overflow-auto p-2">
|
||||
<div className="h-full overflow-auto px-3 py-2">
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
||||
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
|
||||
|
||||
@@ -4,8 +4,6 @@ import {
|
||||
buildGitActionProgressStages,
|
||||
buildMenuItems,
|
||||
requiresDefaultBranchConfirmation,
|
||||
resolveAutoFeatureBranchName,
|
||||
resolveDefaultBranchActionDialogCopy,
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
} from "./GitActionsControl.logic";
|
||||
@@ -516,20 +514,19 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
||||
});
|
||||
|
||||
describe("when: branch has no upstream configured", () => {
|
||||
it("resolveQuickAction is disabled when clean, no upstream, and no local commits are ahead", () => {
|
||||
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "show_hint",
|
||||
label: "Push",
|
||||
hint: "No local commits to push.",
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveQuickAction opens PR when clean, no upstream, no local commits are ahead, and PR exists", () => {
|
||||
it("resolveQuickAction remains disabled when clean, no upstream, and no local commits ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
@@ -546,9 +543,9 @@ describe("when: branch has no upstream configured", () => {
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "open_pr",
|
||||
label: "Open PR",
|
||||
disabled: false,
|
||||
kind: "show_hint",
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -608,136 +605,10 @@ describe("when: branch has no upstream configured", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("resolveQuickAction runs push and create PR when no upstream and commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 2,
|
||||
pr: null,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
label: "Push & create PR",
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("buildMenuItems enables create PR when no upstream and commits are ahead", () => {
|
||||
const items = buildMenuItems(
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
icon: "commit",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
},
|
||||
{
|
||||
id: "push",
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
icon: "push",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "push",
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Create PR",
|
||||
disabled: false,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "create_pr",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("resolveQuickAction is disabled on default branch when no upstream exists and no commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
branch: "main",
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "show_hint",
|
||||
label: "Push",
|
||||
hint: "No local commits to push.",
|
||||
disabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveQuickAction uses push-only on default branch when no upstream exists and commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
branch: "main",
|
||||
hasUpstream: false,
|
||||
aheadCount: 1,
|
||||
pr: null,
|
||||
}),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "run_action",
|
||||
action: "commit_push",
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("buildMenuItems still disables push and create PR when branch is behind", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
behindCount: 1,
|
||||
aheadCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
icon: "commit",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
},
|
||||
{
|
||||
id: "push",
|
||||
label: "Push",
|
||||
disabled: true,
|
||||
icon: "push",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "push",
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Create PR",
|
||||
disabled: true,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "create_pr",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("requiresDefaultBranchConfirmation", () => {
|
||||
it("requires confirmation for push actions on default branch", () => {
|
||||
it("requires confirmation only for push actions on default branch", () => {
|
||||
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
|
||||
assert.isTrue(requiresDefaultBranchConfirmation("commit_push", true));
|
||||
assert.isTrue(requiresDefaultBranchConfirmation("commit_push_pr", true));
|
||||
@@ -745,53 +616,6 @@ describe("requiresDefaultBranchConfirmation", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
it("uses push-only copy when pushing without a commit", () => {
|
||||
const copy = resolveDefaultBranchActionDialogCopy({
|
||||
action: "commit_push",
|
||||
branchName: "main",
|
||||
includesCommit: false,
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Push to default branch?",
|
||||
description:
|
||||
'This action will push local commits on "main". You can continue on this branch or create a feature branch and run the same action there.',
|
||||
continueLabel: "Push to main",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses push-and-pr copy when creating a PR without a commit", () => {
|
||||
const copy = resolveDefaultBranchActionDialogCopy({
|
||||
action: "commit_push_pr",
|
||||
branchName: "main",
|
||||
includesCommit: false,
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Push & create PR from default branch?",
|
||||
description:
|
||||
'This action will push local commits and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
|
||||
continueLabel: "Push & create PR",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps commit copy when the action includes a commit", () => {
|
||||
const copy = resolveDefaultBranchActionDialogCopy({
|
||||
action: "commit_push_pr",
|
||||
branchName: "main",
|
||||
includesCommit: true,
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Commit, push & create PR from default branch?",
|
||||
description:
|
||||
'This action will commit, push, and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
|
||||
continueLabel: "Commit, push & create PR",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGitActionProgressStages", () => {
|
||||
it("shows only push progress when push-only is forced", () => {
|
||||
const stages = buildGitActionProgressStages({
|
||||
@@ -804,17 +628,6 @@ describe("buildGitActionProgressStages", () => {
|
||||
assert.deepEqual(stages, ["Pushing to origin/feature/test..."]);
|
||||
});
|
||||
|
||||
it("skips commit stages for create-pr flow when push-only is forced", () => {
|
||||
const stages = buildGitActionProgressStages({
|
||||
action: "commit_push_pr",
|
||||
hasCustomCommitMessage: false,
|
||||
hasWorkingTreeChanges: true,
|
||||
forcePushOnly: true,
|
||||
pushTarget: "origin/feature/test",
|
||||
});
|
||||
assert.deepEqual(stages, ["Pushing to origin/feature/test...", "Creating PR..."]);
|
||||
});
|
||||
|
||||
it("includes commit stages for commit+push when working tree is dirty", () => {
|
||||
const stages = buildGitActionProgressStages({
|
||||
action: "commit_push",
|
||||
@@ -834,7 +647,6 @@ describe("summarizeGitResult", () => {
|
||||
it("returns commit-focused toast for commit action", () => {
|
||||
const result = summarizeGitResult({
|
||||
action: "commit",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "0123456789abcdef",
|
||||
@@ -853,7 +665,6 @@ describe("summarizeGitResult", () => {
|
||||
it("returns push-focused toast for push action", () => {
|
||||
const result = summarizeGitResult({
|
||||
action: "commit_push",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "abcdef0123456789",
|
||||
@@ -876,7 +687,6 @@ describe("summarizeGitResult", () => {
|
||||
it("returns PR-focused toast for created PR action", () => {
|
||||
const result = summarizeGitResult({
|
||||
action: "commit_push_pr",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "89abcdef01234567",
|
||||
@@ -902,7 +712,6 @@ describe("summarizeGitResult", () => {
|
||||
it("truncates long description text", () => {
|
||||
const result = summarizeGitResult({
|
||||
action: "commit_push_pr",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "89abcdef01234567",
|
||||
@@ -923,33 +732,3 @@ describe("summarizeGitResult", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAutoFeatureBranchName", () => {
|
||||
it("uses semantic preferred branch names when available", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
|
||||
assert.equal(branch, "feature/fix-toast-copy");
|
||||
});
|
||||
|
||||
it("normalizes preferred names that already include a branch namespace", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main"], "feature/refine-toolbar-actions");
|
||||
assert.equal(branch, "feature/refine-toolbar-actions");
|
||||
});
|
||||
|
||||
it("increments suffix when the preferred branch name already exists", () => {
|
||||
const branch = resolveAutoFeatureBranchName(
|
||||
["main", "feature/fix-toast-copy", "feature/fix-toast-copy-2"],
|
||||
"fix toast copy",
|
||||
);
|
||||
assert.equal(branch, "feature/fix-toast-copy-3");
|
||||
});
|
||||
|
||||
it("treats existing branch names as case-insensitive for collision checks", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["Feature/Ticket-1"], "feature/ticket-1");
|
||||
assert.equal(branch, "feature/ticket-1-2");
|
||||
});
|
||||
|
||||
it("falls back to feature/update when no preferred name is provided", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main"]);
|
||||
assert.equal(branch, "feature/update");
|
||||
});
|
||||
});
|
||||
@@ -25,14 +25,6 @@ export interface GitQuickAction {
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
export interface DefaultBranchActionDialogCopy {
|
||||
title: string;
|
||||
description: string;
|
||||
continueLabel: string;
|
||||
}
|
||||
|
||||
export type DefaultBranchConfirmableAction = "commit_push" | "commit_push_pr";
|
||||
|
||||
const SHORT_SHA_LENGTH = 7;
|
||||
const TOAST_DESCRIPTION_MAX = 72;
|
||||
|
||||
@@ -57,9 +49,7 @@ export function buildGitActionProgressStages(input: {
|
||||
hasWorkingTreeChanges: boolean;
|
||||
forcePushOnly?: boolean;
|
||||
pushTarget?: string;
|
||||
featureBranch?: boolean;
|
||||
}): string[] {
|
||||
const branchStages = input.featureBranch ? ["Preparing feature branch..."] : [];
|
||||
const shouldIncludeCommitStages =
|
||||
!input.forcePushOnly && (input.action === "commit" || input.hasWorkingTreeChanges);
|
||||
const commitStages = !shouldIncludeCommitStages
|
||||
@@ -69,12 +59,12 @@ export function buildGitActionProgressStages(input: {
|
||||
: ["Generating commit message...", "Committing..."];
|
||||
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
|
||||
if (input.action === "commit") {
|
||||
return [...branchStages, ...commitStages];
|
||||
return commitStages;
|
||||
}
|
||||
if (input.action === "commit_push") {
|
||||
return [...branchStages, ...commitStages, pushStage];
|
||||
return [...commitStages, pushStage];
|
||||
}
|
||||
return [...branchStages, ...commitStages, pushStage, "Creating PR..."];
|
||||
return [...commitStages, pushStage, "Creating PR..."];
|
||||
}
|
||||
|
||||
const withDescription = (title: string, description: string | undefined) =>
|
||||
@@ -128,6 +118,7 @@ export function buildMenuItems(
|
||||
!hasChanges &&
|
||||
!hasOpenPr &&
|
||||
gitStatus.aheadCount > 0 &&
|
||||
gitStatus.hasUpstream &&
|
||||
!isBehind;
|
||||
const canOpenPr = !isBusy && hasOpenPr;
|
||||
|
||||
@@ -213,29 +204,6 @@ export function resolveQuickAction(
|
||||
};
|
||||
}
|
||||
|
||||
if (!gitStatus.hasUpstream) {
|
||||
if (!isAhead) {
|
||||
if (hasOpenPr) {
|
||||
return { label: "Open PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: "No local commits to push.",
|
||||
};
|
||||
}
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
|
||||
}
|
||||
return {
|
||||
label: "Push & create PR",
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
};
|
||||
}
|
||||
|
||||
if (isDiverged) {
|
||||
return {
|
||||
label: "Sync branch",
|
||||
@@ -284,43 +252,3 @@ export function requiresDefaultBranchConfirmation(
|
||||
if (!isDefaultBranch) return false;
|
||||
return action === "commit_push" || action === "commit_push_pr";
|
||||
}
|
||||
|
||||
export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
action: DefaultBranchConfirmableAction;
|
||||
branchName: string;
|
||||
includesCommit: boolean;
|
||||
}): DefaultBranchActionDialogCopy {
|
||||
const branchLabel = input.branchName;
|
||||
const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`;
|
||||
|
||||
if (input.action === "commit_push") {
|
||||
if (input.includesCommit) {
|
||||
return {
|
||||
title: "Commit & push to default branch?",
|
||||
description: `This action will commit and push changes${suffix}`,
|
||||
continueLabel: `Commit & push to ${branchLabel}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: "Push to default branch?",
|
||||
description: `This action will push local commits${suffix}`,
|
||||
continueLabel: `Push to ${branchLabel}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (input.includesCommit) {
|
||||
return {
|
||||
title: "Commit, push & create PR from default branch?",
|
||||
description: `This action will commit, push, and create a PR${suffix}`,
|
||||
continueLabel: `Commit, push & create PR`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: "Push & create PR from default branch?",
|
||||
description: `This action will push local commits and create a PR${suffix}`,
|
||||
continueLabel: "Push & create PR",
|
||||
};
|
||||
}
|
||||
|
||||
// Re-export from shared for backwards compatibility in this module's exports
|
||||
export { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
|
||||
import { type GitStatusResult, type GitStackedAction, type ThreadId } from "@t3tools/contracts";
|
||||
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||
@@ -8,10 +8,9 @@ import {
|
||||
buildMenuItems,
|
||||
type GitActionIconName,
|
||||
type GitActionMenuItem,
|
||||
type GitDialogAction,
|
||||
type GitQuickAction,
|
||||
type DefaultBranchConfirmableAction,
|
||||
requiresDefaultBranchConfirmation,
|
||||
resolveDefaultBranchActionDialogCopy,
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
} from "./GitActionsControl.logic";
|
||||
@@ -48,17 +47,6 @@ interface GitActionsControlProps {
|
||||
activeThreadId: ThreadId | null;
|
||||
}
|
||||
|
||||
interface PendingDefaultBranchAction {
|
||||
action: DefaultBranchConfirmableAction;
|
||||
branchName: string;
|
||||
includesCommit: boolean;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress: boolean;
|
||||
onConfirmed?: () => void;
|
||||
}
|
||||
|
||||
type GitActionToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
function getMenuActionDisabledReason(
|
||||
item: GitActionMenuItem,
|
||||
gitStatus: GitStatusResult | null,
|
||||
@@ -109,15 +97,26 @@ function getMenuActionDisabledReason(
|
||||
if (!isAhead) {
|
||||
return "No local commits to include in a PR.";
|
||||
}
|
||||
if (!gitStatus.hasUpstream) {
|
||||
return "Set an upstream branch before creating a PR.";
|
||||
}
|
||||
if (isBehind) {
|
||||
return "Branch is behind upstream. Pull/rebase before creating a PR.";
|
||||
}
|
||||
return "Create PR is currently unavailable.";
|
||||
}
|
||||
|
||||
const COMMIT_DIALOG_TITLE = "Commit changes";
|
||||
const COMMIT_DIALOG_DESCRIPTION =
|
||||
"Review and confirm your commit. Leave the message blank to auto-generate one.";
|
||||
const DIALOG_TITLE_BY_ACTION = {
|
||||
commit: "Commit changes",
|
||||
push: "Push branch",
|
||||
create_pr: "Create pull request",
|
||||
};
|
||||
|
||||
const DIALOG_DESCRIPTION_BY_ACTION = {
|
||||
commit: "Review and confirm your commit. Leave the message blank to auto-generate one.",
|
||||
push: "Push this branch now.",
|
||||
create_pr: "Create a pull request using generated title/body content.",
|
||||
};
|
||||
|
||||
function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
|
||||
if (icon === "commit") return <GitCommitIcon />;
|
||||
@@ -144,10 +143,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
[activeThreadId],
|
||||
);
|
||||
const queryClient = useQueryClient();
|
||||
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
|
||||
const [activeDialogAction, setActiveDialogAction] = useState<GitDialogAction | null>(null);
|
||||
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
||||
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
|
||||
useState<PendingDefaultBranchAction | null>(null);
|
||||
|
||||
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
|
||||
|
||||
@@ -194,13 +191,23 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const quickActionDisabledReason = quickAction.disabled
|
||||
? (quickAction.hint ?? "This action is currently unavailable.")
|
||||
: null;
|
||||
const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
|
||||
? resolveDefaultBranchActionDialogCopy({
|
||||
action: pendingDefaultBranchAction.action,
|
||||
branchName: pendingDefaultBranchAction.branchName,
|
||||
includesCommit: pendingDefaultBranchAction.includesCommit,
|
||||
})
|
||||
: null;
|
||||
|
||||
const maybeConfirmPushToDefaultBranch = useCallback(
|
||||
async (action: GitStackedAction): Promise<boolean> => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return false;
|
||||
if (
|
||||
!requiresDefaultBranchConfirmation(action, isDefaultBranch) ||
|
||||
!gitStatusForActions?.branch
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return api.dialogs.confirm(
|
||||
`You're about to push to the default branch "${gitStatusForActions.branch}". Continue?`,
|
||||
);
|
||||
},
|
||||
[gitStatusForActions?.branch, isDefaultBranch],
|
||||
);
|
||||
|
||||
const openExistingPr = useCallback(async () => {
|
||||
const api = readNativeApi();
|
||||
@@ -230,85 +237,43 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
});
|
||||
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
||||
|
||||
const runGitActionWithToast = useCallback(
|
||||
async ({
|
||||
action,
|
||||
commitMessage,
|
||||
forcePushOnlyProgress = false,
|
||||
onConfirmed,
|
||||
skipDefaultBranchPrompt = false,
|
||||
statusOverride,
|
||||
featureBranch = false,
|
||||
isDefaultBranchOverride,
|
||||
progressToastId,
|
||||
}: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
skipDefaultBranchPrompt?: boolean;
|
||||
statusOverride?: GitStatusResult | null;
|
||||
featureBranch?: boolean;
|
||||
isDefaultBranchOverride?: boolean;
|
||||
progressToastId?: GitActionToastId;
|
||||
}) => {
|
||||
const actionStatus = statusOverride ?? gitStatusForActions;
|
||||
const actionBranch = actionStatus?.branch ?? null;
|
||||
const actionIsDefaultBranch = isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);
|
||||
const includesCommit =
|
||||
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
|
||||
if (
|
||||
!skipDefaultBranchPrompt &&
|
||||
requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
|
||||
actionBranch
|
||||
) {
|
||||
if (action !== "commit_push" && action !== "commit_push_pr") {
|
||||
return;
|
||||
}
|
||||
setPendingDefaultBranchAction({
|
||||
action,
|
||||
branchName: actionBranch,
|
||||
includesCommit,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const confirmed = await maybeConfirmPushToDefaultBranch(action);
|
||||
if (!confirmed) return;
|
||||
onConfirmed?.();
|
||||
|
||||
const pushTarget = !featureBranch && actionBranch ? `origin/${actionBranch}` : undefined;
|
||||
const pushTarget = gitStatusForActions?.branch
|
||||
? `origin/${gitStatusForActions.branch}`
|
||||
: undefined;
|
||||
const progressStages = buildGitActionProgressStages({
|
||||
action,
|
||||
hasCustomCommitMessage: !!commitMessage?.trim(),
|
||||
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
|
||||
hasWorkingTreeChanges: !!gitStatusForActions?.hasWorkingTreeChanges,
|
||||
forcePushOnly: forcePushOnlyProgress,
|
||||
featureBranch,
|
||||
...(pushTarget ? { pushTarget } : {}),
|
||||
});
|
||||
const resolvedProgressToastId =
|
||||
progressToastId ??
|
||||
toastManager.add({
|
||||
type: "loading",
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
|
||||
if (progressToastId) {
|
||||
toastManager.update(progressToastId, {
|
||||
type: "loading",
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
}
|
||||
const progressToastId = toastManager.add({
|
||||
type: "loading",
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
|
||||
let stageIndex = 0;
|
||||
const stageInterval = setInterval(() => {
|
||||
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
toastManager.update(progressToastId, {
|
||||
title: progressStages[stageIndex] ?? "Running git action...",
|
||||
type: "loading",
|
||||
timeout: 0,
|
||||
@@ -323,7 +288,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const promise = runImmediateGitActionMutation.mutateAsync({
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -331,25 +295,19 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
stopProgressUpdates();
|
||||
const resultToast = summarizeGitResult(result);
|
||||
|
||||
const existingOpenPrUrl = actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
|
||||
const existingOpenPrUrl =
|
||||
gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : undefined;
|
||||
const prUrl = result.pr.url ?? existingOpenPrUrl;
|
||||
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
|
||||
const shouldOfferOpenPrCta =
|
||||
(action === "commit_push" || action === "commit_push_pr") &&
|
||||
!!prUrl &&
|
||||
(!actionIsDefaultBranch ||
|
||||
result.pr.status === "created" ||
|
||||
result.pr.status === "opened_existing");
|
||||
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
|
||||
const shouldOfferCreatePrCta =
|
||||
action === "commit_push" &&
|
||||
!prUrl &&
|
||||
result.push.status === "pushed" &&
|
||||
!actionIsDefaultBranch;
|
||||
action === "commit_push" && !prUrl && result.push.status === "pushed" && !isDefaultBranch;
|
||||
const closeResultToast = () => {
|
||||
toastManager.close(resolvedProgressToastId);
|
||||
toastManager.close(progressToastId);
|
||||
};
|
||||
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
toastManager.update(progressToastId, {
|
||||
type: "success",
|
||||
title: resultToast.title,
|
||||
description: resultToast.description,
|
||||
@@ -367,8 +325,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
action: "commit_push",
|
||||
forcePushOnlyProgress: true,
|
||||
onConfirmed: closeResultToast,
|
||||
statusOverride: actionStatus,
|
||||
isDefaultBranchOverride: actionIsDefaultBranch,
|
||||
});
|
||||
},
|
||||
},
|
||||
@@ -391,12 +347,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
children: "Create PR",
|
||||
onClick: () => {
|
||||
closeResultToast();
|
||||
void runGitActionWithToast({
|
||||
action: "commit_push_pr",
|
||||
forcePushOnlyProgress: true,
|
||||
statusOverride: actionStatus,
|
||||
isDefaultBranchOverride: actionIsDefaultBranch,
|
||||
});
|
||||
setActiveDialogAction("create_pr");
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -404,7 +355,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
} catch (err) {
|
||||
stopProgressUpdates();
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
toastManager.update(progressToastId, {
|
||||
type: "error",
|
||||
title: "Action failed",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
@@ -414,68 +365,17 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
},
|
||||
|
||||
[
|
||||
gitStatusForActions?.branch,
|
||||
gitStatusForActions?.hasWorkingTreeChanges,
|
||||
gitStatusForActions?.pr,
|
||||
isDefaultBranch,
|
||||
maybeConfirmPushToDefaultBranch,
|
||||
runImmediateGitActionMutation,
|
||||
setPendingDefaultBranchAction,
|
||||
setActiveDialogAction,
|
||||
threadToastData,
|
||||
gitStatusForActions,
|
||||
],
|
||||
);
|
||||
|
||||
const continuePendingDefaultBranchAction = useCallback(() => {
|
||||
if (!pendingDefaultBranchAction) return;
|
||||
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
|
||||
setPendingDefaultBranchAction(null);
|
||||
void runGitActionWithToast({
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
}, [pendingDefaultBranchAction, runGitActionWithToast]);
|
||||
|
||||
const checkoutNewBranchAndRunAction = useCallback(
|
||||
(actionParams: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
}) => {
|
||||
void runGitActionWithToast({
|
||||
...actionParams,
|
||||
featureBranch: true,
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
},
|
||||
[runGitActionWithToast],
|
||||
);
|
||||
|
||||
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
|
||||
if (!pendingDefaultBranchAction) return;
|
||||
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
|
||||
setPendingDefaultBranchAction(null);
|
||||
checkoutNewBranchAndRunAction({
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
});
|
||||
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
|
||||
|
||||
const runDialogActionOnNewBranch = useCallback(() => {
|
||||
if (!isCommitDialogOpen) return;
|
||||
const commitMessage = dialogCommitMessage.trim();
|
||||
|
||||
setIsCommitDialogOpen(false);
|
||||
setDialogCommitMessage("");
|
||||
|
||||
checkoutNewBranchAndRunAction({
|
||||
action: "commit",
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
});
|
||||
}, [isCommitDialogOpen, dialogCommitMessage, checkoutNewBranchAndRunAction]);
|
||||
|
||||
const runQuickAction = useCallback(() => {
|
||||
if (quickAction.kind === "open_pr") {
|
||||
void openExistingPr();
|
||||
@@ -527,31 +427,30 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
|
||||
return;
|
||||
}
|
||||
if (item.dialogAction === "create_pr") {
|
||||
void runGitActionWithToast({ action: "commit_push_pr" });
|
||||
return;
|
||||
if (item.dialogAction) {
|
||||
setActiveDialogAction(item.dialogAction);
|
||||
}
|
||||
setIsCommitDialogOpen(true);
|
||||
},
|
||||
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
|
||||
[openExistingPr, runGitActionWithToast],
|
||||
);
|
||||
|
||||
const runDialogAction = useCallback(() => {
|
||||
if (!isCommitDialogOpen) return;
|
||||
const commitMessage = dialogCommitMessage.trim();
|
||||
setIsCommitDialogOpen(false);
|
||||
setDialogCommitMessage("");
|
||||
if (!activeDialogAction) return;
|
||||
const action: GitStackedAction =
|
||||
activeDialogAction === "commit"
|
||||
? "commit"
|
||||
: activeDialogAction === "push"
|
||||
? "commit_push"
|
||||
: "commit_push_pr";
|
||||
const commitMessage = activeDialogAction === "commit" ? dialogCommitMessage.trim() : "";
|
||||
const forcePushOnlyProgress = activeDialogAction === "push";
|
||||
setActiveDialogAction(null);
|
||||
void runGitActionWithToast({
|
||||
action: "commit",
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(forcePushOnlyProgress ? { forcePushOnlyProgress } : {}),
|
||||
});
|
||||
}, [
|
||||
dialogCommitMessage,
|
||||
isCommitDialogOpen,
|
||||
runGitActionWithToast,
|
||||
setDialogCommitMessage,
|
||||
setIsCommitDialogOpen,
|
||||
]);
|
||||
}, [activeDialogAction, dialogCommitMessage, runGitActionWithToast]);
|
||||
|
||||
const openChangedFileInEditor = useCallback(
|
||||
(filePath: string) => {
|
||||
@@ -707,29 +606,68 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
open={isCommitDialogOpen}
|
||||
open={activeDialogAction !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setIsCommitDialogOpen(false);
|
||||
setActiveDialogAction(null);
|
||||
setDialogCommitMessage("");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogPopup>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
|
||||
<DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
|
||||
<DialogTitle>{DIALOG_TITLE_BY_ACTION[activeDialogAction ?? "commit"]}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{DIALOG_DESCRIPTION_BY_ACTION[activeDialogAction ?? "commit"]}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-4">
|
||||
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
|
||||
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
|
||||
<span className="text-muted-foreground">Branch</span>
|
||||
<span className="flex items-center justify-between gap-2">
|
||||
<span className="font-medium">{gitStatusForActions?.branch ?? "(detached HEAD)"}</span>
|
||||
{isDefaultBranch && (
|
||||
<span className="text-right text-warning text-xs">Warning: default branch</span>
|
||||
)}
|
||||
<span className="font-medium">
|
||||
{gitStatusForActions?.branch ?? "(detached HEAD)"}
|
||||
</span>
|
||||
{activeDialogAction !== "commit" && (
|
||||
<>
|
||||
<span className="text-muted-foreground">Upstream</span>
|
||||
<span className="font-medium">
|
||||
{!gitStatusForActions || !gitStatusForActions.hasUpstream
|
||||
? "No upstream configured"
|
||||
: gitStatusForActions.aheadCount === 0 &&
|
||||
gitStatusForActions.behindCount === 0
|
||||
? "Up to date"
|
||||
: gitStatusForActions.aheadCount > 0 &&
|
||||
gitStatusForActions.behindCount > 0
|
||||
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
|
||||
: gitStatusForActions.aheadCount > 0
|
||||
? `Ahead by ${gitStatusForActions.aheadCount}`
|
||||
: `Behind by ${gitStatusForActions.behindCount}`}
|
||||
</span>
|
||||
<span className="text-muted-foreground">Working tree</span>
|
||||
<span className="font-medium">
|
||||
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges
|
||||
? "Clean"
|
||||
: `${gitStatusForActions.workingTree.files.length} file(s)`}
|
||||
</span>
|
||||
<span className="text-muted-foreground">Diff</span>
|
||||
<span className="font-mono">
|
||||
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges ? (
|
||||
"none"
|
||||
) : (
|
||||
<>
|
||||
<span className="text-success">
|
||||
+{gitStatusForActions.workingTree.insertions}
|
||||
</span>
|
||||
<span className="text-muted-foreground"> / </span>
|
||||
<span className="text-destructive">
|
||||
-{gitStatusForActions.workingTree.deletions}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-muted-foreground">Files</p>
|
||||
@@ -769,61 +707,35 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium">Commit message (optional)</p>
|
||||
<Textarea
|
||||
value={dialogCommitMessage}
|
||||
onChange={(event) => setDialogCommitMessage(event.target.value)}
|
||||
placeholder="Leave empty to auto-generate"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
{activeDialogAction === "commit" && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium">Commit message (optional)</p>
|
||||
<Textarea
|
||||
value={dialogCommitMessage}
|
||||
onChange={(event) => setDialogCommitMessage(event.target.value)}
|
||||
placeholder="Leave empty to auto-generate"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setIsCommitDialogOpen(false);
|
||||
setActiveDialogAction(null);
|
||||
setDialogCommitMessage("");
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={runDialogActionOnNewBranch}>
|
||||
Commit on new branch
|
||||
</Button>
|
||||
<Button size="sm" onClick={runDialogAction}>
|
||||
Commit
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={pendingDefaultBranchAction !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setPendingDefaultBranchAction(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" onClick={() => setPendingDefaultBranchAction(null)}>
|
||||
Abort
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={continuePendingDefaultBranchAction}>
|
||||
{pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
|
||||
</Button>
|
||||
<Button size="sm" onClick={checkoutFeatureBranchAndContinuePendingAction}>
|
||||
Checkout feature branch & continue
|
||||
{activeDialogAction === "commit"
|
||||
? "Commit"
|
||||
: activeDialogAction === "push"
|
||||
? "Push"
|
||||
: "Create PR"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type SVGProps, useId } from "react";
|
||||
import type { SVGProps } from "react";
|
||||
|
||||
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
|
||||
|
||||
@@ -19,126 +19,3 @@ export const CursorIcon: Icon = (props) => (
|
||||
<path d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const VisualStudioCode: Icon = (props) => {
|
||||
const id = useId();
|
||||
const maskId = `${id}-vscode-a`;
|
||||
const topShadowFilterId = `${id}-vscode-b`;
|
||||
const sideShadowFilterId = `${id}-vscode-c`;
|
||||
const overlayGradientId = `${id}-vscode-d`;
|
||||
|
||||
return (
|
||||
<svg {...props} fill="none" viewBox="0 0 100 100">
|
||||
<mask id={maskId} width="100" height="100" x="0" y="0" maskUnits="userSpaceOnUse">
|
||||
<path
|
||||
fill="#fff"
|
||||
fillRule="evenodd"
|
||||
d="M70.912 99.317a6.223 6.223 0 0 0 4.96-.19l20.589-9.907A6.25 6.25 0 0 0 100 83.587V16.413a6.25 6.25 0 0 0-3.54-5.632L75.874.874a6.226 6.226 0 0 0-7.104 1.21L29.355 38.04 12.187 25.01a4.162 4.162 0 0 0-5.318.236l-5.506 5.009a4.168 4.168 0 0 0-.004 6.162L16.247 50 1.36 63.583a4.168 4.168 0 0 0 .004 6.162l5.506 5.01a4.162 4.162 0 0 0 5.318.236l17.168-13.032L68.77 97.917a6.217 6.217 0 0 0 2.143 1.4ZM75.015 27.3 45.11 50l29.906 22.701V27.3Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</mask>
|
||||
<g mask={`url(#${maskId})`}>
|
||||
<path
|
||||
fill="#0065A9"
|
||||
d="M96.461 10.796 75.857.876a6.23 6.23 0 0 0-7.107 1.207l-67.451 61.5a4.167 4.167 0 0 0 .004 6.162l5.51 5.009a4.167 4.167 0 0 0 5.32.236l81.228-61.62c2.725-2.067 6.639-.124 6.639 3.297v-.24a6.25 6.25 0 0 0-3.539-5.63Z"
|
||||
/>
|
||||
<g filter={`url(#${topShadowFilterId})`}>
|
||||
<path
|
||||
fill="#007ACC"
|
||||
d="m96.461 89.204-20.604 9.92a6.229 6.229 0 0 1-7.107-1.207l-67.451-61.5a4.167 4.167 0 0 1 .004-6.162l5.51-5.009a4.167 4.167 0 0 1 5.32-.236l81.228 61.62c2.725 2.067 6.639.124 6.639-3.297v.24a6.25 6.25 0 0 1-3.539 5.63Z"
|
||||
/>
|
||||
</g>
|
||||
<g filter={`url(#${sideShadowFilterId})`}>
|
||||
<path
|
||||
fill="#1F9CF0"
|
||||
d="M75.858 99.126a6.232 6.232 0 0 1-7.108-1.21c2.306 2.307 6.25.674 6.25-2.588V4.672c0-3.262-3.944-4.895-6.25-2.589a6.232 6.232 0 0 1 7.108-1.21l20.6 9.908A6.25 6.25 0 0 1 100 16.413v67.174a6.25 6.25 0 0 1-3.541 5.633l-20.601 9.906Z"
|
||||
/>
|
||||
</g>
|
||||
<path
|
||||
fill={`url(#${overlayGradientId})`}
|
||||
fillRule="evenodd"
|
||||
d="M70.851 99.317a6.224 6.224 0 0 0 4.96-.19L96.4 89.22a6.25 6.25 0 0 0 3.54-5.633V16.413a6.25 6.25 0 0 0-3.54-5.632L75.812.874a6.226 6.226 0 0 0-7.104 1.21L29.294 38.04 12.126 25.01a4.162 4.162 0 0 0-5.317.236l-5.507 5.009a4.168 4.168 0 0 0-.004 6.162L16.186 50 1.298 63.583a4.168 4.168 0 0 0 .004 6.162l5.507 5.009a4.162 4.162 0 0 0 5.317.236L29.294 61.96l39.414 35.958a6.218 6.218 0 0 0 2.143 1.4ZM74.954 27.3 45.048 50l29.906 22.701V27.3Z"
|
||||
clipRule="evenodd"
|
||||
opacity=".25"
|
||||
style={{ mixBlendMode: "overlay" }}
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<filter
|
||||
id={topShadowFilterId}
|
||||
width="116.727"
|
||||
height="92.246"
|
||||
x="-8.394"
|
||||
y="15.829"
|
||||
colorInterpolationFilters="sRGB"
|
||||
filterUnits="userSpaceOnUse"
|
||||
>
|
||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
/>
|
||||
<feOffset />
|
||||
<feGaussianBlur stdDeviation="4.167" />
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
|
||||
<feBlend in2="BackgroundImageFix" mode="overlay" result="effect1_dropShadow" />
|
||||
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
|
||||
</filter>
|
||||
<filter
|
||||
id={sideShadowFilterId}
|
||||
width="47.917"
|
||||
height="116.151"
|
||||
x="60.417"
|
||||
y="-8.076"
|
||||
colorInterpolationFilters="sRGB"
|
||||
filterUnits="userSpaceOnUse"
|
||||
>
|
||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
/>
|
||||
<feOffset />
|
||||
<feGaussianBlur stdDeviation="4.167" />
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
|
||||
<feBlend in2="BackgroundImageFix" mode="overlay" result="effect1_dropShadow" />
|
||||
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
|
||||
</filter>
|
||||
<linearGradient
|
||||
id={overlayGradientId}
|
||||
x1="49.939"
|
||||
x2="49.939"
|
||||
y1=".258"
|
||||
y2="99.742"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#fff" />
|
||||
<stop offset="1" stopColor="#fff" stopOpacity="0" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const Zed: Icon = (props) => {
|
||||
const id = useId();
|
||||
const clipPathId = `${id}-zed-logo-a`;
|
||||
|
||||
return (
|
||||
<svg {...props} fill="none" viewBox="0 0 96 96">
|
||||
<g clipPath={`url(#${clipPathId})`}>
|
||||
<path
|
||||
fill="currentColor"
|
||||
fillRule="evenodd"
|
||||
d="M9 6a3 3 0 0 0-3 3v66H0V9a9 9 0 0 1 9-9h80.379c4.009 0 6.016 4.847 3.182 7.682L43.055 57.187H57V51h6v7.688a4.5 4.5 0 0 1-4.5 4.5H37.055L26.743 73.5H73.5V36h6v37.5a6 6 0 0 1-6 6H20.743L10.243 90H87a3 3 0 0 0 3-3V21h6v66a9 9 0 0 1-9 9H6.621c-4.009 0-6.016-4.847-3.182-7.682L52.757 39H39v6h-6v-7.5a4.5 4.5 0 0 1 4.5-4.5h21.257l10.5-10.5H22.5V60h-6V22.5a6 6 0 0 1 6-6h52.757L85.757 6H9Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id={clipPathId}>
|
||||
<path fill="#fff" d="M0 0h96v96H0z" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
+180
-642
File diff suppressed because it is too large.
Load diff
@@ -389,9 +389,6 @@ function TerminalViewport({
|
||||
fitAddonRef.current = null;
|
||||
terminal.dispose();
|
||||
};
|
||||
// autoFocus is intentionally omitted;
|
||||
// it is only read at mount time and must not trigger terminal teardown/recreation.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [cwd, runtimeEnv, terminalId, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
getDesktopUpdateActionError,
|
||||
getDesktopUpdateButtonTooltip,
|
||||
isDesktopUpdateButtonDisabled,
|
||||
resolveDesktopUpdateButtonAction,
|
||||
shouldHighlightDesktopUpdateError,
|
||||
shouldShowDesktopUpdateButton,
|
||||
shouldToastDesktopUpdateActionResult,
|
||||
} from "./desktopUpdate.logic";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
currentVersion: "1.0.0",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
|
||||
describe("desktop update button state", () => {
|
||||
it("shows a download action when an update is available", () => {
|
||||
const state: DesktopUpdateState = { ...baseState, status: "available", availableVersion: "1.1.0" };
|
||||
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||
expect(resolveDesktopUpdateButtonAction(state)).toBe("download");
|
||||
});
|
||||
|
||||
it("keeps retry action available after a download error", () => {
|
||||
const state: DesktopUpdateState = {
|
||||
...baseState,
|
||||
status: "error",
|
||||
availableVersion: "1.1.0",
|
||||
message: "network timeout",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
};
|
||||
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||
expect(resolveDesktopUpdateButtonAction(state)).toBe("download");
|
||||
expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to retry");
|
||||
});
|
||||
|
||||
it("keeps install action available after an install error", () => {
|
||||
const state: DesktopUpdateState = {
|
||||
...baseState,
|
||||
status: "error",
|
||||
downloadedVersion: "1.1.0",
|
||||
availableVersion: "1.1.0",
|
||||
message: "shutdown timeout",
|
||||
errorContext: "install",
|
||||
canRetry: true,
|
||||
};
|
||||
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||
expect(resolveDesktopUpdateButtonAction(state)).toBe("install");
|
||||
expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to retry");
|
||||
});
|
||||
|
||||
it("hides the button for non-actionable check errors", () => {
|
||||
const state: DesktopUpdateState = {
|
||||
...baseState,
|
||||
status: "error",
|
||||
message: "network unavailable",
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
};
|
||||
expect(shouldShowDesktopUpdateButton(state)).toBe(false);
|
||||
expect(resolveDesktopUpdateButtonAction(state)).toBe("none");
|
||||
});
|
||||
|
||||
it("disables the button while downloading", () => {
|
||||
const state: DesktopUpdateState = {
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
downloadPercent: 42.5,
|
||||
};
|
||||
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||
expect(isDesktopUpdateButtonDisabled(state)).toBe(true);
|
||||
expect(getDesktopUpdateButtonTooltip(state)).toContain("42%");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDesktopUpdateActionError", () => {
|
||||
it("returns user-visible message for accepted failed attempts", () => {
|
||||
const result: DesktopUpdateActionResult = {
|
||||
accepted: true,
|
||||
completed: false,
|
||||
state: {
|
||||
...baseState,
|
||||
status: "available",
|
||||
availableVersion: "1.1.0",
|
||||
message: "checksum mismatch",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
},
|
||||
};
|
||||
expect(getDesktopUpdateActionError(result)).toBe("checksum mismatch");
|
||||
});
|
||||
|
||||
it("ignores messages for non-accepted attempts", () => {
|
||||
const result: DesktopUpdateActionResult = {
|
||||
accepted: false,
|
||||
completed: false,
|
||||
state: {
|
||||
...baseState,
|
||||
status: "error",
|
||||
message: "background failure",
|
||||
errorContext: "check",
|
||||
canRetry: false,
|
||||
},
|
||||
};
|
||||
expect(getDesktopUpdateActionError(result)).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores messages for successful attempts", () => {
|
||||
const result: DesktopUpdateActionResult = {
|
||||
accepted: true,
|
||||
completed: true,
|
||||
state: {
|
||||
...baseState,
|
||||
status: "downloaded",
|
||||
downloadedVersion: "1.1.0",
|
||||
availableVersion: "1.1.0",
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: true,
|
||||
},
|
||||
};
|
||||
expect(getDesktopUpdateActionError(result)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("desktop update UI helpers", () => {
|
||||
it("toasts only for accepted incomplete actions", () => {
|
||||
expect(
|
||||
shouldToastDesktopUpdateActionResult({
|
||||
accepted: true,
|
||||
completed: false,
|
||||
state: baseState,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldToastDesktopUpdateActionResult({
|
||||
accepted: true,
|
||||
completed: true,
|
||||
state: baseState,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("highlights only actionable updater errors", () => {
|
||||
expect(
|
||||
shouldHighlightDesktopUpdateError({
|
||||
...baseState,
|
||||
status: "error",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldHighlightDesktopUpdateError({
|
||||
...baseState,
|
||||
status: "error",
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
export type DesktopUpdateButtonAction = "download" | "install" | "none";
|
||||
|
||||
export function resolveDesktopUpdateButtonAction(
|
||||
state: DesktopUpdateState,
|
||||
): DesktopUpdateButtonAction {
|
||||
if (state.status === "available") {
|
||||
return "download";
|
||||
}
|
||||
if (state.status === "downloaded") {
|
||||
return "install";
|
||||
}
|
||||
if (state.status === "error") {
|
||||
if (state.errorContext === "install" && state.downloadedVersion) {
|
||||
return "install";
|
||||
}
|
||||
if (state.errorContext === "download" && state.availableVersion) {
|
||||
return "download";
|
||||
}
|
||||
}
|
||||
return "none";
|
||||
}
|
||||
|
||||
export function shouldShowDesktopUpdateButton(state: DesktopUpdateState | null): boolean {
|
||||
if (!state || !state.enabled) {
|
||||
return false;
|
||||
}
|
||||
if (state.status === "downloading") {
|
||||
return true;
|
||||
}
|
||||
return resolveDesktopUpdateButtonAction(state) !== "none";
|
||||
}
|
||||
|
||||
export function isDesktopUpdateButtonDisabled(state: DesktopUpdateState | null): boolean {
|
||||
return state?.status === "downloading";
|
||||
}
|
||||
|
||||
export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string {
|
||||
if (state.status === "available") {
|
||||
return `Update ${state.availableVersion ?? "available"} ready to download`;
|
||||
}
|
||||
if (state.status === "downloading") {
|
||||
const progress =
|
||||
typeof state.downloadPercent === "number" ? ` (${Math.floor(state.downloadPercent)}%)` : "";
|
||||
return `Downloading update${progress}`;
|
||||
}
|
||||
if (state.status === "downloaded") {
|
||||
return `Update ${state.downloadedVersion ?? state.availableVersion ?? "ready"} downloaded. Click to restart and install.`;
|
||||
}
|
||||
if (state.status === "error") {
|
||||
if (state.errorContext === "download" && state.availableVersion) {
|
||||
return `Download failed for ${state.availableVersion}. Click to retry.`;
|
||||
}
|
||||
if (state.errorContext === "install" && state.downloadedVersion) {
|
||||
return `Install failed for ${state.downloadedVersion}. Click to retry.`;
|
||||
}
|
||||
return state.message ?? "Update failed";
|
||||
}
|
||||
return "Update available";
|
||||
}
|
||||
|
||||
export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): string | null {
|
||||
if (!result.accepted || result.completed) return null;
|
||||
if (typeof result.state.message !== "string") return null;
|
||||
const message = result.state.message.trim();
|
||||
return message.length > 0 ? message : null;
|
||||
}
|
||||
|
||||
export function shouldToastDesktopUpdateActionResult(result: DesktopUpdateActionResult): boolean {
|
||||
return result.accepted && !result.completed;
|
||||
}
|
||||
|
||||
export function shouldHighlightDesktopUpdateError(state: DesktopUpdateState | null): boolean {
|
||||
if (!state || state.status !== "error") return false;
|
||||
return state.errorContext === "download" || state.errorContext === "install";
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
describe("estimateTimelineMessageHeight", () => {
|
||||
it("uses assistant sizing rules for assistant messages", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "assistant",
|
||||
text: "a".repeat(144),
|
||||
}),
|
||||
).toBe(122);
|
||||
});
|
||||
|
||||
it("uses assistant sizing rules for system messages", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "system",
|
||||
text: "a".repeat(144),
|
||||
}),
|
||||
).toBe(122);
|
||||
});
|
||||
|
||||
it("adds one attachment row for one or two user attachments", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }],
|
||||
}),
|
||||
).toBe(346);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }],
|
||||
}),
|
||||
).toBe(346);
|
||||
});
|
||||
|
||||
it("adds a second attachment row for three or four user attachments", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }],
|
||||
}),
|
||||
).toBe(574);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }],
|
||||
}),
|
||||
).toBe(574);
|
||||
});
|
||||
|
||||
it("does not cap long user message estimates", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "a".repeat(56 * 120),
|
||||
}),
|
||||
).toBe(2736);
|
||||
});
|
||||
|
||||
it("counts explicit newlines for user message estimates", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "first\nsecond\nthird",
|
||||
}),
|
||||
).toBe(162);
|
||||
});
|
||||
|
||||
it("uses narrower width to increase user line wrapping", () => {
|
||||
const message = {
|
||||
role: "user" as const,
|
||||
text: "a".repeat(52),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(140);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(118);
|
||||
});
|
||||
|
||||
it("does not clamp user wrapping too aggressively on very narrow layouts", () => {
|
||||
const message = {
|
||||
role: "user" as const,
|
||||
text: "a".repeat(20),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 100 })).toBe(184);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(118);
|
||||
});
|
||||
|
||||
it("uses narrower width to increase assistant line wrapping", () => {
|
||||
const message = {
|
||||
role: "assistant" as const,
|
||||
text: "a".repeat(200),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(188);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(122);
|
||||
});
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
|
||||
const USER_CHARS_PER_LINE_FALLBACK = 56;
|
||||
const LINE_HEIGHT_PX = 22;
|
||||
const ASSISTANT_BASE_HEIGHT_PX = 78;
|
||||
const USER_BASE_HEIGHT_PX = 96;
|
||||
const ATTACHMENTS_PER_ROW = 2;
|
||||
// Attachment thumbnails render with `max-h-[220px]` plus ~8px row gap.
|
||||
const USER_ATTACHMENT_ROW_HEIGHT_PX = 228;
|
||||
const USER_BUBBLE_WIDTH_RATIO = 0.8;
|
||||
const USER_BUBBLE_HORIZONTAL_PADDING_PX = 32;
|
||||
const ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX = 8;
|
||||
const USER_MONO_AVG_CHAR_WIDTH_PX = 8.4;
|
||||
const ASSISTANT_AVG_CHAR_WIDTH_PX = 7.2;
|
||||
const MIN_USER_CHARS_PER_LINE = 4;
|
||||
const MIN_ASSISTANT_CHARS_PER_LINE = 20;
|
||||
|
||||
interface TimelineMessageHeightInput {
|
||||
role: "user" | "assistant" | "system";
|
||||
text: string;
|
||||
attachments?: ReadonlyArray<{ id: string }>;
|
||||
}
|
||||
|
||||
interface TimelineHeightEstimateLayout {
|
||||
timelineWidthPx: number | null;
|
||||
}
|
||||
|
||||
function estimateWrappedLineCount(text: string, charsPerLine: number): number {
|
||||
if (text.length === 0) return 1;
|
||||
|
||||
// Avoid allocating via split for long logs; iterate once and count wrapped lines.
|
||||
let lines = 0;
|
||||
let currentLineLength = 0;
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
if (text.charCodeAt(index) === 10) {
|
||||
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
|
||||
currentLineLength = 0;
|
||||
continue;
|
||||
}
|
||||
currentLineLength += 1;
|
||||
}
|
||||
|
||||
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
|
||||
return lines;
|
||||
}
|
||||
|
||||
function isFinitePositiveNumber(value: number | null | undefined): value is number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
||||
}
|
||||
|
||||
function estimateCharsPerLineForUser(timelineWidthPx: number | null): number {
|
||||
if (!isFinitePositiveNumber(timelineWidthPx)) return USER_CHARS_PER_LINE_FALLBACK;
|
||||
const bubbleWidthPx = timelineWidthPx * USER_BUBBLE_WIDTH_RATIO;
|
||||
const textWidthPx = Math.max(bubbleWidthPx - USER_BUBBLE_HORIZONTAL_PADDING_PX, 0);
|
||||
return Math.max(MIN_USER_CHARS_PER_LINE, Math.floor(textWidthPx / USER_MONO_AVG_CHAR_WIDTH_PX));
|
||||
}
|
||||
|
||||
function estimateCharsPerLineForAssistant(timelineWidthPx: number | null): number {
|
||||
if (!isFinitePositiveNumber(timelineWidthPx)) return ASSISTANT_CHARS_PER_LINE_FALLBACK;
|
||||
const textWidthPx = Math.max(timelineWidthPx - ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX, 0);
|
||||
return Math.max(
|
||||
MIN_ASSISTANT_CHARS_PER_LINE,
|
||||
Math.floor(textWidthPx / ASSISTANT_AVG_CHAR_WIDTH_PX),
|
||||
);
|
||||
}
|
||||
|
||||
export function estimateTimelineMessageHeight(
|
||||
message: TimelineMessageHeightInput,
|
||||
layout: TimelineHeightEstimateLayout = { timelineWidthPx: null },
|
||||
): number {
|
||||
if (message.role === "assistant") {
|
||||
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
|
||||
}
|
||||
|
||||
if (message.role === "user") {
|
||||
const charsPerLine = estimateCharsPerLineForUser(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
const attachmentCount = message.attachments?.length ?? 0;
|
||||
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
|
||||
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
|
||||
return USER_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX + attachmentHeight;
|
||||
}
|
||||
|
||||
// `system` messages are not rendered in the chat timeline, but keep a stable
|
||||
// explicit branch in case they are present in timeline data.
|
||||
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
|
||||
}
|
||||
@@ -20,9 +20,10 @@ function Combobox<Value, Multiple extends boolean | undefined = false>(
|
||||
props: ComboboxPrimitive.Root.Props<Value, Multiple>,
|
||||
) {
|
||||
const chipsRef = React.useRef<Element | null>(null);
|
||||
const value = React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple]);
|
||||
return (
|
||||
<ComboboxContext.Provider value={value}>
|
||||
<ComboboxContext.Provider
|
||||
value={React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple])}
|
||||
>
|
||||
<ComboboxPrimitive.Root {...props} />
|
||||
</ComboboxContext.Provider>
|
||||
);
|
||||
|
||||
@@ -339,7 +339,6 @@ function SidebarRail({
|
||||
const sidebarInstance = React.useContext(SidebarInstanceContext);
|
||||
const railRef = React.useRef<HTMLButtonElement | null>(null);
|
||||
const suppressClickRef = React.useRef(false);
|
||||
const cleanupResizeListenersRef = React.useRef<(() => void) | null>(null);
|
||||
const resizeStateRef = React.useRef<{
|
||||
moved: boolean;
|
||||
pointerId: number;
|
||||
@@ -368,8 +367,6 @@ function SidebarRail({
|
||||
if (resizeState.rafId !== null) {
|
||||
window.cancelAnimationFrame(resizeState.rafId);
|
||||
}
|
||||
cleanupResizeListenersRef.current?.();
|
||||
cleanupResizeListenersRef.current = null;
|
||||
resizeState.transitionTargets.forEach((element) => {
|
||||
element.style.removeProperty("transition-duration");
|
||||
});
|
||||
@@ -432,46 +429,12 @@ function SidebarRail({
|
||||
width: initialWidth,
|
||||
wrapper,
|
||||
};
|
||||
const stopResizeFromWindowEvent = (nativeEvent: PointerEvent) => {
|
||||
const activeResizeState = resizeStateRef.current;
|
||||
if (!activeResizeState || nativeEvent.pointerId !== activeResizeState.pointerId) {
|
||||
return;
|
||||
}
|
||||
suppressClickRef.current = activeResizeState.moved;
|
||||
stopResize(nativeEvent.pointerId);
|
||||
};
|
||||
const stopResizeFromVisibilityChange = () => {
|
||||
const activeResizeState = resizeStateRef.current;
|
||||
if (!activeResizeState || document.visibilityState === "visible") {
|
||||
return;
|
||||
}
|
||||
suppressClickRef.current = activeResizeState.moved;
|
||||
stopResize(activeResizeState.pointerId);
|
||||
};
|
||||
const stopResizeFromBlur = () => {
|
||||
const activeResizeState = resizeStateRef.current;
|
||||
if (!activeResizeState) {
|
||||
return;
|
||||
}
|
||||
suppressClickRef.current = activeResizeState.moved;
|
||||
stopResize(activeResizeState.pointerId);
|
||||
};
|
||||
window.addEventListener("pointerup", stopResizeFromWindowEvent, true);
|
||||
window.addEventListener("pointercancel", stopResizeFromWindowEvent, true);
|
||||
window.addEventListener("blur", stopResizeFromBlur);
|
||||
document.addEventListener("visibilitychange", stopResizeFromVisibilityChange);
|
||||
cleanupResizeListenersRef.current = () => {
|
||||
window.removeEventListener("pointerup", stopResizeFromWindowEvent, true);
|
||||
window.removeEventListener("pointercancel", stopResizeFromWindowEvent, true);
|
||||
window.removeEventListener("blur", stopResizeFromBlur);
|
||||
document.removeEventListener("visibilitychange", stopResizeFromVisibilityChange);
|
||||
};
|
||||
wrapper.style.setProperty("--sidebar-width", `${initialWidth}px`);
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
document.body.style.cursor = "col-resize";
|
||||
document.body.style.userSelect = "none";
|
||||
},
|
||||
[onPointerDown, open, resolvedResizable, sidebarInstance?.side, stopResize],
|
||||
[onPointerDown, open, resolvedResizable, sidebarInstance?.side],
|
||||
);
|
||||
|
||||
const handlePointerMove = React.useCallback(
|
||||
@@ -553,13 +516,6 @@ function SidebarRail({
|
||||
[endResizeInteraction, onPointerCancel],
|
||||
);
|
||||
|
||||
const handleLostPointerCapture = React.useCallback(() => {
|
||||
const resizeState = resizeStateRef.current;
|
||||
if (!resizeState) return;
|
||||
suppressClickRef.current = resizeState.moved;
|
||||
stopResize(resizeState.pointerId);
|
||||
}, [stopResize]);
|
||||
|
||||
const handleClick = React.useCallback(
|
||||
(event: React.MouseEvent<HTMLButtonElement>) => {
|
||||
onClick?.(event);
|
||||
@@ -623,7 +579,6 @@ function SidebarRail({
|
||||
onClick={handleClick}
|
||||
onPointerCancel={handlePointerCancel}
|
||||
onPointerDown={handlePointerDown}
|
||||
onLostPointerCapture={handleLostPointerCapture}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
ref={railRef}
|
||||
|
||||
@@ -206,10 +206,7 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
"data-[position*=top]:after:top-full",
|
||||
"data-[position*=bottom]:after:bottom-full",
|
||||
// Define some variables
|
||||
// Base UI exposes a shared front-most height for the collapsed stack.
|
||||
// If that shared measurement is briefly stale, long content can render
|
||||
// outside the card until hover expands the toast and swaps to its own height.
|
||||
"[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
|
||||
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
|
||||
// Define offset-y variable
|
||||
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
|
||||
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
|
||||
@@ -261,7 +258,7 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
|
||||
)}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 gap-2">
|
||||
<div className="flex gap-2">
|
||||
{Icon && (
|
||||
<div
|
||||
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
|
||||
@@ -271,22 +268,16 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Toast.Title className="font-medium" data-slot="toast-title" />
|
||||
<Toast.Description
|
||||
className="min-w-0 break-words text-muted-foreground"
|
||||
className="text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{toast.actionProps && (
|
||||
<Toast.Action
|
||||
className={cn(buttonVariants({ size: "xs" }), "shrink-0")}
|
||||
data-slot="toast-action"
|
||||
>
|
||||
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
|
||||
{toast.actionProps.children}
|
||||
</Toast.Action>
|
||||
)}
|
||||
@@ -350,7 +341,7 @@ function AnchoredToasts() {
|
||||
</Toast.Content>
|
||||
) : (
|
||||
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">
|
||||
<div className="flex min-w-0 flex-1 gap-2">
|
||||
<div className="flex gap-2">
|
||||
{Icon && (
|
||||
<div
|
||||
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
|
||||
@@ -360,20 +351,17 @@ function AnchoredToasts() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Toast.Title className="font-medium" data-slot="toast-title" />
|
||||
<Toast.Description
|
||||
className="min-w-0 break-words text-muted-foreground"
|
||||
className="text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{toast.actionProps && (
|
||||
<Toast.Action
|
||||
className={cn(buttonVariants({ size: "xs" }), "shrink-0")}
|
||||
className={buttonVariants({ size: "xs" })}
|
||||
data-slot="toast-action"
|
||||
>
|
||||
{toast.actionProps.children}
|
||||
|
||||
@@ -22,7 +22,6 @@ function ToggleGroup({
|
||||
children,
|
||||
...props
|
||||
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
const value = React.useMemo(() => ({ size, variant }), [size, variant]);
|
||||
return (
|
||||
<ToggleGroupPrimitive
|
||||
className={cn(
|
||||
@@ -43,7 +42,11 @@ function ToggleGroup({
|
||||
orientation={orientation}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider value={value}>{children}</ToggleGroupContext.Provider>
|
||||
<ToggleGroupContext.Provider
|
||||
value={React.useMemo(() => ({ size, variant }), [size, variant])}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
|
||||
describe("splitPromptIntoComposerSegments", () => {
|
||||
it("splits mention tokens followed by whitespace into mention segments", () => {
|
||||
expect(splitPromptIntoComposerSegments("Inspect @AGENTS.md please")).toEqual([
|
||||
{ type: "text", text: "Inspect " },
|
||||
{ type: "mention", path: "AGENTS.md" },
|
||||
{ type: "text", text: " please" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not convert an incomplete trailing mention token", () => {
|
||||
expect(splitPromptIntoComposerSegments("Inspect @AGENTS.md")).toEqual([
|
||||
{ type: "text", text: "Inspect @AGENTS.md" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps newlines around mention tokens", () => {
|
||||
expect(splitPromptIntoComposerSegments("one\n@src/index.ts \ntwo")).toEqual([
|
||||
{ type: "text", text: "one\n" },
|
||||
{ type: "mention", path: "src/index.ts" },
|
||||
{ type: "text", text: " \ntwo" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
export type ComposerPromptSegment =
|
||||
| {
|
||||
type: "text";
|
||||
text: string;
|
||||
}
|
||||
| {
|
||||
type: "mention";
|
||||
path: string;
|
||||
};
|
||||
|
||||
const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g;
|
||||
|
||||
function pushTextSegment(segments: ComposerPromptSegment[], text: string): void {
|
||||
if (!text) return;
|
||||
const last = segments[segments.length - 1];
|
||||
if (last && last.type === "text") {
|
||||
last.text += text;
|
||||
return;
|
||||
}
|
||||
segments.push({ type: "text", text });
|
||||
}
|
||||
|
||||
export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptSegment[] {
|
||||
const segments: ComposerPromptSegment[] = [];
|
||||
if (!prompt) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
let cursor = 0;
|
||||
for (const match of prompt.matchAll(MENTION_TOKEN_REGEX)) {
|
||||
const fullMatch = match[0];
|
||||
const prefix = match[1] ?? "";
|
||||
const path = match[2] ?? "";
|
||||
const matchIndex = match.index ?? 0;
|
||||
const mentionStart = matchIndex + prefix.length;
|
||||
const mentionEnd = mentionStart + fullMatch.length - prefix.length;
|
||||
|
||||
if (mentionStart > cursor) {
|
||||
pushTextSegment(segments, prompt.slice(cursor, mentionStart));
|
||||
}
|
||||
|
||||
if (path.length > 0) {
|
||||
segments.push({ type: "mention", path });
|
||||
} else {
|
||||
pushTextSegment(segments, prompt.slice(mentionStart, mentionEnd));
|
||||
}
|
||||
|
||||
cursor = mentionEnd;
|
||||
}
|
||||
|
||||
if (cursor < prompt.length) {
|
||||
pushTextSegment(segments, prompt.slice(cursor));
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
@@ -1,11 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
detectComposerTrigger,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToMention,
|
||||
replaceTextRange,
|
||||
} from "./composer-logic";
|
||||
import { detectComposerTrigger, replaceTextRange } from "./composer-logic";
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
@@ -54,60 +49,3 @@ describe("replaceTextRange", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("expandCollapsedComposerCursor", () => {
|
||||
it("keeps cursor unchanged when no mention segment is present", () => {
|
||||
expect(expandCollapsedComposerCursor("plain text", 5)).toBe(5);
|
||||
});
|
||||
|
||||
it("maps collapsed mention cursor to expanded text cursor", () => {
|
||||
const text = "what's in my @AGENTS.md fsfdas";
|
||||
const collapsedCursorAfterMention = "what's in my ".length + 2;
|
||||
const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
|
||||
|
||||
expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
|
||||
expandedCursorAfterMention,
|
||||
);
|
||||
});
|
||||
|
||||
it("allows path trigger detection to close after selecting a mention", () => {
|
||||
const text = "what's in my @AGENTS.md ";
|
||||
const collapsedCursorAfterMention = "what's in my ".length + 2;
|
||||
const expandedCursor = expandCollapsedComposerCursor(text, collapsedCursorAfterMention);
|
||||
|
||||
expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("isCollapsedCursorAdjacentToMention", () => {
|
||||
it("returns false when no mention exists", () => {
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps @query typing non-adjacent while no mention pill exists", () => {
|
||||
const text = "hello @pac";
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects left adjacency only when cursor is directly after a mention", () => {
|
||||
const text = "open @AGENTS.md next";
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd + 1, "left")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects right adjacency only when cursor is directly before a mention", () => {
|
||||
const text = "open @AGENTS.md next";
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "right")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart - 1, "right")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,3 @@
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
|
||||
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
||||
|
||||
export interface ComposerTrigger {
|
||||
@@ -26,84 +24,6 @@ function tokenStartForCursor(text: string, cursor: number): number {
|
||||
return index + 1;
|
||||
}
|
||||
|
||||
export function expandCollapsedComposerCursor(text: string, cursorInput: number): number {
|
||||
const collapsedCursor = clampCursor(text, cursorInput);
|
||||
const segments = splitPromptIntoComposerSegments(text);
|
||||
if (segments.length === 0) {
|
||||
return collapsedCursor;
|
||||
}
|
||||
|
||||
let remaining = collapsedCursor;
|
||||
let expandedCursor = 0;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
const expandedLength = segment.path.length + 1;
|
||||
if (remaining <= 1) {
|
||||
return expandedCursor + (remaining === 0 ? 0 : expandedLength);
|
||||
}
|
||||
remaining -= 1;
|
||||
expandedCursor += expandedLength;
|
||||
continue;
|
||||
}
|
||||
|
||||
const segmentLength = segment.text.length;
|
||||
if (remaining <= segmentLength) {
|
||||
return expandedCursor + remaining;
|
||||
}
|
||||
remaining -= segmentLength;
|
||||
expandedCursor += segmentLength;
|
||||
}
|
||||
|
||||
return expandedCursor;
|
||||
}
|
||||
|
||||
function collapsedSegmentLength(segment: { type: "text"; text: string } | { type: "mention" }): number {
|
||||
return segment.type === "mention" ? 1 : segment.text.length;
|
||||
}
|
||||
|
||||
function clampCollapsedComposerCursor(
|
||||
segments: ReadonlyArray<{ type: "text"; text: string } | { type: "mention" }>,
|
||||
cursorInput: number,
|
||||
): number {
|
||||
const collapsedLength = segments.reduce(
|
||||
(total, segment) => total + collapsedSegmentLength(segment),
|
||||
0,
|
||||
);
|
||||
if (!Number.isFinite(cursorInput)) {
|
||||
return collapsedLength;
|
||||
}
|
||||
return Math.max(0, Math.min(collapsedLength, Math.floor(cursorInput)));
|
||||
}
|
||||
|
||||
export function isCollapsedCursorAdjacentToMention(
|
||||
text: string,
|
||||
cursorInput: number,
|
||||
direction: "left" | "right",
|
||||
): boolean {
|
||||
const segments = splitPromptIntoComposerSegments(text);
|
||||
if (!segments.some((segment) => segment.type === "mention")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const cursor = clampCollapsedComposerCursor(segments, cursorInput);
|
||||
let collapsedOffset = 0;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
if (direction === "left" && cursor === collapsedOffset + 1) {
|
||||
return true;
|
||||
}
|
||||
if (direction === "right" && cursor === collapsedOffset) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
collapsedOffset += collapsedSegmentLength(segment);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
||||
const cursor = clampCursor(text, cursorInput);
|
||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
||||
|
||||
@@ -1,350 +0,0 @@
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { type ComposerImageAttachment, useComposerDraftStore } from "./composerDraftStore";
|
||||
|
||||
function makeImage(input: {
|
||||
id: string;
|
||||
previewUrl: string;
|
||||
name?: string;
|
||||
mimeType?: string;
|
||||
sizeBytes?: number;
|
||||
lastModified?: number;
|
||||
}): ComposerImageAttachment {
|
||||
const name = input.name ?? "image.png";
|
||||
const mimeType = input.mimeType ?? "image/png";
|
||||
const sizeBytes = input.sizeBytes ?? 4;
|
||||
const lastModified = input.lastModified ?? 1_700_000_000_000;
|
||||
const file = new File([new Uint8Array(sizeBytes).fill(1)], name, {
|
||||
type: mimeType,
|
||||
lastModified,
|
||||
});
|
||||
return {
|
||||
type: "image",
|
||||
id: input.id,
|
||||
name,
|
||||
mimeType,
|
||||
sizeBytes: file.size,
|
||||
previewUrl: input.previewUrl,
|
||||
file,
|
||||
};
|
||||
}
|
||||
|
||||
describe("composerDraftStore addImages", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-dedupe");
|
||||
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
|
||||
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
originalRevokeObjectUrl = URL.revokeObjectURL;
|
||||
revokeSpy = vi.fn();
|
||||
URL.revokeObjectURL = revokeSpy;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
URL.revokeObjectURL = originalRevokeObjectUrl;
|
||||
});
|
||||
|
||||
it("deduplicates identical images in one batch by file signature", () => {
|
||||
const first = makeImage({
|
||||
id: "img-1",
|
||||
previewUrl: "blob:first",
|
||||
name: "same.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 12,
|
||||
lastModified: 12345,
|
||||
});
|
||||
const duplicate = makeImage({
|
||||
id: "img-2",
|
||||
previewUrl: "blob:duplicate",
|
||||
name: "same.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 12,
|
||||
lastModified: 12345,
|
||||
});
|
||||
|
||||
useComposerDraftStore.getState().addImages(threadId, [first, duplicate]);
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.images.map((image) => image.id)).toEqual(["img-1"]);
|
||||
expect(revokeSpy).toHaveBeenCalledWith("blob:duplicate");
|
||||
});
|
||||
|
||||
it("deduplicates against existing images across calls by file signature", () => {
|
||||
const first = makeImage({
|
||||
id: "img-a",
|
||||
previewUrl: "blob:a",
|
||||
name: "same.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 9,
|
||||
lastModified: 777,
|
||||
});
|
||||
const duplicateLater = makeImage({
|
||||
id: "img-b",
|
||||
previewUrl: "blob:b",
|
||||
name: "same.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 9,
|
||||
lastModified: 999,
|
||||
});
|
||||
|
||||
useComposerDraftStore.getState().addImage(threadId, first);
|
||||
useComposerDraftStore.getState().addImage(threadId, duplicateLater);
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.images.map((image) => image.id)).toEqual(["img-a"]);
|
||||
expect(revokeSpy).toHaveBeenCalledWith("blob:b");
|
||||
});
|
||||
|
||||
it("does not revoke blob URLs that are still used by an accepted duplicate image", () => {
|
||||
const first = makeImage({
|
||||
id: "img-shared",
|
||||
previewUrl: "blob:shared",
|
||||
});
|
||||
const duplicateSameUrl = makeImage({
|
||||
id: "img-shared",
|
||||
previewUrl: "blob:shared",
|
||||
});
|
||||
|
||||
useComposerDraftStore.getState().addImages(threadId, [first, duplicateSameUrl]);
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.images.map((image) => image.id)).toEqual(["img-shared"]);
|
||||
expect(revokeSpy).not.toHaveBeenCalledWith("blob:shared");
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore clearComposerContent", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-clear");
|
||||
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
|
||||
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
originalRevokeObjectUrl = URL.revokeObjectURL;
|
||||
revokeSpy = vi.fn();
|
||||
URL.revokeObjectURL = revokeSpy;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
URL.revokeObjectURL = originalRevokeObjectUrl;
|
||||
});
|
||||
|
||||
it("does not revoke blob preview URLs when clearing composer content", () => {
|
||||
const first = makeImage({
|
||||
id: "img-optimistic",
|
||||
previewUrl: "blob:optimistic",
|
||||
});
|
||||
useComposerDraftStore.getState().addImage(threadId, first);
|
||||
|
||||
useComposerDraftStore.getState().clearComposerContent(threadId);
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft).toBeUndefined();
|
||||
expect(revokeSpy).not.toHaveBeenCalledWith("blob:optimistic");
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore project draft thread mapping", () => {
|
||||
const projectId = ProjectId.makeUnsafe("project-a");
|
||||
const otherProjectId = ProjectId.makeUnsafe("project-b");
|
||||
const threadId = ThreadId.makeUnsafe("thread-a");
|
||||
const otherThreadId = ThreadId.makeUnsafe("thread-b");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("stores and reads project draft thread ids via actions", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
expect(store.getDraftThreadByProjectId(projectId)).toBeNull();
|
||||
expect(store.getDraftThread(threadId)).toBeNull();
|
||||
|
||||
store.setProjectDraftThreadId(projectId, threadId, {
|
||||
branch: "feature/test",
|
||||
worktreePath: "/tmp/worktree-test",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toEqual({
|
||||
threadId,
|
||||
projectId,
|
||||
branch: "feature/test",
|
||||
worktreePath: "/tmp/worktree-test",
|
||||
envMode: "worktree",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toEqual({
|
||||
projectId,
|
||||
branch: "feature/test",
|
||||
worktreePath: "/tmp/worktree-test",
|
||||
envMode: "worktree",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("clears only matching project draft mapping entries", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId);
|
||||
store.setPrompt(threadId, "hello");
|
||||
|
||||
store.clearProjectDraftThreadById(projectId, otherThreadId);
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
|
||||
threadId,
|
||||
);
|
||||
|
||||
store.clearProjectDraftThreadById(projectId, threadId);
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clears project draft mapping by project id", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId);
|
||||
store.setPrompt(threadId, "hello");
|
||||
store.clearProjectDraftThreadId(projectId);
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clears orphaned composer drafts when remapping a project to a new draft thread", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId);
|
||||
store.setPrompt(threadId, "orphan me");
|
||||
|
||||
store.setProjectDraftThreadId(projectId, otherThreadId);
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
|
||||
otherThreadId,
|
||||
);
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps composer drafts when the thread is still mapped by another project", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId);
|
||||
store.setProjectDraftThreadId(otherProjectId, threadId);
|
||||
store.setPrompt(threadId, "keep me");
|
||||
|
||||
store.clearProjectDraftThreadId(projectId);
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId).toBe(
|
||||
threadId,
|
||||
);
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
|
||||
});
|
||||
|
||||
it("clears draft registration independently", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId);
|
||||
store.clearDraftThread(threadId);
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
|
||||
});
|
||||
|
||||
it("updates branch context on an existing draft thread", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId, {
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
});
|
||||
store.setDraftThreadContext(threadId, {
|
||||
branch: "feature/next",
|
||||
worktreePath: "/tmp/feature-next",
|
||||
});
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
|
||||
threadId,
|
||||
);
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
|
||||
projectId,
|
||||
branch: "feature/next",
|
||||
worktreePath: "/tmp/feature-next",
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves existing branch and worktree when setProjectDraftThreadId receives undefined", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId, {
|
||||
branch: "main",
|
||||
worktreePath: "/tmp/main-worktree",
|
||||
});
|
||||
const runtimeUndefinedOptions = {
|
||||
branch: undefined,
|
||||
worktreePath: undefined,
|
||||
} as unknown as {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
};
|
||||
store.setProjectDraftThreadId(projectId, threadId, runtimeUndefinedOptions);
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
|
||||
projectId,
|
||||
branch: "main",
|
||||
worktreePath: "/tmp/main-worktree",
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves worktree env mode without a worktree path", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId, {
|
||||
branch: "feature/base",
|
||||
worktreePath: null,
|
||||
envMode: "worktree",
|
||||
});
|
||||
const runtimeUndefinedOptions = {
|
||||
branch: undefined,
|
||||
worktreePath: undefined,
|
||||
envMode: undefined,
|
||||
} as unknown as {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
envMode?: "local" | "worktree";
|
||||
};
|
||||
store.setProjectDraftThreadId(projectId, threadId, runtimeUndefinedOptions);
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
|
||||
projectId,
|
||||
branch: "feature/base",
|
||||
worktreePath: null,
|
||||
envMode: "worktree",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore setModel", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps explicit DEFAULT_MODEL overrides instead of coercing to null", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModel(threadId, "gpt-5.3-codex");
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe("gpt-5.3-codex");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +1,10 @@
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function showContextMenuFallback<T extends string>(
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
items: readonly { id: T; label: string }[],
|
||||
position?: { x: number; y: number },
|
||||
): Promise<T | null> {
|
||||
return new Promise<T | null>((resolve) => {
|
||||
@@ -43,8 +41,8 @@ export function showContextMenuFallback<T extends string>(
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.textContent = item.label;
|
||||
const isDestructiveAction = item.destructive === true || item.id === "delete";
|
||||
btn.className = isDestructiveAction
|
||||
const isDeleteAction = item.id === "delete";
|
||||
btn.className = isDeleteAction
|
||||
? "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";
|
||||
btn.addEventListener("click", () => cleanup(item.id));
|
||||
|
||||
@@ -16,6 +16,8 @@ export const gitQueryKeys = {
|
||||
export const gitMutationKeys = {
|
||||
init: (cwd: string | null) => ["git", "mutation", "init", cwd] as const,
|
||||
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
|
||||
createBranchAndCheckout: (cwd: string | null) =>
|
||||
["git", "mutation", "create-branch-and-checkout", cwd] as const,
|
||||
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
|
||||
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
|
||||
};
|
||||
@@ -87,6 +89,24 @@ export function gitCheckoutMutationOptions(input: {
|
||||
});
|
||||
}
|
||||
|
||||
export function gitCreateBranchAndCheckoutMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.createBranchAndCheckout(input.cwd),
|
||||
mutationFn: async (branch: string) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git branch creation is unavailable.");
|
||||
await api.git.createBranch({ cwd: input.cwd, branch });
|
||||
return api.git.checkout({ cwd: input.cwd, branch });
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
@@ -96,11 +116,9 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
mutationFn: async ({
|
||||
action,
|
||||
commitMessage,
|
||||
featureBranch,
|
||||
}: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
}) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git action is unavailable.");
|
||||
@@ -108,7 +126,6 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: input.cwd,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
});
|
||||
},
|
||||
onSettled: async () => {
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildTurnDiffTree, summarizeTurnDiffStats } from "./turnDiffTree";
|
||||
|
||||
describe("summarizeTurnDiffStats", () => {
|
||||
it("sums only files with numeric additions/deletions", () => {
|
||||
const stat = summarizeTurnDiffStats([
|
||||
{ path: "README.md", additions: 3, deletions: 1 },
|
||||
{ path: "docs/notes.md" },
|
||||
{ path: "src/index.ts", additions: 5, deletions: 2 },
|
||||
]);
|
||||
|
||||
expect(stat).toEqual({ additions: 8, deletions: 3 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildTurnDiffTree", () => {
|
||||
it("builds nested directory nodes with aggregated stats", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "src/index.ts", additions: 2, deletions: 1 },
|
||||
{ path: "src/components/Button.tsx", additions: 4, deletions: 2 },
|
||||
{ path: "README.md", additions: 1, deletions: 0 },
|
||||
]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "src",
|
||||
path: "src",
|
||||
stat: { additions: 6, deletions: 3 },
|
||||
children: [
|
||||
{
|
||||
kind: "directory",
|
||||
name: "components",
|
||||
path: "src/components",
|
||||
stat: { additions: 4, deletions: 2 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "Button.tsx",
|
||||
path: "src/components/Button.tsx",
|
||||
stat: { additions: 4, deletions: 2 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "README.md",
|
||||
path: "README.md",
|
||||
stat: { additions: 1, deletions: 0 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps files without stat values and excludes them from directory totals", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "docs/notes.md" },
|
||||
{ path: "docs/todo.md", additions: 1, deletions: 1 },
|
||||
]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "docs",
|
||||
path: "docs",
|
||||
stat: { additions: 1, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "notes.md",
|
||||
path: "docs/notes.md",
|
||||
stat: null,
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "todo.md",
|
||||
path: "docs/todo.md",
|
||||
stat: { additions: 1, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes file paths with windows separators", () => {
|
||||
const tree = buildTurnDiffTree([{ path: "apps\\web\\src\\index.ts", additions: 2, deletions: 1 }]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "apps/web/src",
|
||||
path: "apps/web/src",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "apps/web/src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("compacts only single-directory chains and stops at branch points", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "apps/server/src/index.ts", additions: 2, deletions: 1 },
|
||||
{ path: "apps/server/main.ts", additions: 4, deletions: 0 },
|
||||
]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "apps/server",
|
||||
path: "apps/server",
|
||||
stat: { additions: 6, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "directory",
|
||||
name: "src",
|
||||
path: "apps/server/src",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "apps/server/src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "main.ts",
|
||||
path: "apps/server/main.ts",
|
||||
stat: { additions: 4, deletions: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves leading/trailing whitespace in path segments", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "a/file.ts", additions: 1, deletions: 0 },
|
||||
{ path: " a/file.ts", additions: 2, deletions: 0 },
|
||||
]);
|
||||
|
||||
expect(tree).toHaveLength(2);
|
||||
const directoryNodes = tree.filter(
|
||||
(node): node is Extract<(typeof tree)[number], { kind: "directory" }> => node.kind === "directory",
|
||||
);
|
||||
expect(directoryNodes.map((node) => node.name).toSorted()).toEqual([" a", "a"]);
|
||||
expect(directoryNodes.map((node) => node.path).toSorted()).toEqual([" a", "a"]);
|
||||
});
|
||||
});
|
||||
@@ -1,172 +0,0 @@
|
||||
import type { TurnDiffFileChange } from "../types";
|
||||
|
||||
export interface TurnDiffStat {
|
||||
additions: number;
|
||||
deletions: number;
|
||||
}
|
||||
|
||||
export interface TurnDiffTreeDirectoryNode {
|
||||
kind: "directory";
|
||||
name: string;
|
||||
path: string;
|
||||
stat: TurnDiffStat;
|
||||
children: TurnDiffTreeNode[];
|
||||
}
|
||||
|
||||
export interface TurnDiffTreeFileNode {
|
||||
kind: "file";
|
||||
name: string;
|
||||
path: string;
|
||||
stat: TurnDiffStat | null;
|
||||
}
|
||||
|
||||
export type TurnDiffTreeNode = TurnDiffTreeDirectoryNode | TurnDiffTreeFileNode;
|
||||
|
||||
interface MutableDirectoryNode {
|
||||
name: string;
|
||||
path: string;
|
||||
stat: TurnDiffStat;
|
||||
directories: Map<string, MutableDirectoryNode>;
|
||||
files: TurnDiffTreeFileNode[];
|
||||
}
|
||||
|
||||
const SORT_LOCALE_OPTIONS: Intl.CollatorOptions = { numeric: true, sensitivity: "base" };
|
||||
|
||||
function normalizePathSegments(pathValue: string): string[] {
|
||||
return pathValue
|
||||
.replaceAll("\\", "/")
|
||||
.split("/")
|
||||
.filter((segment) => segment.length > 0);
|
||||
}
|
||||
|
||||
function compareByName(a: { name: string }, b: { name: string }): number {
|
||||
return a.name.localeCompare(b.name, undefined, SORT_LOCALE_OPTIONS);
|
||||
}
|
||||
|
||||
function readStat(file: TurnDiffFileChange): TurnDiffStat | null {
|
||||
if (typeof file.additions !== "number" || typeof file.deletions !== "number") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
};
|
||||
}
|
||||
|
||||
function compactDirectoryNode(node: TurnDiffTreeDirectoryNode): TurnDiffTreeDirectoryNode {
|
||||
const compactedChildren = node.children.map((child) =>
|
||||
child.kind === "directory" ? compactDirectoryNode(child) : child,
|
||||
);
|
||||
|
||||
let compactedNode: TurnDiffTreeDirectoryNode = {
|
||||
...node,
|
||||
children: compactedChildren,
|
||||
};
|
||||
|
||||
while (compactedNode.children.length === 1 && compactedNode.children[0]?.kind === "directory") {
|
||||
const onlyChild = compactedNode.children[0];
|
||||
compactedNode = {
|
||||
kind: "directory",
|
||||
name: `${compactedNode.name}/${onlyChild.name}`,
|
||||
path: onlyChild.path,
|
||||
stat: onlyChild.stat,
|
||||
children: onlyChild.children,
|
||||
};
|
||||
}
|
||||
|
||||
return compactedNode;
|
||||
}
|
||||
|
||||
function toTreeNodes(directory: MutableDirectoryNode): TurnDiffTreeNode[] {
|
||||
const subdirectories: TurnDiffTreeDirectoryNode[] = Array.from(directory.directories.values())
|
||||
.toSorted(compareByName)
|
||||
.map<TurnDiffTreeDirectoryNode>((subdirectory) => ({
|
||||
kind: "directory",
|
||||
name: subdirectory.name,
|
||||
path: subdirectory.path,
|
||||
stat: {
|
||||
additions: subdirectory.stat.additions,
|
||||
deletions: subdirectory.stat.deletions,
|
||||
},
|
||||
children: toTreeNodes(subdirectory),
|
||||
}))
|
||||
.map((subdirectory) => compactDirectoryNode(subdirectory));
|
||||
|
||||
const files = directory.files.toSorted(compareByName);
|
||||
return [...subdirectories, ...files];
|
||||
}
|
||||
|
||||
export function summarizeTurnDiffStats(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffStat {
|
||||
return files.reduce(
|
||||
(acc, file) => {
|
||||
const stat = readStat(file);
|
||||
if (!stat) return acc;
|
||||
return {
|
||||
additions: acc.additions + stat.additions,
|
||||
deletions: acc.deletions + stat.deletions,
|
||||
};
|
||||
},
|
||||
{ additions: 0, deletions: 0 },
|
||||
);
|
||||
}
|
||||
|
||||
export function buildTurnDiffTree(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffTreeNode[] {
|
||||
const root: MutableDirectoryNode = {
|
||||
name: "",
|
||||
path: "",
|
||||
stat: { additions: 0, deletions: 0 },
|
||||
directories: new Map(),
|
||||
files: [],
|
||||
};
|
||||
|
||||
for (const file of files) {
|
||||
const segments = normalizePathSegments(file.path);
|
||||
if (segments.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const filePath = segments.join("/");
|
||||
const fileName = segments.at(-1);
|
||||
if (!fileName) {
|
||||
continue;
|
||||
}
|
||||
const stat = readStat(file);
|
||||
const ancestors: MutableDirectoryNode[] = [root];
|
||||
let currentDirectory = root;
|
||||
|
||||
for (const segment of segments.slice(0, -1)) {
|
||||
const nextPath = currentDirectory.path ? `${currentDirectory.path}/${segment}` : segment;
|
||||
const existing = currentDirectory.directories.get(segment);
|
||||
if (existing) {
|
||||
currentDirectory = existing;
|
||||
} else {
|
||||
const created: MutableDirectoryNode = {
|
||||
name: segment,
|
||||
path: nextPath,
|
||||
stat: { additions: 0, deletions: 0 },
|
||||
directories: new Map(),
|
||||
files: [],
|
||||
};
|
||||
currentDirectory.directories.set(segment, created);
|
||||
currentDirectory = created;
|
||||
}
|
||||
ancestors.push(currentDirectory);
|
||||
}
|
||||
|
||||
currentDirectory.files.push({
|
||||
kind: "file",
|
||||
name: fileName,
|
||||
path: filePath,
|
||||
stat,
|
||||
});
|
||||
|
||||
if (stat) {
|
||||
for (const ancestor of ancestors) {
|
||||
ancestor.stat.additions += stat.additions;
|
||||
ancestor.stat.deletions += stat.deletions;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return toTreeNodes(root);
|
||||
}
|
||||
+25
-5
@@ -1,21 +1,41 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";
|
||||
import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack/react-router";
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import "./index.css";
|
||||
|
||||
import { isElectron } from "./env";
|
||||
import { getRouter } from "./router";
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
import { isElectron } from "./env";
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
|
||||
const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
|
||||
const router = getRouter(history);
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
document.title = APP_DISPLAY_NAME;
|
||||
|
||||
const router = createRouter({
|
||||
routeTree,
|
||||
history,
|
||||
context: {
|
||||
queryClient,
|
||||
},
|
||||
Wrap: ({ children }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<StoreProvider>{children}</StoreProvider>
|
||||
</QueryClientProvider>
|
||||
),
|
||||
});
|
||||
|
||||
declare module "@tanstack/react-router" {
|
||||
interface Register {
|
||||
router: typeof router;
|
||||
}
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<RouterProvider router={router} />
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import { createElement } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createRouter } from "@tanstack/react-router";
|
||||
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
type RouterHistory = NonNullable<Parameters<typeof createRouter>[0]["history"]>;
|
||||
|
||||
export function getRouter(history: RouterHistory) {
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
return createRouter({
|
||||
routeTree,
|
||||
history,
|
||||
context: {
|
||||
queryClient,
|
||||
},
|
||||
Wrap: ({ children }) =>
|
||||
createElement(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
createElement(StoreProvider, null, children),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export type AppRouter = ReturnType<typeof getRouter>;
|
||||
|
||||
declare module "@tanstack/react-router" {
|
||||
interface Register {
|
||||
router: AppRouter;
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useStore } from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
@@ -26,9 +25,6 @@ export const Route = createRootRouteWithContext<{
|
||||
}>()({
|
||||
component: RootRouteView,
|
||||
errorComponent: RootRouteErrorView,
|
||||
head: () => ({
|
||||
meta: [{ name: "title", content: APP_DISPLAY_NAME }],
|
||||
}),
|
||||
});
|
||||
|
||||
function RootRouteView() {
|
||||
@@ -127,18 +123,13 @@ function errorDetails(error: unknown): string {
|
||||
}
|
||||
|
||||
function EventRouter() {
|
||||
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
|
||||
const setProjectExpanded = useStore((store) => store.setProjectExpanded);
|
||||
const removeOrphanedTerminalStates = useTerminalStateStore(
|
||||
(store) => store.removeOrphanedTerminalStates,
|
||||
);
|
||||
const { dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const pathname = useRouterState({ select: (state) => state.location.pathname });
|
||||
const pathnameRef = useRef(pathname);
|
||||
const lastConfigIssuesSignatureRef = useRef<string | null>(null);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
|
||||
pathnameRef.current = pathname;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -153,11 +144,7 @@ function EventRouter() {
|
||||
const snapshot = await api.orchestration.getSnapshot();
|
||||
if (disposed) return;
|
||||
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
|
||||
syncServerReadModel(snapshot);
|
||||
const activeThreadIds = new Set(
|
||||
snapshot.threads.filter((t) => t.deletedAt === null).map((t) => t.id),
|
||||
);
|
||||
removeOrphanedTerminalStates(activeThreadIds);
|
||||
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
|
||||
if (pending) {
|
||||
pending = false;
|
||||
await flushSnapshotSync();
|
||||
@@ -170,13 +157,14 @@ function EventRouter() {
|
||||
return;
|
||||
}
|
||||
syncing = true;
|
||||
pending = false;
|
||||
try {
|
||||
pending = false;
|
||||
await flushSnapshotSync();
|
||||
} catch {
|
||||
// Keep prior state and wait for next domain event to trigger a resync.
|
||||
} finally {
|
||||
syncing = false;
|
||||
}
|
||||
syncing = false;
|
||||
};
|
||||
|
||||
void syncSnapshot().catch(() => undefined);
|
||||
@@ -196,13 +184,12 @@ function EventRouter() {
|
||||
if (hasRunningSubprocess === null) {
|
||||
return;
|
||||
}
|
||||
useTerminalStateStore
|
||||
.getState()
|
||||
.setTerminalActivity(
|
||||
ThreadId.makeUnsafe(event.threadId),
|
||||
event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
);
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe(event.threadId),
|
||||
terminalId: event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
});
|
||||
});
|
||||
const unsubWelcome = onServerWelcome((payload) => {
|
||||
void (async () => {
|
||||
@@ -214,7 +201,11 @@ function EventRouter() {
|
||||
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
setProjectExpanded(payload.bootstrapProjectId, true);
|
||||
dispatch({
|
||||
type: "SET_PROJECT_EXPANDED",
|
||||
projectId: payload.bootstrapProjectId,
|
||||
expanded: true,
|
||||
});
|
||||
|
||||
if (pathnameRef.current !== "/") {
|
||||
return;
|
||||
@@ -279,13 +270,7 @@ function EventRouter() {
|
||||
unsubWelcome();
|
||||
unsubServerConfigUpdated();
|
||||
};
|
||||
}, [
|
||||
navigate,
|
||||
queryClient,
|
||||
removeOrphanedTerminalStates,
|
||||
setProjectExpanded,
|
||||
syncServerReadModel,
|
||||
]);
|
||||
}, [dispatch, navigate, queryClient]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
|
||||
|
||||
import ChatView from "../components/ChatView";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { useStore } from "../store";
|
||||
@@ -133,17 +132,13 @@ const DiffPanelInlineSidebar = (props: {
|
||||
};
|
||||
|
||||
function ChatThreadRouteView() {
|
||||
const threadsHydrated = useStore((store) => store.threadsHydrated);
|
||||
const { state } = useStore();
|
||||
const navigate = useNavigate();
|
||||
const threadId = Route.useParams({
|
||||
select: (params) => ThreadId.makeUnsafe(params.threadId),
|
||||
});
|
||||
const search = Route.useSearch();
|
||||
const threadExists = useStore((store) => store.threads.some((thread) => thread.id === threadId));
|
||||
const draftThreadExists = useComposerDraftStore(
|
||||
(store) => Object.hasOwn(store.draftThreadsByThreadId, threadId),
|
||||
);
|
||||
const routeThreadExists = threadExists || draftThreadExists;
|
||||
const threadExists = state.threads.some((thread) => thread.id === threadId);
|
||||
const diffOpen = search.diff === "1";
|
||||
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
|
||||
const closeDiff = useCallback(() => {
|
||||
@@ -167,17 +162,17 @@ function ChatThreadRouteView() {
|
||||
}, [navigate, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!threadsHydrated) {
|
||||
if (!state.threadsHydrated) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!routeThreadExists) {
|
||||
if (!threadExists) {
|
||||
void navigate({ to: "/", replace: true });
|
||||
return;
|
||||
}
|
||||
}, [navigate, routeThreadExists, threadsHydrated, threadId]);
|
||||
}, [navigate, state.threadsHydrated, threadExists, threadId]);
|
||||
|
||||
if (!threadsHydrated || !routeThreadExists) {
|
||||
if (!state.threadsHydrated || !threadExists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -185,7 +180,7 @@ function ChatThreadRouteView() {
|
||||
return (
|
||||
<>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<ChatView key={threadId} threadId={threadId} />
|
||||
<ChatView threadId={threadId} />
|
||||
</SidebarInset>
|
||||
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
|
||||
</>
|
||||
@@ -195,7 +190,7 @@ function ChatThreadRouteView() {
|
||||
return (
|
||||
<>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<ChatView key={threadId} threadId={threadId} />
|
||||
<ChatView threadId={threadId} />
|
||||
</SidebarInset>
|
||||
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||
<Suspense fallback={<DiffLoadingFallback inline={false} />}>
|
||||
|
||||
@@ -48,8 +48,7 @@ const RUNTIME_MODE_OPTIONS = [
|
||||
|
||||
function SettingsRouteView() {
|
||||
const { theme, setTheme, resolvedTheme } = useTheme();
|
||||
const runtimeMode = useStore((store) => store.runtimeMode);
|
||||
const setRuntimeMode = useStore((store) => store.setRuntimeMode);
|
||||
const { state, dispatch } = useStore();
|
||||
const { settings, defaults, updateSettings } = useAppSettings();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
@@ -187,10 +186,9 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<label htmlFor="codex-binary-path" className="block space-y-1">
|
||||
<label className="block space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">Codex binary path</span>
|
||||
<Input
|
||||
id="codex-binary-path"
|
||||
value={codexBinaryPath}
|
||||
onChange={(event) => updateSettings({ codexBinaryPath: event.target.value })}
|
||||
placeholder="codex"
|
||||
@@ -201,10 +199,9 @@ function SettingsRouteView() {
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label htmlFor="codex-home-path" className="block space-y-1">
|
||||
<label className="block space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">CODEX_HOME path</span>
|
||||
<Input
|
||||
id="codex-home-path"
|
||||
value={codexHomePath}
|
||||
onChange={(event) => updateSettings({ codexHomePath: event.target.value })}
|
||||
placeholder="/Users/you/.codex"
|
||||
@@ -245,11 +242,16 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start">
|
||||
<label htmlFor="custom-model-slug" className="block flex-1 space-y-1">
|
||||
<form
|
||||
className="flex flex-col gap-3 sm:flex-row sm:items-start"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
addCustomModel();
|
||||
}}
|
||||
>
|
||||
<label className="block flex-1 space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">Custom model slug</span>
|
||||
<Input
|
||||
id="custom-model-slug"
|
||||
value={customModelInput}
|
||||
onChange={(event) => {
|
||||
setCustomModelInput(event.target.value);
|
||||
@@ -257,11 +259,6 @@ function SettingsRouteView() {
|
||||
setCustomModelError(null);
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
event.preventDefault();
|
||||
addCustomModel();
|
||||
}}
|
||||
placeholder="your-model-slug"
|
||||
spellCheck={false}
|
||||
/>
|
||||
@@ -270,10 +267,10 @@ function SettingsRouteView() {
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<Button className="sm:mt-6" type="button" onClick={addCustomModel}>
|
||||
<Button className="sm:mt-6" type="submit">
|
||||
Add model
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{customModelError ? (
|
||||
<p className="text-xs text-destructive">{customModelError}</p>
|
||||
@@ -336,7 +333,7 @@ function SettingsRouteView() {
|
||||
|
||||
<div className="space-y-2" role="radiogroup" aria-label="Runtime mode preference">
|
||||
{RUNTIME_MODE_OPTIONS.map((option) => {
|
||||
const selected = runtimeMode === option.value;
|
||||
const selected = state.runtimeMode === option.value;
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
@@ -349,7 +346,10 @@ function SettingsRouteView() {
|
||||
: "border-border bg-background text-muted-foreground hover:bg-accent"
|
||||
}`}
|
||||
onClick={() => {
|
||||
setRuntimeMode(option.value);
|
||||
dispatch({
|
||||
type: "SET_RUNTIME_MODE",
|
||||
mode: option.value,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<span className="flex flex-col">
|
||||
|
||||
@@ -3,11 +3,7 @@ import { useEffect } from "react";
|
||||
|
||||
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
|
||||
import ThreadSidebar from "../components/Sidebar";
|
||||
import { Sidebar, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
|
||||
|
||||
const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
|
||||
const THREAD_SIDEBAR_MIN_WIDTH = 16 * 16;
|
||||
const THREAD_SIDEBAR_MAX_WIDTH = 40 * 16;
|
||||
import { Sidebar, SidebarProvider } from "~/components/ui/sidebar";
|
||||
|
||||
function ChatRouteLayout() {
|
||||
const navigate = useNavigate();
|
||||
@@ -34,14 +30,8 @@ function ChatRouteLayout() {
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
className="border-r border-border bg-card text-foreground"
|
||||
resizable={{
|
||||
maxWidth: THREAD_SIDEBAR_MAX_WIDTH,
|
||||
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
|
||||
storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
|
||||
}}
|
||||
>
|
||||
<ThreadSidebar />
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
<DiffWorkerPoolProvider>
|
||||
<Outlet />
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { markThreadUnread, type AppState } from "./store";
|
||||
import type { Thread } from "./types";
|
||||
import { reducer, type AppState } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
@@ -11,6 +11,18 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
turnDiffSummaries: [],
|
||||
@@ -42,8 +54,8 @@ function makeState(thread: Thread): AppState {
|
||||
};
|
||||
}
|
||||
|
||||
describe("store pure functions", () => {
|
||||
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
|
||||
describe("store reducer", () => {
|
||||
it("marks a completed thread as unread by moving lastVisitedAt before completion", () => {
|
||||
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
@@ -59,7 +71,10 @@ describe("store pure functions", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
|
||||
const next = reducer(initialState, {
|
||||
type: "MARK_THREAD_UNREAD",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
|
||||
const updatedThread = next.threads[0];
|
||||
expect(updatedThread).toBeDefined();
|
||||
@@ -69,7 +84,7 @@ describe("store pure functions", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("markThreadUnread does not change a thread without a completed turn", () => {
|
||||
it("does not change a thread without a completed turn", () => {
|
||||
const initialState = makeState(
|
||||
makeThread({
|
||||
latestTurn: null,
|
||||
@@ -77,8 +92,70 @@ describe("store pure functions", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
|
||||
const next = reducer(initialState, {
|
||||
type: "MARK_THREAD_UNREAD",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
|
||||
expect(next).toEqual(initialState);
|
||||
});
|
||||
});
|
||||
|
||||
describe("store terminal activity reducer", () => {
|
||||
it("adds a terminal to runningTerminalIds when subprocess activity starts", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "alt",
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual(["alt"]);
|
||||
});
|
||||
|
||||
it("removes a terminal from runningTerminalIds when subprocess activity stops", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
||||
},
|
||||
],
|
||||
runningTerminalIds: ["alt"],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "alt",
|
||||
hasRunningSubprocess: false,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores activity events for unknown terminal ids", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "missing",
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
});
|
||||
+622
-209
@@ -1,4 +1,13 @@
|
||||
import { Fragment, type ReactNode, createElement, useEffect } from "react";
|
||||
import {
|
||||
type Dispatch,
|
||||
type ReactNode,
|
||||
createContext,
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
ProviderSessionId,
|
||||
@@ -7,15 +16,48 @@ import {
|
||||
type OrchestrationSessionStatus,
|
||||
resolveModelSlug,
|
||||
} from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ChatMessage,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
type Action =
|
||||
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
|
||||
| { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
|
||||
| { type: "MARK_THREAD_UNREAD"; threadId: ThreadId }
|
||||
| { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
|
||||
| {
|
||||
type: "SET_THREAD_TERMINAL_ACTIVITY";
|
||||
threadId: ThreadId;
|
||||
terminalId: string;
|
||||
hasRunningSubprocess: boolean;
|
||||
}
|
||||
| { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
|
||||
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
|
||||
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
|
||||
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
|
||||
| { type: "SPLIT_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "NEW_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "CLOSE_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
|
||||
| { type: "SET_ERROR"; threadId: ThreadId; error: string | null }
|
||||
| {
|
||||
type: "SET_THREAD_BRANCH";
|
||||
threadId: ThreadId;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}
|
||||
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AppState {
|
||||
@@ -45,10 +87,11 @@ const initialState: AppState = {
|
||||
};
|
||||
const persistedExpandedProjectCwds = new Set<string>();
|
||||
|
||||
// ── Persist helpers ──────────────────────────────────────────────────
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
|
||||
try {
|
||||
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
if (!raw) return initialState;
|
||||
@@ -76,6 +119,7 @@ function readPersistedState(): AppState {
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
PERSISTED_STATE_KEY,
|
||||
@@ -94,21 +138,12 @@ function persistState(state: AppState): void {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Pure helpers ──────────────────────────────────────────────────────
|
||||
|
||||
function updateThread(
|
||||
threads: Thread[],
|
||||
threadId: ThreadId,
|
||||
updater: (t: Thread) => Thread,
|
||||
): Thread[] {
|
||||
let changed = false;
|
||||
const next = threads.map((t) => {
|
||||
if (t.id !== threadId) return t;
|
||||
const updated = updater(t);
|
||||
if (updated !== t) changed = true;
|
||||
return updated;
|
||||
});
|
||||
return changed ? next : threads;
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
}
|
||||
|
||||
function mapProjectsFromReadModel(
|
||||
@@ -158,7 +193,9 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
if (typeof window === "undefined") {
|
||||
return "";
|
||||
}
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
@@ -167,7 +204,10 @@ function resolveWsHttpOrigin(): string {
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
if (!wsCandidate) return window.location.origin;
|
||||
if (!wsCandidate) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
try {
|
||||
const wsUrl = new URL(wsCandidate);
|
||||
const protocol =
|
||||
@@ -193,221 +233,594 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
|
||||
return `/attachments/${encodeURIComponent(attachmentId)}`;
|
||||
}
|
||||
|
||||
// ── Pure state transition functions ────────────────────────────────────
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
if (unique.length > 0) {
|
||||
return unique;
|
||||
}
|
||||
return [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}
|
||||
|
||||
export function syncServerReadModel(
|
||||
state: AppState,
|
||||
readModel: OrchestrationReadModel,
|
||||
): AppState {
|
||||
const projects = mapProjectsFromReadModel(
|
||||
readModel.projects.filter((project) => project.deletedAt === null),
|
||||
state.projects,
|
||||
);
|
||||
const existingThreadById = new Map(
|
||||
state.threads.map((thread) => [thread.id, thread] as const),
|
||||
);
|
||||
const threads = readModel.threads
|
||||
.filter((thread) => thread.deletedAt === null)
|
||||
.map((thread) => {
|
||||
const existing = existingThreadById.get(thread.id);
|
||||
return {
|
||||
id: thread.id,
|
||||
codexThreadId: thread.session?.providerThreadId ?? null,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlug(thread.model),
|
||||
session: thread.session
|
||||
? {
|
||||
sessionId:
|
||||
thread.session.providerSessionId ??
|
||||
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
|
||||
provider: toLegacyProvider(thread.session.providerName),
|
||||
status: toLegacySessionStatus(thread.session.status),
|
||||
orchestrationStatus: thread.session.status,
|
||||
threadId: thread.session.providerThreadId,
|
||||
activeTurnId: thread.session.activeTurnId ?? undefined,
|
||||
createdAt: thread.session.updatedAt,
|
||||
updatedAt: thread.session.updatedAt,
|
||||
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
|
||||
}
|
||||
: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const attachments = message.attachments?.map((attachment) => ({
|
||||
type: "image" as const,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
|
||||
}));
|
||||
const normalizedMessage: ChatMessage = {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
...(message.streaming ? {} : { completedAt: message.updatedAt }),
|
||||
...(attachments && attachments.length > 0 ? { attachments } : {}),
|
||||
};
|
||||
return normalizedMessage;
|
||||
}),
|
||||
error: thread.session?.lastError ?? null,
|
||||
createdAt: thread.createdAt,
|
||||
latestTurn: thread.latestTurn,
|
||||
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
|
||||
turnId: checkpoint.turnId,
|
||||
completedAt: checkpoint.completedAt,
|
||||
status: checkpoint.status,
|
||||
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
|
||||
checkpointTurnCount: checkpoint.checkpointTurnCount,
|
||||
checkpointRef: checkpoint.checkpointRef,
|
||||
files: checkpoint.files.map((file) => ({ ...file })),
|
||||
})),
|
||||
activities: thread.activities.map((activity) => ({ ...activity })),
|
||||
};
|
||||
function normalizeRunningTerminalIds(
|
||||
runningTerminalIds: string[],
|
||||
terminalIds: string[],
|
||||
): string[] {
|
||||
if (runningTerminalIds.length === 0) return [];
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
return [...new Set(runningTerminalIds)]
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
|
||||
if (!usedGroupIds.has(groupId)) {
|
||||
usedGroupIds.add(groupId);
|
||||
return groupId;
|
||||
}
|
||||
let suffix = 2;
|
||||
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
const uniqueGroupId = `${groupId}-${suffix}`;
|
||||
usedGroupIds.add(uniqueGroupId);
|
||||
return uniqueGroupId;
|
||||
}
|
||||
|
||||
function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const usedGroupIds = new Set<string>();
|
||||
const groups: ThreadTerminalGroup[] = [];
|
||||
|
||||
for (const group of thread.terminalGroups) {
|
||||
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
|
||||
if (!validTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
return {
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
threadsHydrated: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function markThreadVisited(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
visitedAt?: string,
|
||||
): AppState {
|
||||
const at = visitedAt ?? new Date().toISOString();
|
||||
const visitedAtMs = Date.parse(at);
|
||||
const threads = updateThread(state.threads, threadId, (thread) => {
|
||||
const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
|
||||
if (
|
||||
Number.isFinite(previousVisitedAtMs) &&
|
||||
Number.isFinite(visitedAtMs) &&
|
||||
previousVisitedAtMs >= visitedAtMs
|
||||
) {
|
||||
return thread;
|
||||
if (groupTerminalIds.length === 0) continue;
|
||||
for (const terminalId of groupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
return { ...thread, lastVisitedAt: at };
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
groups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
groups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (groups.length > 0) {
|
||||
return groups;
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function markThreadUnread(state: AppState, threadId: ThreadId): AppState {
|
||||
const threads = updateThread(state.threads, threadId, (thread) => {
|
||||
if (!thread.latestTurn?.completedAt) return thread;
|
||||
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
|
||||
if (Number.isNaN(latestTurnCompletedAtMs)) return thread;
|
||||
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
|
||||
if (thread.lastVisitedAt === unreadVisitedAt) return thread;
|
||||
return { ...thread, lastVisitedAt: unreadVisitedAt };
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
function findGroupIndexByTerminalId(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalId: string,
|
||||
): number {
|
||||
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
|
||||
}
|
||||
|
||||
export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
|
||||
function normalizeThreadTerminals(thread: Thread): Thread {
|
||||
const terminalIds = normalizeTerminalIds(thread.terminalIds);
|
||||
const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
|
||||
? thread.activeTerminalId
|
||||
: (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
|
||||
const activeGroupIndexFromId = terminalGroups.findIndex(
|
||||
(group) => group.id === thread.activeTerminalGroupId,
|
||||
);
|
||||
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
|
||||
const activeGroupIndex =
|
||||
activeGroupIndexFromId >= 0
|
||||
? activeGroupIndexFromId
|
||||
: activeGroupIndexFromTerminal >= 0
|
||||
? activeGroupIndexFromTerminal
|
||||
: 0;
|
||||
const activeTerminalGroupId =
|
||||
terminalGroups[activeGroupIndex]?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(activeTerminalId);
|
||||
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === projectId ? { ...p, expanded: !p.expanded } : p,
|
||||
),
|
||||
...thread,
|
||||
terminalIds,
|
||||
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
|
||||
export function setProjectExpanded(
|
||||
state: AppState,
|
||||
projectId: Project["id"],
|
||||
expanded: boolean,
|
||||
): AppState {
|
||||
let changed = false;
|
||||
const projects = state.projects.map((p) => {
|
||||
if (p.id !== projectId || p.expanded === expanded) return p;
|
||||
changed = true;
|
||||
return { ...p, expanded };
|
||||
function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
if (!thread.terminalIds.includes(terminalId)) {
|
||||
return thread;
|
||||
}
|
||||
|
||||
const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
|
||||
if (remainingTerminalIds.length === 0) {
|
||||
const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID);
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalOpen: false,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: nextTerminalGroupId,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: nextTerminalGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
|
||||
const closedTerminalGroup = thread.terminalGroups.find((group) =>
|
||||
group.terminalIds.includes(terminalId),
|
||||
);
|
||||
const closedTerminalGroupIndex = closedTerminalGroup
|
||||
? closedTerminalGroup.terminalIds.indexOf(terminalId)
|
||||
: -1;
|
||||
const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
|
||||
(id) => id !== terminalId,
|
||||
);
|
||||
const nextActiveTerminalId =
|
||||
thread.activeTerminalId === terminalId
|
||||
? (remainingTerminalsInClosedGroup[
|
||||
Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
|
||||
] ??
|
||||
remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
: thread.activeTerminalId;
|
||||
const nextTerminalGroups = thread.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups: nextTerminalGroups,
|
||||
});
|
||||
return changed ? { ...state, projects } : state;
|
||||
}
|
||||
|
||||
export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
|
||||
const threads = updateThread(state.threads, threadId, (t) => {
|
||||
if (t.error === error) return t;
|
||||
return { ...t, error };
|
||||
function setThreadTerminalActivity(
|
||||
thread: Thread,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
): Thread {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
if (!normalizedThread.terminalIds.includes(terminalId)) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
|
||||
if (hasRunningSubprocess) {
|
||||
runningTerminalIds.add(terminalId);
|
||||
} else {
|
||||
runningTerminalIds.delete(terminalId);
|
||||
}
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
runningTerminalIds: [...runningTerminalIds],
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
}
|
||||
|
||||
export function setThreadBranch(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
branch: string | null,
|
||||
worktreePath: string | null,
|
||||
): AppState {
|
||||
const threads = updateThread(state.threads, threadId, (t) => {
|
||||
if (t.branch === branch && t.worktreePath === worktreePath) return t;
|
||||
const cwdChanged = t.worktreePath !== worktreePath;
|
||||
return {
|
||||
...t,
|
||||
branch,
|
||||
worktreePath,
|
||||
...(cwdChanged ? { session: null } : {}),
|
||||
};
|
||||
});
|
||||
return threads === state.threads ? state : { ...state, threads };
|
||||
// ── Reducer ──────────────────────────────────────────────────────────
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "SYNC_SERVER_READ_MODEL": {
|
||||
const projects = mapProjectsFromReadModel(
|
||||
action.readModel.projects.filter((project) => project.deletedAt === null),
|
||||
state.projects,
|
||||
);
|
||||
const existingThreadById = new Map(
|
||||
state.threads.map((thread) => [thread.id, thread] as const),
|
||||
);
|
||||
const threads = action.readModel.threads
|
||||
.filter((thread) => thread.deletedAt === null)
|
||||
.map((thread) => {
|
||||
const existing = existingThreadById.get(thread.id);
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
id: thread.id,
|
||||
codexThreadId: thread.session?.providerThreadId ?? null,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlug(thread.model),
|
||||
terminalOpen: existing?.terminalOpen ?? false,
|
||||
terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: existing?.runningTerminalIds ?? [],
|
||||
activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: existing?.terminalGroups ?? [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId:
|
||||
existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: thread.session
|
||||
? {
|
||||
sessionId:
|
||||
thread.session.providerSessionId ??
|
||||
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
|
||||
provider: toLegacyProvider(thread.session.providerName),
|
||||
status: toLegacySessionStatus(thread.session.status),
|
||||
orchestrationStatus: thread.session.status,
|
||||
threadId: thread.session.providerThreadId,
|
||||
activeTurnId: thread.session.activeTurnId ?? undefined,
|
||||
createdAt: thread.session.updatedAt,
|
||||
updatedAt: thread.session.updatedAt,
|
||||
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
|
||||
}
|
||||
: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const attachments = message.attachments?.map((attachment) => ({
|
||||
type: "image" as const,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
|
||||
}));
|
||||
const normalizedMessage: ChatMessage = {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
...(message.streaming ? {} : { completedAt: message.updatedAt }),
|
||||
...(attachments && attachments.length > 0 ? { attachments } : {}),
|
||||
};
|
||||
return normalizedMessage;
|
||||
}),
|
||||
error: thread.session?.lastError ?? null,
|
||||
createdAt: thread.createdAt,
|
||||
latestTurn: thread.latestTurn,
|
||||
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
|
||||
turnId: checkpoint.turnId,
|
||||
completedAt: checkpoint.completedAt,
|
||||
status: checkpoint.status,
|
||||
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
|
||||
checkpointTurnCount: checkpoint.checkpointTurnCount,
|
||||
checkpointRef: checkpoint.checkpointRef,
|
||||
files: checkpoint.files.map((file) => ({ ...file })),
|
||||
})),
|
||||
activities: thread.activities.map((activity) => ({ ...activity })),
|
||||
});
|
||||
});
|
||||
return {
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
threadsHydrated: true,
|
||||
};
|
||||
}
|
||||
|
||||
case "MARK_THREAD_VISITED": {
|
||||
const visitedAt = action.visitedAt ?? new Date().toISOString();
|
||||
const visitedAtMs = Date.parse(visitedAt);
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
|
||||
if (
|
||||
Number.isFinite(previousVisitedAtMs) &&
|
||||
Number.isFinite(visitedAtMs) &&
|
||||
previousVisitedAtMs >= visitedAtMs
|
||||
) {
|
||||
return thread;
|
||||
}
|
||||
return {
|
||||
...thread,
|
||||
lastVisitedAt: visitedAt,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "MARK_THREAD_UNREAD": {
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
if (!thread.latestTurn?.completedAt) {
|
||||
return thread;
|
||||
}
|
||||
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
|
||||
if (Number.isNaN(latestTurnCompletedAtMs)) {
|
||||
return thread;
|
||||
}
|
||||
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
|
||||
if (thread.lastVisitedAt === unreadVisitedAt) {
|
||||
return thread;
|
||||
}
|
||||
return {
|
||||
...thread,
|
||||
lastVisitedAt: unreadVisitedAt,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "TOGGLE_PROJECT":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TERMINAL_ACTIVITY":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) =>
|
||||
setThreadTerminalActivity(thread, action.terminalId, action.hasRunningSubprocess),
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_PROJECT_EXPANDED":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
|
||||
),
|
||||
};
|
||||
|
||||
case "TOGGLE_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
terminalOpen: !t.terminalOpen,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TERMINAL_OPEN":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
terminalOpen: action.open,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TERMINAL_HEIGHT":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
terminalHeight: action.height,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SPLIT_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
|
||||
...group,
|
||||
terminalIds: [...group.terminalIds],
|
||||
}));
|
||||
let activeGroupIndex = terminalGroups.findIndex(
|
||||
(group) => group.id === normalizedThread.activeTerminalGroupId,
|
||||
);
|
||||
if (activeGroupIndex < 0) {
|
||||
activeGroupIndex = findGroupIndexByTerminalId(
|
||||
terminalGroups,
|
||||
normalizedThread.activeTerminalId,
|
||||
);
|
||||
}
|
||||
if (activeGroupIndex < 0) {
|
||||
terminalGroups.push({
|
||||
id: fallbackGroupId(normalizedThread.activeTerminalId),
|
||||
terminalIds: [normalizedThread.activeTerminalId],
|
||||
});
|
||||
activeGroupIndex = terminalGroups.length - 1;
|
||||
}
|
||||
|
||||
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
|
||||
if (existingGroupIndex >= 0) {
|
||||
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
|
||||
existingGroupIndex
|
||||
]!.terminalIds.filter((id) => id !== action.terminalId);
|
||||
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
|
||||
terminalGroups.splice(existingGroupIndex, 1);
|
||||
if (existingGroupIndex < activeGroupIndex) {
|
||||
activeGroupIndex -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const destinationGroup = terminalGroups[activeGroupIndex];
|
||||
if (!destinationGroup) {
|
||||
return normalizedThread;
|
||||
}
|
||||
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(
|
||||
normalizedThread.activeTerminalId,
|
||||
);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
|
||||
} else {
|
||||
destinationGroup.terminalIds.push(action.terminalId);
|
||||
}
|
||||
}
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
terminalIds,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId: destinationGroup.id,
|
||||
terminalGroups,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "NEW_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
const terminalGroups = normalizedThread.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
const nextGroupId = fallbackGroupId(action.terminalId);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
terminalIds,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId: nextGroupId,
|
||||
terminalGroups,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_ACTIVE_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
if (!normalizedThread.terminalIds.includes(action.terminalId)) {
|
||||
return thread;
|
||||
}
|
||||
const nextActiveGroupIndex = findGroupIndexByTerminalId(
|
||||
normalizedThread.terminalGroups,
|
||||
action.terminalId,
|
||||
);
|
||||
const activeTerminalGroupId =
|
||||
nextActiveGroupIndex >= 0
|
||||
? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
|
||||
normalizedThread.activeTerminalGroupId)
|
||||
: normalizedThread.activeTerminalGroupId;
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "CLOSE_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) =>
|
||||
closeThreadTerminal(thread, action.terminalId),
|
||||
),
|
||||
};
|
||||
|
||||
case "SET_ERROR":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
error: action.error,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_BRANCH": {
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
||||
// When the effective cwd changes (worktreePath differs), the old
|
||||
// session is no longer valid — clear it so ensureSession creates a
|
||||
// new one with the correct cwd on the next message.
|
||||
const cwdChanged = t.worktreePath !== action.worktreePath;
|
||||
return {
|
||||
...t,
|
||||
branch: action.branch,
|
||||
worktreePath: action.worktreePath,
|
||||
...(cwdChanged ? { session: null } : {}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "SET_RUNTIME_MODE":
|
||||
return {
|
||||
...state,
|
||||
runtimeMode: action.mode,
|
||||
};
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
export function setRuntimeMode(state: AppState, mode: RuntimeMode): AppState {
|
||||
if (state.runtimeMode === mode) return state;
|
||||
return { ...state, runtimeMode: mode };
|
||||
}
|
||||
// ── Context ──────────────────────────────────────────────────────────
|
||||
|
||||
// ── Zustand store ────────────────────────────────────────────────────
|
||||
|
||||
interface AppStore extends AppState {
|
||||
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
|
||||
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
|
||||
markThreadUnread: (threadId: ThreadId) => void;
|
||||
toggleProject: (projectId: Project["id"]) => void;
|
||||
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
|
||||
setError: (threadId: ThreadId, error: string | null) => void;
|
||||
setThreadBranch: (
|
||||
threadId: ThreadId,
|
||||
branch: string | null,
|
||||
worktreePath: string | null,
|
||||
) => void;
|
||||
setRuntimeMode: (mode: RuntimeMode) => void;
|
||||
}
|
||||
|
||||
export const useStore = create<AppStore>((set) => ({
|
||||
...readPersistedState(),
|
||||
syncServerReadModel: (readModel) =>
|
||||
set((state) => syncServerReadModel(state, readModel)),
|
||||
markThreadVisited: (threadId, visitedAt) =>
|
||||
set((state) => markThreadVisited(state, threadId, visitedAt)),
|
||||
markThreadUnread: (threadId) =>
|
||||
set((state) => markThreadUnread(state, threadId)),
|
||||
toggleProject: (projectId) =>
|
||||
set((state) => toggleProject(state, projectId)),
|
||||
setProjectExpanded: (projectId, expanded) =>
|
||||
set((state) => setProjectExpanded(state, projectId, expanded)),
|
||||
setError: (threadId, error) =>
|
||||
set((state) => setError(state, threadId, error)),
|
||||
setThreadBranch: (threadId, branch, worktreePath) =>
|
||||
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
|
||||
setRuntimeMode: (mode) =>
|
||||
set((state) => setRuntimeMode(state, mode)),
|
||||
}));
|
||||
|
||||
// Persist on every state change (only runtimeMode + expandedProjectCwds)
|
||||
useStore.subscribe((state) => persistState(state));
|
||||
const StoreContext = createContext<{
|
||||
state: AppState;
|
||||
dispatch: Dispatch<Action>;
|
||||
}>({ state: initialState, dispatch: () => {} });
|
||||
|
||||
export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
|
||||
|
||||
useEffect(() => {
|
||||
persistState(useStore.getState());
|
||||
}, []);
|
||||
return createElement(Fragment, null, children);
|
||||
persistState(state);
|
||||
}, [state]);
|
||||
|
||||
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
|
||||
}
|
||||
|
||||
export function useStore() {
|
||||
return useContext(StoreContext);
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "./terminalStateStore";
|
||||
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
|
||||
describe("terminalStateStore actions", () => {
|
||||
beforeEach(() => {
|
||||
if (typeof localStorage !== "undefined") {
|
||||
localStorage.clear();
|
||||
}
|
||||
useTerminalStateStore.setState({ terminalStateByThreadId: {} });
|
||||
});
|
||||
|
||||
it("returns a closed default terminal state for unknown threads", () => {
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState).toEqual({
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
});
|
||||
});
|
||||
|
||||
it("opens and splits terminals into the active group", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.setTerminalOpen(THREAD_ID, true);
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState.terminalOpen).toBe(true);
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates new terminals in a separate group", () => {
|
||||
useTerminalStateStore.getState().newTerminal(THREAD_ID, "terminal-2");
|
||||
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.activeTerminalGroupId).toBe("group-terminal-2");
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default"] },
|
||||
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("tracks and clears terminal subprocess activity", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
store.setTerminalActivity(THREAD_ID, "terminal-2", true);
|
||||
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).runningTerminalIds).toEqual([
|
||||
"terminal-2",
|
||||
]);
|
||||
|
||||
store.setTerminalActivity(THREAD_ID, "terminal-2", false);
|
||||
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).runningTerminalIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("resets to default and clears persisted entry when closing the last terminal", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.closeTerminal(THREAD_ID, "default");
|
||||
|
||||
expect(useTerminalStateStore.getState().terminalStateByThreadId[THREAD_ID]).toBeUndefined();
|
||||
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).terminalIds).toEqual(["default"]);
|
||||
});
|
||||
|
||||
it("keeps a valid active terminal after closing an active split terminal", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
store.splitTerminal(THREAD_ID, "terminal-3");
|
||||
store.closeTerminal(THREAD_ID, "terminal-3");
|
||||
|
||||
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,532 +0,0 @@
|
||||
/**
|
||||
* Single Zustand store for terminal UI state keyed by threadId.
|
||||
*
|
||||
* Terminal transition helpers are intentionally private to keep the public
|
||||
* API constrained to store actions/selectors.
|
||||
*/
|
||||
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
interface ThreadTerminalState {
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
}
|
||||
|
||||
const TERMINAL_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))].slice(
|
||||
0,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
);
|
||||
return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}
|
||||
|
||||
function normalizeRunningTerminalIds(runningTerminalIds: string[], terminalIds: string[]): string[] {
|
||||
if (runningTerminalIds.length === 0) return [];
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
return [...new Set(runningTerminalIds)]
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(baseId: string, usedGroupIds: Set<string>): string {
|
||||
let candidate = baseId;
|
||||
let index = 2;
|
||||
while (usedGroupIds.has(candidate)) {
|
||||
candidate = `${baseId}-${index}`;
|
||||
index += 1;
|
||||
}
|
||||
usedGroupIds.add(candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function findGroupIndexByTerminalId(terminalGroups: ThreadTerminalGroup[], terminalId: string): number {
|
||||
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
function normalizeTerminalGroups(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalIds: string[],
|
||||
): ThreadTerminalGroup[] {
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const nextGroups: ThreadTerminalGroup[] = [];
|
||||
const usedGroupIds = new Set<string>();
|
||||
|
||||
for (const group of terminalGroups) {
|
||||
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
|
||||
if (!validTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (groupTerminalIds.length === 0) continue;
|
||||
for (const terminalId of groupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (nextGroups.length === 0) {
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return nextGroups;
|
||||
}
|
||||
|
||||
function arraysEqual(a: string[], b: string[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let index = 0; index < a.length; index += 1) {
|
||||
if (a[index] !== b[index]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalGroup[]): boolean {
|
||||
if (left.length !== right.length) return false;
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
const leftGroup = left[index];
|
||||
const rightGroup = right[index];
|
||||
if (!leftGroup || !rightGroup) return false;
|
||||
if (leftGroup.id !== rightGroup.id) return false;
|
||||
if (!arraysEqual(leftGroup.terminalIds, rightGroup.terminalIds)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTerminalState): boolean {
|
||||
return (
|
||||
left.terminalOpen === right.terminalOpen &&
|
||||
left.terminalHeight === right.terminalHeight &&
|
||||
left.activeTerminalId === right.activeTerminalId &&
|
||||
left.activeTerminalGroupId === right.activeTerminalGroupId &&
|
||||
arraysEqual(left.terminalIds, right.terminalIds) &&
|
||||
arraysEqual(left.runningTerminalIds, right.runningTerminalIds) &&
|
||||
terminalGroupsEqual(left.terminalGroups, right.terminalGroups)
|
||||
);
|
||||
}
|
||||
|
||||
const DEFAULT_THREAD_TERMINAL_STATE: ThreadTerminalState = Object.freeze({
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
});
|
||||
|
||||
function createDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
return {
|
||||
...DEFAULT_THREAD_TERMINAL_STATE,
|
||||
terminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.terminalIds],
|
||||
runningTerminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalIds],
|
||||
terminalGroups: copyTerminalGroups(DEFAULT_THREAD_TERMINAL_STATE.terminalGroups),
|
||||
};
|
||||
}
|
||||
|
||||
function getDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
return DEFAULT_THREAD_TERMINAL_STATE;
|
||||
}
|
||||
|
||||
function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTerminalState {
|
||||
const terminalIds = normalizeTerminalIds(state.terminalIds);
|
||||
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
const runningTerminalIds = normalizeRunningTerminalIds(state.runningTerminalIds, nextTerminalIds);
|
||||
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
|
||||
? state.activeTerminalId
|
||||
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);
|
||||
const activeGroupIdFromState = terminalGroups.some((group) => group.id === state.activeTerminalGroupId)
|
||||
? state.activeTerminalGroupId
|
||||
: null;
|
||||
const activeGroupIdFromTerminal =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? null;
|
||||
|
||||
const normalized: ThreadTerminalState = {
|
||||
terminalOpen: state.terminalOpen,
|
||||
terminalHeight:
|
||||
Number.isFinite(state.terminalHeight) && state.terminalHeight > 0
|
||||
? state.terminalHeight
|
||||
: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: nextTerminalIds,
|
||||
runningTerminalIds,
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId:
|
||||
activeGroupIdFromState ??
|
||||
activeGroupIdFromTerminal ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
};
|
||||
return threadTerminalStateEqual(state, normalized) ? state : normalized;
|
||||
}
|
||||
|
||||
function isDefaultThreadTerminalState(state: ThreadTerminalState): boolean {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
return threadTerminalStateEqual(normalized, DEFAULT_THREAD_TERMINAL_STATE);
|
||||
}
|
||||
|
||||
function isValidTerminalId(terminalId: string): boolean {
|
||||
return terminalId.trim().length > 0;
|
||||
}
|
||||
|
||||
function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[] {
|
||||
return groups.map((group) => ({
|
||||
id: group.id,
|
||||
terminalIds: [...group.terminalIds],
|
||||
}));
|
||||
}
|
||||
|
||||
function upsertTerminalIntoGroups(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
mode: "split" | "new",
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!isValidTerminalId(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const isNewTerminal = !normalized.terminalIds.includes(terminalId);
|
||||
if (isNewTerminal && normalized.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const terminalIds = isNewTerminal ? [...normalized.terminalIds, terminalId] : normalized.terminalIds;
|
||||
const terminalGroups = copyTerminalGroups(normalized.terminalGroups);
|
||||
|
||||
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, terminalId);
|
||||
if (existingGroupIndex >= 0) {
|
||||
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[existingGroupIndex]!.terminalIds.filter(
|
||||
(id) => id !== terminalId,
|
||||
);
|
||||
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
|
||||
terminalGroups.splice(existingGroupIndex, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === "new") {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [terminalId] });
|
||||
return normalizeThreadTerminalState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
let activeGroupIndex = terminalGroups.findIndex((group) => group.id === normalized.activeTerminalGroupId);
|
||||
if (activeGroupIndex < 0) {
|
||||
activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalized.activeTerminalId);
|
||||
}
|
||||
if (activeGroupIndex < 0) {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(fallbackGroupId(normalized.activeTerminalId), usedGroupIds);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [normalized.activeTerminalId] });
|
||||
activeGroupIndex = terminalGroups.length - 1;
|
||||
}
|
||||
|
||||
const destinationGroup = terminalGroups[activeGroupIndex];
|
||||
if (!destinationGroup) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (!destinationGroup.terminalIds.includes(terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(normalized.activeTerminalId);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, terminalId);
|
||||
} else {
|
||||
destinationGroup.terminalIds.push(terminalId);
|
||||
}
|
||||
}
|
||||
|
||||
return normalizeThreadTerminalState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: destinationGroup.id,
|
||||
});
|
||||
}
|
||||
|
||||
function setThreadTerminalOpen(state: ThreadTerminalState, open: boolean): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (normalized.terminalOpen === open) return normalized;
|
||||
return { ...normalized, terminalOpen: open };
|
||||
}
|
||||
|
||||
function setThreadTerminalHeight(state: ThreadTerminalState, height: number): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!Number.isFinite(height) || height <= 0 || normalized.terminalHeight === height) {
|
||||
return normalized;
|
||||
}
|
||||
return { ...normalized, terminalHeight: height };
|
||||
}
|
||||
|
||||
function splitThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
return upsertTerminalIntoGroups(state, terminalId, "split");
|
||||
}
|
||||
|
||||
function newThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
return upsertTerminalIntoGroups(state, terminalId, "new");
|
||||
}
|
||||
|
||||
function setThreadActiveTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const activeTerminalGroupId =
|
||||
normalized.terminalGroups.find((group) => group.terminalIds.includes(terminalId))?.id ??
|
||||
normalized.activeTerminalGroupId;
|
||||
if (
|
||||
normalized.activeTerminalId === terminalId &&
|
||||
normalized.activeTerminalGroupId === activeTerminalGroupId
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
return {
|
||||
...normalized,
|
||||
activeTerminalId: terminalId,
|
||||
activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
|
||||
function closeThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const remainingTerminalIds = normalized.terminalIds.filter((id) => id !== terminalId);
|
||||
if (remainingTerminalIds.length === 0) {
|
||||
return createDefaultThreadTerminalState();
|
||||
}
|
||||
|
||||
const closedTerminalIndex = normalized.terminalIds.indexOf(terminalId);
|
||||
const nextActiveTerminalId =
|
||||
normalized.activeTerminalId === terminalId
|
||||
? (remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
: normalized.activeTerminalId;
|
||||
|
||||
const terminalGroups = normalized.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
|
||||
const nextActiveTerminalGroupId =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(nextActiveTerminalId);
|
||||
|
||||
return normalizeThreadTerminalState({
|
||||
terminalOpen: normalized.terminalOpen,
|
||||
terminalHeight: normalized.terminalHeight,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: normalized.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextActiveTerminalGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
function setThreadTerminalActivity(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const alreadyRunning = normalized.runningTerminalIds.includes(terminalId);
|
||||
if (hasRunningSubprocess === alreadyRunning) {
|
||||
return normalized;
|
||||
}
|
||||
const runningTerminalIds = new Set(normalized.runningTerminalIds);
|
||||
if (hasRunningSubprocess) {
|
||||
runningTerminalIds.add(terminalId);
|
||||
} else {
|
||||
runningTerminalIds.delete(terminalId);
|
||||
}
|
||||
return { ...normalized, runningTerminalIds: [...runningTerminalIds] };
|
||||
}
|
||||
|
||||
export function selectThreadTerminalState(
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>,
|
||||
threadId: ThreadId,
|
||||
): ThreadTerminalState {
|
||||
if (threadId.length === 0) {
|
||||
return getDefaultThreadTerminalState();
|
||||
}
|
||||
return terminalStateByThreadId[threadId] ?? getDefaultThreadTerminalState();
|
||||
}
|
||||
|
||||
function updateTerminalStateByThreadId(
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>,
|
||||
threadId: ThreadId,
|
||||
updater: (state: ThreadTerminalState) => ThreadTerminalState,
|
||||
): Record<ThreadId, ThreadTerminalState> {
|
||||
if (threadId.length === 0) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
|
||||
const current = selectThreadTerminalState(terminalStateByThreadId, threadId);
|
||||
const next = updater(current);
|
||||
if (next === current) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
|
||||
if (isDefaultThreadTerminalState(next)) {
|
||||
if (terminalStateByThreadId[threadId] === undefined) {
|
||||
return terminalStateByThreadId;
|
||||
}
|
||||
const { [threadId]: _removed, ...rest } = terminalStateByThreadId;
|
||||
return rest as Record<ThreadId, ThreadTerminalState>;
|
||||
}
|
||||
|
||||
return {
|
||||
...terminalStateByThreadId,
|
||||
[threadId]: next,
|
||||
};
|
||||
}
|
||||
|
||||
interface TerminalStateStoreState {
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>;
|
||||
setTerminalOpen: (threadId: ThreadId, open: boolean) => void;
|
||||
setTerminalHeight: (threadId: ThreadId, height: number) => void;
|
||||
splitTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
newTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
setActiveTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
closeTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
setTerminalActivity: (
|
||||
threadId: ThreadId,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
) => void;
|
||||
clearTerminalState: (threadId: ThreadId) => void;
|
||||
removeOrphanedTerminalStates: (activeThreadIds: Set<ThreadId>) => void;
|
||||
}
|
||||
|
||||
export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
persist(
|
||||
(set) => {
|
||||
const updateTerminal = (
|
||||
threadId: ThreadId,
|
||||
updater: (state: ThreadTerminalState) => ThreadTerminalState,
|
||||
) => {
|
||||
set((state) => {
|
||||
const nextTerminalStateByThreadId = updateTerminalStateByThreadId(
|
||||
state.terminalStateByThreadId,
|
||||
threadId,
|
||||
updater,
|
||||
);
|
||||
if (nextTerminalStateByThreadId === state.terminalStateByThreadId) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
terminalStateByThreadId: nextTerminalStateByThreadId,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
terminalStateByThreadId: {},
|
||||
setTerminalOpen: (threadId, open) =>
|
||||
updateTerminal(threadId, (state) => setThreadTerminalOpen(state, open)),
|
||||
setTerminalHeight: (threadId, height) =>
|
||||
updateTerminal(threadId, (state) => setThreadTerminalHeight(state, height)),
|
||||
splitTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => splitThreadTerminal(state, terminalId)),
|
||||
newTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => newThreadTerminal(state, terminalId)),
|
||||
setActiveTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => setThreadActiveTerminal(state, terminalId)),
|
||||
closeTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => closeThreadTerminal(state, terminalId)),
|
||||
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
|
||||
updateTerminal(threadId, (state) =>
|
||||
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
|
||||
),
|
||||
clearTerminalState: (threadId) =>
|
||||
updateTerminal(threadId, () => createDefaultThreadTerminalState()),
|
||||
removeOrphanedTerminalStates: (activeThreadIds) =>
|
||||
set((state) => {
|
||||
const orphanedIds = Object.keys(state.terminalStateByThreadId).filter(
|
||||
(id) => !activeThreadIds.has(id as ThreadId),
|
||||
);
|
||||
if (orphanedIds.length === 0) return state;
|
||||
const next = { ...state.terminalStateByThreadId };
|
||||
for (const id of orphanedIds) {
|
||||
delete next[id as ThreadId];
|
||||
}
|
||||
return { terminalStateByThreadId: next };
|
||||
}),
|
||||
};
|
||||
},
|
||||
{
|
||||
name: TERMINAL_STATE_STORAGE_KEY,
|
||||
version: 1,
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
partialize: (state) => ({
|
||||
terminalStateByThreadId: state.terminalStateByThreadId,
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
export function truncateTitle(text: string, maxLength = 300): string {
|
||||
export function truncateTitle(text: string, maxLength = 50): string {
|
||||
const trimmed = text.trim();
|
||||
if (trimmed.length <= maxLength) {
|
||||
return trimmed;
|
||||
|
||||
@@ -79,6 +79,13 @@ export interface Thread {
|
||||
projectId: ProjectId;
|
||||
title: string;
|
||||
model: string;
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
session: ThreadSession | null;
|
||||
messages: ChatMessage[];
|
||||
error: string | null;
|
||||
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user