Compare commits
159
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61a8ca2c31 | ||
|
|
8294392062 | ||
|
|
b58b8fd0fd | ||
|
|
9f068356a4 | ||
|
|
f239c90628 | ||
|
|
991dd05e72 | ||
|
|
96bf54e293 | ||
|
|
5ca9b54d66 | ||
|
|
4ab5fca4ca | ||
|
|
69a4fa8215 | ||
|
|
9e04bad0a5 | ||
|
|
a574d9c936 | ||
|
|
005e13089a | ||
|
|
d9cce6402a | ||
|
|
508872e04b | ||
|
|
aced302b63 | ||
|
|
0b8dfee17b | ||
|
|
6ab246676e | ||
|
|
122c94a24a | ||
|
|
b59c6d6ab1 | ||
|
|
c9995995a4 | ||
|
|
545a9193e2 | ||
|
|
fa0205cba3 | ||
|
|
8a20bd7f54 | ||
|
|
10660f376c | ||
|
|
ae235f7155 | ||
|
|
a356cd0d0f | ||
|
|
58b932ffb8 | ||
|
|
d58af33fba | ||
|
|
a56418f8bc | ||
|
|
596e1590df | ||
|
|
70c9147c7f | ||
|
|
c0054cb56f | ||
|
|
41734dfbbf | ||
|
|
8f42d34db9 | ||
|
|
70857ce299 | ||
|
|
5e0ec38383 | ||
|
|
913d0409f6 | ||
|
|
ac0e720de1 | ||
|
|
5144d32b77 | ||
|
|
128cc21516 | ||
|
|
215ff36362 | ||
|
|
505b4d0bc3 | ||
|
|
343c0a9472 | ||
|
|
82681606d0 | ||
|
|
c91b79b6e2 | ||
|
|
5e55aa387f | ||
|
|
a21095bc9a | ||
|
|
ba03241df3 | ||
|
|
a8059dc2c0 | ||
|
|
be873bca3e | ||
|
|
e8bde958f1 | ||
|
|
95f21c1099 | ||
|
|
8cd92150b1 | ||
|
|
d0ab35931e | ||
|
|
882684a80c | ||
|
|
96efd1cef0 | ||
|
|
c8974ede6d | ||
|
|
0c637e3d5e | ||
|
|
0e2d50a620 | ||
|
|
f3b3c54859 | ||
|
|
02eca40c3b | ||
|
|
c6ee3aee9f | ||
|
|
586e0ecea9 | ||
|
|
dcd18413a2 | ||
|
|
73f296b4cf | ||
|
|
1419bf3989 | ||
|
|
dca85c402c | ||
|
|
56a3ad0f8b | ||
|
|
36f484c25a | ||
|
|
03c6685097 | ||
|
|
23afddfbf9 | ||
|
|
e3a2dfb9d0 | ||
|
|
3dd004c323 | ||
|
|
1af43dbf90 | ||
|
|
16fed12dcc | ||
|
|
29825f2f8a | ||
|
|
efcee4b863 | ||
|
|
26edcab8b4 | ||
|
|
c626892adf | ||
|
|
3c66cdf2fe | ||
|
|
db31c36213 | ||
|
|
cafe3352f1 | ||
|
|
7a39ce34fa | ||
|
|
483702df77 | ||
|
|
206eb6a785 | ||
|
|
de9ec2bc73 | ||
|
|
1a66e517cd | ||
|
|
33e6f35ce9 | ||
|
|
e8896fe02d | ||
|
|
e89b053269 | ||
|
|
d052d481d8 | ||
|
|
fcbb494af7 | ||
|
|
2980a853e5 | ||
|
|
56de1465fa | ||
|
|
b500106fde | ||
|
|
7f2a95fe14 | ||
|
|
4b3825e500 | ||
|
|
d48b42c017 | ||
|
|
fb45896588 | ||
|
|
b52518f85f | ||
|
|
3e99019af8 | ||
|
|
7d4b02689e | ||
|
|
9962f57ad0 | ||
|
|
8b538e2802 | ||
|
|
a6c57e169a | ||
|
|
6f92f0a668 | ||
|
|
35817601ff | ||
|
|
2b154db938 | ||
|
|
b9ff7aa5cd | ||
|
|
b5188e8cea | ||
|
|
992db16586 | ||
|
|
2aad749e24 | ||
|
|
aa267ebb05 | ||
|
|
1a33f25970 | ||
|
|
e8dfc42f44 | ||
|
|
21c823ecdc | ||
|
|
80498f1709 | ||
|
|
e6c5a4a4bb | ||
|
|
732b3abf99 | ||
|
|
ffbf541ff8 | ||
|
|
709f961e1c | ||
|
|
1653383573 | ||
|
|
c7ae6b9471 | ||
|
|
bbcf9ba9db | ||
|
|
3f81f9dcb4 | ||
|
|
b073fea5fb | ||
|
|
834236931e | ||
|
|
872b907372 | ||
|
|
0b8e098c10 | ||
|
|
7c6a0f869d | ||
|
|
3a43047102 | ||
|
|
041acf158a | ||
|
|
f9752d7c08 | ||
|
|
766592b83b | ||
|
|
1c3c412ce4 | ||
|
|
f9e6d1290d | ||
|
|
8ef653fcc0 | ||
|
|
fb8d66b8d3 | ||
|
|
e70b34de62 | ||
|
|
b1584fab8f | ||
|
|
718084065e | ||
|
|
57dd091e05 | ||
|
|
a1f208f1e6 | ||
|
|
581aa7279f | ||
|
|
0b29924648 | ||
|
|
49472da669 | ||
|
|
69a2eac2ff | ||
|
|
5fd632c357 | ||
|
|
bb2164c945 | ||
|
|
8c91aa5570 | ||
|
|
6db8257b1e | ||
|
|
f6e7166e79 | ||
|
|
2da8290040 | ||
|
|
37e17e9207 | ||
|
|
fe86836b43 | ||
|
|
973e62373e | ||
|
|
dcdb9ac923 | ||
|
|
46347e2bd2 |
No files matched your search
@@ -9,7 +9,7 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
quality:
|
quality:
|
||||||
name: Lint, Typecheck, Test, Build
|
name: Lint, Typecheck, Test, Build
|
||||||
runs-on: ubuntu-latest
|
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|||||||
@@ -0,0 +1,309 @@
|
|||||||
|
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: ${{ steps.release_ref.outputs.value }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- id: release_meta
|
||||||
|
name: Resolve release version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||||
|
raw="${{ github.event.inputs.version }}"
|
||||||
|
else
|
||||||
|
raw="${GITHUB_REF_NAME}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
version="${raw#v}"
|
||||||
|
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||||
|
echo "Invalid release version: $raw" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- 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: Update version strings
|
||||||
|
if: github.event_name == 'workflow_dispatch'
|
||||||
|
env:
|
||||||
|
RELEASE_VERSION: ${{ steps.release_meta.outputs.version }}
|
||||||
|
run: |
|
||||||
|
node --input-type=module -e '
|
||||||
|
import { readFileSync, writeFileSync } from "node:fs";
|
||||||
|
|
||||||
|
const files = [
|
||||||
|
"apps/server/package.json",
|
||||||
|
"apps/desktop/package.json",
|
||||||
|
"apps/web/package.json",
|
||||||
|
"packages/contracts/package.json",
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
const packageJson = JSON.parse(readFileSync(file, "utf8"));
|
||||||
|
packageJson.version = process.env.RELEASE_VERSION;
|
||||||
|
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||||
|
}
|
||||||
|
'
|
||||||
|
|
||||||
|
- name: Refresh lockfile
|
||||||
|
if: github.event_name == 'workflow_dispatch'
|
||||||
|
run: bun install
|
||||||
|
|
||||||
|
- 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
|
||||||
|
|
||||||
|
- name: Commit and push release version + tag
|
||||||
|
if: github.event_name == 'workflow_dispatch'
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
RELEASE_TAG: ${{ steps.release_meta.outputs.tag }}
|
||||||
|
run: |
|
||||||
|
if git ls-remote --exit-code --tags origin "$RELEASE_TAG" >/dev/null 2>&1; then
|
||||||
|
echo "Tag $RELEASE_TAG already exists on origin." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||||
|
|
||||||
|
if ! git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||||
|
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" -m "Co-authored-by: codex <[email protected]>"
|
||||||
|
fi
|
||||||
|
|
||||||
|
git tag "$RELEASE_TAG"
|
||||||
|
git push origin "HEAD:${GITHUB_REF_NAME}"
|
||||||
|
git push origin "refs/tags/$RELEASE_TAG"
|
||||||
|
|
||||||
|
- id: release_ref
|
||||||
|
name: Resolve source ref
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||||
|
echo "value=refs/tags/${{ steps.release_meta.outputs.tag }}" >> "$GITHUB_OUTPUT"
|
||||||
|
else
|
||||||
|
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
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 }}"
|
||||||
|
)
|
||||||
|
|
||||||
|
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: Upload build artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
|
||||||
|
path: release/*
|
||||||
|
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
|
||||||
|
|
||||||
|
# - 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: Set CLI package version from release tag
|
||||||
|
# env:
|
||||||
|
# RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||||
|
# run: |
|
||||||
|
# node --input-type=module -e '
|
||||||
|
# import { readFileSync, writeFileSync } from "node:fs";
|
||||||
|
# const packagePath = "apps/server/package.json";
|
||||||
|
# const packageJson = JSON.parse(readFileSync(packagePath, "utf8"));
|
||||||
|
# packageJson.version = process.env.RELEASE_VERSION;
|
||||||
|
# writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||||
|
# '
|
||||||
|
|
||||||
|
# - name: Build CLI package
|
||||||
|
# run: bun run build --filter=@t3tools/web --filter=t3
|
||||||
|
|
||||||
|
# - name: Publish CLI package
|
||||||
|
# run: bun --cwd apps/server publish --access public
|
||||||
|
|
||||||
|
release:
|
||||||
|
name: Publish GitHub Release
|
||||||
|
needs: [preflight, build]
|
||||||
|
# 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 }}
|
||||||
|
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||||
|
generate_release_notes: true
|
||||||
|
files: release-assets/*
|
||||||
|
fail_on_unmatched_files: true
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import path from "path";
|
||||||
|
import fs from "fs";
|
||||||
|
|
||||||
|
const FAVICON_CANDIDATES = [
|
||||||
|
"favicon.svg", "favicon.ico", "favicon.png",
|
||||||
|
"public/favicon.svg", "public/favicon.ico", "public/favicon.png",
|
||||||
|
"app/favicon.ico", "app/favicon.png", "app/icon.svg", "app/icon.png", "app/icon.ico",
|
||||||
|
"src/favicon.ico", "src/favicon.svg", "src/app/favicon.ico", "src/app/icon.svg", "src/app/icon.png",
|
||||||
|
];
|
||||||
|
|
||||||
|
const ICON_SOURCE_FILES = [
|
||||||
|
"index.html", "public/index.html",
|
||||||
|
"app/routes/__root.tsx", "src/routes/__root.tsx",
|
||||||
|
"app/root.tsx", "src/root.tsx", "src/index.html",
|
||||||
|
];
|
||||||
|
|
||||||
|
const LINK_ICON_HTML_RE = /<link[^>]*rel=["'](?:icon|shortcut icon)["'][^>]*href=["']([^"'?]+)/i;
|
||||||
|
const LINK_ICON_OBJ_RE = /rel:\s*["'](?:icon|shortcut icon)["'][^}]*href:\s*["']([^"'?]+)/i;
|
||||||
|
|
||||||
|
function test(projectCwd) {
|
||||||
|
console.log("--- Testing:", projectCwd, "---");
|
||||||
|
|
||||||
|
for (const c of FAVICON_CANDIDATES) {
|
||||||
|
const full = path.join(projectCwd, c);
|
||||||
|
if (fs.existsSync(full) && fs.statSync(full).isFile()) {
|
||||||
|
console.log(" Phase 1 FOUND:", c);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(" Phase 1: no match");
|
||||||
|
|
||||||
|
for (const sf of ICON_SOURCE_FILES) {
|
||||||
|
const full = path.join(projectCwd, sf);
|
||||||
|
if (!fs.existsSync(full)) continue;
|
||||||
|
const content = fs.readFileSync(full, "utf8");
|
||||||
|
const href = content.match(LINK_ICON_HTML_RE)?.[1] || content.match(LINK_ICON_OBJ_RE)?.[1];
|
||||||
|
if (href) {
|
||||||
|
const clean = href.replace(/^\//, "");
|
||||||
|
const tryPaths = [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||||
|
for (const p of tryPaths) {
|
||||||
|
if (fs.existsSync(p)) {
|
||||||
|
console.log(" Phase 2 FOUND:", sf, "->", href, "->", p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(" Phase 2 href found but file missing:", href);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(" Phase 2: no match");
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTestPaths() {
|
||||||
|
const cliPaths = process.argv.slice(2).map((p) => p.trim()).filter(Boolean);
|
||||||
|
if (cliPaths.length > 0) return cliPaths;
|
||||||
|
|
||||||
|
const envPaths = process.env.TEST_PATHS?.split(path.delimiter).map((p) => p.trim()).filter(Boolean);
|
||||||
|
if (envPaths?.length) return envPaths;
|
||||||
|
|
||||||
|
return [process.cwd()];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const p of getTestPaths()) {
|
||||||
|
test(path.resolve(p));
|
||||||
|
}
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
# CLAUDE.md
|
# CLAUDE.md
|
||||||
|
|
||||||
|
## Task Completion Requirements
|
||||||
|
|
||||||
|
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
|
||||||
|
|
||||||
## Project Snapshot
|
## Project Snapshot
|
||||||
|
|
||||||
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
|
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
|
||||||
@@ -18,7 +22,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
|
|||||||
|
|
||||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
- `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.
|
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
|
||||||
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||||
|
|
||||||
## Codex App Server (Important)
|
## Codex App Server (Important)
|
||||||
|
|
||||||
|
|||||||
@@ -75,8 +75,11 @@ npx t3
|
|||||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||||
- `bun run test` — Runs workspace tests.
|
- `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` — Builds a shareable macOS `.dmg` into `./release`.
|
||||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
- `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
|
### Desktop `.dmg` packaging notes
|
||||||
|
|
||||||
@@ -86,12 +89,18 @@ npx t3
|
|||||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
- 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.
|
- 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 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
|
### Running multiple dev instances
|
||||||
|
|
||||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||||
|
|
||||||
- Default ports: server `3773`, web `5173`
|
- Default ports: server `3773`, web `5733`
|
||||||
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
||||||
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
||||||
|
|
||||||
@@ -122,3 +131,6 @@ Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI
|
|||||||
## CI quality gates
|
## 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/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",
|
"name": "@t3tools/desktop",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0-alpha.4",
|
||||||
"private": true,
|
"private": true,
|
||||||
"main": "dist-electron/main.js",
|
"main": "dist-electron/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import waitOn from "wait-on";
|
|||||||
|
|
||||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||||
|
|
||||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
|
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||||
const devServerUrl = `http://localhost:${port}`;
|
const devServerUrl = `http://localhost:${port}`;
|
||||||
|
|
||||||
await waitOn({
|
await waitOn({
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ import {
|
|||||||
|
|
||||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||||
|
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||||
|
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||||
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
||||||
@@ -54,6 +56,7 @@ import {
|
|||||||
makeTestProviderAdapterHarness,
|
makeTestProviderAdapterHarness,
|
||||||
type TestProviderAdapterHarness,
|
type TestProviderAdapterHarness,
|
||||||
} from "./TestProviderAdapter.integration.ts";
|
} from "./TestProviderAdapter.integration.ts";
|
||||||
|
import { ServerConfig } from "../src/config.ts";
|
||||||
|
|
||||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||||
return execFileSync("git", args, {
|
return execFileSync("git", args, {
|
||||||
@@ -215,21 +218,29 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
|||||||
Layer.provide(providerSessionDirectoryLayer),
|
Layer.provide(providerSessionDirectoryLayer),
|
||||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||||
);
|
);
|
||||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
|
||||||
|
|
||||||
const runtimeServicesLayer = Layer.mergeAll(
|
const runtimeServicesLayer = Layer.mergeAll(
|
||||||
orchestrationLayer,
|
orchestrationLayer,
|
||||||
OrchestrationProjectionSnapshotQueryLive,
|
OrchestrationProjectionSnapshotQueryLive,
|
||||||
ProjectionCheckpointRepositoryLive,
|
ProjectionCheckpointRepositoryLive,
|
||||||
ProjectionPendingApprovalRepositoryLive,
|
ProjectionPendingApprovalRepositoryLive,
|
||||||
checkpointStoreLayer,
|
CheckpointStoreLive,
|
||||||
providerLayer,
|
providerLayer,
|
||||||
);
|
);
|
||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
);
|
);
|
||||||
|
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||||
|
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||||
|
Effect.succeed({ branch: input.newBranch }),
|
||||||
|
} as unknown as GitCoreShape);
|
||||||
|
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||||
|
generateBranchName: () => Effect.succeed({ branch: null }),
|
||||||
|
} as unknown as TextGenerationShape);
|
||||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
|
Layer.provideMerge(gitCoreLayer),
|
||||||
|
Layer.provideMerge(textGenerationLayer),
|
||||||
);
|
);
|
||||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
@@ -241,6 +252,7 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
const layer = orchestrationReactorLayer.pipe(
|
const layer = orchestrationReactorLayer.pipe(
|
||||||
Layer.provide(persistenceLayer),
|
Layer.provide(persistenceLayer),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -136,6 +136,8 @@ const startTurn = (input: {
|
|||||||
text: input.text,
|
text: input.text,
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -317,7 +319,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
|||||||
const secondTurnThread = yield* harness.waitForThread(
|
const secondTurnThread = yield* harness.waitForThread(
|
||||||
THREAD_ID,
|
THREAD_ID,
|
||||||
(entry) =>
|
(entry) =>
|
||||||
entry.latestTurnId === "turn-2" &&
|
entry.latestTurn?.turnId === "turn-2" &&
|
||||||
entry.checkpoints.length === 2 &&
|
entry.checkpoints.length === 2 &&
|
||||||
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2),
|
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2),
|
||||||
);
|
);
|
||||||
@@ -651,7 +653,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
|||||||
yield* harness.waitForThread(
|
yield* harness.waitForThread(
|
||||||
THREAD_ID,
|
THREAD_ID,
|
||||||
(entry) =>
|
(entry) =>
|
||||||
entry.latestTurnId === "turn-2" &&
|
entry.latestTurn?.turnId === "turn-2" &&
|
||||||
entry.checkpoints.length === 2 &&
|
entry.checkpoints.length === 2 &&
|
||||||
entry.activities.some((activity) => activity.turnId === "turn-2"),
|
entry.activities.some((activity) => activity.turnId === "turn-2"),
|
||||||
8000,
|
8000,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "t3",
|
"name": "t3",
|
||||||
"version": "0.1.0",
|
"version": "0.0.0-alpha.4",
|
||||||
"bin": {
|
"bin": {
|
||||||
"t3": "./dist/index.mjs"
|
"t3": "./dist/index.mjs"
|
||||||
},
|
},
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./dist/index.mjs",
|
"main": "./dist/index.mjs",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.ts",
|
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
|
||||||
"build": "tsdown && node scripts/bundle-client.ts",
|
"build": "tsdown && node scripts/bundle-client.ts",
|
||||||
"start": "node dist/index.mjs",
|
"start": "node dist/index.mjs",
|
||||||
"prepare": "effect-language-service patch",
|
"prepare": "effect-language-service patch",
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
|
||||||
|
|
||||||
|
export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
|
||||||
|
const normalized = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
||||||
|
if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return normalized.replace(/\\/g, "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveAttachmentRelativePath(input: {
|
||||||
|
readonly stateDir: string;
|
||||||
|
readonly relativePath: string;
|
||||||
|
}): string | null {
|
||||||
|
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
||||||
|
if (!normalizedRelativePath) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
|
||||||
|
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||||
|
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createAttachmentId,
|
||||||
|
parseThreadSegmentFromAttachmentId,
|
||||||
|
resolveAttachmentPathById,
|
||||||
|
} from "./attachmentStore.ts";
|
||||||
|
|
||||||
|
describe("attachmentStore", () => {
|
||||||
|
it("sanitizes thread ids when creating attachment ids", () => {
|
||||||
|
const attachmentId = createAttachmentId("thread.folder/unsafe space");
|
||||||
|
expect(attachmentId).toBeTruthy();
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const threadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||||
|
expect(threadSegment).toBeTruthy();
|
||||||
|
expect(threadSegment).toMatch(/^[a-z0-9_-]+$/i);
|
||||||
|
expect(threadSegment).not.toContain(".");
|
||||||
|
expect(threadSegment).not.toContain("%");
|
||||||
|
expect(threadSegment).not.toContain("/");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses exact thread segments from attachment ids without prefix collisions", () => {
|
||||||
|
const fooId = "foo-00000000-0000-4000-8000-000000000001";
|
||||||
|
const fooBarId = "foo-bar-00000000-0000-4000-8000-000000000002";
|
||||||
|
|
||||||
|
expect(parseThreadSegmentFromAttachmentId(fooId)).toBe("foo");
|
||||||
|
expect(parseThreadSegmentFromAttachmentId(fooBarId)).toBe("foo-bar");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("normalizes created thread segments to lowercase", () => {
|
||||||
|
const attachmentId = createAttachmentId("Thread.Foo");
|
||||||
|
expect(attachmentId).toBeTruthy();
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||||
|
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||||
|
try {
|
||||||
|
const attachmentId = "thread-1-attachment";
|
||||||
|
const attachmentsDir = path.join(stateDir, "attachments");
|
||||||
|
fs.mkdirSync(attachmentsDir, { recursive: true });
|
||||||
|
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||||
|
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
||||||
|
|
||||||
|
const resolved = resolveAttachmentPathById({
|
||||||
|
stateDir,
|
||||||
|
attachmentId,
|
||||||
|
});
|
||||||
|
expect(resolved).toBe(pngPath);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when no attachment file exists for the id", () => {
|
||||||
|
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||||
|
try {
|
||||||
|
const resolved = resolveAttachmentPathById({
|
||||||
|
stateDir,
|
||||||
|
attachmentId: "thread-1-missing",
|
||||||
|
});
|
||||||
|
expect(resolved).toBeNull();
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { existsSync } from "node:fs";
|
||||||
|
|
||||||
|
import type { ChatAttachment } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
import {
|
||||||
|
normalizeAttachmentRelativePath,
|
||||||
|
resolveAttachmentRelativePath,
|
||||||
|
} from "./attachmentPaths.ts";
|
||||||
|
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
|
||||||
|
|
||||||
|
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
|
||||||
|
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
|
||||||
|
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
|
||||||
|
const ATTACHMENT_ID_UUID_PATTERN =
|
||||||
|
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||||
|
const ATTACHMENT_ID_PATTERN = new RegExp(
|
||||||
|
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
|
||||||
|
"i",
|
||||||
|
);
|
||||||
|
|
||||||
|
export function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||||
|
const segment = threadId
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9_-]+/gi, "-")
|
||||||
|
.replace(/-+/g, "-")
|
||||||
|
.replace(/^[-_]+|[-_]+$/g, "")
|
||||||
|
.slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
|
||||||
|
.replace(/[-_]+$/g, "");
|
||||||
|
if (segment.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return segment;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAttachmentId(threadId: string): string | null {
|
||||||
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
|
if (!threadSegment) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return `${threadSegment}-${randomUUID()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
|
||||||
|
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
|
||||||
|
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
|
||||||
|
if (!match) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return match[1]?.toLowerCase() ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function attachmentRelativePath(attachment: ChatAttachment): string {
|
||||||
|
switch (attachment.type) {
|
||||||
|
case "image": {
|
||||||
|
const extension = inferImageExtension({
|
||||||
|
mimeType: attachment.mimeType,
|
||||||
|
fileName: attachment.name,
|
||||||
|
});
|
||||||
|
return `${attachment.id}${extension}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveAttachmentPath(input: {
|
||||||
|
readonly stateDir: string;
|
||||||
|
readonly attachment: ChatAttachment;
|
||||||
|
}): string | null {
|
||||||
|
return resolveAttachmentRelativePath({
|
||||||
|
stateDir: input.stateDir,
|
||||||
|
relativePath: attachmentRelativePath(input.attachment),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveAttachmentPathById(input: {
|
||||||
|
readonly stateDir: string;
|
||||||
|
readonly attachmentId: string;
|
||||||
|
}): string | null {
|
||||||
|
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
||||||
|
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
||||||
|
const maybePath = resolveAttachmentRelativePath({
|
||||||
|
stateDir: input.stateDir,
|
||||||
|
relativePath: `${normalizedId}${extension}`,
|
||||||
|
});
|
||||||
|
if (maybePath && existsSync(maybePath)) {
|
||||||
|
return maybePath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
|
||||||
|
const normalized = normalizeAttachmentRelativePath(relativePath);
|
||||||
|
if (!normalized || normalized.includes("/")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const extensionIndex = normalized.lastIndexOf(".");
|
||||||
|
if (extensionIndex <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const id = normalized.slice(0, extensionIndex);
|
||||||
|
return id.length > 0 && !id.includes(".") ? id : null;
|
||||||
|
}
|
||||||
@@ -45,7 +45,14 @@ function makeSnapshot(input: {
|
|||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: input.worktreePath,
|
worktreePath: input.worktreePath,
|
||||||
latestTurnId: TurnId.makeUnsafe("turn-1"),
|
latestTurn: {
|
||||||
|
turnId: TurnId.makeUnsafe("turn-1"),
|
||||||
|
state: "completed",
|
||||||
|
requestedAt: "2026-01-01T00:00:00.000Z",
|
||||||
|
startedAt: "2026-01-01T00:00:00.000Z",
|
||||||
|
completedAt: "2026-01-01T00:00:00.000Z",
|
||||||
|
assistantMessageId: null,
|
||||||
|
},
|
||||||
createdAt: "2026-01-01T00:00:00.000Z",
|
createdAt: "2026-01-01T00:00:00.000Z",
|
||||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
|
|||||||
@@ -191,10 +191,7 @@ describe("sendTurn", () => {
|
|||||||
attachments: [
|
attachments: [
|
||||||
{
|
{
|
||||||
type: "image",
|
type: "image",
|
||||||
name: "error.png",
|
url: "data:image/png;base64,AAAA",
|
||||||
mimeType: "image/png",
|
|
||||||
sizeBytes: 1_024,
|
|
||||||
dataUrl: "data:image/png;base64,AAAA",
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
model: "gpt-5.3",
|
model: "gpt-5.3",
|
||||||
@@ -242,10 +239,7 @@ describe("sendTurn", () => {
|
|||||||
attachments: [
|
attachments: [
|
||||||
{
|
{
|
||||||
type: "image",
|
type: "image",
|
||||||
name: "diagram.png",
|
url: "data:image/png;base64,BBBB",
|
||||||
mimeType: "image/png",
|
|
||||||
sizeBytes: 256,
|
|
||||||
dataUrl: "data:image/png;base64,BBBB",
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
normalizeModelSlug,
|
normalizeModelSlug,
|
||||||
type ProviderApprovalDecision,
|
type ProviderApprovalDecision,
|
||||||
type ProviderEvent,
|
type ProviderEvent,
|
||||||
type ProviderSendTurnInput,
|
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
type ProviderSessionStartInput,
|
type ProviderSessionStartInput,
|
||||||
type ProviderTurnStartResult,
|
type ProviderTurnStartResult,
|
||||||
@@ -71,6 +70,14 @@ interface JsonRpcNotification {
|
|||||||
params?: unknown;
|
params?: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CodexAppServerSendTurnInput {
|
||||||
|
readonly sessionId: ProviderSessionId;
|
||||||
|
readonly input?: string;
|
||||||
|
readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>;
|
||||||
|
readonly model?: string;
|
||||||
|
readonly effort?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CodexThreadTurnSnapshot {
|
export interface CodexThreadTurnSnapshot {
|
||||||
id: ProviderTurnId;
|
id: ProviderTurnId;
|
||||||
items: unknown[];
|
items: unknown[];
|
||||||
@@ -290,7 +297,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||||
const context = this.requireSession(input.sessionId);
|
const context = this.requireSession(input.sessionId);
|
||||||
if (!context.session.threadId) {
|
if (!context.session.threadId) {
|
||||||
throw new Error("Session is missing a thread id.");
|
throw new Error("Session is missing a thread id.");
|
||||||
@@ -310,7 +317,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
if (attachment.type === "image") {
|
if (attachment.type === "image") {
|
||||||
turnInput.push({
|
turnInput.push({
|
||||||
type: "image",
|
type: "image",
|
||||||
url: attachment.dataUrl,
|
url: attachment.url,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,7 +36,29 @@ export interface ServerConfigShape {
|
|||||||
*/
|
*/
|
||||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||||
"t3/config/ServerConfig",
|
"t3/config/ServerConfig",
|
||||||
) {}
|
) {
|
||||||
|
static readonly layerTest = (cwd: string, statedir: string) =>
|
||||||
|
Layer.effect(
|
||||||
|
ServerConfig,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
return {
|
||||||
|
cwd,
|
||||||
|
stateDir: statedir,
|
||||||
|
mode: "web",
|
||||||
|
autoBootstrapProjectFromCwd: false,
|
||||||
|
logWebSocketEvents: false,
|
||||||
|
port: 0,
|
||||||
|
host: undefined,
|
||||||
|
authToken: undefined,
|
||||||
|
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||||
|
staticDir: undefined,
|
||||||
|
devUrl: undefined,
|
||||||
|
noBrowser: false,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Helpers
|
// Helpers
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,17 @@ import { it } from "@effect/vitest";
|
|||||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||||
import { expect } from "vitest";
|
import { expect } from "vitest";
|
||||||
|
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||||
import { TextGenerationError } from "../Errors.ts";
|
import { TextGenerationError } from "../Errors.ts";
|
||||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
|
||||||
|
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
|
||||||
|
CodexTextGenerationLive.pipe(
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
);
|
||||||
|
|
||||||
function makeFakeCodexBinary(dir: string) {
|
function makeFakeCodexBinary(dir: string) {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
@@ -21,13 +28,36 @@ function makeFakeCodexBinary(dir: string) {
|
|||||||
"#!/bin/sh",
|
"#!/bin/sh",
|
||||||
'output_path=""',
|
'output_path=""',
|
||||||
"while [ $# -gt 0 ]; do",
|
"while [ $# -gt 0 ]; do",
|
||||||
|
' if [ "$1" = "--image" ]; then',
|
||||||
|
" shift",
|
||||||
|
' if [ -n "$1" ]; then',
|
||||||
|
' seen_image="1"',
|
||||||
|
" fi",
|
||||||
|
" continue",
|
||||||
|
" fi",
|
||||||
' if [ "$1" = "--output-last-message" ]; then',
|
' if [ "$1" = "--output-last-message" ]; then',
|
||||||
" shift",
|
" shift",
|
||||||
' output_path="$1"',
|
' output_path="$1"',
|
||||||
" fi",
|
" fi",
|
||||||
" shift",
|
" shift",
|
||||||
"done",
|
"done",
|
||||||
"cat >/dev/null",
|
'stdin_content="$(cat)"',
|
||||||
|
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
|
||||||
|
' printf "%s\\n" "missing --image input" >&2',
|
||||||
|
" exit 2",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
|
||||||
|
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||||
|
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||||
|
" exit 3",
|
||||||
|
" }",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
|
||||||
|
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
|
||||||
|
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
||||||
|
" exit 4",
|
||||||
|
" fi",
|
||||||
|
"fi",
|
||||||
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
|
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
|
||||||
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
||||||
"fi",
|
"fi",
|
||||||
@@ -48,6 +78,9 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
output: string;
|
output: string;
|
||||||
exitCode?: number;
|
exitCode?: number;
|
||||||
stderr?: string;
|
stderr?: string;
|
||||||
|
requireImage?: boolean;
|
||||||
|
stdinMustContain?: string;
|
||||||
|
stdinMustNotContain?: string;
|
||||||
},
|
},
|
||||||
effect: Effect.Effect<A, E, R>,
|
effect: Effect.Effect<A, E, R>,
|
||||||
) {
|
) {
|
||||||
@@ -60,6 +93,9 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||||
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||||
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
||||||
|
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
|
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
|
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
|
|
||||||
yield* Effect.sync(() => {
|
yield* Effect.sync(() => {
|
||||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||||
@@ -76,6 +112,24 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
} else {
|
} else {
|
||||||
delete process.env.T3_FAKE_CODEX_STDERR;
|
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (input.requireImage) {
|
||||||
|
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stdinMustContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stdinMustNotContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -83,6 +137,9 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
previousOutput,
|
previousOutput,
|
||||||
previousExitCode,
|
previousExitCode,
|
||||||
previousStderr,
|
previousStderr,
|
||||||
|
previousRequireImage,
|
||||||
|
previousStdinMustContain,
|
||||||
|
previousStdinMustNotContain,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
() => effect,
|
() => effect,
|
||||||
@@ -107,14 +164,29 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
} else {
|
} else {
|
||||||
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
|
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (previous.previousRequireImage === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStdinMustContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStdinMustNotContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
|
||||||
|
}
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const CodexTextGenerationTestLayer = Layer.provideMerge(
|
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
||||||
CodexTextGenerationLive,
|
|
||||||
NodeServices.layer,
|
|
||||||
);
|
|
||||||
|
|
||||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||||
it.effect("generates and sanitizes commit messages", () =>
|
it.effect("generates and sanitizes commit messages", () =>
|
||||||
@@ -170,6 +242,216 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect("generates branch names and normalizes branch fragments", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: " Feat/Session ",
|
||||||
|
}),
|
||||||
|
stdinMustNotContain: "Image attachments supplied to the model",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Please update session handling.",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("feat/session");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: "fix/session-timeout",
|
||||||
|
}),
|
||||||
|
stdinMustNotContain: "Attachment metadata:",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix timeout behavior.",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("fix/session-timeout");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("passes image attachments through as codex image inputs", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: "fix/ui-regression",
|
||||||
|
}),
|
||||||
|
requireImage: true,
|
||||||
|
stdinMustContain: "Attachment metadata:",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||||
|
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||||
|
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||||
|
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
const generated = yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix layout bug from screenshot.",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: attachmentId,
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("fix/ui-regression");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: "fix/ui-regression",
|
||||||
|
}),
|
||||||
|
requireImage: true,
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const attachmentId =
|
||||||
|
`thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||||
|
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||||
|
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||||
|
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
const generated = yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix layout bug from screenshot.",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: attachmentId,
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.pipe(
|
||||||
|
Effect.tap(() =>
|
||||||
|
fs.stat(imagePath).pipe(
|
||||||
|
Effect.map((fileInfo) => {
|
||||||
|
expect(fileInfo.type).toBe("File");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Effect.ensuring(
|
||||||
|
fs.remove(imagePath).pipe(Effect.catch(() => Effect.void)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(generated.branch).toBe("fix/ui-regression");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("ignores missing attachment ids for codex image inputs", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
branch: "fix/ui-regression",
|
||||||
|
}),
|
||||||
|
requireImage: true,
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
|
||||||
|
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||||
|
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
const result = yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix layout bug from screenshot.",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: missingAttachmentId,
|
||||||
|
name: "outside.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.pipe(
|
||||||
|
Effect.match({
|
||||||
|
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||||
|
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result._tag).toBe("Left");
|
||||||
|
if (result._tag === "Left") {
|
||||||
|
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||||
|
expect(result.left.message).toContain("missing --image input");
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect(
|
||||||
|
"fails with typed TextGenerationError when codex returns wrong branch payload shape",
|
||||||
|
() =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
title: "This is not a branch payload",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const result = yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Fix websocket reconnect flake",
|
||||||
|
})
|
||||||
|
.pipe(
|
||||||
|
Effect.match({
|
||||||
|
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||||
|
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result._tag).toBe("Left");
|
||||||
|
if (result._tag === "Left") {
|
||||||
|
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||||
|
expect(result.left.message).toContain("Codex returned invalid structured output");
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
|
it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -3,8 +3,12 @@ import { randomUUID } from "node:crypto";
|
|||||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
|
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { TextGenerationError } from "../Errors.ts";
|
import { TextGenerationError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
|
type BranchNameGenerationInput,
|
||||||
|
type BranchNameGenerationResult,
|
||||||
type CommitMessageGenerationResult,
|
type CommitMessageGenerationResult,
|
||||||
type PrContentGenerationResult,
|
type PrContentGenerationResult,
|
||||||
type TextGenerationShape,
|
type TextGenerationShape,
|
||||||
@@ -15,25 +19,16 @@ const CODEX_MODEL = "gpt-5.3-codex";
|
|||||||
const CODEX_REASONING_EFFORT = "low";
|
const CODEX_REASONING_EFFORT = "low";
|
||||||
const CODEX_TIMEOUT_MS = 180_000;
|
const CODEX_TIMEOUT_MS = 180_000;
|
||||||
|
|
||||||
const COMMIT_OUTPUT_SCHEMA_JSON = {
|
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
|
||||||
type: "object",
|
const document = Schema.toJsonSchemaDocument(schema);
|
||||||
properties: {
|
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||||
subject: { type: "string" },
|
return {
|
||||||
body: { type: "string" },
|
...document.schema,
|
||||||
},
|
$defs: document.definitions,
|
||||||
required: ["subject", "body"],
|
};
|
||||||
additionalProperties: false,
|
}
|
||||||
} as const;
|
return document.schema;
|
||||||
|
}
|
||||||
const PR_OUTPUT_SCHEMA_JSON = {
|
|
||||||
type: "object",
|
|
||||||
properties: {
|
|
||||||
title: { type: "string" },
|
|
||||||
body: { type: "string" },
|
|
||||||
},
|
|
||||||
required: ["title", "body"],
|
|
||||||
additionalProperties: false,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
function normalizeCodexError(
|
function normalizeCodexError(
|
||||||
operation: string,
|
operation: string,
|
||||||
@@ -71,32 +66,6 @@ function normalizeCodexError(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseCommitOutput(raw: unknown): { subject: string; body: string } {
|
|
||||||
if (!raw || typeof raw !== "object") {
|
|
||||||
throw new Error("Codex returned a non-object commit message payload.");
|
|
||||||
}
|
|
||||||
const record = raw as Record<string, unknown>;
|
|
||||||
const subject = typeof record.subject === "string" ? record.subject.trim() : "";
|
|
||||||
const body = typeof record.body === "string" ? record.body : "";
|
|
||||||
if (subject.length === 0) {
|
|
||||||
throw new Error("Codex returned an empty commit subject.");
|
|
||||||
}
|
|
||||||
return { subject, body };
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePrOutput(raw: unknown): { title: string; body: string } {
|
|
||||||
if (!raw || typeof raw !== "object") {
|
|
||||||
throw new Error("Codex returned a non-object PR payload.");
|
|
||||||
}
|
|
||||||
const record = raw as Record<string, unknown>;
|
|
||||||
const title = typeof record.title === "string" ? record.title.trim() : "";
|
|
||||||
const body = typeof record.body === "string" ? record.body.trim() : "";
|
|
||||||
if (title.length === 0 || body.length === 0) {
|
|
||||||
throw new Error("Codex returned an invalid PR title/body payload.");
|
|
||||||
}
|
|
||||||
return { title, body };
|
|
||||||
}
|
|
||||||
|
|
||||||
function limitSection(value: string, maxChars: number): string {
|
function limitSection(value: string, maxChars: number): string {
|
||||||
if (value.length <= maxChars) return value;
|
if (value.length <= maxChars) return value;
|
||||||
const truncated = value.slice(0, maxChars);
|
const truncated = value.slice(0, maxChars);
|
||||||
@@ -124,10 +93,33 @@ function sanitizePrTitle(raw: string): string {
|
|||||||
return "Update project changes";
|
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 makeCodexTextGeneration = Effect.gen(function* () {
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
|
|
||||||
|
type MaterializedImageAttachments = {
|
||||||
|
readonly imagePaths: ReadonlyArray<string>;
|
||||||
|
};
|
||||||
|
|
||||||
const readStreamAsString = <E>(
|
const readStreamAsString = <E>(
|
||||||
operation: string,
|
operation: string,
|
||||||
@@ -171,24 +163,59 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||||
|
|
||||||
const runCodexJson = <T>({
|
const materializeImageAttachments = (
|
||||||
|
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
|
||||||
|
attachments: BranchNameGenerationInput["attachments"],
|
||||||
|
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
if (!attachments || attachments.length === 0) {
|
||||||
|
return { imagePaths: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const imagePaths: string[] = [];
|
||||||
|
for (const attachment of attachments) {
|
||||||
|
if (attachment.type !== "image") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const resolvedPath = resolveAttachmentPath({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
attachment,
|
||||||
|
});
|
||||||
|
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const fileInfo = yield* fileSystem
|
||||||
|
.stat(resolvedPath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
imagePaths.push(resolvedPath);
|
||||||
|
}
|
||||||
|
return { imagePaths };
|
||||||
|
});
|
||||||
|
|
||||||
|
const runCodexJson = <S extends Schema.Top>({
|
||||||
operation,
|
operation,
|
||||||
cwd,
|
cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson,
|
outputSchemaJson,
|
||||||
parse,
|
imagePaths = [],
|
||||||
|
cleanupPaths = [],
|
||||||
}: {
|
}: {
|
||||||
operation: "generateCommitMessage" | "generatePrContent";
|
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||||
cwd: string;
|
cwd: string;
|
||||||
prompt: string;
|
prompt: string;
|
||||||
outputSchemaJson: object;
|
outputSchemaJson: S;
|
||||||
parse: (raw: unknown) => T;
|
imagePaths?: ReadonlyArray<string>;
|
||||||
}): Effect.Effect<T, TextGenerationError> =>
|
cleanupPaths?: ReadonlyArray<string>;
|
||||||
|
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const schemaPath = yield* writeTempFile(
|
const schemaPath = yield* writeTempFile(
|
||||||
operation,
|
operation,
|
||||||
"codex-schema",
|
"codex-schema",
|
||||||
JSON.stringify(outputSchemaJson),
|
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
|
||||||
);
|
);
|
||||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||||
|
|
||||||
@@ -208,6 +235,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
schemaPath,
|
schemaPath,
|
||||||
"--output-last-message",
|
"--output-last-message",
|
||||||
outputPath,
|
outputPath,
|
||||||
|
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||||
"-",
|
"-",
|
||||||
],
|
],
|
||||||
{
|
{
|
||||||
@@ -254,9 +282,12 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const cleanup = Effect.all([safeUnlink(schemaPath), safeUnlink(outputPath)], {
|
const cleanup = Effect.all(
|
||||||
concurrency: "unbounded",
|
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||||
}).pipe(Effect.asVoid);
|
{
|
||||||
|
concurrency: "unbounded",
|
||||||
|
},
|
||||||
|
).pipe(Effect.asVoid);
|
||||||
|
|
||||||
return yield* Effect.gen(function* () {
|
return yield* Effect.gen(function* () {
|
||||||
yield* runCodexCommand.pipe(
|
yield* runCodexCommand.pipe(
|
||||||
@@ -273,7 +304,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const rawOutput = yield* fileSystem.readFileString(outputPath).pipe(
|
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
(cause) =>
|
(cause) =>
|
||||||
new TextGenerationError({
|
new TextGenerationError({
|
||||||
@@ -282,30 +313,17 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
cause,
|
cause,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||||
|
Effect.catchTag("SchemaError", (cause) =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: "Codex returned invalid structured output.",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
const trimmed = rawOutput.trim();
|
|
||||||
if (trimmed.length === 0) {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Codex returned an empty response.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const parsedJson = yield* Effect.try({
|
|
||||||
try: () => JSON.parse(trimmed) as unknown,
|
|
||||||
catch: (cause) =>
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Codex returned invalid JSON output.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
return yield* Effect.try({
|
|
||||||
try: () => parse(parsedJson),
|
|
||||||
catch: (cause) =>
|
|
||||||
normalizeCodexError(operation, cause, "Codex returned invalid structured output"),
|
|
||||||
});
|
|
||||||
}).pipe(Effect.ensuring(cleanup));
|
}).pipe(Effect.ensuring(cleanup));
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -331,8 +349,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
operation: "generateCommitMessage",
|
operation: "generateCommitMessage",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
|
outputSchemaJson: Schema.Struct({
|
||||||
parse: (raw) => parseCommitOutput(raw),
|
subject: Schema.String,
|
||||||
|
body: Schema.String,
|
||||||
|
}),
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.map(
|
Effect.map(
|
||||||
(generated) =>
|
(generated) =>
|
||||||
@@ -371,8 +391,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
operation: "generatePrContent",
|
operation: "generatePrContent",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
|
outputSchemaJson: Schema.Struct({
|
||||||
parse: (raw) => parsePrOutput(raw),
|
title: Schema.String,
|
||||||
|
body: Schema.String,
|
||||||
|
}),
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.map(
|
Effect.map(
|
||||||
(generated) =>
|
(generated) =>
|
||||||
@@ -384,9 +406,55 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const { imagePaths } = yield* materializeImageAttachments("generateBranchName", input.attachments);
|
||||||
|
const attachmentLines = (input.attachments ?? []).map(
|
||||||
|
(attachment) =>
|
||||||
|
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const promptSections = [
|
||||||
|
"You generate concise git branch names.",
|
||||||
|
"Return a JSON object with key: branch.",
|
||||||
|
"Rules:",
|
||||||
|
"- Branch should describe the requested work from the user message.",
|
||||||
|
"- Keep it short and specific (2-6 words).",
|
||||||
|
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
|
||||||
|
"- If images are attached, use them as primary context for visual/UI issues.",
|
||||||
|
"",
|
||||||
|
"User message:",
|
||||||
|
limitSection(input.message, 8_000),
|
||||||
|
];
|
||||||
|
if (attachmentLines.length > 0) {
|
||||||
|
promptSections.push(
|
||||||
|
"",
|
||||||
|
"Attachment metadata:",
|
||||||
|
limitSection(attachmentLines.join("\n"), 4_000),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const prompt = promptSections.join("\n");
|
||||||
|
|
||||||
|
const generated = yield* runCodexJson({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
cwd: input.cwd,
|
||||||
|
prompt,
|
||||||
|
outputSchemaJson: Schema.Struct({
|
||||||
|
branch: Schema.String,
|
||||||
|
}),
|
||||||
|
imagePaths,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
branch: sanitizeBranchName(generated.branch),
|
||||||
|
} satisfies BranchNameGenerationResult;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
generateCommitMessage,
|
generateCommitMessage,
|
||||||
generatePrContent,
|
generatePrContent,
|
||||||
|
generateBranchName,
|
||||||
} satisfies TextGenerationShape;
|
} satisfies TextGenerationShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -106,6 +106,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
|
|||||||
listBranches: (input) => core.listBranches(input),
|
listBranches: (input) => core.listBranches(input),
|
||||||
createWorktree: (input) => core.createWorktree(input),
|
createWorktree: (input) => core.createWorktree(input),
|
||||||
removeWorktree: (input) => core.removeWorktree(input),
|
removeWorktree: (input) => core.removeWorktree(input),
|
||||||
|
renameBranch: (input) => core.renameBranch(input),
|
||||||
createBranch: (input) => core.createBranch(input),
|
createBranch: (input) => core.createBranch(input),
|
||||||
checkoutBranch: (input) => core.checkoutBranch(input),
|
checkoutBranch: (input) => core.checkoutBranch(input),
|
||||||
initRepo: (input) => core.initRepo(input),
|
initRepo: (input) => core.initRepo(input),
|
||||||
@@ -154,6 +155,13 @@ function removeGitWorktree(input: Parameters<GitCoreShape["removeWorktree"]>[0])
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function renameGitBranch(input: Parameters<GitCoreShape["renameBranch"]>[0]) {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const core = yield* GitCore;
|
||||||
|
return yield* core.renameBranch(input);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function pullGitBranch({ cwd }: { cwd: string }) {
|
function pullGitBranch({ cwd }: { cwd: string }) {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const core = yield* GitCore;
|
const core = yield* GitCore;
|
||||||
@@ -266,6 +274,18 @@ 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", () =>
|
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const tmp = yield* makeTmpDir();
|
const tmp = yield* makeTmpDir();
|
||||||
@@ -370,6 +390,82 @@ it.layer(TestLayer)("git integration", (it) => {
|
|||||||
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
|
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 ──
|
// ── checkoutGitBranch ──
|
||||||
@@ -592,6 +688,87 @@ 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", () =>
|
it.effect("throws when checkout would overwrite uncommitted changes", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const tmp = yield* makeTmpDir();
|
const tmp = yield* makeTmpDir();
|
||||||
@@ -650,6 +827,129 @@ it.layer(TestLayer)("git integration", (it) => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── renameGitBranch ──
|
||||||
|
|
||||||
|
describe("renameGitBranch", () => {
|
||||||
|
it.effect("renames the current branch", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||||
|
yield* checkoutGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||||
|
|
||||||
|
const renamed = yield* renameGitBranch({
|
||||||
|
cwd: tmp,
|
||||||
|
oldBranch: "feature/old-name",
|
||||||
|
newBranch: "feature/new-name",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(renamed.branch).toBe("feature/new-name");
|
||||||
|
|
||||||
|
const branches = yield* listGitBranches({ cwd: tmp });
|
||||||
|
expect(branches.branches.some((branch) => branch.name === "feature/old-name")).toBe(false);
|
||||||
|
const current = branches.branches.find((branch) => branch.current);
|
||||||
|
expect(current?.name).toBe("feature/new-name");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("returns success without git invocation when old/new names match", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
const current = (yield* listGitBranches({ cwd: tmp })).branches.find((b) => b.current)!;
|
||||||
|
|
||||||
|
const renamed = yield* renameGitBranch({
|
||||||
|
cwd: tmp,
|
||||||
|
oldBranch: current.name,
|
||||||
|
newBranch: current.name,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(renamed.branch).toBe(current.name);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("appends numeric suffix when target branch already exists", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session" });
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||||
|
yield* checkoutGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||||
|
|
||||||
|
const renamed = yield* renameGitBranch({
|
||||||
|
cwd: tmp,
|
||||||
|
oldBranch: "t3code/tmp-working",
|
||||||
|
newBranch: "t3code/feat/session",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(renamed.branch).toBe("t3code/feat/session-1");
|
||||||
|
const branches = yield* listGitBranches({ cwd: tmp });
|
||||||
|
expect(branches.branches.some((branch) => branch.name === "t3code/feat/session")).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
expect(branches.branches.some((branch) => branch.name === "t3code/feat/session-1")).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
const current = branches.branches.find((branch) => branch.current);
|
||||||
|
expect(current?.name).toBe("t3code/feat/session-1");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("increments suffix until it finds an available branch name", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session" });
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session-1" });
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||||
|
yield* checkoutGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||||
|
|
||||||
|
const renamed = yield* renameGitBranch({
|
||||||
|
cwd: tmp,
|
||||||
|
oldBranch: "t3code/tmp-working",
|
||||||
|
newBranch: "t3code/feat/session",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(renamed.branch).toBe("t3code/feat/session-2");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("uses '--' separator for branch rename arguments", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
yield* createGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||||
|
yield* checkoutGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||||
|
|
||||||
|
const realGitService = yield* GitService;
|
||||||
|
let renameArgs: ReadonlyArray<string> | null = null;
|
||||||
|
const core = yield* makeIsolatedGitCore({
|
||||||
|
execute: (input) => {
|
||||||
|
if (input.args[0] === "branch" && input.args[1] === "-m") {
|
||||||
|
renameArgs = [...input.args];
|
||||||
|
}
|
||||||
|
return realGitService.execute(input);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const renamed = yield* core.renameBranch({
|
||||||
|
cwd: tmp,
|
||||||
|
oldBranch: "feature/old-name",
|
||||||
|
newBranch: "feature/new-name",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(renamed.branch).toBe("feature/new-name");
|
||||||
|
expect(renameArgs).toEqual([
|
||||||
|
"branch",
|
||||||
|
"-m",
|
||||||
|
"--",
|
||||||
|
"feature/old-name",
|
||||||
|
"feature/new-name",
|
||||||
|
]);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
// ── createGitWorktree + removeGitWorktree ──
|
// ── createGitWorktree + removeGitWorktree ──
|
||||||
|
|
||||||
describe("createGitWorktree", () => {
|
describe("createGitWorktree", () => {
|
||||||
@@ -972,6 +1272,135 @@ 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", () =>
|
it.effect("includes command context when worktree removal fails", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const tmp = yield* makeTmpDir();
|
const tmp = yield* makeTmpDir();
|
||||||
@@ -1153,5 +1582,54 @@ it.layer(TestLayer)("git integration", (it) => {
|
|||||||
expect(didFailRecency).toBe(true);
|
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,6 +7,7 @@ import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
|
|||||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||||
|
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
|
||||||
|
|
||||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||||
cwd: string;
|
cwd: string;
|
||||||
@@ -76,10 +77,101 @@ function parsePorcelainPath(line: string): string | null {
|
|||||||
return filePath.length > 0 ? filePath : 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 {
|
function commandLabel(args: readonly string[]): string {
|
||||||
return `git ${args.join(" ")}`;
|
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(
|
function createGitCommandError(
|
||||||
operation: string,
|
operation: string,
|
||||||
cwd: string,
|
cwd: string,
|
||||||
@@ -158,6 +250,43 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
Effect.map((result) => result.stdout),
|
Effect.map((result) => result.stdout),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
|
||||||
|
executeGit(
|
||||||
|
"GitCore.branchExists",
|
||||||
|
cwd,
|
||||||
|
["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
|
||||||
|
{
|
||||||
|
allowNonZeroExit: true,
|
||||||
|
timeoutMs: 5_000,
|
||||||
|
},
|
||||||
|
).pipe(Effect.map((result) => result.code === 0));
|
||||||
|
|
||||||
|
const resolveAvailableBranchName = (
|
||||||
|
cwd: string,
|
||||||
|
desiredBranch: string,
|
||||||
|
): Effect.Effect<string, GitCommandError> =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const isDesiredTaken = yield* branchExists(cwd, desiredBranch);
|
||||||
|
if (!isDesiredTaken) {
|
||||||
|
return desiredBranch;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let suffix = 1; suffix <= 100; suffix += 1) {
|
||||||
|
const candidate = `${desiredBranch}-${suffix}`;
|
||||||
|
const isCandidateTaken = yield* branchExists(cwd, candidate);
|
||||||
|
if (!isCandidateTaken) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return yield* createGitCommandError(
|
||||||
|
"GitCore.renameBranch",
|
||||||
|
cwd,
|
||||||
|
["branch", "-m", "--", desiredBranch],
|
||||||
|
`Could not find an available branch name for '${desiredBranch}'.`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
const resolveCurrentUpstream = (
|
const resolveCurrentUpstream = (
|
||||||
cwd: string,
|
cwd: string,
|
||||||
): Effect.Effect<
|
): Effect.Effect<
|
||||||
@@ -259,12 +388,114 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
yield* fetchUpstreamRef(cwd, upstream);
|
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> =>
|
const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const branchRecency = yield* executeGit(
|
const branchRecency = yield* executeGit(
|
||||||
"GitCore.readBranchRecency",
|
"GitCore.readBranchRecency",
|
||||||
cwd,
|
cwd,
|
||||||
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
|
[
|
||||||
|
"for-each-ref",
|
||||||
|
"--format=%(refname:short)%09%(committerdate:unix)",
|
||||||
|
"refs/heads",
|
||||||
|
"refs/remotes",
|
||||||
|
],
|
||||||
{
|
{
|
||||||
timeoutMs: 15_000,
|
timeoutMs: 15_000,
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
@@ -343,6 +574,14 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
|
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 stagedEntries = parseNumstatEntries(stagedNumstatStdout);
|
||||||
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
|
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
|
||||||
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
|
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
|
||||||
@@ -393,7 +632,7 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
hasUpstream: details.hasUpstream,
|
hasUpstream: details.hasUpstream,
|
||||||
aheadCount: details.aheadCount,
|
aheadCount: details.aheadCount,
|
||||||
behindCount: details.behindCount,
|
behindCount: details.behindCount,
|
||||||
openPr: null,
|
pr: null,
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -452,12 +691,40 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
|
const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
|
||||||
return {
|
if (hasNoLocalDelta) {
|
||||||
status: "skipped_up_to_date" as const,
|
if (details.hasUpstream) {
|
||||||
branch,
|
return {
|
||||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
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) {
|
if (!details.hasUpstream) {
|
||||||
@@ -564,7 +831,7 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||||
);
|
);
|
||||||
const result = yield* executeGit(
|
const localBranchResult = yield* executeGit(
|
||||||
"GitCore.listBranches.branchNoColor",
|
"GitCore.listBranches.branchNoColor",
|
||||||
input.cwd,
|
input.cwd,
|
||||||
["branch", "--no-color"],
|
["branch", "--no-color"],
|
||||||
@@ -574,8 +841,8 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
if (result.code !== 0) {
|
if (localBranchResult.code !== 0) {
|
||||||
const stderr = result.stderr.trim();
|
const stderr = localBranchResult.stderr.trim();
|
||||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||||
return { branches: [], isRepo: false };
|
return { branches: [], isRepo: false };
|
||||||
}
|
}
|
||||||
@@ -587,7 +854,40 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
|
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 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(
|
executeGit(
|
||||||
"GitCore.listBranches.defaultRef",
|
"GitCore.listBranches.defaultRef",
|
||||||
@@ -607,11 +907,25 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
remoteBranchResultEffect,
|
||||||
|
remoteNamesResultEffect,
|
||||||
branchRecencyPromise,
|
branchRecencyPromise,
|
||||||
],
|
],
|
||||||
{ concurrency: "unbounded" },
|
{ 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 =
|
const defaultBranch =
|
||||||
defaultRef.code === 0
|
defaultRef.code === 0
|
||||||
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||||
@@ -636,19 +950,17 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const branches = result.stdout
|
const localBranches = localBranchResult.stdout
|
||||||
.split("\n")
|
.split("\n")
|
||||||
.map((line) => line.trim())
|
.map(parseBranchLine)
|
||||||
.filter((line) => line.length > 0)
|
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||||
.map((line) => {
|
.map((branch) => ({
|
||||||
const name = line.replace(/^[*+]\s+/, "");
|
name: branch.name,
|
||||||
return {
|
current: branch.current,
|
||||||
name,
|
isRemote: false,
|
||||||
current: line.startsWith("* "),
|
isDefault: branch.name === defaultBranch,
|
||||||
isDefault: name === defaultBranch,
|
worktreePath: worktreeMap.get(branch.name) ?? null,
|
||||||
worktreePath: worktreeMap.get(name) ?? null,
|
}))
|
||||||
};
|
|
||||||
})
|
|
||||||
.toSorted((a, b) => {
|
.toSorted((a, b) => {
|
||||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||||
@@ -660,6 +972,43 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
return a.name.localeCompare(b.name);
|
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 };
|
return { branches, isRepo: true };
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -711,6 +1060,26 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const renameBranch: GitCoreShape["renameBranch"] = (input) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
if (input.oldBranch === input.newBranch) {
|
||||||
|
return { branch: input.newBranch };
|
||||||
|
}
|
||||||
|
const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch);
|
||||||
|
|
||||||
|
yield* executeGit(
|
||||||
|
"GitCore.renameBranch",
|
||||||
|
input.cwd,
|
||||||
|
["branch", "-m", "--", input.oldBranch, targetBranch],
|
||||||
|
{
|
||||||
|
timeoutMs: 10_000,
|
||||||
|
fallbackErrorMessage: "git branch rename failed",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return { branch: targetBranch };
|
||||||
|
});
|
||||||
|
|
||||||
const createBranch: GitCoreShape["createBranch"] = (input) =>
|
const createBranch: GitCoreShape["createBranch"] = (input) =>
|
||||||
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
|
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
|
||||||
timeoutMs: 10_000,
|
timeoutMs: 10_000,
|
||||||
@@ -719,17 +1088,83 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
|
|
||||||
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
|
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
|
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, {
|
||||||
timeoutMs: 10_000,
|
timeoutMs: 10_000,
|
||||||
fallbackErrorMessage: "git checkout failed",
|
fallbackErrorMessage: "git checkout failed",
|
||||||
});
|
});
|
||||||
|
|
||||||
// Refresh upstream refs in the background so checkout remains responsive.
|
// Refresh upstream refs in the background so checkout remains responsive.
|
||||||
yield* Effect.sync(() => {
|
yield* Effect.forkScoped(
|
||||||
void Effect.runPromise(
|
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
|
||||||
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
|
);
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const initRepo: GitCoreShape["initRepo"] = (input) =>
|
const initRepo: GitCoreShape["initRepo"] = (input) =>
|
||||||
@@ -750,6 +1185,7 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
listBranches,
|
listBranches,
|
||||||
createWorktree,
|
createWorktree,
|
||||||
removeWorktree,
|
removeWorktree,
|
||||||
|
renameBranch,
|
||||||
createBranch,
|
createBranch,
|
||||||
checkoutBranch,
|
checkoutBranch,
|
||||||
initRepo,
|
initRepo,
|
||||||
|
|||||||
@@ -41,6 +41,10 @@ interface FakeGitTextGeneration {
|
|||||||
diffSummary: string;
|
diffSummary: string;
|
||||||
diffPatch: string;
|
diffPatch: string;
|
||||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
||||||
|
generateBranchName: (input: {
|
||||||
|
cwd: string;
|
||||||
|
message: string;
|
||||||
|
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeTempDir(
|
function makeTempDir(
|
||||||
@@ -110,6 +114,10 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
|||||||
title: "Add stacked git actions",
|
title: "Add stacked git actions",
|
||||||
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
|
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
|
||||||
}),
|
}),
|
||||||
|
generateBranchName: () =>
|
||||||
|
Effect.succeed({
|
||||||
|
branch: "update-workflow",
|
||||||
|
}),
|
||||||
...overrides,
|
...overrides,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -136,6 +144,17 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
generateBranchName: (input) =>
|
||||||
|
implementation.generateBranchName(input).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) =>
|
||||||
|
new TextGenerationError({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
detail: "fake text generation failed",
|
||||||
|
...(cause !== undefined ? { cause } : {}),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -297,7 +316,7 @@ function makeManager(input?: {
|
|||||||
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||||
|
|
||||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||||
it.effect("status includes open PR metadata when branch already has an open PR", () =>
|
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
yield* initRepo(repoDir);
|
yield* initRepo(repoDir);
|
||||||
@@ -324,17 +343,103 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.branch).toBe("feature/status-open-pr");
|
expect(status.branch).toBe("feature/status-open-pr");
|
||||||
expect(status.openPr).toEqual({
|
expect(status.pr).toEqual({
|
||||||
number: 13,
|
number: 13,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/status-open-pr",
|
headBranch: "feature/status-open-pr",
|
||||||
|
state: "open",
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("status is resilient to gh lookup failures and returns openPr null", () =>
|
it.effect("status returns merged PR state when latest PR was merged", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
|
yield* initRepo(repoDir);
|
||||||
|
yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]);
|
||||||
|
|
||||||
|
const { manager } = yield* makeManager({
|
||||||
|
ghScenario: {
|
||||||
|
prListSequence: [
|
||||||
|
JSON.stringify([
|
||||||
|
{
|
||||||
|
number: 22,
|
||||||
|
title: "Merged PR",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||||
|
baseRefName: "main",
|
||||||
|
headRefName: "feature/status-merged-pr",
|
||||||
|
state: "MERGED",
|
||||||
|
mergedAt: "2026-01-30T10:00:00Z",
|
||||||
|
updatedAt: "2026-01-30T10:00:00Z",
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
|
expect(status.branch).toBe("feature/status-merged-pr");
|
||||||
|
expect(status.pr).toEqual({
|
||||||
|
number: 22,
|
||||||
|
title: "Merged PR",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||||
|
baseBranch: "main",
|
||||||
|
headBranch: "feature/status-merged-pr",
|
||||||
|
state: "merged",
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
|
yield* initRepo(repoDir);
|
||||||
|
yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]);
|
||||||
|
|
||||||
|
const { manager } = yield* makeManager({
|
||||||
|
ghScenario: {
|
||||||
|
prListSequence: [
|
||||||
|
JSON.stringify([
|
||||||
|
{
|
||||||
|
number: 45,
|
||||||
|
title: "Merged PR",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/45",
|
||||||
|
baseRefName: "main",
|
||||||
|
headRefName: "feature/status-open-over-merged",
|
||||||
|
state: "MERGED",
|
||||||
|
mergedAt: "2026-01-31T10:00:00Z",
|
||||||
|
updatedAt: "2026-02-01T10:00:00Z",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
number: 46,
|
||||||
|
title: "Open PR",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||||
|
baseRefName: "main",
|
||||||
|
headRefName: "feature/status-open-over-merged",
|
||||||
|
state: "OPEN",
|
||||||
|
updatedAt: "2026-01-30T10:00:00Z",
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
|
expect(status.branch).toBe("feature/status-open-over-merged");
|
||||||
|
expect(status.pr).toEqual({
|
||||||
|
number: 46,
|
||||||
|
title: "Open PR",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||||
|
baseBranch: "main",
|
||||||
|
headBranch: "feature/status-open-over-merged",
|
||||||
|
state: "open",
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
yield* initRepo(repoDir);
|
yield* initRepo(repoDir);
|
||||||
@@ -354,7 +459,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const status = yield* manager.status({ cwd: repoDir });
|
const status = yield* manager.status({ cwd: repoDir });
|
||||||
expect(status.branch).toBe("feature/status-no-gh");
|
expect(status.branch).toBe("feature/status-no-gh");
|
||||||
expect(status.openPr).toBeNull();
|
expect(status.pr).toBeNull();
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -465,6 +570,56 @@ 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.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", () =>
|
it.effect("skips push when branch is already up to date", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
|
|||||||
@@ -16,6 +16,62 @@ interface OpenPrInfo {
|
|||||||
headRefName: string;
|
headRefName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface PullRequestInfo extends OpenPrInfo {
|
||||||
|
state: "open" | "closed" | "merged";
|
||||||
|
updatedAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
||||||
|
if (!Array.isArray(raw)) return [];
|
||||||
|
|
||||||
|
const parsed: PullRequestInfo[] = [];
|
||||||
|
for (const entry of raw) {
|
||||||
|
if (!entry || typeof entry !== "object") continue;
|
||||||
|
const record = entry as Record<string, unknown>;
|
||||||
|
const number = record.number;
|
||||||
|
const title = record.title;
|
||||||
|
const url = record.url;
|
||||||
|
const baseRefName = record.baseRefName;
|
||||||
|
const headRefName = record.headRefName;
|
||||||
|
const state = record.state;
|
||||||
|
const mergedAt = record.mergedAt;
|
||||||
|
const updatedAt = record.updatedAt;
|
||||||
|
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
typeof title !== "string" ||
|
||||||
|
typeof url !== "string" ||
|
||||||
|
typeof baseRefName !== "string" ||
|
||||||
|
typeof headRefName !== "string"
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let normalizedState: "open" | "closed" | "merged";
|
||||||
|
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||||
|
normalizedState = "merged";
|
||||||
|
} else if (state === "OPEN" || state === undefined || state === null) {
|
||||||
|
normalizedState = "open";
|
||||||
|
} else if (state === "CLOSED") {
|
||||||
|
normalizedState = "closed";
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
parsed.push({
|
||||||
|
number,
|
||||||
|
title,
|
||||||
|
url,
|
||||||
|
baseRefName,
|
||||||
|
headRefName,
|
||||||
|
state: normalizedState,
|
||||||
|
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
||||||
return new GitManagerError({
|
return new GitManagerError({
|
||||||
operation,
|
operation,
|
||||||
@@ -79,12 +135,13 @@ function extractBranchFromRef(ref: string): string {
|
|||||||
return normalized.slice(firstSlash + 1).trim();
|
return normalized.slice(firstSlash + 1).trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
function toStatusOpenPr(pr: OpenPrInfo): {
|
function toStatusPr(pr: PullRequestInfo): {
|
||||||
number: number;
|
number: number;
|
||||||
title: string;
|
title: string;
|
||||||
url: string;
|
url: string;
|
||||||
baseBranch: string;
|
baseBranch: string;
|
||||||
headBranch: string;
|
headBranch: string;
|
||||||
|
state: "open" | "closed" | "merged";
|
||||||
} {
|
} {
|
||||||
return {
|
return {
|
||||||
number: pr.number,
|
number: pr.number,
|
||||||
@@ -92,6 +149,7 @@ function toStatusOpenPr(pr: OpenPrInfo): {
|
|||||||
url: pr.url,
|
url: pr.url,
|
||||||
baseBranch: pr.baseRefName,
|
baseBranch: pr.baseRefName,
|
||||||
headBranch: pr.headRefName,
|
headBranch: pr.headRefName,
|
||||||
|
state: pr.state,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,10 +181,56 @@ export const makeGitManager = Effect.gen(function* () {
|
|||||||
url: first.url,
|
url: first.url,
|
||||||
baseRefName: first.baseRefName,
|
baseRefName: first.baseRefName,
|
||||||
headRefName: first.headRefName,
|
headRefName: first.headRefName,
|
||||||
} satisfies OpenPrInfo;
|
state: "open",
|
||||||
|
updatedAt: null,
|
||||||
|
} satisfies PullRequestInfo;
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const findLatestPr = (cwd: string, branch: string) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const stdout = yield* gitHubCli
|
||||||
|
.execute({
|
||||||
|
cwd,
|
||||||
|
args: [
|
||||||
|
"pr",
|
||||||
|
"list",
|
||||||
|
"--head",
|
||||||
|
branch,
|
||||||
|
"--state",
|
||||||
|
"all",
|
||||||
|
"--limit",
|
||||||
|
"20",
|
||||||
|
"--json",
|
||||||
|
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.pipe(Effect.map((result) => result.stdout));
|
||||||
|
|
||||||
|
const raw = stdout.trim();
|
||||||
|
if (raw.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsedJson = yield* Effect.try({
|
||||||
|
try: () => JSON.parse(raw) as unknown,
|
||||||
|
catch: (cause) =>
|
||||||
|
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
||||||
|
});
|
||||||
|
|
||||||
|
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
|
||||||
|
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
|
||||||
|
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
|
||||||
|
return right - left;
|
||||||
|
});
|
||||||
|
|
||||||
|
const latestOpenPr = parsed.find((pr) => pr.state === "open");
|
||||||
|
if (latestOpenPr) {
|
||||||
|
return latestOpenPr;
|
||||||
|
}
|
||||||
|
return parsed[0] ?? null;
|
||||||
|
});
|
||||||
|
|
||||||
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
|
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
||||||
@@ -258,10 +362,10 @@ export const makeGitManager = Effect.gen(function* () {
|
|||||||
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
|
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
|
||||||
const details = yield* gitCore.statusDetails(input.cwd);
|
const details = yield* gitCore.statusDetails(input.cwd);
|
||||||
|
|
||||||
const openPr =
|
const pr =
|
||||||
details.branch && details.hasUpstream
|
details.branch !== null
|
||||||
? yield* findOpenPr(input.cwd, details.branch).pipe(
|
? yield* findLatestPr(input.cwd, details.branch).pipe(
|
||||||
Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
|
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
|
||||||
Effect.catch(() => Effect.succeed(null)),
|
Effect.catch(() => Effect.succeed(null)),
|
||||||
)
|
)
|
||||||
: null;
|
: null;
|
||||||
@@ -273,7 +377,7 @@ export const makeGitManager = Effect.gen(function* () {
|
|||||||
hasUpstream: details.hasUpstream,
|
hasUpstream: details.hasUpstream,
|
||||||
aheadCount: details.aheadCount,
|
aheadCount: details.aheadCount,
|
||||||
behindCount: details.behindCount,
|
behindCount: details.behindCount,
|
||||||
openPr,
|
pr,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import type {
|
|||||||
|
|
||||||
import type { GitCommandError } from "../Errors.ts";
|
import type { GitCommandError } from "../Errors.ts";
|
||||||
|
|
||||||
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
|
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||||
upstreamRef: string | null;
|
upstreamRef: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,6 +46,16 @@ export interface GitRangeContext {
|
|||||||
diffPatch: string;
|
diffPatch: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface GitRenameBranchInput {
|
||||||
|
cwd: string;
|
||||||
|
oldBranch: string;
|
||||||
|
newBranch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitRenameBranchResult {
|
||||||
|
branch: string;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GitCoreShape - Service API for low-level Git repository interactions.
|
* GitCoreShape - Service API for low-level Git repository interactions.
|
||||||
*/
|
*/
|
||||||
@@ -101,7 +111,7 @@ export interface GitCoreShape {
|
|||||||
) => Effect.Effect<string | null, GitCommandError>;
|
) => Effect.Effect<string | null, GitCommandError>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* List local branches and branch metadata.
|
* List local + remote branches and branch metadata.
|
||||||
*/
|
*/
|
||||||
readonly listBranches: (
|
readonly listBranches: (
|
||||||
input: GitListBranchesInput,
|
input: GitListBranchesInput,
|
||||||
@@ -124,6 +134,13 @@ export interface GitCoreShape {
|
|||||||
*/
|
*/
|
||||||
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rename an existing local branch.
|
||||||
|
*/
|
||||||
|
readonly renameBranch: (
|
||||||
|
input: GitRenameBranchInput,
|
||||||
|
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a local branch.
|
* Create a local branch.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
*/
|
*/
|
||||||
import { ServiceMap } from "effect";
|
import { ServiceMap } from "effect";
|
||||||
import type { Effect } from "effect";
|
import type { Effect } from "effect";
|
||||||
|
import type { ChatAttachment } from "@t3tools/contracts";
|
||||||
|
|
||||||
import type { TextGenerationError } from "../Errors.ts";
|
import type { TextGenerationError } from "../Errors.ts";
|
||||||
|
|
||||||
@@ -37,11 +38,22 @@ export interface PrContentGenerationResult {
|
|||||||
body: string;
|
body: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BranchNameGenerationInput {
|
||||||
|
cwd: string;
|
||||||
|
message: string;
|
||||||
|
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BranchNameGenerationResult {
|
||||||
|
branch: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface TextGenerationService {
|
export interface TextGenerationService {
|
||||||
generateCommitMessage(
|
generateCommitMessage(
|
||||||
input: CommitMessageGenerationInput,
|
input: CommitMessageGenerationInput,
|
||||||
): Promise<CommitMessageGenerationResult>;
|
): Promise<CommitMessageGenerationResult>;
|
||||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
||||||
|
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -61,6 +73,13 @@ export interface TextGenerationShape {
|
|||||||
readonly generatePrContent: (
|
readonly generatePrContent: (
|
||||||
input: PrContentGenerationInput,
|
input: PrContentGenerationInput,
|
||||||
) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;
|
) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a concise branch name from a user message.
|
||||||
|
*/
|
||||||
|
readonly generateBranchName: (
|
||||||
|
input: BranchNameGenerationInput,
|
||||||
|
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||||
|
|
||||||
|
describe("imageMime", () => {
|
||||||
|
it("parses base64 data URL with mime type", () => {
|
||||||
|
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({
|
||||||
|
mimeType: "image/png",
|
||||||
|
base64: "SGVsbG8=",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses base64 data URL with mime parameters", () => {
|
||||||
|
expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({
|
||||||
|
mimeType: "image/png",
|
||||||
|
base64: "SGVsbG8=",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects non-base64 data URL", () => {
|
||||||
|
expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects missing mime type", () => {
|
||||||
|
expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses base64 data URL with spaces in payload", () => {
|
||||||
|
expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({
|
||||||
|
mimeType: "image/png",
|
||||||
|
base64: "SGVsbG8=",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not read inherited keys from mime extension map", () => {
|
||||||
|
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import Mime from "@effect/platform-node/Mime";
|
||||||
|
|
||||||
|
export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
|
||||||
|
"image/avif": ".avif",
|
||||||
|
"image/bmp": ".bmp",
|
||||||
|
"image/gif": ".gif",
|
||||||
|
"image/heic": ".heic",
|
||||||
|
"image/heif": ".heif",
|
||||||
|
"image/jpeg": ".jpg",
|
||||||
|
"image/jpg": ".jpg",
|
||||||
|
"image/png": ".png",
|
||||||
|
"image/svg+xml": ".svg",
|
||||||
|
"image/tiff": ".tiff",
|
||||||
|
"image/webp": ".webp",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
||||||
|
".avif",
|
||||||
|
".bmp",
|
||||||
|
".gif",
|
||||||
|
".heic",
|
||||||
|
".heif",
|
||||||
|
".ico",
|
||||||
|
".jpeg",
|
||||||
|
".jpg",
|
||||||
|
".png",
|
||||||
|
".svg",
|
||||||
|
".tiff",
|
||||||
|
".webp",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export function parseBase64DataUrl(
|
||||||
|
dataUrl: string,
|
||||||
|
): { readonly mimeType: string; readonly base64: string } | null {
|
||||||
|
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
|
||||||
|
if (!match) return null;
|
||||||
|
|
||||||
|
const headerParts = (match[1] ?? "")
|
||||||
|
.split(";")
|
||||||
|
.map((part) => part.trim())
|
||||||
|
.filter((part) => part.length > 0);
|
||||||
|
if (headerParts.length < 2) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const trailingToken = headerParts.at(-1)?.toLowerCase();
|
||||||
|
if (trailingToken !== "base64") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mimeType = headerParts[0]?.toLowerCase();
|
||||||
|
const base64 = match[2]?.replace(/\s+/g, "");
|
||||||
|
if (!mimeType || !base64) return null;
|
||||||
|
|
||||||
|
return { mimeType, base64 };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
|
||||||
|
const key = input.mimeType.toLowerCase();
|
||||||
|
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
|
||||||
|
? IMAGE_EXTENSION_BY_MIME_TYPE[key]
|
||||||
|
: undefined;
|
||||||
|
if (fromMime) {
|
||||||
|
return fromMime;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fromMimeExtension = Mime.getExtension(input.mimeType);
|
||||||
|
if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) {
|
||||||
|
return fromMimeExtension;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileName = input.fileName?.trim() ?? "";
|
||||||
|
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
|
||||||
|
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
|
||||||
|
if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {
|
||||||
|
return fileNameExtension;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ".bin";
|
||||||
|
}
|
||||||
@@ -49,10 +49,21 @@ const testLayer = Layer.mergeAll(
|
|||||||
const runCli = (
|
const runCli = (
|
||||||
args: ReadonlyArray<string>,
|
args: ReadonlyArray<string>,
|
||||||
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
|
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
|
||||||
) =>
|
) => {
|
||||||
Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))),
|
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
ConfigProvider.layer(
|
||||||
|
ConfigProvider.fromEnv({
|
||||||
|
env: {
|
||||||
|
T3CODE_STATE_DIR: uniqueStateDir,
|
||||||
|
...env,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
ProviderThreadId,
|
ProviderThreadId,
|
||||||
|
ProviderTurnId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
@@ -36,10 +37,12 @@ import {
|
|||||||
type ProviderServiceShape,
|
type ProviderServiceShape,
|
||||||
} from "../../provider/Services/ProviderService.ts";
|
} from "../../provider/Services/ProviderService.ts";
|
||||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||||
|
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||||
|
|
||||||
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
|
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
|
||||||
@@ -91,7 +94,7 @@ function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd
|
|||||||
async function waitForThread(
|
async function waitForThread(
|
||||||
engine: OrchestrationEngineShape,
|
engine: OrchestrationEngineShape,
|
||||||
predicate: (thread: {
|
predicate: (thread: {
|
||||||
latestTurnId: string | null;
|
latestTurn: { turnId: string } | null;
|
||||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||||
activities: ReadonlyArray<{ kind: string }>;
|
activities: ReadonlyArray<{ kind: string }>;
|
||||||
}) => boolean,
|
}) => boolean,
|
||||||
@@ -99,7 +102,7 @@ async function waitForThread(
|
|||||||
) {
|
) {
|
||||||
const deadline = Date.now() + timeoutMs;
|
const deadline = Date.now() + timeoutMs;
|
||||||
const poll = async (): Promise<{
|
const poll = async (): Promise<{
|
||||||
latestTurnId: string | null;
|
latestTurn: { turnId: string } | null;
|
||||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||||
activities: ReadonlyArray<{ kind: string }>;
|
activities: ReadonlyArray<{ kind: string }>;
|
||||||
}> => {
|
}> => {
|
||||||
@@ -231,11 +234,13 @@ describe("CheckpointReactor", () => {
|
|||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
);
|
);
|
||||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
|
||||||
const layer = CheckpointReactorLive.pipe(
|
const layer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||||
Layer.provideMerge(checkpointStoreLayer),
|
Layer.provideMerge(CheckpointStoreLive),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
runtime = ManagedRuntime.make(layer);
|
runtime = ManagedRuntime.make(layer);
|
||||||
@@ -317,6 +322,8 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -332,7 +339,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asProviderTurnId("turn-1"),
|
||||||
});
|
});
|
||||||
await waitForGitRefExists(
|
await waitForGitRefExists(
|
||||||
harness.cwd,
|
harness.cwd,
|
||||||
@@ -347,14 +354,14 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asProviderTurnId("turn-1"),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
});
|
});
|
||||||
|
|
||||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(
|
||||||
harness.engine,
|
harness.engine,
|
||||||
(entry) => entry.latestTurnId === "turn-1" && entry.checkpoints.length === 1,
|
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
|
||||||
);
|
);
|
||||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||||
expect(
|
expect(
|
||||||
@@ -379,6 +386,83 @@ describe("CheckpointReactor", () => {
|
|||||||
).toBe("v2\n");
|
).toBe("v2\n");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("ignores auxiliary thread turn completion while primary turn is active", async () => {
|
||||||
|
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||||
|
const createdAt = new Date().toISOString();
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.session.set",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
session: {
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
status: "running",
|
||||||
|
providerName: "codex",
|
||||||
|
providerSessionId: asSessionId("sess-1"),
|
||||||
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
activeTurnId: asTurnId("turn-main"),
|
||||||
|
lastError: null,
|
||||||
|
updatedAt: createdAt,
|
||||||
|
},
|
||||||
|
createdAt,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
harness.provider.emit({
|
||||||
|
type: "turn.started",
|
||||||
|
eventId: EventId.makeUnsafe("evt-turn-started-main"),
|
||||||
|
provider: "codex",
|
||||||
|
sessionId: asSessionId("sess-1"),
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
turnId: asProviderTurnId("turn-main"),
|
||||||
|
});
|
||||||
|
await waitForGitRefExists(
|
||||||
|
harness.cwd,
|
||||||
|
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||||
|
);
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||||
|
|
||||||
|
harness.provider.emit({
|
||||||
|
type: "turn.completed",
|
||||||
|
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
|
||||||
|
provider: "codex",
|
||||||
|
sessionId: asSessionId("sess-1"),
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-aux"),
|
||||||
|
turnId: asProviderTurnId("turn-aux"),
|
||||||
|
status: "completed",
|
||||||
|
});
|
||||||
|
|
||||||
|
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||||
|
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
|
const midThread = midReadModel.threads.find(
|
||||||
|
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||||
|
);
|
||||||
|
expect(midThread?.checkpoints).toHaveLength(0);
|
||||||
|
|
||||||
|
harness.provider.emit({
|
||||||
|
type: "turn.completed",
|
||||||
|
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
|
||||||
|
provider: "codex",
|
||||||
|
sessionId: asSessionId("sess-1"),
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
turnId: asProviderTurnId("turn-main"),
|
||||||
|
status: "completed",
|
||||||
|
});
|
||||||
|
|
||||||
|
const thread = await waitForThread(
|
||||||
|
harness.engine,
|
||||||
|
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
|
||||||
|
);
|
||||||
|
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
||||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||||
const createdAt = new Date().toISOString();
|
const createdAt = new Date().toISOString();
|
||||||
@@ -394,6 +478,8 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -409,7 +495,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asTurnId("turn-missing-baseline"),
|
turnId: asProviderTurnId("turn-missing-baseline"),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -445,6 +531,8 @@ describe("CheckpointReactor", () => {
|
|||||||
text: "start turn",
|
text: "start turn",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -481,6 +569,8 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-missing"),
|
providerSessionId: asSessionId("sess-missing"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: asTurnId("turn-missing-cwd"),
|
activeTurnId: asTurnId("turn-missing-cwd"),
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -497,7 +587,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-missing"),
|
sessionId: asSessionId("sess-missing"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||||
turnId: asTurnId("turn-missing-cwd"),
|
turnId: asProviderTurnId("turn-missing-cwd"),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -529,6 +619,8 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -544,7 +636,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asTurnId("turn-3"),
|
turnId: asProviderTurnId("turn-3"),
|
||||||
turnCount: 3,
|
turnCount: 3,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
});
|
});
|
||||||
@@ -580,6 +672,8 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -595,7 +689,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asTurnId("turn-runtime-failure"),
|
turnId: asProviderTurnId("turn-runtime-failure"),
|
||||||
turnCount: 1,
|
turnCount: 1,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
});
|
});
|
||||||
@@ -607,7 +701,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asTurnId("turn-after-runtime-failure"),
|
turnId: asProviderTurnId("turn-after-runtime-failure"),
|
||||||
});
|
});
|
||||||
|
|
||||||
await waitForGitRefExists(
|
await waitForGitRefExists(
|
||||||
@@ -634,6 +728,8 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -684,7 +780,7 @@ describe("CheckpointReactor", () => {
|
|||||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||||
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
|
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
|
||||||
|
|
||||||
expect(thread.latestTurnId).toBe("turn-1");
|
expect(thread.latestTurn?.turnId).toBe("turn-1");
|
||||||
expect(thread.checkpoints).toHaveLength(1);
|
expect(thread.checkpoints).toHaveLength(1);
|
||||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||||
@@ -713,6 +809,8 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
EventId,
|
EventId,
|
||||||
MessageId,
|
MessageId,
|
||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
|
ProviderThreadId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
@@ -36,6 +37,17 @@ function toTurnId(value: string | undefined): TurnId | null {
|
|||||||
return value === undefined ? null : TurnId.makeUnsafe(value);
|
return value === undefined ? null : TurnId.makeUnsafe(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
|
||||||
|
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||||
|
if (left === null || left === undefined || right === null || right === undefined) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return left === right;
|
||||||
|
}
|
||||||
|
|
||||||
function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
|
function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case "failed":
|
case "failed":
|
||||||
@@ -173,6 +185,21 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const projectedProviderThreadId = thread.session?.providerThreadId ?? null;
|
||||||
|
const eventProviderThreadId = toProviderThreadId(event.threadId);
|
||||||
|
if (
|
||||||
|
projectedProviderThreadId !== null &&
|
||||||
|
eventProviderThreadId !== null &&
|
||||||
|
!sameId(projectedProviderThreadId, eventProviderThreadId)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// When a primary turn is active, only that turn may produce completion checkpoints.
|
||||||
|
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
|
if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ import {
|
|||||||
OrchestrationProjectionPipeline,
|
OrchestrationProjectionPipeline,
|
||||||
type OrchestrationProjectionPipelineShape,
|
type OrchestrationProjectionPipelineShape,
|
||||||
} from "../Services/ProjectionPipeline.ts";
|
} from "../Services/ProjectionPipeline.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||||
@@ -37,6 +39,8 @@ async function createOrchestrationSystem() {
|
|||||||
Layer.provide(OrchestrationEventStoreLive),
|
Layer.provide(OrchestrationEventStoreLive),
|
||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
@@ -92,6 +96,8 @@ describe("OrchestrationEngine", () => {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -308,6 +314,8 @@ describe("OrchestrationEngine", () => {
|
|||||||
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
|
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
|
||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
Layer.provide(SqlitePersistenceMemory),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
@@ -428,6 +436,8 @@ describe("OrchestrationEngine", () => {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
|
approvalPolicy: "on-request" as const,
|
||||||
|
sandboxMode: "workspace-write" as const,
|
||||||
createdAt,
|
createdAt,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -586,6 +596,8 @@ describe("OrchestrationEngine", () => {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
createdAt: now(),
|
createdAt: now(),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,10 @@
|
|||||||
import { ApprovalRequestId, type OrchestrationEvent } from "@t3tools/contracts";
|
import {
|
||||||
import { Effect, Layer, Option, Stream } from "effect";
|
ApprovalRequestId,
|
||||||
|
type ChatAttachment,
|
||||||
|
type OrchestrationEvent,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
|
|
||||||
import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
|
import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
|
||||||
@@ -27,10 +32,17 @@ import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/
|
|||||||
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
||||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||||
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
import {
|
import {
|
||||||
OrchestrationProjectionPipeline,
|
OrchestrationProjectionPipeline,
|
||||||
type OrchestrationProjectionPipelineShape,
|
type OrchestrationProjectionPipelineShape,
|
||||||
} from "../Services/ProjectionPipeline.ts";
|
} from "../Services/ProjectionPipeline.ts";
|
||||||
|
import {
|
||||||
|
attachmentRelativePath,
|
||||||
|
parseAttachmentIdFromRelativePath,
|
||||||
|
parseThreadSegmentFromAttachmentId,
|
||||||
|
toSafeThreadAttachmentSegment,
|
||||||
|
} from "../../attachmentStore.ts";
|
||||||
|
|
||||||
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||||
projects: "projection.projects",
|
projects: "projection.projects",
|
||||||
@@ -48,9 +60,23 @@ type ProjectorName =
|
|||||||
|
|
||||||
interface ProjectorDefinition {
|
interface ProjectorDefinition {
|
||||||
readonly name: ProjectorName;
|
readonly name: ProjectorName;
|
||||||
readonly apply: (event: OrchestrationEvent) => Effect.Effect<void, ProjectionRepositoryError>;
|
readonly apply: (
|
||||||
|
event: OrchestrationEvent,
|
||||||
|
attachmentSideEffects: AttachmentSideEffects,
|
||||||
|
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface AttachmentSideEffects {
|
||||||
|
readonly deletedThreadIds: Set<string>;
|
||||||
|
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const materializeAttachmentsForProjection = Effect.fn(
|
||||||
|
(input: {
|
||||||
|
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||||
|
}) => Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
|
||||||
|
);
|
||||||
|
|
||||||
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||||
if (typeof payload !== "object" || payload === null) {
|
if (typeof payload !== "object" || payload === null) {
|
||||||
return null;
|
return null;
|
||||||
@@ -163,6 +189,130 @@ function retainProjectionActivitiesAfterRevert(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function collectThreadAttachmentRelativePaths(
|
||||||
|
threadId: string,
|
||||||
|
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||||
|
): Set<string> {
|
||||||
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
|
if (!threadSegment) {
|
||||||
|
return new Set();
|
||||||
|
}
|
||||||
|
const relativePaths = new Set<string>();
|
||||||
|
for (const message of messages) {
|
||||||
|
for (const attachment of message.attachments ?? []) {
|
||||||
|
if (attachment.type !== "image") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
|
||||||
|
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
relativePaths.add(attachmentRelativePath(attachment));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return relativePaths;
|
||||||
|
}
|
||||||
|
|
||||||
|
const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSideEffects) {
|
||||||
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
|
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
|
||||||
|
const path = yield* Effect.service(Path.Path);
|
||||||
|
|
||||||
|
const attachmentsRootDir = path.join(serverConfig.stateDir, "attachments");
|
||||||
|
|
||||||
|
yield* Effect.forEach(
|
||||||
|
sideEffects.deletedThreadIds,
|
||||||
|
(threadId) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
|
if (!threadSegment) {
|
||||||
|
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
|
||||||
|
threadId,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const entries = yield* fileSystem
|
||||||
|
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||||
|
yield* Effect.forEach(
|
||||||
|
entries,
|
||||||
|
(entry) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||||
|
if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||||
|
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
|
||||||
|
force: true,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
|
||||||
|
yield* Effect.forEach(
|
||||||
|
sideEffects.prunedThreadRelativePaths.entries(),
|
||||||
|
([threadId, keptThreadRelativePaths]) => {
|
||||||
|
if (sideEffects.deletedThreadIds.has(threadId)) {
|
||||||
|
return Effect.void;
|
||||||
|
}
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
|
if (!threadSegment) {
|
||||||
|
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const entries = yield* fileSystem
|
||||||
|
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||||
|
yield* Effect.forEach(
|
||||||
|
entries,
|
||||||
|
(entry) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||||
|
if (relativePath.length === 0 || relativePath.includes("/")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||||
|
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const absolutePath = path.join(attachmentsRootDir, relativePath);
|
||||||
|
const fileInfo = yield* fileSystem
|
||||||
|
.stat(absolutePath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!keptThreadRelativePaths.has(relativePath)) {
|
||||||
|
yield* fileSystem.remove(absolutePath, { force: true });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||||
const sql = yield* SqlClient.SqlClient;
|
const sql = yield* SqlClient.SqlClient;
|
||||||
const eventStore = yield* OrchestrationEventStore;
|
const eventStore = yield* OrchestrationEventStore;
|
||||||
@@ -175,7 +325,11 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||||
|
|
||||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event) =>
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const serverConfig = yield* ServerConfig;
|
||||||
|
|
||||||
|
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "project.created":
|
case "project.created":
|
||||||
@@ -233,7 +387,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadsProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.created":
|
case "thread.created":
|
||||||
@@ -272,6 +426,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "thread.deleted": {
|
case "thread.deleted": {
|
||||||
|
attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);
|
||||||
const existingRow = yield* projectionThreadRepository.getById({
|
const existingRow = yield* projectionThreadRepository.getById({
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
});
|
});
|
||||||
@@ -351,7 +506,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (
|
||||||
|
event,
|
||||||
|
attachmentSideEffects,
|
||||||
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.message-sent": {
|
case "thread.message-sent": {
|
||||||
@@ -367,12 +525,19 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
: existingMessage && event.payload.text.length === 0
|
: existingMessage && event.payload.text.length === 0
|
||||||
? existingMessage.text
|
? existingMessage.text
|
||||||
: event.payload.text;
|
: event.payload.text;
|
||||||
|
const nextAttachments =
|
||||||
|
event.payload.attachments !== undefined
|
||||||
|
? yield* materializeAttachmentsForProjection({
|
||||||
|
attachments: event.payload.attachments,
|
||||||
|
})
|
||||||
|
: existingMessage?.attachments;
|
||||||
yield* projectionThreadMessageRepository.upsert({
|
yield* projectionThreadMessageRepository.upsert({
|
||||||
messageId: event.payload.messageId,
|
messageId: event.payload.messageId,
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
turnId: event.payload.turnId,
|
turnId: event.payload.turnId,
|
||||||
role: event.payload.role,
|
role: event.payload.role,
|
||||||
text: nextText,
|
text: nextText,
|
||||||
|
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
|
||||||
isStreaming: event.payload.streaming,
|
isStreaming: event.payload.streaming,
|
||||||
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
|
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
|
||||||
updatedAt: event.payload.updatedAt,
|
updatedAt: event.payload.updatedAt,
|
||||||
@@ -406,6 +571,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
|
yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
|
||||||
concurrency: 1,
|
concurrency: 1,
|
||||||
}).pipe(Effect.asVoid);
|
}).pipe(Effect.asVoid);
|
||||||
|
attachmentSideEffects.prunedThreadRelativePaths.set(
|
||||||
|
event.payload.threadId,
|
||||||
|
collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows),
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -414,7 +583,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
|
||||||
|
event,
|
||||||
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.activity-appended":
|
case "thread.activity-appended":
|
||||||
@@ -462,7 +634,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
|
||||||
|
event,
|
||||||
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
if (event.type !== "thread.session-set") {
|
if (event.type !== "thread.session-set") {
|
||||||
return;
|
return;
|
||||||
@@ -473,13 +648,18 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
providerName: event.payload.session.providerName,
|
providerName: event.payload.session.providerName,
|
||||||
providerSessionId: event.payload.session.providerSessionId,
|
providerSessionId: event.payload.session.providerSessionId,
|
||||||
providerThreadId: event.payload.session.providerThreadId,
|
providerThreadId: event.payload.session.providerThreadId,
|
||||||
|
approvalPolicy: event.payload.session.approvalPolicy,
|
||||||
|
sandboxMode: event.payload.session.sandboxMode,
|
||||||
activeTurnId: event.payload.session.activeTurnId,
|
activeTurnId: event.payload.session.activeTurnId,
|
||||||
lastError: event.payload.session.lastError,
|
lastError: event.payload.session.lastError,
|
||||||
updatedAt: event.payload.session.updatedAt,
|
updatedAt: event.payload.session.updatedAt,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
|
||||||
|
event,
|
||||||
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.turn-start-requested": {
|
case "thread.turn-start-requested": {
|
||||||
@@ -712,7 +892,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
|
|
||||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||||
|
|
||||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (event) =>
|
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (
|
||||||
|
event,
|
||||||
|
_attachmentSideEffects,
|
||||||
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "thread.activity-appended": {
|
case "thread.activity-appended": {
|
||||||
@@ -835,17 +1018,35 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||||
sql.withTransaction(
|
Effect.gen(function* () {
|
||||||
projector.apply(event).pipe(
|
const attachmentSideEffects: AttachmentSideEffects = {
|
||||||
Effect.flatMap(() =>
|
deletedThreadIds: new Set<string>(),
|
||||||
projectionStateRepository.upsert({
|
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||||
|
};
|
||||||
|
|
||||||
|
yield* sql.withTransaction(
|
||||||
|
projector.apply(event, attachmentSideEffects).pipe(
|
||||||
|
Effect.flatMap(() =>
|
||||||
|
projectionStateRepository.upsert({
|
||||||
|
projector: projector.name,
|
||||||
|
lastAppliedSequence: event.sequence,
|
||||||
|
updatedAt: event.occurredAt,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
yield* runAttachmentSideEffects(attachmentSideEffects).pipe(
|
||||||
|
Effect.catch((cause) =>
|
||||||
|
Effect.logWarning("failed to apply projected attachment side-effects", {
|
||||||
projector: projector.name,
|
projector: projector.name,
|
||||||
lastAppliedSequence: event.sequence,
|
sequence: event.sequence,
|
||||||
updatedAt: event.occurredAt,
|
eventType: event.type,
|
||||||
|
cause,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
);
|
||||||
);
|
});
|
||||||
|
|
||||||
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
||||||
projectionStateRepository
|
projectionStateRepository
|
||||||
@@ -867,6 +1068,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
||||||
concurrency: 1,
|
concurrency: 1,
|
||||||
}).pipe(
|
}).pipe(
|
||||||
|
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||||
|
Effect.provideService(Path.Path, path),
|
||||||
|
Effect.provideService(ServerConfig, serverConfig),
|
||||||
Effect.asVoid,
|
Effect.asVoid,
|
||||||
Effect.catchTag("SqlError", (sqlError) =>
|
Effect.catchTag("SqlError", (sqlError) =>
|
||||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
||||||
@@ -878,6 +1082,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
bootstrapProjector,
|
bootstrapProjector,
|
||||||
{ concurrency: 1 },
|
{ concurrency: 1 },
|
||||||
).pipe(
|
).pipe(
|
||||||
|
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||||
|
Effect.provideService(Path.Path, path),
|
||||||
|
Effect.provideService(ServerConfig, serverConfig),
|
||||||
Effect.asVoid,
|
Effect.asVoid,
|
||||||
Effect.tap(() =>
|
Effect.tap(() =>
|
||||||
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
||||||
@@ -899,6 +1106,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
|||||||
OrchestrationProjectionPipeline,
|
OrchestrationProjectionPipeline,
|
||||||
makeOrchestrationProjectionPipeline,
|
makeOrchestrationProjectionPipeline,
|
||||||
).pipe(
|
).pipe(
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||||
|
|||||||
@@ -143,6 +143,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
provider_name,
|
provider_name,
|
||||||
provider_session_id,
|
provider_session_id,
|
||||||
provider_thread_id,
|
provider_thread_id,
|
||||||
|
approval_policy,
|
||||||
|
sandbox_mode,
|
||||||
active_turn_id,
|
active_turn_id,
|
||||||
last_error,
|
last_error,
|
||||||
updated_at
|
updated_at
|
||||||
@@ -153,6 +155,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
'codex',
|
'codex',
|
||||||
'provider-session-1',
|
'provider-session-1',
|
||||||
'provider-thread-1',
|
'provider-thread-1',
|
||||||
|
'on-request',
|
||||||
|
'workspace-write',
|
||||||
'turn-1',
|
'turn-1',
|
||||||
NULL,
|
NULL,
|
||||||
'2026-02-24T00:00:07.000Z'
|
'2026-02-24T00:00:07.000Z'
|
||||||
@@ -239,7 +243,14 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
latestTurnId: asTurnId("turn-1"),
|
latestTurn: {
|
||||||
|
turnId: asTurnId("turn-1"),
|
||||||
|
state: "completed",
|
||||||
|
requestedAt: "2026-02-24T00:00:08.000Z",
|
||||||
|
startedAt: "2026-02-24T00:00:08.000Z",
|
||||||
|
completedAt: "2026-02-24T00:00:08.000Z",
|
||||||
|
assistantMessageId: asMessageId("message-1"),
|
||||||
|
},
|
||||||
createdAt: "2026-02-24T00:00:02.000Z",
|
createdAt: "2026-02-24T00:00:02.000Z",
|
||||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
@@ -282,6 +293,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asProviderSessionId("provider-session-1"),
|
providerSessionId: asProviderSessionId("provider-session-1"),
|
||||||
providerThreadId: asProviderThreadId("provider-thread-1"),
|
providerThreadId: asProviderThreadId("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: asTurnId("turn-1"),
|
activeTurnId: asTurnId("turn-1"),
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
import {
|
import {
|
||||||
|
ChatAttachment,
|
||||||
|
IsoDateTime,
|
||||||
|
MessageId,
|
||||||
OrchestrationCheckpointFile,
|
OrchestrationCheckpointFile,
|
||||||
OrchestrationReadModel,
|
OrchestrationReadModel,
|
||||||
ProjectScript,
|
ProjectScript,
|
||||||
|
TurnId,
|
||||||
type OrchestrationCheckpointSummary,
|
type OrchestrationCheckpointSummary,
|
||||||
|
type OrchestrationLatestTurn,
|
||||||
type OrchestrationMessage,
|
type OrchestrationMessage,
|
||||||
type OrchestrationProject,
|
type OrchestrationProject,
|
||||||
type OrchestrationSession,
|
type OrchestrationSession,
|
||||||
@@ -38,12 +43,13 @@ const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
|||||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
|
||||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||||
Struct.assign({
|
Struct.assign({
|
||||||
isStreaming: Schema.Number,
|
isStreaming: Schema.Number,
|
||||||
|
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||||
Struct.assign({
|
Struct.assign({
|
||||||
payload: Schema.fromJsonString(Schema.Unknown),
|
payload: Schema.fromJsonString(Schema.Unknown),
|
||||||
@@ -55,6 +61,15 @@ const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
|
|||||||
files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
|
files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
const ProjectionLatestTurnDbRowSchema = Schema.Struct({
|
||||||
|
threadId: ProjectionThread.fields.threadId,
|
||||||
|
turnId: TurnId,
|
||||||
|
state: Schema.String,
|
||||||
|
requestedAt: IsoDateTime,
|
||||||
|
startedAt: Schema.NullOr(IsoDateTime),
|
||||||
|
completedAt: Schema.NullOr(IsoDateTime),
|
||||||
|
assistantMessageId: Schema.NullOr(MessageId),
|
||||||
|
});
|
||||||
const ProjectionStateDbRowSchema = ProjectionState;
|
const ProjectionStateDbRowSchema = ProjectionState;
|
||||||
|
|
||||||
const REQUIRED_SNAPSHOT_PROJECTORS = [
|
const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||||
@@ -158,6 +173,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
turn_id AS "turnId",
|
turn_id AS "turnId",
|
||||||
role,
|
role,
|
||||||
text,
|
text,
|
||||||
|
attachments_json AS "attachments",
|
||||||
is_streaming AS "isStreaming",
|
is_streaming AS "isStreaming",
|
||||||
created_at AS "createdAt",
|
created_at AS "createdAt",
|
||||||
updated_at AS "updatedAt"
|
updated_at AS "updatedAt"
|
||||||
@@ -196,6 +212,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
provider_name AS "providerName",
|
provider_name AS "providerName",
|
||||||
provider_session_id AS "providerSessionId",
|
provider_session_id AS "providerSessionId",
|
||||||
provider_thread_id AS "providerThreadId",
|
provider_thread_id AS "providerThreadId",
|
||||||
|
approval_policy AS "approvalPolicy",
|
||||||
|
sandbox_mode AS "sandboxMode",
|
||||||
active_turn_id AS "activeTurnId",
|
active_turn_id AS "activeTurnId",
|
||||||
last_error AS "lastError",
|
last_error AS "lastError",
|
||||||
updated_at AS "updatedAt"
|
updated_at AS "updatedAt"
|
||||||
@@ -224,6 +242,25 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
`,
|
`,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const listLatestTurnRows = SqlSchema.findAll({
|
||||||
|
Request: Schema.Void,
|
||||||
|
Result: ProjectionLatestTurnDbRowSchema,
|
||||||
|
execute: () =>
|
||||||
|
sql`
|
||||||
|
SELECT
|
||||||
|
thread_id AS "threadId",
|
||||||
|
turn_id AS "turnId",
|
||||||
|
state,
|
||||||
|
requested_at AS "requestedAt",
|
||||||
|
started_at AS "startedAt",
|
||||||
|
completed_at AS "completedAt",
|
||||||
|
assistant_message_id AS "assistantMessageId"
|
||||||
|
FROM projection_turns
|
||||||
|
WHERE turn_id IS NOT NULL
|
||||||
|
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
||||||
|
`,
|
||||||
|
});
|
||||||
|
|
||||||
const listProjectionStateRows = SqlSchema.findAll({
|
const listProjectionStateRows = SqlSchema.findAll({
|
||||||
Request: Schema.Void,
|
Request: Schema.Void,
|
||||||
Result: ProjectionStateDbRowSchema,
|
Result: ProjectionStateDbRowSchema,
|
||||||
@@ -248,6 +285,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
activityRows,
|
activityRows,
|
||||||
sessionRows,
|
sessionRows,
|
||||||
checkpointRows,
|
checkpointRows,
|
||||||
|
latestTurnRows,
|
||||||
stateRows,
|
stateRows,
|
||||||
] = yield* Effect.all([
|
] = yield* Effect.all([
|
||||||
listProjectRows(undefined).pipe(
|
listProjectRows(undefined).pipe(
|
||||||
@@ -298,6 +336,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
listLatestTurnRows(undefined).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
toPersistenceSqlOrDecodeError(
|
||||||
|
"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query",
|
||||||
|
"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
listProjectionStateRows(undefined).pipe(
|
listProjectionStateRows(undefined).pipe(
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
toPersistenceSqlOrDecodeError(
|
toPersistenceSqlOrDecodeError(
|
||||||
@@ -312,6 +358,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
||||||
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
||||||
const sessionsByThread = new Map<string, OrchestrationSession>();
|
const sessionsByThread = new Map<string, OrchestrationSession>();
|
||||||
|
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
|
||||||
|
|
||||||
let updatedAt: string | null = null;
|
let updatedAt: string | null = null;
|
||||||
|
|
||||||
@@ -332,6 +379,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
id: row.messageId,
|
id: row.messageId,
|
||||||
role: row.role,
|
role: row.role,
|
||||||
text: row.text,
|
text: row.text,
|
||||||
|
...(row.attachments !== null ? { attachments: row.attachments } : {}),
|
||||||
turnId: row.turnId,
|
turnId: row.turnId,
|
||||||
streaming: row.isStreaming === 1,
|
streaming: row.isStreaming === 1,
|
||||||
createdAt: row.createdAt,
|
createdAt: row.createdAt,
|
||||||
@@ -370,6 +418,34 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
checkpointsByThread.set(row.threadId, threadCheckpoints);
|
checkpointsByThread.set(row.threadId, threadCheckpoints);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const row of latestTurnRows) {
|
||||||
|
updatedAt = maxIso(updatedAt, row.requestedAt);
|
||||||
|
if (row.startedAt !== null) {
|
||||||
|
updatedAt = maxIso(updatedAt, row.startedAt);
|
||||||
|
}
|
||||||
|
if (row.completedAt !== null) {
|
||||||
|
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||||
|
}
|
||||||
|
if (latestTurnByThread.has(row.threadId)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
latestTurnByThread.set(row.threadId, {
|
||||||
|
turnId: row.turnId,
|
||||||
|
state:
|
||||||
|
row.state === "error"
|
||||||
|
? "error"
|
||||||
|
: row.state === "interrupted"
|
||||||
|
? "interrupted"
|
||||||
|
: row.state === "completed"
|
||||||
|
? "completed"
|
||||||
|
: "running",
|
||||||
|
requestedAt: row.requestedAt,
|
||||||
|
startedAt: row.startedAt,
|
||||||
|
completedAt: row.completedAt,
|
||||||
|
assistantMessageId: row.assistantMessageId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
for (const row of sessionRows) {
|
for (const row of sessionRows) {
|
||||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||||
sessionsByThread.set(row.threadId, {
|
sessionsByThread.set(row.threadId, {
|
||||||
@@ -378,6 +454,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
providerName: row.providerName,
|
providerName: row.providerName,
|
||||||
providerSessionId: row.providerSessionId,
|
providerSessionId: row.providerSessionId,
|
||||||
providerThreadId: row.providerThreadId,
|
providerThreadId: row.providerThreadId,
|
||||||
|
approvalPolicy: row.approvalPolicy,
|
||||||
|
sandboxMode: row.sandboxMode,
|
||||||
activeTurnId: row.activeTurnId,
|
activeTurnId: row.activeTurnId,
|
||||||
lastError: row.lastError,
|
lastError: row.lastError,
|
||||||
updatedAt: row.updatedAt,
|
updatedAt: row.updatedAt,
|
||||||
@@ -402,7 +480,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
model: row.model,
|
model: row.model,
|
||||||
branch: row.branch,
|
branch: row.branch,
|
||||||
worktreePath: row.worktreePath,
|
worktreePath: row.worktreePath,
|
||||||
latestTurnId: row.latestTurnId,
|
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||||
createdAt: row.createdAt,
|
createdAt: row.createdAt,
|
||||||
updatedAt: row.updatedAt,
|
updatedAt: row.updatedAt,
|
||||||
deletedAt: row.deletedAt,
|
deletedAt: row.deletedAt,
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
@@ -13,6 +17,8 @@ import {
|
|||||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { TextGenerationError } from "../../git/Errors.ts";
|
||||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||||
@@ -20,11 +26,14 @@ import {
|
|||||||
ProviderService,
|
ProviderService,
|
||||||
type ProviderServiceShape,
|
type ProviderServiceShape,
|
||||||
} from "../../provider/Services/ProviderService.ts";
|
} from "../../provider/Services/ProviderService.ts";
|
||||||
|
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
|
||||||
|
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
|
||||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||||
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
|
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
|
||||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
@@ -56,6 +65,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
unknown
|
unknown
|
||||||
> | null = null;
|
> | null = null;
|
||||||
let scope: Scope.Closeable | null = null;
|
let scope: Scope.Closeable | null = null;
|
||||||
|
const createdStateDirs = new Set<string>();
|
||||||
|
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
if (scope) {
|
if (scope) {
|
||||||
@@ -66,21 +76,29 @@ describe("ProviderCommandReactor", () => {
|
|||||||
await runtime.dispose();
|
await runtime.dispose();
|
||||||
}
|
}
|
||||||
runtime = null;
|
runtime = null;
|
||||||
|
for (const stateDir of createdStateDirs) {
|
||||||
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
createdStateDirs.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function createHarness() {
|
async function createHarness(input?: { readonly stateDir?: string }) {
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||||
|
createdStateDirs.add(stateDir);
|
||||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||||
const startSession = vi.fn((_: unknown, __: unknown) =>
|
let nextSessionIndex = 1;
|
||||||
Effect.succeed({
|
const startSession = vi.fn((_: unknown, __: unknown) => {
|
||||||
sessionId: asSessionId("sess-1"),
|
const sessionIndex = nextSessionIndex++;
|
||||||
|
return Effect.succeed({
|
||||||
|
sessionId: asSessionId(`sess-${sessionIndex}`),
|
||||||
provider: "codex" as const,
|
provider: "codex" as const,
|
||||||
status: "ready" as const,
|
status: "ready" as const,
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe(`provider-thread-${sessionIndex}`),
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
}),
|
});
|
||||||
);
|
});
|
||||||
const sendTurn = vi.fn((_: unknown) =>
|
const sendTurn = vi.fn((_: unknown) =>
|
||||||
Effect.succeed({
|
Effect.succeed({
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
@@ -90,6 +108,16 @@ describe("ProviderCommandReactor", () => {
|
|||||||
const interruptTurn = vi.fn((_: unknown) => Effect.void);
|
const interruptTurn = vi.fn((_: unknown) => Effect.void);
|
||||||
const respondToRequest = vi.fn((_: unknown) => Effect.void);
|
const respondToRequest = vi.fn((_: unknown) => Effect.void);
|
||||||
const stopSession = vi.fn((_: unknown) => Effect.void);
|
const stopSession = vi.fn((_: unknown) => Effect.void);
|
||||||
|
const renameBranch = vi.fn((_: unknown) =>
|
||||||
|
Effect.succeed({
|
||||||
|
branch: "t3code/generated-name",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>(() =>
|
||||||
|
Effect.succeed({
|
||||||
|
branch: "generated-name",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||||
const service: ProviderServiceShape = {
|
const service: ProviderServiceShape = {
|
||||||
@@ -113,8 +141,15 @@ describe("ProviderCommandReactor", () => {
|
|||||||
const layer = ProviderCommandReactorLive.pipe(
|
const layer = ProviderCommandReactorLive.pipe(
|
||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||||
|
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
||||||
|
Layer.provideMerge(
|
||||||
|
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
runtime = ManagedRuntime.make(layer);
|
const runtime = ManagedRuntime.make(layer);
|
||||||
|
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
||||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||||
@@ -153,6 +188,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
interruptTurn,
|
interruptTurn,
|
||||||
respondToRequest,
|
respondToRequest,
|
||||||
stopSession,
|
stopSession,
|
||||||
|
renameBranch,
|
||||||
|
generateBranchName,
|
||||||
|
stateDir,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,6 +209,8 @@ describe("ProviderCommandReactor", () => {
|
|||||||
text: "hello reactor",
|
text: "hello reactor",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -181,11 +221,422 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||||
cwd: "/tmp/provider-project",
|
cwd: "/tmp/provider-project",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
});
|
});
|
||||||
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||||
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
||||||
|
expect(thread?.session?.approvalPolicy).toBe("on-request");
|
||||||
|
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("generates and renames temporary worktree branch on first turn", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
branch: "t3code/89abc123",
|
||||||
|
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-worktree-rename"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-worktree-rename"),
|
||||||
|
role: "user",
|
||||||
|
text: "Fix visual bug from screenshot",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-1-att-rename",
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||||
|
await waitFor(() => harness.renameBranch.mock.calls.length === 1);
|
||||||
|
|
||||||
|
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
|
||||||
|
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||||
|
message: "Fix visual bug from screenshot",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-1-att-rename",
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(harness.renameBranch.mock.calls[0]?.[0]).toEqual({
|
||||||
|
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||||
|
oldBranch: "t3code/89abc123",
|
||||||
|
newBranch: "t3code/generated-name",
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const readModel = Effect.runSync(harness.engine.getReadModel());
|
||||||
|
const thread = readModel.threads.find(
|
||||||
|
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||||
|
);
|
||||||
|
return thread?.branch === "t3code/generated-name";
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("passes persisted attachment references to branch generation and turn start", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-persisted"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
branch: "t3code/abcdef12",
|
||||||
|
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-persisted-attachments"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-persisted-attachments"),
|
||||||
|
role: "user",
|
||||||
|
text: "Fix visual bug from screenshot",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-1-att-persisted",
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||||
|
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||||
|
|
||||||
|
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
|
||||||
|
cwd: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
|
||||||
|
message: "Fix visual bug from screenshot",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-1-att-persisted",
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-1-att-persisted",
|
||||||
|
name: "bug.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips worktree branch generation after the first user turn", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-2"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
branch: "t3code/1234abcd",
|
||||||
|
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-1234abcd",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-first"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-first"),
|
||||||
|
role: "user",
|
||||||
|
text: "first",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-second"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-second"),
|
||||||
|
role: "user",
|
||||||
|
text: "second",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||||
|
expect(harness.generateBranchName.mock.calls.length).toBe(1);
|
||||||
|
expect(harness.renameBranch.mock.calls.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips worktree rename when branch-name generation fails", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
harness.generateBranchName.mockImplementationOnce(() =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
detail: "model returned invalid payload",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-null"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
branch: "t3code/0000abcd",
|
||||||
|
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-0000abcd",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-null-branch"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-null-branch"),
|
||||||
|
role: "user",
|
||||||
|
text: "Fix visual regression",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||||
|
await Effect.runPromise(Effect.sleep("20 millis"));
|
||||||
|
expect(harness.renameBranch.mock.calls.length).toBe(0);
|
||||||
|
|
||||||
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||||
|
expect(thread?.branch).toBe("t3code/0000abcd");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-1"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-unchanged-1"),
|
||||||
|
role: "user",
|
||||||
|
text: "first",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||||
|
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-2"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-unchanged-2"),
|
||||||
|
role: "user",
|
||||||
|
text: "second",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||||
|
expect(harness.startSession.mock.calls.length).toBe(1);
|
||||||
|
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("restarts the provider session when runtime mode changes", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-runtime-mode-1"),
|
||||||
|
role: "user",
|
||||||
|
text: "first",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "never",
|
||||||
|
sandboxMode: "danger-full-access",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||||
|
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-2"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-runtime-mode-2"),
|
||||||
|
role: "user",
|
||||||
|
text: "second",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||||
|
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||||
|
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||||
|
|
||||||
|
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ sessionId: asSessionId("sess-1") });
|
||||||
|
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||||
|
resumeThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
});
|
||||||
|
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||||
|
sessionId: asSessionId("sess-2"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||||
|
expect(thread?.session?.providerSessionId).toBe("sess-2");
|
||||||
|
expect(thread?.session?.approvalPolicy).toBe("on-request");
|
||||||
|
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not stop the active session when restart fails before rebind", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-1"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-restart-failure-1"),
|
||||||
|
role: "user",
|
||||||
|
text: "first",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "never",
|
||||||
|
sandboxMode: "danger-full-access",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||||
|
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||||
|
|
||||||
|
harness.startSession.mockImplementationOnce(
|
||||||
|
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
|
||||||
|
);
|
||||||
|
|
||||||
|
await Effect.runPromise(
|
||||||
|
harness.engine.dispatch({
|
||||||
|
type: "thread.turn.start",
|
||||||
|
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-2"),
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
message: {
|
||||||
|
messageId: asMessageId("user-message-restart-failure-2"),
|
||||||
|
role: "user",
|
||||||
|
text: "second",
|
||||||
|
attachments: [],
|
||||||
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
createdAt: now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||||
|
await Effect.runPromise(Effect.sleep("30 millis"));
|
||||||
|
|
||||||
|
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||||
|
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||||
|
|
||||||
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||||
|
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
||||||
|
expect(thread?.session?.approvalPolicy).toBe("never");
|
||||||
|
expect(thread?.session?.sandboxMode).toBe("danger-full-access");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
||||||
@@ -203,6 +654,8 @@ describe("ProviderCommandReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: asTurnId("turn-1"),
|
activeTurnId: asTurnId("turn-1"),
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -242,6 +695,8 @@ describe("ProviderCommandReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -284,6 +739,8 @@ describe("ProviderCommandReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
|
|||||||
@@ -3,14 +3,20 @@ import {
|
|||||||
CommandId,
|
CommandId,
|
||||||
EventId,
|
EventId,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
|
type ProviderApprovalPolicy,
|
||||||
type ProviderKind,
|
type ProviderKind,
|
||||||
|
type ProviderSandboxMode,
|
||||||
type OrchestrationSession,
|
type OrchestrationSession,
|
||||||
type ThreadId,
|
type ThreadId,
|
||||||
|
type ProviderSession,
|
||||||
|
type ProviderThreadId,
|
||||||
type TurnId,
|
type TurnId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||||
|
|
||||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||||
|
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||||
|
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
|
||||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||||
import {
|
import {
|
||||||
@@ -60,10 +66,43 @@ const serverCommandId = (tag: string): CommandId =>
|
|||||||
|
|
||||||
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||||
|
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
|
||||||
|
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
||||||
|
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||||
|
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||||
|
|
||||||
|
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||||
|
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||||
|
const normalized = raw
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/^refs\/heads\//, "")
|
||||||
|
.replace(/['"`]/g, "");
|
||||||
|
|
||||||
|
const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`)
|
||||||
|
? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length)
|
||||||
|
: normalized;
|
||||||
|
|
||||||
|
const branchFragment = withoutPrefix
|
||||||
|
.replace(/[^a-z0-9/_-]+/g, "-")
|
||||||
|
.replace(/\/+/g, "/")
|
||||||
|
.replace(/-+/g, "-")
|
||||||
|
.replace(/^[./_-]+|[./_-]+$/g, "")
|
||||||
|
.slice(0, 64)
|
||||||
|
.replace(/[./_-]+$/g, "");
|
||||||
|
|
||||||
|
const safeFragment = branchFragment.length > 0 ? branchFragment : "update";
|
||||||
|
return `${WORKTREE_BRANCH_PREFIX}/${safeFragment}`;
|
||||||
|
}
|
||||||
|
|
||||||
const make = Effect.gen(function* () {
|
const make = Effect.gen(function* () {
|
||||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||||
const providerService = yield* ProviderService;
|
const providerService = yield* ProviderService;
|
||||||
|
const git = yield* GitCore;
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||||
capacity: HANDLED_TURN_START_KEY_MAX,
|
capacity: HANDLED_TURN_START_KEY_MAX,
|
||||||
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
||||||
@@ -128,6 +167,10 @@ const make = Effect.gen(function* () {
|
|||||||
const ensureSessionForThread = Effect.fnUntraced(function* (
|
const ensureSessionForThread = Effect.fnUntraced(function* (
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
createdAt: string,
|
createdAt: string,
|
||||||
|
options?: {
|
||||||
|
readonly approvalPolicy?: ProviderApprovalPolicy;
|
||||||
|
readonly sandboxMode?: ProviderSandboxMode;
|
||||||
|
},
|
||||||
) {
|
) {
|
||||||
const readModel = yield* orchestrationEngine.getReadModel();
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||||
@@ -135,11 +178,10 @@ const make = Effect.gen(function* () {
|
|||||||
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
||||||
}
|
}
|
||||||
|
|
||||||
const existingSessionId = thread.session?.providerSessionId;
|
const desiredApprovalPolicy =
|
||||||
if (existingSessionId) {
|
options?.approvalPolicy ?? thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY;
|
||||||
return existingSessionId;
|
const desiredSandboxMode =
|
||||||
}
|
options?.sandboxMode ?? thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE;
|
||||||
|
|
||||||
const preferredProvider: ProviderKind | undefined =
|
const preferredProvider: ProviderKind | undefined =
|
||||||
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
|
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
|
||||||
? thread.session.providerName
|
? thread.session.providerName
|
||||||
@@ -149,28 +191,65 @@ const make = Effect.gen(function* () {
|
|||||||
projects: readModel.projects,
|
projects: readModel.projects,
|
||||||
});
|
});
|
||||||
|
|
||||||
const startedSession = yield* providerService.startSession(threadId, {
|
const startProviderSession = (resumeThreadId?: ProviderThreadId | null) =>
|
||||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
providerService.startSession(threadId, {
|
||||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||||
...(thread.model ? { model: thread.model } : {}),
|
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||||
});
|
...(thread.model ? { model: thread.model } : {}),
|
||||||
|
...(resumeThreadId ? { resumeThreadId } : {}),
|
||||||
|
approvalPolicy: desiredApprovalPolicy,
|
||||||
|
sandboxMode: desiredSandboxMode,
|
||||||
|
});
|
||||||
|
|
||||||
yield* setThreadSession({
|
const bindSessionToThread = (session: ProviderSession) =>
|
||||||
threadId,
|
setThreadSession({
|
||||||
session: {
|
|
||||||
threadId,
|
threadId,
|
||||||
status: mapProviderSessionStatusToOrchestrationStatus(startedSession.status),
|
session: {
|
||||||
providerName: startedSession.provider,
|
threadId,
|
||||||
providerSessionId: startedSession.sessionId,
|
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
||||||
providerThreadId: startedSession.threadId ?? null,
|
providerName: session.provider,
|
||||||
// Provider turn ids are not orchestration turn ids.
|
providerSessionId: session.sessionId,
|
||||||
activeTurnId: null,
|
providerThreadId: session.threadId ?? null,
|
||||||
lastError: startedSession.lastError ?? null,
|
approvalPolicy: desiredApprovalPolicy,
|
||||||
updatedAt: startedSession.updatedAt,
|
sandboxMode: desiredSandboxMode,
|
||||||
},
|
// Provider turn ids are not orchestration turn ids.
|
||||||
createdAt,
|
activeTurnId: null,
|
||||||
});
|
lastError: session.lastError ?? null,
|
||||||
|
updatedAt: session.updatedAt,
|
||||||
|
},
|
||||||
|
createdAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
const existingSessionId = thread.session?.providerSessionId;
|
||||||
|
if (existingSessionId) {
|
||||||
|
const approvalPolicyChanged =
|
||||||
|
options?.approvalPolicy !== undefined &&
|
||||||
|
options.approvalPolicy !== thread.session?.approvalPolicy;
|
||||||
|
const sandboxModeChanged =
|
||||||
|
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
|
||||||
|
|
||||||
|
if (!approvalPolicyChanged && !sandboxModeChanged) {
|
||||||
|
return existingSessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
const restartedSession = yield* startProviderSession(
|
||||||
|
thread.session?.providerThreadId ?? null,
|
||||||
|
);
|
||||||
|
yield* bindSessionToThread(restartedSession);
|
||||||
|
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
|
||||||
|
Effect.catchCause((cause) =>
|
||||||
|
Effect.logWarning("provider command reactor failed to stop superseded provider session", {
|
||||||
|
threadId,
|
||||||
|
sessionId: existingSessionId,
|
||||||
|
cause: Cause.pretty(cause),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return restartedSession.sessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
const startedSession = yield* startProviderSession();
|
||||||
|
yield* bindSessionToThread(startedSession);
|
||||||
return startedSession.sessionId;
|
return startedSession.sessionId;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -180,13 +259,18 @@ const make = Effect.gen(function* () {
|
|||||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||||
readonly model?: string;
|
readonly model?: string;
|
||||||
readonly effort?: string;
|
readonly effort?: string;
|
||||||
|
readonly approvalPolicy: ProviderApprovalPolicy;
|
||||||
|
readonly sandboxMode: ProviderSandboxMode;
|
||||||
readonly createdAt: string;
|
readonly createdAt: string;
|
||||||
}) {
|
}) {
|
||||||
const thread = yield* resolveThread(input.threadId);
|
const thread = yield* resolveThread(input.threadId);
|
||||||
if (!thread) {
|
if (!thread) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt);
|
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||||
|
approvalPolicy: input.approvalPolicy,
|
||||||
|
sandboxMode: input.sandboxMode,
|
||||||
|
});
|
||||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||||
const normalizedAttachments = input.attachments ?? [];
|
const normalizedAttachments = input.attachments ?? [];
|
||||||
|
|
||||||
@@ -199,6 +283,74 @@ const make = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fnUntraced(function* (input: {
|
||||||
|
readonly threadId: ThreadId;
|
||||||
|
readonly branch: string | null;
|
||||||
|
readonly worktreePath: string | null;
|
||||||
|
readonly messageId: string;
|
||||||
|
readonly messageText: string;
|
||||||
|
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||||
|
}) {
|
||||||
|
if (!input.branch || !input.worktreePath) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isTemporaryWorktreeBranch(input.branch)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const thread = yield* resolveThread(input.threadId);
|
||||||
|
if (!thread) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userMessages = thread.messages.filter((message) => message.role === "user");
|
||||||
|
if (userMessages.length !== 1 || userMessages[0]?.id !== input.messageId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldBranch = input.branch;
|
||||||
|
const cwd = input.worktreePath;
|
||||||
|
const attachments = input.attachments ?? [];
|
||||||
|
yield* textGeneration
|
||||||
|
.generateBranchName({
|
||||||
|
cwd,
|
||||||
|
message: input.messageText,
|
||||||
|
...(attachments.length > 0 ? { attachments } : {}),
|
||||||
|
})
|
||||||
|
.pipe(
|
||||||
|
Effect.catch((error) =>
|
||||||
|
Effect.logWarning(
|
||||||
|
"provider command reactor failed to generate worktree branch name; skipping rename",
|
||||||
|
{ threadId: input.threadId, cwd, oldBranch, reason: error.message },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Effect.flatMap((generated) => {
|
||||||
|
if (!generated) return Effect.void;
|
||||||
|
|
||||||
|
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||||
|
if (targetBranch === oldBranch) return Effect.void;
|
||||||
|
|
||||||
|
return Effect.flatMap(
|
||||||
|
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
|
||||||
|
(renamed) =>
|
||||||
|
orchestrationEngine.dispatch({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: serverCommandId("worktree-branch-rename"),
|
||||||
|
threadId: input.threadId,
|
||||||
|
branch: renamed.branch,
|
||||||
|
worktreePath: cwd,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
Effect.catchCause((cause) =>
|
||||||
|
Effect.logWarning(
|
||||||
|
"provider command reactor failed to generate or rename worktree branch",
|
||||||
|
{ threadId: input.threadId, cwd, oldBranch, cause: Cause.pretty(cause) },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
const processTurnStartRequested = Effect.fnUntraced(function* (
|
const processTurnStartRequested = Effect.fnUntraced(function* (
|
||||||
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
|
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
|
||||||
) {
|
) {
|
||||||
@@ -225,12 +377,23 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
|
||||||
|
threadId: event.payload.threadId,
|
||||||
|
branch: thread.branch,
|
||||||
|
worktreePath: thread.worktreePath,
|
||||||
|
messageId: message.id,
|
||||||
|
messageText: message.text,
|
||||||
|
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||||
|
}).pipe(Effect.forkScoped);
|
||||||
|
|
||||||
yield* sendTurnForThread({
|
yield* sendTurnForThread({
|
||||||
threadId: event.payload.threadId,
|
threadId: event.payload.threadId,
|
||||||
messageText: message.text,
|
messageText: message.text,
|
||||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||||
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
|
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
|
||||||
|
approvalPolicy: event.payload.approvalPolicy,
|
||||||
|
sandboxMode: event.payload.sandboxMode,
|
||||||
createdAt: event.payload.createdAt,
|
createdAt: event.payload.createdAt,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -307,6 +470,8 @@ const make = Effect.gen(function* () {
|
|||||||
providerName: thread.session?.providerName ?? null,
|
providerName: thread.session?.providerName ?? null,
|
||||||
providerSessionId: null,
|
providerSessionId: null,
|
||||||
providerThreadId: null,
|
providerThreadId: null,
|
||||||
|
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
||||||
|
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: thread.session?.lastError ?? null,
|
lastError: thread.session?.lastError ?? null,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
|
|||||||
@@ -28,9 +28,12 @@ import {
|
|||||||
type OrchestrationEngineShape,
|
type OrchestrationEngineShape,
|
||||||
} from "../Services/OrchestrationEngine.ts";
|
} from "../Services/OrchestrationEngine.ts";
|
||||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
|
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||||
@@ -120,6 +123,8 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
const layer = ProviderRuntimeIngestionLive.pipe(
|
const layer = ProviderRuntimeIngestionLive.pipe(
|
||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
runtime = ManagedRuntime.make(layer);
|
runtime = ManagedRuntime.make(layer);
|
||||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||||
@@ -164,6 +169,8 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
@@ -218,6 +225,116 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
expect(thread.session?.lastError).toBe("turn failed");
|
expect(thread.session?.lastError).toBe("turn failed");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("ignores auxiliary turn completions from a different provider thread", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
harness.emit({
|
||||||
|
type: "turn.started",
|
||||||
|
eventId: asEventId("evt-turn-started-primary"),
|
||||||
|
provider: "codex",
|
||||||
|
sessionId: asSessionId("sess-1"),
|
||||||
|
createdAt: now,
|
||||||
|
threadId: asProviderThreadId("provider-thread-1"),
|
||||||
|
turnId: asProviderTurnId("turn-primary"),
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitForThread(
|
||||||
|
harness.engine,
|
||||||
|
(thread) =>
|
||||||
|
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary",
|
||||||
|
);
|
||||||
|
|
||||||
|
harness.emit({
|
||||||
|
type: "turn.completed",
|
||||||
|
eventId: asEventId("evt-turn-completed-aux"),
|
||||||
|
provider: "codex",
|
||||||
|
sessionId: asSessionId("sess-1"),
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
threadId: asProviderThreadId("provider-thread-aux"),
|
||||||
|
turnId: asProviderTurnId("turn-aux"),
|
||||||
|
status: "completed",
|
||||||
|
});
|
||||||
|
|
||||||
|
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||||
|
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
|
const midThread = midReadModel.threads.find(
|
||||||
|
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||||
|
);
|
||||||
|
expect(midThread?.session?.status).toBe("running");
|
||||||
|
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
||||||
|
|
||||||
|
harness.emit({
|
||||||
|
type: "turn.completed",
|
||||||
|
eventId: asEventId("evt-turn-completed-primary"),
|
||||||
|
provider: "codex",
|
||||||
|
sessionId: asSessionId("sess-1"),
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
threadId: asProviderThreadId("provider-thread-1"),
|
||||||
|
turnId: asProviderTurnId("turn-primary"),
|
||||||
|
status: "completed",
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitForThread(
|
||||||
|
harness.engine,
|
||||||
|
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores non-active turn completion when runtime omits thread id", async () => {
|
||||||
|
const harness = await createHarness();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
harness.emit({
|
||||||
|
type: "turn.started",
|
||||||
|
eventId: asEventId("evt-turn-started-guarded"),
|
||||||
|
provider: "codex",
|
||||||
|
sessionId: asSessionId("sess-1"),
|
||||||
|
createdAt: now,
|
||||||
|
turnId: asProviderTurnId("turn-guarded-main"),
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitForThread(
|
||||||
|
harness.engine,
|
||||||
|
(thread) =>
|
||||||
|
thread.session?.status === "running" &&
|
||||||
|
thread.session?.activeTurnId === "turn-guarded-main",
|
||||||
|
);
|
||||||
|
|
||||||
|
harness.emit({
|
||||||
|
type: "turn.completed",
|
||||||
|
eventId: asEventId("evt-turn-completed-guarded-other"),
|
||||||
|
provider: "codex",
|
||||||
|
sessionId: asSessionId("sess-1"),
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
turnId: asProviderTurnId("turn-guarded-other"),
|
||||||
|
status: "completed",
|
||||||
|
});
|
||||||
|
|
||||||
|
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||||
|
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
|
const midThread = midReadModel.threads.find(
|
||||||
|
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||||
|
);
|
||||||
|
expect(midThread?.session?.status).toBe("running");
|
||||||
|
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
||||||
|
|
||||||
|
harness.emit({
|
||||||
|
type: "turn.completed",
|
||||||
|
eventId: asEventId("evt-turn-completed-guarded-main"),
|
||||||
|
provider: "codex",
|
||||||
|
sessionId: asSessionId("sess-1"),
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
turnId: asProviderTurnId("turn-guarded-main"),
|
||||||
|
status: "completed",
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitForThread(
|
||||||
|
harness.engine,
|
||||||
|
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it("maps message delta/completed into finalized assistant messages", async () => {
|
it("maps message delta/completed into finalized assistant messages", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -291,7 +408,9 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
|
|
||||||
await Effect.runPromise(Effect.sleep("30 millis"));
|
await Effect.runPromise(Effect.sleep("30 millis"));
|
||||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
const midThread = midReadModel.threads.find(
|
||||||
|
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||||
|
);
|
||||||
expect(midThread?.messages.some((message) => message.id === "assistant:item-buffered")).toBe(
|
expect(midThread?.messages.some((message) => message.id === "assistant:item-buffered")).toBe(
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
@@ -306,10 +425,10 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
itemId: asItemId("item-buffered"),
|
itemId: asItemId("item-buffered"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(harness.engine, (entry) =>
|
||||||
harness.engine,
|
entry.messages.some(
|
||||||
(entry) =>
|
(message) => message.id === "assistant:item-buffered" && !message.streaming,
|
||||||
entry.messages.some((message) => message.id === "assistant:item-buffered" && !message.streaming),
|
),
|
||||||
);
|
);
|
||||||
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffered");
|
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffered");
|
||||||
expect(message?.text).toBe("buffer me");
|
expect(message?.text).toBe("buffer me");
|
||||||
@@ -332,6 +451,8 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
assistantDeliveryMode: "streaming",
|
assistantDeliveryMode: "streaming",
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -363,15 +484,13 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
delta: "hello live",
|
delta: "hello live",
|
||||||
});
|
});
|
||||||
|
|
||||||
const liveThread = await waitForThread(
|
const liveThread = await waitForThread(harness.engine, (entry) =>
|
||||||
harness.engine,
|
entry.messages.some(
|
||||||
(entry) =>
|
(message) =>
|
||||||
entry.messages.some(
|
message.id === "assistant:item-streaming-mode" &&
|
||||||
(message) =>
|
message.streaming &&
|
||||||
message.id === "assistant:item-streaming-mode" &&
|
message.text === "hello live",
|
||||||
message.streaming &&
|
),
|
||||||
message.text === "hello live",
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
const liveMessage = liveThread.messages.find(
|
const liveMessage = liveThread.messages.find(
|
||||||
(entry) => entry.id === "assistant:item-streaming-mode",
|
(entry) => entry.id === "assistant:item-streaming-mode",
|
||||||
@@ -388,12 +507,10 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
itemId: asItemId("item-streaming-mode"),
|
itemId: asItemId("item-streaming-mode"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const finalThread = await waitForThread(
|
const finalThread = await waitForThread(harness.engine, (entry) =>
|
||||||
harness.engine,
|
entry.messages.some(
|
||||||
(entry) =>
|
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
|
||||||
entry.messages.some(
|
),
|
||||||
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
const finalMessage = finalThread.messages.find(
|
const finalMessage = finalThread.messages.find(
|
||||||
(entry) => entry.id === "assistant:item-streaming-mode",
|
(entry) => entry.id === "assistant:item-streaming-mode",
|
||||||
@@ -442,12 +559,10 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
itemId: asItemId("item-buffer-spill"),
|
itemId: asItemId("item-buffer-spill"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(harness.engine, (entry) =>
|
||||||
harness.engine,
|
entry.messages.some(
|
||||||
(entry) =>
|
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
|
||||||
entry.messages.some(
|
),
|
||||||
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffer-spill");
|
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffer-spill");
|
||||||
expect(message?.text.length).toBe(oversizedText.length);
|
expect(message?.text.length).toBe(oversizedText.length);
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import {
|
|||||||
CommandId,
|
CommandId,
|
||||||
MessageId,
|
MessageId,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
|
type ProviderApprovalPolicy,
|
||||||
|
type ProviderSandboxMode,
|
||||||
ProviderThreadId,
|
ProviderThreadId,
|
||||||
type ThreadId,
|
type ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
@@ -24,11 +26,14 @@ const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId
|
|||||||
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
||||||
|
|
||||||
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
|
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
|
||||||
|
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "on-request";
|
||||||
|
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
||||||
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
||||||
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
|
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
|
||||||
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
|
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
|
||||||
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);
|
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);
|
||||||
const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
|
const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
|
||||||
|
const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0";
|
||||||
|
|
||||||
type TurnStartRequestedDomainEvent = Extract<
|
type TurnStartRequestedDomainEvent = Extract<
|
||||||
OrchestrationEvent,
|
OrchestrationEvent,
|
||||||
@@ -49,6 +54,17 @@ function toTurnId(value: string | undefined): TurnId | undefined {
|
|||||||
return value === undefined ? undefined : TurnId.makeUnsafe(value);
|
return value === undefined ? undefined : TurnId.makeUnsafe(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
|
||||||
|
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||||
|
if (left === null || left === undefined || right === null || right === undefined) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return left === right;
|
||||||
|
}
|
||||||
|
|
||||||
function truncateDetail(value: string, limit = 180): string {
|
function truncateDetail(value: string, limit = 180): string {
|
||||||
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
||||||
}
|
}
|
||||||
@@ -328,6 +344,62 @@ const make = Effect.gen(function* () {
|
|||||||
if (!thread) return;
|
if (!thread) return;
|
||||||
|
|
||||||
const now = event.createdAt;
|
const now = event.createdAt;
|
||||||
|
const sessionProviderThreadId = thread.session?.providerThreadId ?? null;
|
||||||
|
const eventProviderThreadId = toProviderThreadId(event.threadId);
|
||||||
|
const eventTurnId = toTurnId("turnId" in event ? event.turnId : undefined);
|
||||||
|
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||||
|
|
||||||
|
const matchesThreadScope =
|
||||||
|
eventProviderThreadId === null ||
|
||||||
|
sessionProviderThreadId === null ||
|
||||||
|
sameId(eventProviderThreadId, sessionProviderThreadId);
|
||||||
|
const conflictsWithActiveTurn =
|
||||||
|
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
|
||||||
|
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
|
||||||
|
|
||||||
|
const shouldApplyThreadLifecycle = (() => {
|
||||||
|
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
switch (event.type) {
|
||||||
|
case "session.exited":
|
||||||
|
return true;
|
||||||
|
case "session.started":
|
||||||
|
case "thread.started":
|
||||||
|
if (!matchesThreadScope) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Never let auxiliary/provider-side spawned threads replace the primary thread binding.
|
||||||
|
if (
|
||||||
|
eventProviderThreadId !== null &&
|
||||||
|
sessionProviderThreadId !== null &&
|
||||||
|
!sameId(eventProviderThreadId, sessionProviderThreadId)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
case "turn.started":
|
||||||
|
if (!matchesThreadScope) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return !conflictsWithActiveTurn;
|
||||||
|
case "turn.completed":
|
||||||
|
if (!matchesThreadScope) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Only the active turn may close the lifecycle state.
|
||||||
|
if (activeTurnId !== null && eventTurnId !== undefined) {
|
||||||
|
return sameId(activeTurnId, eventTurnId);
|
||||||
|
}
|
||||||
|
// Without an active turn, only accept completion when no thread mismatch signal exists.
|
||||||
|
return eventProviderThreadId === null || sessionProviderThreadId === null;
|
||||||
|
default:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
if (
|
if (
|
||||||
event.type === "session.started" ||
|
event.type === "session.started" ||
|
||||||
@@ -336,8 +408,7 @@ const make = Effect.gen(function* () {
|
|||||||
event.type === "turn.started" ||
|
event.type === "turn.started" ||
|
||||||
event.type === "turn.completed"
|
event.type === "turn.completed"
|
||||||
) {
|
) {
|
||||||
const activeTurnId =
|
const nextActiveTurnId = event.type === "turn.started" ? (eventTurnId ?? null) : null;
|
||||||
event.type === "turn.started" ? (toTurnId(event.turnId) ?? null) : null;
|
|
||||||
const providerThreadIdFromEvent =
|
const providerThreadIdFromEvent =
|
||||||
event.type === "thread.started"
|
event.type === "thread.started"
|
||||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||||
@@ -345,7 +416,7 @@ const make = Effect.gen(function* () {
|
|||||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||||
: null;
|
: null;
|
||||||
const providerThreadId =
|
const providerThreadId =
|
||||||
providerThreadIdFromEvent ?? thread.session?.providerThreadId ?? null;
|
providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
||||||
const status =
|
const status =
|
||||||
event.type === "turn.started"
|
event.type === "turn.started"
|
||||||
? "running"
|
? "running"
|
||||||
@@ -361,22 +432,26 @@ const make = Effect.gen(function* () {
|
|||||||
? null
|
? null
|
||||||
: (thread.session?.lastError ?? null);
|
: (thread.session?.lastError ?? null);
|
||||||
|
|
||||||
yield* orchestrationEngine.dispatch({
|
if (shouldApplyThreadLifecycle) {
|
||||||
type: "thread.session.set",
|
yield* orchestrationEngine.dispatch({
|
||||||
commandId: providerCommandId(event, "thread-session-set"),
|
type: "thread.session.set",
|
||||||
threadId: thread.id,
|
commandId: providerCommandId(event, "thread-session-set"),
|
||||||
session: {
|
|
||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
status,
|
session: {
|
||||||
providerName: event.provider,
|
threadId: thread.id,
|
||||||
providerSessionId: event.sessionId,
|
status,
|
||||||
providerThreadId,
|
providerName: event.provider,
|
||||||
activeTurnId,
|
providerSessionId: event.sessionId,
|
||||||
lastError,
|
providerThreadId,
|
||||||
updatedAt: now,
|
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
||||||
},
|
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
||||||
createdAt: now,
|
activeTurnId: nextActiveTurnId,
|
||||||
});
|
lastError,
|
||||||
|
updatedAt: now,
|
||||||
|
},
|
||||||
|
createdAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "message.delta" && event.delta.length > 0) {
|
if (event.type === "message.delta" && event.delta.length > 0) {
|
||||||
@@ -464,27 +539,38 @@ const make = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "runtime.error") {
|
if (event.type === "runtime.error") {
|
||||||
|
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
|
||||||
|
? true
|
||||||
|
: matchesThreadScope &&
|
||||||
|
(activeTurnId === null ||
|
||||||
|
eventTurnId === undefined ||
|
||||||
|
sameId(activeTurnId, eventTurnId));
|
||||||
|
|
||||||
const providerThreadId =
|
const providerThreadId =
|
||||||
event.threadId !== undefined
|
event.threadId !== undefined
|
||||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||||
: (thread.session?.providerThreadId ?? null);
|
: (thread.session?.providerThreadId ?? null);
|
||||||
|
|
||||||
yield* orchestrationEngine.dispatch({
|
if (shouldApplyRuntimeError) {
|
||||||
type: "thread.session.set",
|
yield* orchestrationEngine.dispatch({
|
||||||
commandId: providerCommandId(event, "runtime-error-session-set"),
|
type: "thread.session.set",
|
||||||
threadId: thread.id,
|
commandId: providerCommandId(event, "runtime-error-session-set"),
|
||||||
session: {
|
|
||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
status: "error",
|
session: {
|
||||||
providerName: event.provider,
|
threadId: thread.id,
|
||||||
providerSessionId: event.sessionId,
|
status: "error",
|
||||||
providerThreadId,
|
providerName: event.provider,
|
||||||
activeTurnId: toTurnId(event.turnId) ?? null,
|
providerSessionId: event.sessionId,
|
||||||
lastError: event.message,
|
providerThreadId,
|
||||||
updatedAt: now,
|
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
||||||
},
|
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
||||||
createdAt: now,
|
activeTurnId: eventTurnId ?? null,
|
||||||
});
|
lastError: event.message,
|
||||||
|
updatedAt: now,
|
||||||
|
},
|
||||||
|
createdAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const activities = runtimeEventToActivities(event);
|
const activities = runtimeEventToActivities(event);
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ const readModel: OrchestrationReadModel = {
|
|||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
latestTurnId: null,
|
latestTurn: null,
|
||||||
messages: [],
|
messages: [],
|
||||||
session: null,
|
session: null,
|
||||||
activities: [],
|
activities: [],
|
||||||
@@ -70,7 +70,7 @@ const readModel: OrchestrationReadModel = {
|
|||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
latestTurnId: null,
|
latestTurn: null,
|
||||||
messages: [],
|
messages: [],
|
||||||
session: null,
|
session: null,
|
||||||
activities: [],
|
activities: [],
|
||||||
@@ -90,6 +90,8 @@ const messageSendCommand: OrchestrationCommand = {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -152,6 +152,8 @@ describe("decider project scripts", () => {
|
|||||||
},
|
},
|
||||||
model: "gpt-5",
|
model: "gpt-5",
|
||||||
effort: "high",
|
effort: "high",
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
},
|
},
|
||||||
readModel,
|
readModel,
|
||||||
@@ -169,5 +171,13 @@ describe("decider project scripts", () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
|
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
|
||||||
|
expect(turnStartEvent.payload).toMatchObject({
|
||||||
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
|
messageId: asMessageId("message-user-1"),
|
||||||
|
model: "gpt-5",
|
||||||
|
effort: "high",
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -254,6 +254,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
|||||||
...(command.model !== undefined ? { model: command.model } : {}),
|
...(command.model !== undefined ? { model: command.model } : {}),
|
||||||
...(command.effort !== undefined ? { effort: command.effort } : {}),
|
...(command.effort !== undefined ? { effort: command.effort } : {}),
|
||||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||||
|
approvalPolicy: command.approvalPolicy,
|
||||||
|
sandboxMode: command.sandboxMode,
|
||||||
createdAt: command.createdAt,
|
createdAt: command.createdAt,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -75,7 +75,7 @@ describe("orchestration projector", () => {
|
|||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
latestTurnId: null,
|
latestTurn: null,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
@@ -135,6 +135,8 @@ describe("orchestration projector", () => {
|
|||||||
payload: {
|
payload: {
|
||||||
threadId: "thread-1",
|
threadId: "thread-1",
|
||||||
messageId: "message-1",
|
messageId: "message-1",
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
createdAt: "2026-01-01T00:00:00.000Z",
|
createdAt: "2026-01-01T00:00:00.000Z",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@@ -193,6 +195,8 @@ describe("orchestration projector", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: "session-1",
|
providerSessionId: "session-1",
|
||||||
providerThreadId: "provider-thread-1",
|
providerThreadId: "provider-thread-1",
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
activeTurnId: "turn-1",
|
activeTurnId: "turn-1",
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: startedAt,
|
updatedAt: startedAt,
|
||||||
@@ -203,7 +207,7 @@ describe("orchestration projector", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const thread = afterRunning.threads[0];
|
const thread = afterRunning.threads[0];
|
||||||
expect(thread?.latestTurnId).toBe("turn-1");
|
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
||||||
expect(thread?.session?.status).toBe("running");
|
expect(thread?.session?.status).toBe("running");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -500,7 +504,7 @@ describe("orchestration projector", () => {
|
|||||||
thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
|
thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
|
||||||
).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
|
).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
|
||||||
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
|
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
|
||||||
expect(thread?.latestTurnId).toBe("turn-1");
|
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not fallback-retain messages tied to removed turn IDs", async () => {
|
it("does not fallback-retain messages tied to removed turn IDs", async () => {
|
||||||
|
|||||||
@@ -26,6 +26,12 @@ type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
|
|||||||
const MAX_THREAD_MESSAGES = 2_000;
|
const MAX_THREAD_MESSAGES = 2_000;
|
||||||
const MAX_THREAD_CHECKPOINTS = 500;
|
const MAX_THREAD_CHECKPOINTS = 500;
|
||||||
|
|
||||||
|
function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
|
||||||
|
if (status === "error") return "error" as const;
|
||||||
|
if (status === "missing") return "interrupted" as const;
|
||||||
|
return "completed" as const;
|
||||||
|
}
|
||||||
|
|
||||||
function updateThread(
|
function updateThread(
|
||||||
threads: ReadonlyArray<OrchestrationThread>,
|
threads: ReadonlyArray<OrchestrationThread>,
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
@@ -220,7 +226,7 @@ export function projectEvent(
|
|||||||
model: payload.model,
|
model: payload.model,
|
||||||
branch: payload.branch,
|
branch: payload.branch,
|
||||||
worktreePath: payload.worktreePath,
|
worktreePath: payload.worktreePath,
|
||||||
latestTurnId: null,
|
latestTurn: null,
|
||||||
createdAt: payload.createdAt,
|
createdAt: payload.createdAt,
|
||||||
updatedAt: payload.updatedAt,
|
updatedAt: payload.updatedAt,
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
@@ -351,7 +357,26 @@ export function projectEvent(
|
|||||||
...nextBase,
|
...nextBase,
|
||||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||||
session,
|
session,
|
||||||
latestTurnId: session.activeTurnId,
|
latestTurn:
|
||||||
|
session.status === "running" && session.activeTurnId !== null
|
||||||
|
? {
|
||||||
|
turnId: session.activeTurnId,
|
||||||
|
state: "running",
|
||||||
|
requestedAt:
|
||||||
|
thread.latestTurn?.turnId === session.activeTurnId
|
||||||
|
? thread.latestTurn.requestedAt
|
||||||
|
: session.updatedAt,
|
||||||
|
startedAt:
|
||||||
|
thread.latestTurn?.turnId === session.activeTurnId
|
||||||
|
? (thread.latestTurn.startedAt ?? session.updatedAt)
|
||||||
|
: session.updatedAt,
|
||||||
|
completedAt: null,
|
||||||
|
assistantMessageId:
|
||||||
|
thread.latestTurn?.turnId === session.activeTurnId
|
||||||
|
? thread.latestTurn.assistantMessageId
|
||||||
|
: null,
|
||||||
|
}
|
||||||
|
: thread.latestTurn,
|
||||||
updatedAt: event.occurredAt,
|
updatedAt: event.occurredAt,
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
@@ -396,7 +421,20 @@ export function projectEvent(
|
|||||||
...nextBase,
|
...nextBase,
|
||||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||||
checkpoints,
|
checkpoints,
|
||||||
latestTurnId: payload.turnId,
|
latestTurn: {
|
||||||
|
turnId: payload.turnId,
|
||||||
|
state: checkpointStatusToLatestTurnState(payload.status),
|
||||||
|
requestedAt:
|
||||||
|
thread.latestTurn?.turnId === payload.turnId
|
||||||
|
? thread.latestTurn.requestedAt
|
||||||
|
: payload.completedAt,
|
||||||
|
startedAt:
|
||||||
|
thread.latestTurn?.turnId === payload.turnId
|
||||||
|
? (thread.latestTurn.startedAt ?? payload.completedAt)
|
||||||
|
: payload.completedAt,
|
||||||
|
completedAt: payload.completedAt,
|
||||||
|
assistantMessageId: payload.assistantMessageId,
|
||||||
|
},
|
||||||
updatedAt: event.occurredAt,
|
updatedAt: event.occurredAt,
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
@@ -422,8 +460,18 @@ export function projectEvent(
|
|||||||
).slice(-MAX_THREAD_MESSAGES);
|
).slice(-MAX_THREAD_MESSAGES);
|
||||||
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
|
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
|
||||||
|
|
||||||
const latestTurnId =
|
const latestCheckpoint = checkpoints.at(-1) ?? null;
|
||||||
checkpoints.length > 0 ? (checkpoints[checkpoints.length - 1]?.turnId ?? null) : null;
|
const latestTurn =
|
||||||
|
latestCheckpoint === null
|
||||||
|
? null
|
||||||
|
: {
|
||||||
|
turnId: latestCheckpoint.turnId,
|
||||||
|
state: checkpointStatusToLatestTurnState(latestCheckpoint.status),
|
||||||
|
requestedAt: latestCheckpoint.completedAt,
|
||||||
|
startedAt: latestCheckpoint.completedAt,
|
||||||
|
completedAt: latestCheckpoint.completedAt,
|
||||||
|
assistantMessageId: latestCheckpoint.assistantMessageId,
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...nextBase,
|
...nextBase,
|
||||||
@@ -431,7 +479,7 @@ export function projectEvent(
|
|||||||
checkpoints,
|
checkpoints,
|
||||||
messages,
|
messages,
|
||||||
activities,
|
activities,
|
||||||
latestTurnId,
|
latestTurn,
|
||||||
updatedAt: event.occurredAt,
|
updatedAt: event.occurredAt,
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import { MessageId, ThreadId } from "@t3tools/contracts";
|
||||||
|
import { assert, it } from "@effect/vitest";
|
||||||
|
import { Effect, Layer } from "effect";
|
||||||
|
|
||||||
|
import { ProjectionThreadMessageRepository } from "../Services/ProjectionThreadMessages.ts";
|
||||||
|
import { ProjectionThreadMessageRepositoryLive } from "./ProjectionThreadMessages.ts";
|
||||||
|
import { SqlitePersistenceMemory } from "./Sqlite.ts";
|
||||||
|
|
||||||
|
const layer = it.layer(
|
||||||
|
ProjectionThreadMessageRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||||
|
);
|
||||||
|
|
||||||
|
layer("ProjectionThreadMessageRepository", (it) => {
|
||||||
|
it.effect("preserves existing attachments when upsert omits attachments", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const repository = yield* ProjectionThreadMessageRepository;
|
||||||
|
const threadId = ThreadId.makeUnsafe("thread-preserve-attachments");
|
||||||
|
const messageId = MessageId.makeUnsafe("message-preserve-attachments");
|
||||||
|
const createdAt = "2026-02-28T19:00:00.000Z";
|
||||||
|
const updatedAt = "2026-02-28T19:00:01.000Z";
|
||||||
|
const persistedAttachments = [
|
||||||
|
{
|
||||||
|
type: "image" as const,
|
||||||
|
id: "thread-preserve-attachments-att-1",
|
||||||
|
name: "example.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
yield* repository.upsert({
|
||||||
|
messageId,
|
||||||
|
threadId,
|
||||||
|
turnId: null,
|
||||||
|
role: "user",
|
||||||
|
text: "initial",
|
||||||
|
attachments: persistedAttachments,
|
||||||
|
isStreaming: false,
|
||||||
|
createdAt,
|
||||||
|
updatedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
yield* repository.upsert({
|
||||||
|
messageId,
|
||||||
|
threadId,
|
||||||
|
turnId: null,
|
||||||
|
role: "user",
|
||||||
|
text: "updated",
|
||||||
|
isStreaming: false,
|
||||||
|
createdAt,
|
||||||
|
updatedAt: "2026-02-28T19:00:02.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
const rows = yield* repository.listByThreadId({ threadId });
|
||||||
|
assert.equal(rows.length, 1);
|
||||||
|
assert.equal(rows[0]?.text, "updated");
|
||||||
|
assert.deepEqual(rows[0]?.attachments, persistedAttachments);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("allows explicit attachment clearing with an empty array", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const repository = yield* ProjectionThreadMessageRepository;
|
||||||
|
const threadId = ThreadId.makeUnsafe("thread-clear-attachments");
|
||||||
|
const messageId = MessageId.makeUnsafe("message-clear-attachments");
|
||||||
|
const createdAt = "2026-02-28T19:10:00.000Z";
|
||||||
|
|
||||||
|
yield* repository.upsert({
|
||||||
|
messageId,
|
||||||
|
threadId,
|
||||||
|
turnId: null,
|
||||||
|
role: "assistant",
|
||||||
|
text: "with attachment",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
type: "image",
|
||||||
|
id: "thread-clear-attachments-att-1",
|
||||||
|
name: "example.png",
|
||||||
|
mimeType: "image/png",
|
||||||
|
sizeBytes: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
isStreaming: false,
|
||||||
|
createdAt,
|
||||||
|
updatedAt: "2026-02-28T19:10:01.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
yield* repository.upsert({
|
||||||
|
messageId,
|
||||||
|
threadId,
|
||||||
|
turnId: null,
|
||||||
|
role: "assistant",
|
||||||
|
text: "cleared",
|
||||||
|
attachments: [],
|
||||||
|
isStreaming: false,
|
||||||
|
createdAt,
|
||||||
|
updatedAt: "2026-02-28T19:10:02.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
const rows = yield* repository.listByThreadId({ threadId });
|
||||||
|
assert.equal(rows.length, 1);
|
||||||
|
assert.equal(rows[0]?.text, "cleared");
|
||||||
|
assert.deepEqual(rows[0]?.attachments, []);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||||
import { Effect, Layer, Schema, Struct } from "effect";
|
import { Effect, Layer, Schema, Struct } from "effect";
|
||||||
|
import { ChatAttachment } from "@t3tools/contracts";
|
||||||
|
|
||||||
import { toPersistenceSqlError } from "../Errors.ts";
|
import { toPersistenceSqlError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
@@ -14,6 +15,7 @@ import {
|
|||||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||||
Struct.assign({
|
Struct.assign({
|
||||||
isStreaming: Schema.Number,
|
isStreaming: Schema.Number,
|
||||||
|
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -22,14 +24,17 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
|
|
||||||
const upsertProjectionThreadMessageRow = SqlSchema.void({
|
const upsertProjectionThreadMessageRow = SqlSchema.void({
|
||||||
Request: ProjectionThreadMessage,
|
Request: ProjectionThreadMessage,
|
||||||
execute: (row) =>
|
execute: (row) => {
|
||||||
sql`
|
const nextAttachmentsJson =
|
||||||
|
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
|
||||||
|
return sql`
|
||||||
INSERT INTO projection_thread_messages (
|
INSERT INTO projection_thread_messages (
|
||||||
message_id,
|
message_id,
|
||||||
thread_id,
|
thread_id,
|
||||||
turn_id,
|
turn_id,
|
||||||
role,
|
role,
|
||||||
text,
|
text,
|
||||||
|
attachments_json,
|
||||||
is_streaming,
|
is_streaming,
|
||||||
created_at,
|
created_at,
|
||||||
updated_at
|
updated_at
|
||||||
@@ -40,6 +45,14 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
${row.turnId},
|
${row.turnId},
|
||||||
${row.role},
|
${row.role},
|
||||||
${row.text},
|
${row.text},
|
||||||
|
COALESCE(
|
||||||
|
${nextAttachmentsJson},
|
||||||
|
(
|
||||||
|
SELECT attachments_json
|
||||||
|
FROM projection_thread_messages
|
||||||
|
WHERE message_id = ${row.messageId}
|
||||||
|
)
|
||||||
|
),
|
||||||
${row.isStreaming ? 1 : 0},
|
${row.isStreaming ? 1 : 0},
|
||||||
${row.createdAt},
|
${row.createdAt},
|
||||||
${row.updatedAt}
|
${row.updatedAt}
|
||||||
@@ -50,10 +63,15 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
turn_id = excluded.turn_id,
|
turn_id = excluded.turn_id,
|
||||||
role = excluded.role,
|
role = excluded.role,
|
||||||
text = excluded.text,
|
text = excluded.text,
|
||||||
|
attachments_json = COALESCE(
|
||||||
|
excluded.attachments_json,
|
||||||
|
projection_thread_messages.attachments_json
|
||||||
|
),
|
||||||
is_streaming = excluded.is_streaming,
|
is_streaming = excluded.is_streaming,
|
||||||
created_at = excluded.created_at,
|
created_at = excluded.created_at,
|
||||||
updated_at = excluded.updated_at
|
updated_at = excluded.updated_at
|
||||||
`,
|
`;
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const listProjectionThreadMessageRows = SqlSchema.findAll({
|
const listProjectionThreadMessageRows = SqlSchema.findAll({
|
||||||
@@ -67,6 +85,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
turn_id AS "turnId",
|
turn_id AS "turnId",
|
||||||
role,
|
role,
|
||||||
text,
|
text,
|
||||||
|
attachments_json AS "attachments",
|
||||||
is_streaming AS "isStreaming",
|
is_streaming AS "isStreaming",
|
||||||
created_at AS "createdAt",
|
created_at AS "createdAt",
|
||||||
updated_at AS "updatedAt"
|
updated_at AS "updatedAt"
|
||||||
@@ -97,8 +116,15 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
Effect.map((rows) =>
|
Effect.map((rows) =>
|
||||||
rows.map((row) => ({
|
rows.map((row) => ({
|
||||||
...row,
|
messageId: row.messageId,
|
||||||
|
threadId: row.threadId,
|
||||||
|
turnId: row.turnId,
|
||||||
|
role: row.role,
|
||||||
|
text: row.text,
|
||||||
isStreaming: row.isStreaming === 1,
|
isStreaming: row.isStreaming === 1,
|
||||||
|
createdAt: row.createdAt,
|
||||||
|
updatedAt: row.updatedAt,
|
||||||
|
...(row.attachments !== null ? { attachments: row.attachments } : {}),
|
||||||
})),
|
})),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
provider_name,
|
provider_name,
|
||||||
provider_session_id,
|
provider_session_id,
|
||||||
provider_thread_id,
|
provider_thread_id,
|
||||||
|
approval_policy,
|
||||||
|
sandbox_mode,
|
||||||
active_turn_id,
|
active_turn_id,
|
||||||
last_error,
|
last_error,
|
||||||
updated_at
|
updated_at
|
||||||
@@ -35,6 +37,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
${row.providerName},
|
${row.providerName},
|
||||||
${row.providerSessionId},
|
${row.providerSessionId},
|
||||||
${row.providerThreadId},
|
${row.providerThreadId},
|
||||||
|
${row.approvalPolicy},
|
||||||
|
${row.sandboxMode},
|
||||||
${row.activeTurnId},
|
${row.activeTurnId},
|
||||||
${row.lastError},
|
${row.lastError},
|
||||||
${row.updatedAt}
|
${row.updatedAt}
|
||||||
@@ -45,6 +49,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
provider_name = excluded.provider_name,
|
provider_name = excluded.provider_name,
|
||||||
provider_session_id = excluded.provider_session_id,
|
provider_session_id = excluded.provider_session_id,
|
||||||
provider_thread_id = excluded.provider_thread_id,
|
provider_thread_id = excluded.provider_thread_id,
|
||||||
|
approval_policy = excluded.approval_policy,
|
||||||
|
sandbox_mode = excluded.sandbox_mode,
|
||||||
active_turn_id = excluded.active_turn_id,
|
active_turn_id = excluded.active_turn_id,
|
||||||
last_error = excluded.last_error,
|
last_error = excluded.last_error,
|
||||||
updated_at = excluded.updated_at
|
updated_at = excluded.updated_at
|
||||||
@@ -62,6 +68,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
provider_name AS "providerName",
|
provider_name AS "providerName",
|
||||||
provider_session_id AS "providerSessionId",
|
provider_session_id AS "providerSessionId",
|
||||||
provider_thread_id AS "providerThreadId",
|
provider_thread_id AS "providerThreadId",
|
||||||
|
approval_policy AS "approvalPolicy",
|
||||||
|
sandbox_mode AS "sandboxMode",
|
||||||
active_turn_id AS "activeTurnId",
|
active_turn_id AS "activeTurnId",
|
||||||
last_error AS "lastError",
|
last_error AS "lastError",
|
||||||
updated_at AS "updatedAt"
|
updated_at AS "updatedAt"
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ import Migration0002 from "./Migrations/002_OrchestrationCommandReceipts.ts";
|
|||||||
import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
|
import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
|
||||||
import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
|
import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
|
||||||
import Migration0005 from "./Migrations/005_Projections.ts";
|
import Migration0005 from "./Migrations/005_Projections.ts";
|
||||||
|
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
|
||||||
|
import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Migration loader with all migrations defined inline.
|
* Migration loader with all migrations defined inline.
|
||||||
@@ -34,6 +36,8 @@ const loader = Migrator.fromRecord({
|
|||||||
"3_CheckpointDiffBlobs": Migration0003,
|
"3_CheckpointDiffBlobs": Migration0003,
|
||||||
"4_ProviderSessionRuntime": Migration0004,
|
"4_ProviderSessionRuntime": Migration0004,
|
||||||
"5_Projections": Migration0005,
|
"5_Projections": Migration0005,
|
||||||
|
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
|
||||||
|
"7_ProjectionThreadMessageAttachments": Migration0007,
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
|
import * as Effect from "effect/Effect";
|
||||||
|
|
||||||
|
const DEFAULT_APPROVAL_POLICY = "never";
|
||||||
|
const DEFAULT_SANDBOX_MODE = "workspace-write";
|
||||||
|
|
||||||
|
export default Effect.gen(function* () {
|
||||||
|
const sql = yield* SqlClient.SqlClient;
|
||||||
|
|
||||||
|
yield* sql`
|
||||||
|
ALTER TABLE projection_thread_sessions
|
||||||
|
ADD COLUMN approval_policy TEXT NOT NULL DEFAULT 'never'
|
||||||
|
`;
|
||||||
|
|
||||||
|
yield* sql`
|
||||||
|
ALTER TABLE projection_thread_sessions
|
||||||
|
ADD COLUMN sandbox_mode TEXT NOT NULL DEFAULT 'workspace-write'
|
||||||
|
`;
|
||||||
|
|
||||||
|
yield* sql`
|
||||||
|
UPDATE projection_thread_sessions
|
||||||
|
SET approval_policy = ${DEFAULT_APPROVAL_POLICY}
|
||||||
|
WHERE approval_policy IS NULL
|
||||||
|
`;
|
||||||
|
yield* sql`
|
||||||
|
UPDATE projection_thread_sessions
|
||||||
|
SET sandbox_mode = ${DEFAULT_SANDBOX_MODE}
|
||||||
|
WHERE sandbox_mode IS NULL
|
||||||
|
`;
|
||||||
|
});
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
|
import * as Effect from "effect/Effect";
|
||||||
|
|
||||||
|
export default Effect.gen(function* () {
|
||||||
|
const sql = yield* SqlClient.SqlClient;
|
||||||
|
|
||||||
|
yield* sql`
|
||||||
|
ALTER TABLE projection_thread_messages
|
||||||
|
ADD COLUMN attachments_json TEXT
|
||||||
|
`;
|
||||||
|
});
|
||||||
@@ -4,23 +4,27 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
|
|||||||
|
|
||||||
import * as SqliteClient from "./NodeSqliteClient.ts";
|
import * as SqliteClient from "./NodeSqliteClient.ts";
|
||||||
|
|
||||||
it.effect("runs prepared queries and returns positional values", () =>
|
const layer = it.layer(SqliteClient.layerMemory());
|
||||||
Effect.gen(function* () {
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
|
layer("NodeSqliteClient", (it) => {
|
||||||
yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
|
it.effect("runs prepared queries and returns positional values", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const sql = yield* SqlClient.SqlClient;
|
||||||
|
|
||||||
const rows = yield* sql<{ readonly id: number; readonly name: string }>`
|
yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
|
||||||
|
yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
|
||||||
|
|
||||||
|
const rows = yield* sql<{ readonly id: number; readonly name: string }>`
|
||||||
SELECT id, name FROM entries ORDER BY id
|
SELECT id, name FROM entries ORDER BY id
|
||||||
`;
|
`;
|
||||||
assert.equal(rows.length, 2);
|
assert.equal(rows.length, 2);
|
||||||
assert.equal(rows[0]?.name, "alpha");
|
assert.equal(rows[0]?.name, "alpha");
|
||||||
assert.equal(rows[1]?.name, "beta");
|
assert.equal(rows[1]?.name, "beta");
|
||||||
|
|
||||||
const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
|
const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
|
||||||
assert.equal(values.length, 2);
|
assert.equal(values.length, 2);
|
||||||
assert.equal(values[0]?.[1], "alpha");
|
assert.equal(values[0]?.[1], "alpha");
|
||||||
assert.equal(values[1]?.[1], "beta");
|
assert.equal(values[1]?.[1], "beta");
|
||||||
}).pipe(Effect.provide(SqliteClient.layerMemory())),
|
}),
|
||||||
);
|
);
|
||||||
|
});
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
* @module ProjectionThreadMessageRepository
|
* @module ProjectionThreadMessageRepository
|
||||||
*/
|
*/
|
||||||
import {
|
import {
|
||||||
|
ChatAttachment,
|
||||||
OrchestrationMessageRole,
|
OrchestrationMessageRole,
|
||||||
MessageId,
|
MessageId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
@@ -24,6 +25,7 @@ export const ProjectionThreadMessage = Schema.Struct({
|
|||||||
turnId: Schema.NullOr(TurnId),
|
turnId: Schema.NullOr(TurnId),
|
||||||
role: OrchestrationMessageRole,
|
role: OrchestrationMessageRole,
|
||||||
text: Schema.String,
|
text: Schema.String,
|
||||||
|
attachments: Schema.optional(Schema.Array(ChatAttachment)),
|
||||||
isStreaming: Schema.Boolean,
|
isStreaming: Schema.Boolean,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
updatedAt: IsoDateTime,
|
updatedAt: IsoDateTime,
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
import {
|
import {
|
||||||
IsoDateTime,
|
IsoDateTime,
|
||||||
OrchestrationSessionStatus,
|
OrchestrationSessionStatus,
|
||||||
|
ProviderApprovalPolicy,
|
||||||
|
ProviderSandboxMode,
|
||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
ProviderThreadId,
|
ProviderThreadId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
@@ -25,6 +27,8 @@ export const ProjectionThreadSession = Schema.Struct({
|
|||||||
providerName: Schema.NullOr(Schema.String),
|
providerName: Schema.NullOr(Schema.String),
|
||||||
providerSessionId: Schema.NullOr(ProviderSessionId),
|
providerSessionId: Schema.NullOr(ProviderSessionId),
|
||||||
providerThreadId: Schema.NullOr(ProviderThreadId),
|
providerThreadId: Schema.NullOr(ProviderThreadId),
|
||||||
|
approvalPolicy: ProviderApprovalPolicy,
|
||||||
|
sandboxMode: ProviderSandboxMode,
|
||||||
activeTurnId: Schema.NullOr(TurnId),
|
activeTurnId: Schema.NullOr(TurnId),
|
||||||
lastError: Schema.NullOr(Schema.String),
|
lastError: Schema.NullOr(Schema.String),
|
||||||
updatedAt: IsoDateTime,
|
updatedAt: IsoDateTime,
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import http from "node:http";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||||
|
|
||||||
|
interface HttpResponse {
|
||||||
|
statusCode: number;
|
||||||
|
contentType: string | null;
|
||||||
|
body: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tempDirs: string[] = [];
|
||||||
|
|
||||||
|
function makeTempDir(prefix: string): string {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function withRouteServer(
|
||||||
|
run: (baseUrl: string) => Promise<void>,
|
||||||
|
): Promise<void> {
|
||||||
|
const server = http.createServer((req, res) => {
|
||||||
|
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
||||||
|
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||||
|
res.end("Not Found");
|
||||||
|
});
|
||||||
|
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
server.listen(0, "127.0.0.1", (error?: Error) => {
|
||||||
|
if (error) {
|
||||||
|
reject(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const address = server.address();
|
||||||
|
if (typeof address !== "object" || address === null) {
|
||||||
|
throw new Error("Expected server address to be an object");
|
||||||
|
}
|
||||||
|
const baseUrl = `http://127.0.0.1:${address.port}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await run(baseUrl);
|
||||||
|
} finally {
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
server.close((error?: Error) => {
|
||||||
|
if (error) {
|
||||||
|
reject(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request(baseUrl: string, pathname: string): Promise<HttpResponse> {
|
||||||
|
const response = await fetch(`${baseUrl}${pathname}`);
|
||||||
|
return {
|
||||||
|
statusCode: response.status,
|
||||||
|
contentType: response.headers.get("content-type"),
|
||||||
|
body: await response.text(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("tryHandleProjectFaviconRequest", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 400 when cwd is missing", async () => {
|
||||||
|
await withRouteServer(async (baseUrl) => {
|
||||||
|
const response = await request(baseUrl, "/api/project-favicon");
|
||||||
|
expect(response.statusCode).toBe(400);
|
||||||
|
expect(response.body).toBe("Missing cwd parameter");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("serves a well-known favicon file from the project root", async () => {
|
||||||
|
const projectDir = makeTempDir("t3code-favicon-route-root-");
|
||||||
|
fs.writeFileSync(path.join(projectDir, "favicon.svg"), "<svg>favicon</svg>", "utf8");
|
||||||
|
|
||||||
|
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).toBe("<svg>favicon</svg>");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves icon href from source files when no well-known favicon exists", async () => {
|
||||||
|
const projectDir = makeTempDir("t3code-favicon-route-source-");
|
||||||
|
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
|
||||||
|
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(projectDir, "index.html"), '<link rel="icon" href="/brand/logo.svg">');
|
||||||
|
fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8");
|
||||||
|
|
||||||
|
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).toBe("<svg>brand</svg>");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves icon link when href appears before rel in HTML", async () => {
|
||||||
|
const projectDir = makeTempDir("t3code-favicon-route-html-order-");
|
||||||
|
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
|
||||||
|
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(projectDir, "index.html"), '<link href="/brand/logo.svg" rel="icon">');
|
||||||
|
fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8");
|
||||||
|
|
||||||
|
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).toBe("<svg>brand-html-order</svg>");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves object-style icon metadata when href appears before rel", async () => {
|
||||||
|
const projectDir = makeTempDir("t3code-favicon-route-obj-order-");
|
||||||
|
const iconPath = path.join(projectDir, "public", "brand", "obj.svg");
|
||||||
|
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||||
|
fs.mkdirSync(path.join(projectDir, "src"), { recursive: true });
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(projectDir, "src", "root.tsx"),
|
||||||
|
'const links = [{ href: "/brand/obj.svg", rel: "icon" }];',
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
fs.writeFileSync(iconPath, "<svg>brand-obj-order</svg>", "utf8");
|
||||||
|
|
||||||
|
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).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"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import http from "node:http";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||||
|
".png": "image/png",
|
||||||
|
".jpg": "image/jpeg",
|
||||||
|
".svg": "image/svg+xml",
|
||||||
|
".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",
|
||||||
|
"favicon.ico",
|
||||||
|
"favicon.png",
|
||||||
|
"public/favicon.svg",
|
||||||
|
"public/favicon.ico",
|
||||||
|
"public/favicon.png",
|
||||||
|
"app/favicon.ico",
|
||||||
|
"app/favicon.png",
|
||||||
|
"app/icon.svg",
|
||||||
|
"app/icon.png",
|
||||||
|
"app/icon.ico",
|
||||||
|
"src/favicon.ico",
|
||||||
|
"src/favicon.svg",
|
||||||
|
"src/app/favicon.ico",
|
||||||
|
"src/app/icon.svg",
|
||||||
|
"src/app/icon.png",
|
||||||
|
"assets/icon.svg",
|
||||||
|
"assets/icon.png",
|
||||||
|
"assets/logo.svg",
|
||||||
|
"assets/logo.png",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Files that may contain a <link rel="icon"> or icon metadata declaration.
|
||||||
|
const ICON_SOURCE_FILES = [
|
||||||
|
"index.html",
|
||||||
|
"public/index.html",
|
||||||
|
"app/routes/__root.tsx",
|
||||||
|
"src/routes/__root.tsx",
|
||||||
|
"app/root.tsx",
|
||||||
|
"src/root.tsx",
|
||||||
|
"src/index.html",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
||||||
|
const LINK_ICON_HTML_RE =
|
||||||
|
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
||||||
|
const LINK_ICON_OBJ_RE =
|
||||||
|
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
||||||
|
|
||||||
|
function extractIconHref(source: string): string | null {
|
||||||
|
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
||||||
|
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||||
|
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
||||||
|
if (objMatch?.[1]) return objMatch[1];
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveIconHref(projectCwd: string, href: string): string[] {
|
||||||
|
const clean = href.replace(/^\//, "");
|
||||||
|
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
|
||||||
|
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
|
||||||
|
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
||||||
|
}
|
||||||
|
|
||||||
|
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
|
||||||
|
const ext = path.extname(filePath).toLowerCase();
|
||||||
|
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
|
||||||
|
fs.readFile(filePath, (readErr, data) => {
|
||||||
|
if (readErr) {
|
||||||
|
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||||
|
res.end("Read error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.writeHead(200, {
|
||||||
|
"Content-Type": contentType,
|
||||||
|
"Cache-Control": "public, max-age=3600",
|
||||||
|
});
|
||||||
|
res.end(data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
const projectCwd = url.searchParams.get("cwd");
|
||||||
|
if (!projectCwd) {
|
||||||
|
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||||
|
res.end("Missing cwd parameter");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
|
||||||
|
if (index >= paths.length) {
|
||||||
|
onExhausted();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const candidate = paths[index]!;
|
||||||
|
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||||
|
tryResolvedPaths(paths, index + 1, onExhausted);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fs.stat(candidate, (err, stats) => {
|
||||||
|
if (err || !stats?.isFile()) {
|
||||||
|
tryResolvedPaths(paths, index + 1, onExhausted);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
serveFaviconFile(candidate, res);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const trySourceFiles = (index: number): void => {
|
||||||
|
if (index >= ICON_SOURCE_FILES.length) {
|
||||||
|
serveFallbackFavicon(res);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
|
||||||
|
fs.readFile(sourceFile, "utf8", (err, content) => {
|
||||||
|
if (err) {
|
||||||
|
trySourceFiles(index + 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const href = extractIconHref(content);
|
||||||
|
if (!href) {
|
||||||
|
trySourceFiles(index + 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const candidates = resolveIconHref(projectCwd, href);
|
||||||
|
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const tryCandidates = (index: number): void => {
|
||||||
|
if (index >= FAVICON_CANDIDATES.length) {
|
||||||
|
trySourceFiles(0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
|
||||||
|
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||||
|
tryCandidates(index + 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fs.stat(candidate, (err, stats) => {
|
||||||
|
if (err || !stats?.isFile()) {
|
||||||
|
tryCandidates(index + 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
serveFaviconFile(candidate, res);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
tryCandidates(0);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -4,7 +4,6 @@ import {
|
|||||||
ProviderItemId,
|
ProviderItemId,
|
||||||
type ProviderApprovalDecision,
|
type ProviderApprovalDecision,
|
||||||
type ProviderEvent,
|
type ProviderEvent,
|
||||||
type ProviderSendTurnInput,
|
|
||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
type ProviderSessionStartInput,
|
type ProviderSessionStartInput,
|
||||||
@@ -12,12 +11,17 @@ import {
|
|||||||
ProviderTurnId,
|
ProviderTurnId,
|
||||||
type ProviderTurnStartResult,
|
type ProviderTurnStartResult,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { afterAll, assert, it, vi } from "@effect/vitest";
|
import { afterAll, assert, it, vi } from "@effect/vitest";
|
||||||
import { assertFailure } from "@effect/vitest/utils";
|
import { assertFailure } from "@effect/vitest/utils";
|
||||||
|
|
||||||
import { Effect, Fiber, Stream } from "effect";
|
import { Effect, Fiber, Layer, Stream } from "effect";
|
||||||
|
|
||||||
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
import {
|
||||||
|
CodexAppServerManager,
|
||||||
|
type CodexAppServerSendTurnInput,
|
||||||
|
} from "../../codexAppServerManager.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||||
@@ -44,7 +48,7 @@ class FakeCodexManager extends CodexAppServerManager {
|
|||||||
);
|
);
|
||||||
|
|
||||||
public sendTurnImpl = vi.fn(
|
public sendTurnImpl = vi.fn(
|
||||||
async (_input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> => ({
|
async (_input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> => ({
|
||||||
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
}),
|
}),
|
||||||
@@ -78,7 +82,7 @@ class FakeCodexManager extends CodexAppServerManager {
|
|||||||
return this.startSessionImpl(input);
|
return this.startSessionImpl(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
override sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
override sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||||
return this.sendTurnImpl(input);
|
return this.sendTurnImpl(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,7 +122,12 @@ class FakeCodexManager extends CodexAppServerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const validationManager = new FakeCodexManager();
|
const validationManager = new FakeCodexManager();
|
||||||
const validationLayer = it.layer(makeCodexAdapterLive({ manager: validationManager }));
|
const validationLayer = it.layer(
|
||||||
|
makeCodexAdapterLive({ manager: validationManager }).pipe(
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
validationLayer("CodexAdapterLive validation", (it) => {
|
validationLayer("CodexAdapterLive validation", (it) => {
|
||||||
it.effect("returns validation error for non-codex provider on startSession", () =>
|
it.effect("returns validation error for non-codex provider on startSession", () =>
|
||||||
@@ -147,7 +156,12 @@ const sessionErrorManager = new FakeCodexManager();
|
|||||||
sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
|
sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
|
||||||
throw new Error("Unknown session: sess-missing");
|
throw new Error("Unknown session: sess-missing");
|
||||||
});
|
});
|
||||||
const sessionErrorLayer = it.layer(makeCodexAdapterLive({ manager: sessionErrorManager }));
|
const sessionErrorLayer = it.layer(
|
||||||
|
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||||
it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () =>
|
it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () =>
|
||||||
@@ -178,7 +192,12 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const lifecycleManager = new FakeCodexManager();
|
const lifecycleManager = new FakeCodexManager();
|
||||||
const lifecycleLayer = it.layer(makeCodexAdapterLive({ manager: lifecycleManager }));
|
const lifecycleLayer = it.layer(
|
||||||
|
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||||
it.effect("maps completed agent message items to canonical message.completed events", () =>
|
it.effect("maps completed agent message items to canonical message.completed events", () =>
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
ProviderThreadId,
|
ProviderThreadId,
|
||||||
ProviderTurnId,
|
ProviderTurnId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect, Layer, Queue, Schema, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Queue, Schema, Stream } from "effect";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ProviderAdapterProcessError,
|
ProviderAdapterProcessError,
|
||||||
@@ -29,6 +29,8 @@ import {
|
|||||||
} from "../Errors.ts";
|
} from "../Errors.ts";
|
||||||
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||||
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
||||||
|
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||||
|
|
||||||
const PROVIDER = "codex" as const;
|
const PROVIDER = "codex" as const;
|
||||||
@@ -426,6 +428,8 @@ function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntime
|
|||||||
|
|
||||||
const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
const nativeEventLogger =
|
const nativeEventLogger =
|
||||||
options?.nativeEventLogPath !== undefined
|
options?.nativeEventLogPath !== undefined
|
||||||
? makeEventNdjsonLogger(options.nativeEventLogPath)
|
? makeEventNdjsonLogger(options.nativeEventLogPath)
|
||||||
@@ -475,9 +479,48 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
|||||||
};
|
};
|
||||||
|
|
||||||
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
|
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
|
||||||
Effect.tryPromise({
|
Effect.gen(function* () {
|
||||||
try: () => manager.sendTurn(input),
|
const codexAttachments = yield* Effect.forEach(
|
||||||
catch: (cause) => toRequestError(input.sessionId, "turn/start", cause),
|
input.attachments ?? [],
|
||||||
|
(attachment) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const attachmentPath = resolveAttachmentPath({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
attachment,
|
||||||
|
});
|
||||||
|
if (!attachmentPath) {
|
||||||
|
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)),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
type: "image" as const,
|
||||||
|
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
|
||||||
|
return yield* Effect.tryPromise({
|
||||||
|
try: () => {
|
||||||
|
const managerInput = {
|
||||||
|
sessionId: input.sessionId,
|
||||||
|
...(input.input !== undefined ? { input: input.input } : {}),
|
||||||
|
...(input.model !== undefined ? { model: input.model } : {}),
|
||||||
|
...(input.effort !== undefined ? { effort: input.effort } : {}),
|
||||||
|
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
|
||||||
|
};
|
||||||
|
return manager.sendTurn(managerInput);
|
||||||
|
},
|
||||||
|
catch: (cause) => toRequestError(input.sessionId, "turn/start", cause),
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const interruptTurn: CodexAdapterShape["interruptTurn"] = (sessionId, turnId) =>
|
const interruptTurn: CodexAdapterShape["interruptTurn"] = (sessionId, turnId) =>
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ import {
|
|||||||
|
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||||
|
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||||
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
|
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
|
||||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||||
@@ -377,6 +378,7 @@ it.effect(
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
|
cwd: "/tmp/project",
|
||||||
resumeThreadId: startedSession.threadId,
|
resumeThreadId: startedSession.threadId,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -464,6 +466,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
|
cwd: "/tmp/project",
|
||||||
resumeThreadId: initial.threadId,
|
resumeThreadId: initial.threadId,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -474,6 +477,38 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const provider = yield* ProviderService;
|
||||||
|
|
||||||
|
const initial = yield* provider.startSession(asThreadId("thread-1"), {
|
||||||
|
provider: "codex",
|
||||||
|
cwd: "/tmp/project-send-turn",
|
||||||
|
});
|
||||||
|
|
||||||
|
yield* provider.stopAll();
|
||||||
|
routing.codex.startSession.mockClear();
|
||||||
|
routing.codex.sendTurn.mockClear();
|
||||||
|
|
||||||
|
yield* provider.sendTurn({
|
||||||
|
sessionId: initial.sessionId,
|
||||||
|
input: "resume",
|
||||||
|
attachments: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(routing.codex.startSession.mock.calls, [
|
||||||
|
[
|
||||||
|
{
|
||||||
|
provider: "codex",
|
||||||
|
cwd: "/tmp/project-send-turn",
|
||||||
|
resumeThreadId: initial.threadId,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
it.effect("stops all sessions and clears adapter runtime", () =>
|
it.effect("stops all sessions and clears adapter runtime", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const provider = yield* ProviderService;
|
const provider = yield* ProviderService;
|
||||||
@@ -564,7 +599,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
sessionId: session.sessionId,
|
sessionId: session.sessionId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: asProviderThreadId("thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
};
|
};
|
||||||
@@ -612,7 +647,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
sessionId: session.sessionId,
|
sessionId: session.sessionId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: asProviderThreadId("thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
toolKind: "command",
|
toolKind: "command",
|
||||||
title: "Command run",
|
title: "Command run",
|
||||||
@@ -624,7 +659,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
sessionId: session.sessionId,
|
sessionId: session.sessionId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: asProviderThreadId("thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
delta: "hello",
|
delta: "hello",
|
||||||
},
|
},
|
||||||
@@ -634,7 +669,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
sessionId: session.sessionId,
|
sessionId: session.sessionId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
threadId: asProviderThreadId("thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -93,6 +93,18 @@ function toRuntimePayloadFromSession(session: ProviderSession): Record<string, u
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readPersistedCwd(
|
||||||
|
runtimePayload: ProviderSessionBinding["runtimePayload"],
|
||||||
|
): string | undefined {
|
||||||
|
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined;
|
||||||
|
if (typeof rawCwd !== "string") return undefined;
|
||||||
|
const trimmed = rawCwd.trim();
|
||||||
|
return trimmed.length > 0 ? trimmed : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const canonicalEventLogger =
|
const canonicalEventLogger =
|
||||||
@@ -266,8 +278,11 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||||
|
|
||||||
const resumed = yield* adapter.startSession({
|
const resumed = yield* adapter.startSession({
|
||||||
provider: input.binding.provider,
|
provider: input.binding.provider,
|
||||||
|
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||||
...(resumeThreadId ? { resumeThreadId } : {}),
|
...(resumeThreadId ? { resumeThreadId } : {}),
|
||||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
|
|||||||
return Layer.mergeAll(
|
return Layer.mergeAll(
|
||||||
runtimeRepositoryLayer,
|
runtimeRepositoryLayer,
|
||||||
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||||
|
NodeServices.layer,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,5 +224,5 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
|||||||
}).pipe(Effect.provide(directoryLayer));
|
}).pipe(Effect.provide(directoryLayer));
|
||||||
|
|
||||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
}).pipe(Effect.provide(NodeServices.layer)));
|
}));
|
||||||
});
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { Effect, Layer } from "effect";
|
import { Effect, FileSystem, Layer } from "effect";
|
||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||||
|
|
||||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
|
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
|
||||||
@@ -37,7 +37,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
|||||||
export function makeServerProviderLayer(): Layer.Layer<
|
export function makeServerProviderLayer(): Layer.Layer<
|
||||||
ProviderService,
|
ProviderService,
|
||||||
ProviderUnsupportedError,
|
ProviderUnsupportedError,
|
||||||
SqlClient.SqlClient | ServerConfig
|
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const { stateDir } = yield* ServerConfig;
|
const { stateDir } = yield* ServerConfig;
|
||||||
@@ -56,21 +56,24 @@ export function makeServerProviderLayer(): Layer.Layer<
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function makeServerRuntimeServicesLayer() {
|
export function makeServerRuntimeServicesLayer() {
|
||||||
|
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
|
||||||
|
const textGenerationLayer = CodexTextGenerationLive;
|
||||||
|
|
||||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||||
Layer.provide(OrchestrationEventStoreLive),
|
Layer.provide(OrchestrationEventStoreLive),
|
||||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||||
);
|
);
|
||||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
|
||||||
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
|
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
|
||||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||||
Layer.provideMerge(checkpointStoreLayer),
|
Layer.provideMerge(CheckpointStoreLive),
|
||||||
);
|
);
|
||||||
|
|
||||||
const runtimeServicesLayer = Layer.mergeAll(
|
const runtimeServicesLayer = Layer.mergeAll(
|
||||||
orchestrationLayer,
|
orchestrationLayer,
|
||||||
OrchestrationProjectionSnapshotQueryLive,
|
OrchestrationProjectionSnapshotQueryLive,
|
||||||
checkpointStoreLayer,
|
CheckpointStoreLive,
|
||||||
checkpointDiffQueryLayer,
|
checkpointDiffQueryLayer,
|
||||||
);
|
);
|
||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
@@ -78,6 +81,8 @@ export function makeServerRuntimeServicesLayer() {
|
|||||||
);
|
);
|
||||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
|
Layer.provideMerge(gitCoreLayer),
|
||||||
|
Layer.provideMerge(textGenerationLayer),
|
||||||
);
|
);
|
||||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
@@ -92,12 +97,10 @@ export function makeServerRuntimeServicesLayer() {
|
|||||||
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
|
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
|
||||||
);
|
);
|
||||||
|
|
||||||
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
|
|
||||||
|
|
||||||
const gitManagerLayer = GitManagerLive.pipe(
|
const gitManagerLayer = GitManagerLive.pipe(
|
||||||
Layer.provideMerge(gitCoreLayer),
|
Layer.provideMerge(gitCoreLayer),
|
||||||
Layer.provideMerge(GitHubCliLive),
|
Layer.provideMerge(GitHubCliLive),
|
||||||
Layer.provideMerge(CodexTextGenerationLive),
|
Layer.provideMerge(textGenerationLayer),
|
||||||
);
|
);
|
||||||
|
|
||||||
return Layer.mergeAll(
|
return Layer.mergeAll(
|
||||||
|
|||||||
@@ -394,6 +394,21 @@ describe("TerminalManager", () => {
|
|||||||
manager.dispose();
|
manager.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("ignores trailing writes after terminal exit", async () => {
|
||||||
|
const { manager, ptyAdapter } = makeManager();
|
||||||
|
await manager.open(openInput());
|
||||||
|
const process = ptyAdapter.processes[0];
|
||||||
|
expect(process).toBeDefined();
|
||||||
|
if (!process) return;
|
||||||
|
|
||||||
|
process.emitExit({ exitCode: 0, signal: 0 });
|
||||||
|
|
||||||
|
await expect(manager.write({ threadId: "thread-1", data: "\r" })).resolves.toBeUndefined();
|
||||||
|
expect(process.writes).toEqual([]);
|
||||||
|
|
||||||
|
manager.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
it("emits subprocess activity events when child-process state changes", async () => {
|
it("emits subprocess activity events when child-process state changes", async () => {
|
||||||
let hasRunningSubprocess = false;
|
let hasRunningSubprocess = false;
|
||||||
const { manager } = makeManager(5, {
|
const { manager } = makeManager(5, {
|
||||||
|
|||||||
@@ -438,6 +438,9 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
|||||||
const input = decodeTerminalWriteInput(raw);
|
const input = decodeTerminalWriteInput(raw);
|
||||||
const session = this.requireSession(input.threadId, input.terminalId);
|
const session = this.requireSession(input.threadId, input.terminalId);
|
||||||
if (!session.process || session.status !== "running") {
|
if (!session.process || session.status !== "running") {
|
||||||
|
if (session.status === "exited") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
|
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ import fs from "node:fs";
|
|||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
import { Effect, Exit, Layer, PubSub, Scope, Stream } from "effect";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||||
import { createServer } from "./wsServer";
|
import { createServer } from "./wsServer";
|
||||||
import WebSocket from "ws";
|
import WebSocket from "ws";
|
||||||
@@ -38,14 +39,15 @@ import type {
|
|||||||
TerminalWriteInput,
|
TerminalWriteInput,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
|
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
|
||||||
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
||||||
import { SqlClient } from "effect/unstable/sql";
|
import { SqlClient, SqlError } from "effect/unstable/sql";
|
||||||
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
||||||
import { Open, type OpenShape } from "./open";
|
import { Open, type OpenShape } from "./open";
|
||||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||||
import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||||
import { GitCore } from "./git/Services/GitCore.ts";
|
import { GitCore } from "./git/Services/GitCore.ts";
|
||||||
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||||
|
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||||
|
|
||||||
interface PendingMessages {
|
interface PendingMessages {
|
||||||
queue: unknown[];
|
queue: unknown[];
|
||||||
@@ -295,6 +297,36 @@ async function waitForPush(
|
|||||||
return take(maxMessages);
|
return take(maxMessages);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function requestPath(
|
||||||
|
port: number,
|
||||||
|
requestPath: string,
|
||||||
|
): Promise<{ statusCode: number; body: string }> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const req = Http.request(
|
||||||
|
{
|
||||||
|
hostname: "127.0.0.1",
|
||||||
|
port,
|
||||||
|
path: requestPath,
|
||||||
|
method: "GET",
|
||||||
|
},
|
||||||
|
(res) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
res.on("data", (chunk) => {
|
||||||
|
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||||
|
});
|
||||||
|
res.on("end", () => {
|
||||||
|
resolve({
|
||||||
|
statusCode: res.statusCode ?? 0,
|
||||||
|
body: Buffer.concat(chunks).toString("utf8"),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
req.once("error", reject);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
|
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
|
||||||
const resolved: Array<ResolvedKeybindingsConfig[number]> = [];
|
const resolved: Array<ResolvedKeybindingsConfig[number]> = [];
|
||||||
for (const binding of bindings) {
|
for (const binding of bindings) {
|
||||||
@@ -323,17 +355,24 @@ describe("WebSocket Server", () => {
|
|||||||
|
|
||||||
async function createTestServer(
|
async function createTestServer(
|
||||||
options: {
|
options: {
|
||||||
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>;
|
persistenceLayer?: Layer.Layer<
|
||||||
|
SqlClient.SqlClient,
|
||||||
|
SqlError.SqlError | MigrationError | PlatformError.PlatformError
|
||||||
|
>;
|
||||||
cwd?: string;
|
cwd?: string;
|
||||||
autoBootstrapProjectFromCwd?: boolean;
|
autoBootstrapProjectFromCwd?: boolean;
|
||||||
logWebSocketEvents?: boolean;
|
logWebSocketEvents?: boolean;
|
||||||
devUrl?: string;
|
devUrl?: string;
|
||||||
authToken?: string;
|
authToken?: string;
|
||||||
stateDir?: string;
|
stateDir?: string;
|
||||||
|
staticDir?: string;
|
||||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||||
open?: OpenShape;
|
open?: OpenShape;
|
||||||
gitManager?: GitManagerShape;
|
gitManager?: GitManagerShape;
|
||||||
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
|
gitCore?: Pick<
|
||||||
|
GitCoreShape,
|
||||||
|
"listBranches" | "initRepo" | "pullCurrentBranch"
|
||||||
|
>;
|
||||||
terminalManager?: TerminalManagerShape;
|
terminalManager?: TerminalManagerShape;
|
||||||
} = {},
|
} = {},
|
||||||
): Promise<Http.Server> {
|
): Promise<Http.Server> {
|
||||||
@@ -353,7 +392,7 @@ describe("WebSocket Server", () => {
|
|||||||
cwd: options.cwd ?? "/test/project",
|
cwd: options.cwd ?? "/test/project",
|
||||||
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
||||||
stateDir,
|
stateDir,
|
||||||
staticDir: undefined,
|
staticDir: options.staticDir,
|
||||||
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
|
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
|
||||||
noBrowser: true,
|
noBrowser: true,
|
||||||
authToken: options.authToken,
|
authToken: options.authToken,
|
||||||
@@ -381,6 +420,7 @@ describe("WebSocket Server", () => {
|
|||||||
Layer.provideMerge(runtimeLayer),
|
Layer.provideMerge(runtimeLayer),
|
||||||
Layer.provideMerge(openLayer),
|
Layer.provideMerge(openLayer),
|
||||||
Layer.provideMerge(serverConfigLayer),
|
Layer.provideMerge(serverConfigLayer),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
const runtimeServices = await Effect.runPromise(
|
const runtimeServices = await Effect.runPromise(
|
||||||
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
||||||
@@ -437,6 +477,80 @@ describe("WebSocket Server", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("serves persisted attachments from stateDir", async () => {
|
||||||
|
const stateDir = makeTempDir("t3code-state-attachments-");
|
||||||
|
const attachmentPath = path.join(stateDir, "attachments", "thread-a", "message-a", "0.png");
|
||||||
|
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||||
|
fs.writeFileSync(attachmentPath, Buffer.from("hello-attachment"));
|
||||||
|
|
||||||
|
server = await createTestServer({ cwd: "/test/project", stateDir });
|
||||||
|
const addr = server.address();
|
||||||
|
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||||
|
expect(port).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const response = await fetch(`http://127.0.0.1:${port}/attachments/thread-a/message-a/0.png`);
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(response.headers.get("content-type")).toContain("image/png");
|
||||||
|
const bytes = Buffer.from(await response.arrayBuffer());
|
||||||
|
expect(bytes).toEqual(Buffer.from("hello-attachment"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("serves persisted attachments for URL-encoded paths", async () => {
|
||||||
|
const stateDir = makeTempDir("t3code-state-attachments-encoded-");
|
||||||
|
const attachmentPath = path.join(
|
||||||
|
stateDir,
|
||||||
|
"attachments",
|
||||||
|
"thread%20folder",
|
||||||
|
"message%20folder",
|
||||||
|
"file%20name.png",
|
||||||
|
);
|
||||||
|
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||||
|
fs.writeFileSync(attachmentPath, Buffer.from("hello-encoded-attachment"));
|
||||||
|
|
||||||
|
server = await createTestServer({ cwd: "/test/project", stateDir });
|
||||||
|
const addr = server.address();
|
||||||
|
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||||
|
expect(port).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
`http://127.0.0.1:${port}/attachments/thread%20folder/message%20folder/file%20name.png`,
|
||||||
|
);
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(response.headers.get("content-type")).toContain("image/png");
|
||||||
|
const bytes = Buffer.from(await response.arrayBuffer());
|
||||||
|
expect(bytes).toEqual(Buffer.from("hello-encoded-attachment"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("serves static index for root path", async () => {
|
||||||
|
const stateDir = makeTempDir("t3code-state-static-root-");
|
||||||
|
const staticDir = makeTempDir("t3code-static-root-");
|
||||||
|
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>static-root</h1>", "utf8");
|
||||||
|
|
||||||
|
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
|
||||||
|
const addr = server.address();
|
||||||
|
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||||
|
expect(port).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const response = await fetch(`http://127.0.0.1:${port}/`);
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(await response.text()).toContain("static-root");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects static path traversal attempts", async () => {
|
||||||
|
const stateDir = makeTempDir("t3code-state-static-traversal-");
|
||||||
|
const staticDir = makeTempDir("t3code-static-traversal-");
|
||||||
|
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>safe</h1>", "utf8");
|
||||||
|
|
||||||
|
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
|
||||||
|
const addr = server.address();
|
||||||
|
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||||
|
expect(port).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const response = await requestPath(port, "/..%2f..%2fetc/passwd");
|
||||||
|
expect(response.statusCode).toBe(400);
|
||||||
|
expect(response.body).toBe("Invalid static file path");
|
||||||
|
});
|
||||||
|
|
||||||
it("bootstraps the cwd project on startup when enabled", async () => {
|
it("bootstraps the cwd project on startup when enabled", async () => {
|
||||||
server = await createTestServer({
|
server = await createTestServer({
|
||||||
cwd: "/test/bootstrap-workspace",
|
cwd: "/test/bootstrap-workspace",
|
||||||
@@ -448,23 +562,117 @@ describe("WebSocket Server", () => {
|
|||||||
|
|
||||||
const ws = await connectWs(port);
|
const ws = await connectWs(port);
|
||||||
connections.push(ws);
|
connections.push(ws);
|
||||||
await waitForMessage(ws); // welcome
|
const welcome = (await waitForMessage(ws)) as WsPush; // welcome
|
||||||
|
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
|
||||||
|
expect(welcome.data).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
cwd: "/test/bootstrap-workspace",
|
||||||
|
projectName: "bootstrap-workspace",
|
||||||
|
bootstrapProjectId: expect.any(String),
|
||||||
|
bootstrapThreadId: expect.any(String),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot);
|
const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot);
|
||||||
expect(snapshotResponse.error).toBeUndefined();
|
expect(snapshotResponse.error).toBeUndefined();
|
||||||
const snapshot = snapshotResponse.result as {
|
const snapshot = snapshotResponse.result as {
|
||||||
projects: Array<{ workspaceRoot: string; title: string; defaultModel: string | null }>;
|
projects: Array<{
|
||||||
|
id: string;
|
||||||
|
workspaceRoot: string;
|
||||||
|
title: string;
|
||||||
|
defaultModel: string | null;
|
||||||
|
}>;
|
||||||
|
threads: Array<{
|
||||||
|
id: string;
|
||||||
|
projectId: string;
|
||||||
|
title: string;
|
||||||
|
model: string;
|
||||||
|
branch: string | null;
|
||||||
|
worktreePath: string | null;
|
||||||
|
}>;
|
||||||
};
|
};
|
||||||
|
const bootstrapProjectId = (welcome.data as { bootstrapProjectId?: string }).bootstrapProjectId;
|
||||||
|
const bootstrapThreadId = (welcome.data as { bootstrapThreadId?: string }).bootstrapThreadId;
|
||||||
|
expect(bootstrapProjectId).toBeDefined();
|
||||||
|
expect(bootstrapThreadId).toBeDefined();
|
||||||
|
|
||||||
expect(snapshot.projects).toEqual(
|
expect(snapshot.projects).toEqual(
|
||||||
expect.arrayContaining([
|
expect.arrayContaining([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
|
id: bootstrapProjectId,
|
||||||
workspaceRoot: "/test/bootstrap-workspace",
|
workspaceRoot: "/test/bootstrap-workspace",
|
||||||
title: "bootstrap-workspace",
|
title: "bootstrap-workspace",
|
||||||
defaultModel: "gpt-5-codex",
|
defaultModel: "gpt-5-codex",
|
||||||
}),
|
}),
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
|
expect(snapshot.threads).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
id: bootstrapThreadId,
|
||||||
|
projectId: bootstrapProjectId,
|
||||||
|
title: "New thread",
|
||||||
|
model: "gpt-5-codex",
|
||||||
|
branch: null,
|
||||||
|
worktreePath: null,
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
|
||||||
|
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
|
||||||
|
const persistenceLayer = makeSqlitePersistenceLive(path.join(stateDir, "state.sqlite")).pipe(
|
||||||
|
Layer.provide(NodeServices.layer),
|
||||||
|
);
|
||||||
|
const cwd = "/test/bootstrap-existing";
|
||||||
|
|
||||||
|
server = await createTestServer({
|
||||||
|
cwd,
|
||||||
|
stateDir,
|
||||||
|
persistenceLayer,
|
||||||
|
autoBootstrapProjectFromCwd: true,
|
||||||
|
});
|
||||||
|
let addr = server.address();
|
||||||
|
let port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||||
|
expect(port).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const firstWs = await connectWs(port);
|
||||||
|
connections.push(firstWs);
|
||||||
|
const firstWelcome = (await waitForMessage(firstWs)) as WsPush;
|
||||||
|
const firstBootstrapProjectId = (firstWelcome.data as { bootstrapProjectId?: string })
|
||||||
|
.bootstrapProjectId;
|
||||||
|
const firstBootstrapThreadId = (firstWelcome.data as { bootstrapThreadId?: string })
|
||||||
|
.bootstrapThreadId;
|
||||||
|
expect(firstBootstrapProjectId).toBeDefined();
|
||||||
|
expect(firstBootstrapThreadId).toBeDefined();
|
||||||
|
|
||||||
|
firstWs.close();
|
||||||
|
await closeTestServer();
|
||||||
|
server = null;
|
||||||
|
|
||||||
|
server = await createTestServer({
|
||||||
|
cwd,
|
||||||
|
stateDir,
|
||||||
|
persistenceLayer,
|
||||||
|
autoBootstrapProjectFromCwd: true,
|
||||||
|
});
|
||||||
|
addr = server.address();
|
||||||
|
port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||||
|
expect(port).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const secondWs = await connectWs(port);
|
||||||
|
connections.push(secondWs);
|
||||||
|
const secondWelcome = (await waitForMessage(secondWs)) as WsPush;
|
||||||
|
expect(secondWelcome.channel).toBe(WS_CHANNELS.serverWelcome);
|
||||||
|
expect(secondWelcome.data).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
cwd,
|
||||||
|
projectName: "bootstrap-existing",
|
||||||
|
bootstrapProjectId: firstBootstrapProjectId,
|
||||||
|
bootstrapThreadId: firstBootstrapThreadId,
|
||||||
|
}),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("logs outbound websocket push events in dev mode", async () => {
|
it("logs outbound websocket push events in dev mode", async () => {
|
||||||
@@ -960,6 +1168,8 @@ describe("WebSocket Server", () => {
|
|||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
assistantDeliveryMode: "streaming",
|
assistantDeliveryMode: "streaming",
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandboxMode: "workspace-write",
|
||||||
createdAt,
|
createdAt,
|
||||||
});
|
});
|
||||||
expect(startTurnResponse.error).toBeUndefined();
|
expect(startTurnResponse.error).toBeUndefined();
|
||||||
@@ -1301,6 +1511,7 @@ describe("WebSocket Server", () => {
|
|||||||
expect(pullResponse.result).toBeUndefined();
|
expect(pullResponse.result).toBeUndefined();
|
||||||
expect(pullResponse.error?.message).toContain("No upstream configured");
|
expect(pullResponse.error?.message).toContain("No upstream configured");
|
||||||
expect(pullCurrentBranch).toHaveBeenCalledWith("/repo/path");
|
expect(pullCurrentBranch).toHaveBeenCalledWith("/repo/path");
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("supports git.status over websocket", async () => {
|
it("supports git.status over websocket", async () => {
|
||||||
@@ -1315,7 +1526,7 @@ describe("WebSocket Server", () => {
|
|||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
openPr: null,
|
pr: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
const status = vi.fn(() => Effect.succeed(statusResult));
|
const status = vi.fn(() => Effect.succeed(statusResult));
|
||||||
|
|||||||
+320
-76
@@ -6,16 +6,19 @@
|
|||||||
*
|
*
|
||||||
* @module Server
|
* @module Server
|
||||||
*/
|
*/
|
||||||
import fs from "node:fs";
|
|
||||||
import http from "node:http";
|
import http from "node:http";
|
||||||
import path from "node:path";
|
|
||||||
import type { Duplex } from "node:stream";
|
import type { Duplex } from "node:stream";
|
||||||
|
|
||||||
|
import Mime from "@effect/platform-node/Mime";
|
||||||
import {
|
import {
|
||||||
CommandId,
|
CommandId,
|
||||||
|
type ClientOrchestrationCommand,
|
||||||
|
type OrchestrationCommand,
|
||||||
ORCHESTRATION_WS_CHANNELS,
|
ORCHESTRATION_WS_CHANNELS,
|
||||||
ORCHESTRATION_WS_METHODS,
|
ORCHESTRATION_WS_METHODS,
|
||||||
|
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
|
ThreadId,
|
||||||
TerminalEvent,
|
TerminalEvent,
|
||||||
WS_CHANNELS,
|
WS_CHANNELS,
|
||||||
WS_METHODS,
|
WS_METHODS,
|
||||||
@@ -24,7 +27,20 @@ import {
|
|||||||
WsResponse,
|
WsResponse,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||||
import { Cause, Effect, Exit, Layer, Ref, Schema, Scope, ServiceMap, Stream, Struct } from "effect";
|
import {
|
||||||
|
Cause,
|
||||||
|
Effect,
|
||||||
|
Exit,
|
||||||
|
FileSystem,
|
||||||
|
Layer,
|
||||||
|
Path,
|
||||||
|
Ref,
|
||||||
|
Schema,
|
||||||
|
Scope,
|
||||||
|
ServiceMap,
|
||||||
|
Stream,
|
||||||
|
Struct,
|
||||||
|
} from "effect";
|
||||||
import { WebSocketServer, type WebSocket } from "ws";
|
import { WebSocketServer, type WebSocket } from "ws";
|
||||||
|
|
||||||
import { createLogger } from "./logger";
|
import { createLogger } from "./logger";
|
||||||
@@ -41,21 +57,14 @@ import { clamp } from "effect/Number";
|
|||||||
import { Open } from "./open";
|
import { Open } from "./open";
|
||||||
import { ServerConfig } from "./config";
|
import { ServerConfig } from "./config";
|
||||||
import { GitCore } from "./git/Services/GitCore.ts";
|
import { GitCore } from "./git/Services/GitCore.ts";
|
||||||
|
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||||
const MIME_TYPES: Record<string, string> = {
|
import {
|
||||||
".html": "text/html; charset=utf-8",
|
ATTACHMENTS_ROUTE_PREFIX,
|
||||||
".js": "application/javascript; charset=utf-8",
|
normalizeAttachmentRelativePath,
|
||||||
".css": "text/css; charset=utf-8",
|
resolveAttachmentRelativePath,
|
||||||
".json": "application/json; charset=utf-8",
|
} from "./attachmentPaths";
|
||||||
".png": "image/png",
|
import { createAttachmentId, resolveAttachmentPath, resolveAttachmentPathById } from "./attachmentStore.ts";
|
||||||
".jpg": "image/jpeg",
|
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||||
".svg": "image/svg+xml",
|
|
||||||
".ico": "image/x-icon",
|
|
||||||
".woff": "font/woff",
|
|
||||||
".woff2": "font/woff2",
|
|
||||||
".ttf": "font/ttf",
|
|
||||||
".map": "application/json",
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ServerShape - Service API for server lifecycle control.
|
* ServerShape - Service API for server lifecycle control.
|
||||||
@@ -67,7 +76,7 @@ export interface ServerShape {
|
|||||||
readonly start: Effect.Effect<
|
readonly start: Effect.Effect<
|
||||||
http.Server,
|
http.Server,
|
||||||
ServerLifecycleError,
|
ServerLifecycleError,
|
||||||
Scope.Scope | ServerRuntimeServices | ServerConfig
|
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||||
>;
|
>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -166,7 +175,7 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
|
|||||||
export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||||
http.Server,
|
http.Server,
|
||||||
ServerLifecycleError,
|
ServerLifecycleError,
|
||||||
Scope.Scope | ServerRuntimeServices | ServerConfig
|
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||||
> {
|
> {
|
||||||
const serverConfig = yield* ServerConfig;
|
const serverConfig = yield* ServerConfig;
|
||||||
const {
|
const {
|
||||||
@@ -185,6 +194,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
const terminalManager = yield* TerminalManager;
|
const terminalManager = yield* TerminalManager;
|
||||||
const keybindingsManager = yield* Keybindings;
|
const keybindingsManager = yield* Keybindings;
|
||||||
const git = yield* GitCore;
|
const git = yield* GitCore;
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
|
||||||
yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
|
yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
|
||||||
Effect.catch((error) =>
|
Effect.catch((error) =>
|
||||||
@@ -229,59 +240,249 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
||||||
|
readonly command: ClientOrchestrationCommand;
|
||||||
|
}) {
|
||||||
|
if (input.command.type !== "thread.turn.start") {
|
||||||
|
return input.command as OrchestrationCommand;
|
||||||
|
}
|
||||||
|
const turnStartCommand = input.command;
|
||||||
|
|
||||||
|
const normalizedAttachments = yield* Effect.forEach(
|
||||||
|
turnStartCommand.message.attachments,
|
||||||
|
(attachment) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||||
|
if (!parsed || !parsed.mimeType.startsWith("image/")) {
|
||||||
|
return yield* new RouteRequestError({
|
||||||
|
message: `Invalid image attachment payload for '${attachment.name}'.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const bytes = Buffer.from(parsed.base64, "base64");
|
||||||
|
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||||
|
return yield* new RouteRequestError({
|
||||||
|
message: `Image attachment '${attachment.name}' is empty or too large.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const attachmentId = createAttachmentId(turnStartCommand.threadId);
|
||||||
|
if (!attachmentId) {
|
||||||
|
return yield* new RouteRequestError({
|
||||||
|
message: "Failed to create a safe attachment id.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const persistedAttachment = {
|
||||||
|
type: "image" as const,
|
||||||
|
id: attachmentId,
|
||||||
|
name: attachment.name,
|
||||||
|
mimeType: parsed.mimeType.toLowerCase(),
|
||||||
|
sizeBytes: bytes.byteLength,
|
||||||
|
};
|
||||||
|
|
||||||
|
const attachmentPath = resolveAttachmentPath({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
attachment: persistedAttachment,
|
||||||
|
});
|
||||||
|
if (!attachmentPath) {
|
||||||
|
return yield* new RouteRequestError({
|
||||||
|
message: `Failed to resolve persisted path for '${attachment.name}'.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
() =>
|
||||||
|
new RouteRequestError({
|
||||||
|
message: `Failed to create attachment directory for '${attachment.name}'.`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
() =>
|
||||||
|
new RouteRequestError({
|
||||||
|
message: `Failed to persist attachment '${attachment.name}'.`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return persistedAttachment;
|
||||||
|
}),
|
||||||
|
{ concurrency: 1 },
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...turnStartCommand,
|
||||||
|
message: {
|
||||||
|
...turnStartCommand.message,
|
||||||
|
attachments: normalizedAttachments,
|
||||||
|
},
|
||||||
|
} satisfies OrchestrationCommand;
|
||||||
|
});
|
||||||
|
|
||||||
// HTTP server — serves static files or redirects to Vite dev server
|
// HTTP server — serves static files or redirects to Vite dev server
|
||||||
const httpServer = http.createServer((req, res) => {
|
const httpServer = http.createServer((req, res) => {
|
||||||
// In dev mode, redirect to Vite dev server
|
const respond = (
|
||||||
if (devUrl) {
|
statusCode: number,
|
||||||
res.writeHead(302, { Location: devUrl.href });
|
headers: Record<string, string>,
|
||||||
res.end();
|
body?: string | Uint8Array,
|
||||||
return;
|
) => {
|
||||||
}
|
res.writeHead(statusCode, headers);
|
||||||
|
res.end(body);
|
||||||
|
};
|
||||||
|
|
||||||
// Serve static files from the web app build
|
void Effect.runPromise(
|
||||||
if (!staticDir) {
|
Effect.gen(function* () {
|
||||||
res.writeHead(503, { "Content-Type": "text/plain" });
|
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||||
res.end("No static directory configured and no dev URL set.");
|
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
|
||||||
let filePath = path.join(staticDir, url.pathname);
|
|
||||||
|
|
||||||
// SPA fallback: if no file extension and not found, serve index.html
|
|
||||||
const ext = path.extname(filePath);
|
|
||||||
if (!ext) {
|
|
||||||
filePath = path.join(filePath, "index.html");
|
|
||||||
}
|
|
||||||
|
|
||||||
fs.stat(filePath, (err, stats) => {
|
|
||||||
if (err || !stats?.isFile()) {
|
|
||||||
// SPA fallback
|
|
||||||
const indexPath = path.join(staticDir, "index.html");
|
|
||||||
fs.readFile(indexPath, (readErr, data) => {
|
|
||||||
if (readErr) {
|
|
||||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
||||||
res.end("Not Found");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
||||||
res.end(data);
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileExt = path.extname(filePath);
|
|
||||||
const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream";
|
|
||||||
|
|
||||||
fs.readFile(filePath, (readErr, data) => {
|
|
||||||
if (readErr) {
|
|
||||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
||||||
res.end("Internal Server Error");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
res.writeHead(200, { "Content-Type": contentType });
|
|
||||||
res.end(data);
|
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||||
});
|
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||||
|
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||||
|
if (!normalizedRelativePath) {
|
||||||
|
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isIdLookup =
|
||||||
|
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
|
||||||
|
const filePath = isIdLookup
|
||||||
|
? resolveAttachmentPathById({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
attachmentId: normalizedRelativePath,
|
||||||
|
})
|
||||||
|
: resolveAttachmentRelativePath({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
relativePath: normalizedRelativePath,
|
||||||
|
});
|
||||||
|
if (!filePath) {
|
||||||
|
respond(
|
||||||
|
isIdLookup ? 404 : 400,
|
||||||
|
{ "Content-Type": "text/plain" },
|
||||||
|
isIdLookup ? "Not Found" : "Invalid attachment path",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileInfo = yield* fileSystem
|
||||||
|
.stat(filePath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
respond(404, { "Content-Type": "text/plain" }, "Not Found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||||
|
res.writeHead(200, {
|
||||||
|
"Content-Type": contentType,
|
||||||
|
"Cache-Control": "public, max-age=31536000, immutable",
|
||||||
|
});
|
||||||
|
const streamExit = yield* Stream.runForEach(fileSystem.stream(filePath), (chunk) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
if (!res.destroyed) {
|
||||||
|
res.write(chunk);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
).pipe(Effect.exit);
|
||||||
|
if (streamExit._tag === "Failure") {
|
||||||
|
if (!res.destroyed) {
|
||||||
|
res.destroy();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!res.writableEnded) {
|
||||||
|
res.end();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// In dev mode, redirect to Vite dev server
|
||||||
|
if (devUrl) {
|
||||||
|
respond(302, { Location: devUrl.href });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serve static files from the web app build
|
||||||
|
if (!staticDir) {
|
||||||
|
respond(
|
||||||
|
503,
|
||||||
|
{ "Content-Type": "text/plain" },
|
||||||
|
"No static directory configured and no dev URL set.",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const staticRoot = path.resolve(staticDir);
|
||||||
|
const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname;
|
||||||
|
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
||||||
|
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
||||||
|
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
|
||||||
|
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
|
||||||
|
if (
|
||||||
|
staticRelativePath.length === 0 ||
|
||||||
|
hasRawLeadingParentSegment ||
|
||||||
|
hasPathTraversalSegment ||
|
||||||
|
staticRelativePath.includes("\0")
|
||||||
|
) {
|
||||||
|
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isWithinStaticRoot = (candidate: string) =>
|
||||||
|
candidate === staticRoot ||
|
||||||
|
candidate.startsWith(
|
||||||
|
staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
let filePath = path.resolve(staticRoot, staticRelativePath);
|
||||||
|
if (!isWithinStaticRoot(filePath)) {
|
||||||
|
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ext = path.extname(filePath);
|
||||||
|
if (!ext) {
|
||||||
|
filePath = path.resolve(filePath, "index.html");
|
||||||
|
if (!isWithinStaticRoot(filePath)) {
|
||||||
|
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileInfo = yield* fileSystem
|
||||||
|
.stat(filePath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
const indexPath = path.resolve(staticRoot, "index.html");
|
||||||
|
const indexData = yield* fileSystem
|
||||||
|
.readFile(indexPath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!indexData) {
|
||||||
|
respond(404, { "Content-Type": "text/plain" }, "Not Found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||||
|
const data = yield* fileSystem
|
||||||
|
.readFile(filePath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!data) {
|
||||||
|
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
respond(200, { "Content-Type": contentType }, data);
|
||||||
|
}),
|
||||||
|
).catch(() => {
|
||||||
|
if (!res.headersSent) {
|
||||||
|
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -337,22 +538,59 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
|
|
||||||
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
|
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
|
||||||
|
|
||||||
|
let welcomeBootstrapProjectId: ProjectId | undefined;
|
||||||
|
let welcomeBootstrapThreadId: ThreadId | undefined;
|
||||||
|
|
||||||
if (autoBootstrapProjectFromCwd) {
|
if (autoBootstrapProjectFromCwd) {
|
||||||
yield* Effect.gen(function* () {
|
yield* Effect.gen(function* () {
|
||||||
const snapshot = yield* projectionReadModelQuery.getSnapshot();
|
const snapshot = yield* projectionReadModelQuery.getSnapshot();
|
||||||
const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd);
|
const existingProject = snapshot.projects.find(
|
||||||
if (!existing) {
|
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
|
||||||
|
);
|
||||||
|
let bootstrapProjectId: ProjectId;
|
||||||
|
let bootstrapProjectDefaultModel: string;
|
||||||
|
|
||||||
|
if (!existingProject) {
|
||||||
const createdAt = new Date().toISOString();
|
const createdAt = new Date().toISOString();
|
||||||
const projectName = path.basename(cwd) || "project";
|
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
|
||||||
|
const bootstrapProjectTitle = path.basename(cwd) || "project";
|
||||||
|
bootstrapProjectDefaultModel = "gpt-5-codex";
|
||||||
yield* orchestrationEngine.dispatch({
|
yield* orchestrationEngine.dispatch({
|
||||||
type: "project.create",
|
type: "project.create",
|
||||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||||
projectId: ProjectId.makeUnsafe(crypto.randomUUID()),
|
projectId: bootstrapProjectId,
|
||||||
title: projectName,
|
title: bootstrapProjectTitle,
|
||||||
workspaceRoot: cwd,
|
workspaceRoot: cwd,
|
||||||
defaultModel: "gpt-5-codex",
|
defaultModel: bootstrapProjectDefaultModel,
|
||||||
createdAt,
|
createdAt,
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
bootstrapProjectId = existingProject.id;
|
||||||
|
bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingThread = snapshot.threads.find(
|
||||||
|
(thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null,
|
||||||
|
);
|
||||||
|
if (!existingThread) {
|
||||||
|
const createdAt = new Date().toISOString();
|
||||||
|
const threadId = ThreadId.makeUnsafe(crypto.randomUUID());
|
||||||
|
yield* orchestrationEngine.dispatch({
|
||||||
|
type: "thread.create",
|
||||||
|
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||||
|
threadId,
|
||||||
|
projectId: bootstrapProjectId,
|
||||||
|
title: "New thread",
|
||||||
|
model: bootstrapProjectDefaultModel,
|
||||||
|
branch: null,
|
||||||
|
worktreePath: null,
|
||||||
|
createdAt,
|
||||||
|
});
|
||||||
|
welcomeBootstrapProjectId = bootstrapProjectId;
|
||||||
|
welcomeBootstrapThreadId = threadId;
|
||||||
|
} else {
|
||||||
|
welcomeBootstrapProjectId = bootstrapProjectId;
|
||||||
|
welcomeBootstrapThreadId = existingThread.id;
|
||||||
}
|
}
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
@@ -368,7 +606,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
|
|
||||||
case ORCHESTRATION_WS_METHODS.dispatchCommand: {
|
case ORCHESTRATION_WS_METHODS.dispatchCommand: {
|
||||||
const { command } = request.body;
|
const { command } = request.body;
|
||||||
return yield* orchestrationEngine.dispatch(command);
|
const normalizedCommand = yield* normalizeDispatchCommand({ command });
|
||||||
|
return yield* orchestrationEngine.dispatch(normalizedCommand);
|
||||||
}
|
}
|
||||||
|
|
||||||
case ORCHESTRATION_WS_METHODS.getTurnDiff: {
|
case ORCHESTRATION_WS_METHODS.getTurnDiff: {
|
||||||
@@ -581,7 +820,12 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
const welcome: WsPush = {
|
const welcome: WsPush = {
|
||||||
type: "push",
|
type: "push",
|
||||||
channel: WS_CHANNELS.serverWelcome,
|
channel: WS_CHANNELS.serverWelcome,
|
||||||
data: { cwd, projectName },
|
data: {
|
||||||
|
cwd,
|
||||||
|
projectName,
|
||||||
|
...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
|
||||||
|
...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
logOutgoingPush(welcome, 1);
|
logOutgoingPush(welcome, 1);
|
||||||
ws.send(JSON.stringify(welcome));
|
ws.send(JSON.stringify(welcome));
|
||||||
|
|||||||
@@ -14,7 +14,9 @@
|
|||||||
"importFromBarrel": "error",
|
"importFromBarrel": "error",
|
||||||
"anyUnknownInErrorContext": "warning",
|
"anyUnknownInErrorContext": "warning",
|
||||||
"instanceOfSchema": "warning",
|
"instanceOfSchema": "warning",
|
||||||
"deterministicKeys": "warning"
|
"deterministicKeys": "warning",
|
||||||
|
"preferSchemaOverJson": "off",
|
||||||
|
"globalErrorInEffectFailure": "off"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@t3tools/web",
|
"name": "@t3tools/web",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0-alpha.4",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -22,14 +22,13 @@
|
|||||||
"@xterm/xterm": "^6.0.0",
|
"@xterm/xterm": "^6.0.0",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
"highlight.js": "^11.11.1",
|
|
||||||
"lucide-react": "^0.564.0",
|
"lucide-react": "^0.564.0",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"rehype-highlight": "^7.0.2",
|
|
||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"tailwind-merge": "^3.4.0"
|
"tailwind-merge": "^3.4.0",
|
||||||
|
"zustand": "^5.0.11"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@effect/language-service": "catalog:",
|
"@effect/language-service": "catalog:",
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||||
|
|
||||||
|
describe("normalizeCustomModelSlugs", () => {
|
||||||
|
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||||
|
expect(
|
||||||
|
normalizeCustomModelSlugs([
|
||||||
|
" custom/internal-model ",
|
||||||
|
"gpt-5.3-codex",
|
||||||
|
"5.3",
|
||||||
|
"custom/internal-model",
|
||||||
|
"",
|
||||||
|
null,
|
||||||
|
]),
|
||||||
|
).toEqual(["custom/internal-model"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getAppModelOptions", () => {
|
||||||
|
it("appends saved custom models after the built-in options", () => {
|
||||||
|
const options = getAppModelOptions(["custom/internal-model"]);
|
||||||
|
|
||||||
|
expect(options.map((option) => option.slug)).toEqual([
|
||||||
|
"gpt-5.3-codex",
|
||||||
|
"gpt-5.3-codex-spark",
|
||||||
|
"gpt-5.2-codex",
|
||||||
|
"gpt-5.2",
|
||||||
|
"custom/internal-model",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the currently selected custom model available even if it is no longer saved", () => {
|
||||||
|
const options = getAppModelOptions([], "custom/selected-model");
|
||||||
|
|
||||||
|
expect(options.at(-1)).toEqual({
|
||||||
|
slug: "custom/selected-model",
|
||||||
|
name: "custom/selected-model",
|
||||||
|
isCustom: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import { useCallback, useSyncExternalStore } from "react";
|
import { useCallback, useSyncExternalStore } from "react";
|
||||||
import { Option, Schema } from "effect";
|
import { Option, Schema } from "effect";
|
||||||
|
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||||
|
|
||||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||||
|
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||||
|
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||||
|
const BUILT_IN_MODEL_SLUGS = new Set<string>(MODEL_OPTIONS.map((option) => option.slug));
|
||||||
|
|
||||||
const AppSettingsSchema = Schema.Struct({
|
const AppSettingsSchema = Schema.Struct({
|
||||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||||
@@ -14,8 +18,16 @@ const AppSettingsSchema = Schema.Struct({
|
|||||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
enableAssistantStreaming: Schema.Boolean.pipe(
|
||||||
Schema.withConstructorDefault(() => Option.some(false)),
|
Schema.withConstructorDefault(() => Option.some(false)),
|
||||||
),
|
),
|
||||||
|
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||||
|
Schema.withConstructorDefault(() => Option.some([])),
|
||||||
|
),
|
||||||
});
|
});
|
||||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||||
|
export interface AppModelOption {
|
||||||
|
slug: string;
|
||||||
|
name: string;
|
||||||
|
isCustom: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
||||||
|
|
||||||
@@ -23,6 +35,76 @@ let listeners: Array<() => void> = [];
|
|||||||
let cachedRawSettings: string | null | undefined;
|
let cachedRawSettings: string | null | undefined;
|
||||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||||
|
|
||||||
|
export function normalizeCustomModelSlugs(
|
||||||
|
models: Iterable<string | null | undefined>,
|
||||||
|
): AppSettings["customCodexModels"] {
|
||||||
|
const normalizedModels: string[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
|
||||||
|
for (const candidate of models) {
|
||||||
|
const normalized = normalizeModelSlug(candidate);
|
||||||
|
if (
|
||||||
|
!normalized ||
|
||||||
|
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
|
||||||
|
BUILT_IN_MODEL_SLUGS.has(normalized) ||
|
||||||
|
seen.has(normalized)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
seen.add(normalized);
|
||||||
|
normalizedModels.push(normalized);
|
||||||
|
if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalizedModels;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||||
|
return {
|
||||||
|
...settings,
|
||||||
|
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAppModelOptions(
|
||||||
|
customModels: readonly string[],
|
||||||
|
selectedModel?: string | null,
|
||||||
|
): AppModelOption[] {
|
||||||
|
const options: AppModelOption[] = MODEL_OPTIONS.map(({ slug, name }) => ({
|
||||||
|
slug,
|
||||||
|
name,
|
||||||
|
isCustom: false,
|
||||||
|
}));
|
||||||
|
const seen = new Set(options.map((option) => option.slug));
|
||||||
|
|
||||||
|
for (const slug of normalizeCustomModelSlugs(customModels)) {
|
||||||
|
if (seen.has(slug)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
seen.add(slug);
|
||||||
|
options.push({
|
||||||
|
slug,
|
||||||
|
name: slug,
|
||||||
|
isCustom: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedSelectedModel = normalizeModelSlug(selectedModel);
|
||||||
|
if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
|
||||||
|
options.push({
|
||||||
|
slug: normalizedSelectedModel,
|
||||||
|
name: normalizedSelectedModel,
|
||||||
|
isCustom: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
function emitChange(): void {
|
function emitChange(): void {
|
||||||
for (const listener of listeners) {
|
for (const listener of listeners) {
|
||||||
listener();
|
listener();
|
||||||
@@ -35,7 +117,7 @@ function parsePersistedSettings(value: string | null): AppSettings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value);
|
return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
|
||||||
} catch {
|
} catch {
|
||||||
return DEFAULT_APP_SETTINGS;
|
return DEFAULT_APP_SETTINGS;
|
||||||
}
|
}
|
||||||
@@ -96,10 +178,12 @@ export function useAppSettings() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||||
const next = Schema.decodeSync(AppSettingsSchema)({
|
const next = normalizeAppSettings(
|
||||||
...getAppSettingsSnapshot(),
|
Schema.decodeSync(AppSettingsSchema)({
|
||||||
...patch,
|
...getAppSettingsSnapshot(),
|
||||||
});
|
...patch,
|
||||||
|
}),
|
||||||
|
);
|
||||||
persistSettings(next);
|
persistSettings(next);
|
||||||
emitChange();
|
emitChange();
|
||||||
}, []);
|
}, []);
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import { ThreadId, type GitBranch } from "@t3tools/contracts";
|
import { ThreadId, type GitBranch } from "@t3tools/contracts";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
import {
|
||||||
|
dedupeRemoteBranchesWithLocalMatches,
|
||||||
|
deriveLocalBranchNameFromRemoteRef,
|
||||||
|
deriveSyncedLocalBranch,
|
||||||
|
} from "./BranchToolbar.logic";
|
||||||
|
|
||||||
const branches: GitBranch[] = [
|
const branches: GitBranch[] = [
|
||||||
{
|
{
|
||||||
@@ -57,3 +61,124 @@ describe("deriveSyncedLocalBranch", () => {
|
|||||||
expect(result).toBeNull();
|
expect(result).toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -8,6 +8,54 @@ interface DeriveSyncedLocalBranchInput {
|
|||||||
queryBranches: ReadonlyArray<GitBranch> | undefined;
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (remoteName) {
|
||||||
|
const remotePrefix = `${remoteName}/`;
|
||||||
|
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
|
||||||
|
candidates.add(branchName.slice(remotePrefix.length));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function deriveSyncedLocalBranch({
|
export function deriveSyncedLocalBranch({
|
||||||
activeThreadId,
|
activeThreadId,
|
||||||
activeWorktreePath,
|
activeWorktreePath,
|
||||||
|
|||||||
@@ -9,8 +9,13 @@ import {
|
|||||||
gitCreateBranchAndCheckoutMutationOptions,
|
gitCreateBranchAndCheckoutMutationOptions,
|
||||||
} from "../lib/gitReactQuery";
|
} from "../lib/gitReactQuery";
|
||||||
import { readNativeApi } from "../nativeApi";
|
import { readNativeApi } from "../nativeApi";
|
||||||
|
import { useComposerDraftStore } from "../composerDraftStore";
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
import {
|
||||||
|
dedupeRemoteBranchesWithLocalMatches,
|
||||||
|
deriveLocalBranchNameFromRemoteRef,
|
||||||
|
deriveSyncedLocalBranch,
|
||||||
|
} from "./BranchToolbar.logic";
|
||||||
import { Button } from "./ui/button";
|
import { Button } from "./ui/button";
|
||||||
import {
|
import {
|
||||||
Combobox,
|
Combobox,
|
||||||
@@ -39,27 +44,35 @@ export default function BranchToolbar({
|
|||||||
onComposerFocusRequest,
|
onComposerFocusRequest,
|
||||||
}: BranchToolbarProps) {
|
}: BranchToolbarProps) {
|
||||||
const { state, dispatch } = useStore();
|
const { state, dispatch } = useStore();
|
||||||
|
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
|
||||||
|
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||||
const [branchQuery, setBranchQuery] = useState("");
|
const [branchQuery, setBranchQuery] = useState("");
|
||||||
|
|
||||||
const activeThread = state.threads.find((thread) => thread.id === threadId);
|
const serverThread = state.threads.find((thread) => thread.id === threadId);
|
||||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
|
||||||
const activeThreadId = activeThread?.id;
|
const activeProject = state.projects.find((project) => project.id === activeProjectId);
|
||||||
const activeThreadBranch = activeThread?.branch ?? null;
|
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
|
||||||
const activeWorktreePath = activeThread?.worktreePath ?? null;
|
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
|
||||||
|
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||||
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
|
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
|
||||||
|
const hasServerThread = serverThread !== undefined;
|
||||||
|
const effectiveEnvMode: "local" | "worktree" =
|
||||||
|
activeWorktreePath || (!hasServerThread && draftThread?.envMode === "worktree")
|
||||||
|
? "worktree"
|
||||||
|
: envMode;
|
||||||
|
|
||||||
// ── Queries ───────────────────────────────────────────────────────────
|
// ── Queries ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||||
|
|
||||||
const branches = branchesQuery.data?.branches ?? [];
|
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
|
||||||
const branchNames = branches.map((branch) => branch.name);
|
const branchNames = branches.map((branch) => branch.name);
|
||||||
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
|
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
|
||||||
const trimmedBranchQuery = branchQuery.trim();
|
const trimmedBranchQuery = branchQuery.trim();
|
||||||
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0;
|
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
|
||||||
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
|
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
|
||||||
const createBranchItemValue = canCreateBranch
|
const createBranchItemValue = canCreateBranch
|
||||||
? `__create_new_branch__:${trimmedBranchQuery}`
|
? `__create_new_branch__:${trimmedBranchQuery}`
|
||||||
@@ -84,14 +97,14 @@ export default function BranchToolbar({
|
|||||||
const syncedBranch = deriveSyncedLocalBranch({
|
const syncedBranch = deriveSyncedLocalBranch({
|
||||||
activeThreadId,
|
activeThreadId,
|
||||||
activeWorktreePath,
|
activeWorktreePath,
|
||||||
envMode,
|
envMode: effectiveEnvMode,
|
||||||
activeThreadBranch,
|
activeThreadBranch,
|
||||||
queryBranches,
|
queryBranches,
|
||||||
});
|
});
|
||||||
if (!activeThreadId || !syncedBranch) return;
|
if (!activeThreadId || !syncedBranch) return;
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
|
|
||||||
if (api) {
|
if (api && hasServerThread) {
|
||||||
void api.orchestration.dispatchCommand({
|
void api.orchestration.dispatchCommand({
|
||||||
type: "thread.meta.update",
|
type: "thread.meta.update",
|
||||||
commandId: newCommandId(),
|
commandId: newCommandId(),
|
||||||
@@ -100,13 +113,30 @@ export default function BranchToolbar({
|
|||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
dispatch({
|
if (hasServerThread) {
|
||||||
type: "SET_THREAD_BRANCH",
|
dispatch({
|
||||||
threadId: activeThreadId,
|
type: "SET_THREAD_BRANCH",
|
||||||
|
threadId: activeThreadId,
|
||||||
|
branch: syncedBranch,
|
||||||
|
worktreePath: null,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setDraftThreadContext(threadId, {
|
||||||
branch: syncedBranch,
|
branch: syncedBranch,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
});
|
});
|
||||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
}, [
|
||||||
|
activeThreadId,
|
||||||
|
activeWorktreePath,
|
||||||
|
activeThreadBranch,
|
||||||
|
queryBranches,
|
||||||
|
effectiveEnvMode,
|
||||||
|
dispatch,
|
||||||
|
hasServerThread,
|
||||||
|
setDraftThreadContext,
|
||||||
|
threadId,
|
||||||
|
]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isBranchMenuOpen) return;
|
if (isBranchMenuOpen) return;
|
||||||
@@ -125,7 +155,7 @@ export default function BranchToolbar({
|
|||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
// If the effective cwd is about to change, stop the running session so the
|
// If the effective cwd is about to change, stop the running session so the
|
||||||
// next message creates a new one with the correct cwd.
|
// next message creates a new one with the correct cwd.
|
||||||
const sessionId = activeThread?.session?.sessionId;
|
const sessionId = serverThread?.session?.sessionId;
|
||||||
if (sessionId && worktreePath !== activeWorktreePath && api) {
|
if (sessionId && worktreePath !== activeWorktreePath && api) {
|
||||||
void api.orchestration
|
void api.orchestration
|
||||||
.dispatchCommand({
|
.dispatchCommand({
|
||||||
@@ -136,7 +166,7 @@ export default function BranchToolbar({
|
|||||||
})
|
})
|
||||||
.catch(() => undefined);
|
.catch(() => undefined);
|
||||||
}
|
}
|
||||||
if (api) {
|
if (api && hasServerThread) {
|
||||||
void api.orchestration.dispatchCommand({
|
void api.orchestration.dispatchCommand({
|
||||||
type: "thread.meta.update",
|
type: "thread.meta.update",
|
||||||
commandId: newCommandId(),
|
commandId: newCommandId(),
|
||||||
@@ -145,7 +175,15 @@ export default function BranchToolbar({
|
|||||||
worktreePath,
|
worktreePath,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
|
if (hasServerThread) {
|
||||||
|
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setDraftThreadContext(threadId, {
|
||||||
|
branch,
|
||||||
|
worktreePath,
|
||||||
|
envMode: effectiveEnvMode,
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const selectBranch = (branch: GitBranch) => {
|
const selectBranch = (branch: GitBranch) => {
|
||||||
@@ -153,7 +191,7 @@ export default function BranchToolbar({
|
|||||||
if (!api || !activeThreadId || !branchCwd) return;
|
if (!api || !activeThreadId || !branchCwd) return;
|
||||||
|
|
||||||
// For new worktree mode, selecting a branch picks the base branch.
|
// For new worktree mode, selecting a branch picks the base branch.
|
||||||
if (envMode === "worktree" && !envLocked && !activeWorktreePath) {
|
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
|
||||||
setThreadError(null);
|
setThreadError(null);
|
||||||
setThreadBranch(branch.name, null);
|
setThreadBranch(branch.name, null);
|
||||||
setIsBranchMenuOpen(false);
|
setIsBranchMenuOpen(false);
|
||||||
@@ -174,10 +212,21 @@ export default function BranchToolbar({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const selectedBranchName = branch.isRemote
|
||||||
|
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
||||||
|
: branch.name;
|
||||||
|
|
||||||
checkoutMutation.mutate(branch.name, {
|
checkoutMutation.mutate(branch.name, {
|
||||||
onSuccess: () => {
|
onSuccess: async () => {
|
||||||
setThreadError(null);
|
setThreadError(null);
|
||||||
setThreadBranch(branch.name, activeWorktreePath);
|
let nextBranchName = selectedBranchName;
|
||||||
|
if (branch.isRemote) {
|
||||||
|
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||||
|
if (status?.branch) {
|
||||||
|
nextBranchName = status.branch;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setThreadBranch(nextBranchName, activeWorktreePath);
|
||||||
setIsBranchMenuOpen(false);
|
setIsBranchMenuOpen(false);
|
||||||
onComposerFocusRequest?.();
|
onComposerFocusRequest?.();
|
||||||
},
|
},
|
||||||
@@ -206,7 +255,7 @@ export default function BranchToolbar({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!activeThread || !activeProject) return null;
|
if (!activeThreadId || !activeProject) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
|
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
|
||||||
@@ -221,9 +270,11 @@ export default function BranchToolbar({
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||||
size="xs"
|
size="xs"
|
||||||
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
|
onClick={() =>
|
||||||
|
onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{envMode === "worktree" ? "New worktree" : "Local"}
|
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -233,7 +284,7 @@ export default function BranchToolbar({
|
|||||||
autoHighlight
|
autoHighlight
|
||||||
onOpenChange={(open) => setIsBranchMenuOpen(open)}
|
onOpenChange={(open) => setIsBranchMenuOpen(open)}
|
||||||
open={isBranchMenuOpen}
|
open={isBranchMenuOpen}
|
||||||
value={activeThread.branch}
|
value={activeThreadBranch}
|
||||||
>
|
>
|
||||||
<ComboboxTrigger
|
<ComboboxTrigger
|
||||||
render={<Button variant="ghost" size="xs" />}
|
render={<Button variant="ghost" size="xs" />}
|
||||||
@@ -241,10 +292,10 @@ export default function BranchToolbar({
|
|||||||
disabled={branchesQuery.isLoading}
|
disabled={branchesQuery.isLoading}
|
||||||
>
|
>
|
||||||
<span className="max-w-[240px] truncate">
|
<span className="max-w-[240px] truncate">
|
||||||
{activeThread.branch
|
{activeThreadBranch
|
||||||
? envMode === "worktree" && !activeWorktreePath
|
? effectiveEnvMode === "worktree" && !activeWorktreePath
|
||||||
? `From ${activeThread.branch}`
|
? `From ${activeThreadBranch}`
|
||||||
: activeThread.branch
|
: activeThreadBranch
|
||||||
: "Select branch"}
|
: "Select branch"}
|
||||||
</span>
|
</span>
|
||||||
<ChevronDownIcon />
|
<ChevronDownIcon />
|
||||||
@@ -283,23 +334,28 @@ export default function BranchToolbar({
|
|||||||
|
|
||||||
const hasSecondaryWorktree =
|
const hasSecondaryWorktree =
|
||||||
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
|
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
|
||||||
|
const badge = branch.current
|
||||||
|
? "current"
|
||||||
|
: hasSecondaryWorktree
|
||||||
|
? "worktree"
|
||||||
|
: branch.isRemote
|
||||||
|
? "remote"
|
||||||
|
: branch.isDefault
|
||||||
|
? "default"
|
||||||
|
: null;
|
||||||
return (
|
return (
|
||||||
<ComboboxItem
|
<ComboboxItem
|
||||||
hideIndicator
|
hideIndicator
|
||||||
key={itemValue}
|
key={itemValue}
|
||||||
value={itemValue}
|
value={itemValue}
|
||||||
className={
|
className={
|
||||||
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined
|
itemValue === activeThreadBranch ? "bg-accent text-foreground" : undefined
|
||||||
}
|
}
|
||||||
onClick={() => selectBranch(branch)}
|
onClick={() => selectBranch(branch)}
|
||||||
>
|
>
|
||||||
<div className="flex w-full items-center justify-between gap-2">
|
<div className="flex w-full items-center justify-between gap-2">
|
||||||
<span className="truncate">{itemValue}</span>
|
<span className="truncate">{itemValue}</span>
|
||||||
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
|
{badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
|
||||||
<span className="shrink-0 text-[10px] text-muted-foreground/45">
|
|
||||||
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</ComboboxItem>
|
</ComboboxItem>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,18 +1,207 @@
|
|||||||
import { memo, useMemo } from "react";
|
import {
|
||||||
|
getSharedHighlighter,
|
||||||
|
type DiffsHighlighter,
|
||||||
|
type SupportedLanguages,
|
||||||
|
} from "@pierre/diffs";
|
||||||
|
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||||
|
import {
|
||||||
|
Children,
|
||||||
|
Suspense,
|
||||||
|
isValidElement,
|
||||||
|
use,
|
||||||
|
useCallback,
|
||||||
|
memo,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
type ReactNode,
|
||||||
|
} from "react";
|
||||||
import type { Components } from "react-markdown";
|
import type { Components } from "react-markdown";
|
||||||
import ReactMarkdown from "react-markdown";
|
import ReactMarkdown from "react-markdown";
|
||||||
import rehypeHighlight from "rehype-highlight";
|
|
||||||
import remarkGfm from "remark-gfm";
|
import remarkGfm from "remark-gfm";
|
||||||
import { readNativeApi } from "../nativeApi";
|
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||||
|
import { fnv1a32 } from "../lib/diffRendering";
|
||||||
|
import { LRUCache } from "../lib/lruCache";
|
||||||
|
import { useTheme } from "../hooks/useTheme";
|
||||||
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||||
|
import { readNativeApi } from "../nativeApi";
|
||||||
import { preferredTerminalEditor } from "../terminal-links";
|
import { preferredTerminalEditor } from "../terminal-links";
|
||||||
|
|
||||||
interface ChatMarkdownProps {
|
interface ChatMarkdownProps {
|
||||||
text: string;
|
text: string;
|
||||||
cwd: string | undefined;
|
cwd: string | undefined;
|
||||||
|
isStreaming?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
|
||||||
|
const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
|
||||||
|
const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
|
||||||
|
const highlightedCodeCache = new LRUCache<string>(
|
||||||
|
MAX_HIGHLIGHT_CACHE_ENTRIES,
|
||||||
|
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||||
|
);
|
||||||
|
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||||
|
|
||||||
|
function extractFenceLanguage(className: string | undefined): string {
|
||||||
|
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
|
||||||
|
return match?.[1] ?? "text";
|
||||||
|
}
|
||||||
|
|
||||||
|
function nodeToPlainText(node: ReactNode): string {
|
||||||
|
if (typeof node === "string" || typeof node === "number") {
|
||||||
|
return String(node);
|
||||||
|
}
|
||||||
|
if (Array.isArray(node)) {
|
||||||
|
return node.map((child) => nodeToPlainText(child)).join("");
|
||||||
|
}
|
||||||
|
if (isValidElement<{ children?: ReactNode }>(node)) {
|
||||||
|
return nodeToPlainText(node.props.children);
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractCodeBlock(
|
||||||
|
children: ReactNode,
|
||||||
|
): { className: string | undefined; code: string } | null {
|
||||||
|
const childNodes = Children.toArray(children);
|
||||||
|
if (childNodes.length !== 1) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const onlyChild = childNodes[0];
|
||||||
|
if (
|
||||||
|
!isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
|
||||||
|
onlyChild.type !== "code"
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
className: onlyChild.props.className,
|
||||||
|
code: nodeToPlainText(onlyChild.props.children),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
|
||||||
|
return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function estimateHighlightedSize(html: string, code: string): number {
|
||||||
|
return Math.max(html.length * 2, code.length * 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||||
|
const cached = highlighterPromiseCache.get(language);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
const promise = getSharedHighlighter({
|
||||||
|
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||||
|
langs: [language as SupportedLanguages],
|
||||||
|
preferredHighlighter: "shiki-js",
|
||||||
|
});
|
||||||
|
highlighterPromiseCache.set(language, promise);
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
const handleCopy = useCallback(() => {
|
||||||
|
if (typeof navigator === "undefined" || navigator.clipboard == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void navigator.clipboard
|
||||||
|
.writeText(code)
|
||||||
|
.then(() => {
|
||||||
|
if (copiedTimerRef.current != null) {
|
||||||
|
clearTimeout(copiedTimerRef.current);
|
||||||
|
}
|
||||||
|
setCopied(true);
|
||||||
|
copiedTimerRef.current = setTimeout(() => {
|
||||||
|
setCopied(false);
|
||||||
|
copiedTimerRef.current = null;
|
||||||
|
}, 1200);
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
}, [code]);
|
||||||
|
|
||||||
|
useEffect(
|
||||||
|
() => () => {
|
||||||
|
if (copiedTimerRef.current != null) {
|
||||||
|
clearTimeout(copiedTimerRef.current);
|
||||||
|
copiedTimerRef.current = null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="chat-markdown-codeblock">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="chat-markdown-copy-button"
|
||||||
|
onClick={handleCopy}
|
||||||
|
title={copied ? "Copied" : "Copy code"}
|
||||||
|
aria-label={copied ? "Copied" : "Copy code"}
|
||||||
|
>
|
||||||
|
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||||
|
</button>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SuspenseShikiCodeBlockProps {
|
||||||
|
className: string | undefined;
|
||||||
|
code: string;
|
||||||
|
themeName: DiffThemeName;
|
||||||
|
isStreaming: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SuspenseShikiCodeBlock({
|
||||||
|
className,
|
||||||
|
code,
|
||||||
|
themeName,
|
||||||
|
isStreaming,
|
||||||
|
}: SuspenseShikiCodeBlockProps) {
|
||||||
|
const language = extractFenceLanguage(className);
|
||||||
|
const cacheKey = createHighlightCacheKey(code, language, themeName);
|
||||||
|
const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
|
||||||
|
|
||||||
|
if (cachedHighlightedHtml != null) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="chat-markdown-shiki"
|
||||||
|
dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const highlighter = use(getHighlighterPromise(language));
|
||||||
|
const highlightedHtml = useMemo(
|
||||||
|
() => highlighter.codeToHtml(code, { lang: language, theme: themeName }),
|
||||||
|
[code, highlighter, language, themeName],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isStreaming) {
|
||||||
|
highlightedCodeCache.set(
|
||||||
|
cacheKey,
|
||||||
|
highlightedHtml,
|
||||||
|
estimateHighlightedSize(highlightedHtml, code),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, [cacheKey, code, highlightedHtml, isStreaming]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||||
|
const { resolvedTheme } = useTheme();
|
||||||
|
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||||
const markdownComponents = useMemo<Components>(
|
const markdownComponents = useMemo<Components>(
|
||||||
() => ({
|
() => ({
|
||||||
a({ node: _node, href, ...props }) {
|
a({ node: _node, href, ...props }) {
|
||||||
@@ -38,17 +227,32 @@ function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
pre({ node: _node, children, ...props }) {
|
||||||
|
const codeBlock = extractCodeBlock(children);
|
||||||
|
if (!codeBlock) {
|
||||||
|
return <pre {...props}>{children}</pre>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MarkdownCodeBlock code={codeBlock.code}>
|
||||||
|
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||||
|
<SuspenseShikiCodeBlock
|
||||||
|
className={codeBlock.className}
|
||||||
|
code={codeBlock.code}
|
||||||
|
themeName={diffThemeName}
|
||||||
|
isStreaming={isStreaming}
|
||||||
|
/>
|
||||||
|
</Suspense>
|
||||||
|
</MarkdownCodeBlock>
|
||||||
|
);
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
[cwd],
|
[cwd, diffThemeName, isStreaming],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
|
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
|
||||||
<ReactMarkdown
|
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||||
remarkPlugins={[remarkGfm]}
|
|
||||||
rehypePlugins={[[rehypeHighlight, { detect: true, ignoreMissing: true }]]}
|
|
||||||
components={markdownComponents}
|
|
||||||
>
|
|
||||||
{text}
|
{text}
|
||||||
</ReactMarkdown>
|
</ReactMarkdown>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+1252
-496
File diff suppressed because it is too large.
Load diff
@@ -7,16 +7,83 @@ import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "luci
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||||
import { cn } from "~/lib/utils";
|
import { cn } from "~/lib/utils";
|
||||||
|
import { readNativeApi } from "../nativeApi";
|
||||||
|
import { preferredTerminalEditor, resolvePathLinkTarget } from "../terminal-links";
|
||||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||||
import { isElectron } from "../env";
|
import { isElectron } from "../env";
|
||||||
import { useTheme } from "../hooks/useTheme";
|
import { useTheme } from "../hooks/useTheme";
|
||||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||||
|
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||||
|
|
||||||
type DiffRenderMode = "stacked" | "split";
|
type DiffRenderMode = "stacked" | "split";
|
||||||
type DiffThemeType = "light" | "dark" | "system";
|
type DiffThemeType = "light" | "dark";
|
||||||
|
|
||||||
|
const DIFF_PANEL_UNSAFE_CSS = `
|
||||||
|
[data-diffs-header],
|
||||||
|
[data-diff],
|
||||||
|
[data-file],
|
||||||
|
[data-error-wrapper],
|
||||||
|
[data-virtualizer-buffer] {
|
||||||
|
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||||
|
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||||
|
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||||
|
--diffs-token-light-bg: transparent;
|
||||||
|
--diffs-token-dark-bg: transparent;
|
||||||
|
|
||||||
|
--diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
|
||||||
|
--diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
|
||||||
|
--diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
|
||||||
|
--diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
|
||||||
|
|
||||||
|
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
|
||||||
|
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
|
||||||
|
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
|
||||||
|
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
|
||||||
|
|
||||||
|
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
|
||||||
|
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
|
||||||
|
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
|
||||||
|
--diffs-bg-deletion-emphasis-override: color-mix(
|
||||||
|
in srgb,
|
||||||
|
var(--background) 80%,
|
||||||
|
var(--destructive)
|
||||||
|
);
|
||||||
|
|
||||||
|
background-color: var(--diffs-bg) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-file-info] {
|
||||||
|
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||||
|
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 =
|
type RenderablePatch =
|
||||||
| {
|
| {
|
||||||
@@ -102,6 +169,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
||||||
const activeThreadId = routeThreadId;
|
const activeThreadId = routeThreadId;
|
||||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||||
|
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||||
|
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||||
useTurnDiffSummaries(activeThread);
|
useTurnDiffSummaries(activeThread);
|
||||||
const orderedTurnDiffSummaries = useMemo(
|
const orderedTurnDiffSummaries = useMemo(
|
||||||
@@ -222,6 +291,18 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
target?.scrollIntoView({ block: "nearest" });
|
target?.scrollIntoView({ block: "nearest" });
|
||||||
}, [selectedFilePath, renderableFiles]);
|
}, [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) => {
|
const selectTurn = (turnId: TurnId) => {
|
||||||
if (!activeThread) return;
|
if (!activeThread) return;
|
||||||
void navigate({
|
void navigate({
|
||||||
@@ -421,7 +502,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-full min-w-0 flex-col bg-card",
|
"flex h-full min-w-0 flex-col bg-background",
|
||||||
mode === "inline"
|
mode === "inline"
|
||||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||||
: "w-full",
|
: "w-full",
|
||||||
@@ -445,7 +526,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
<div
|
||||||
|
ref={patchViewportRef}
|
||||||
|
className="diff-panel-viewport min-h-0 min-w-0 flex-1 overflow-hidden"
|
||||||
|
>
|
||||||
{checkpointDiffError && !renderablePatch && (
|
{checkpointDiffError && !renderablePatch && (
|
||||||
<div className="px-3">
|
<div className="px-3">
|
||||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||||
@@ -463,7 +547,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
</div>
|
</div>
|
||||||
) : renderablePatch.kind === "files" ? (
|
) : renderablePatch.kind === "files" ? (
|
||||||
<Virtualizer
|
<Virtualizer
|
||||||
className="h-full min-h-0 overflow-auto px-3 py-2"
|
className="diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2"
|
||||||
config={{
|
config={{
|
||||||
overscrollSize: 600,
|
overscrollSize: 600,
|
||||||
intersectionObserverMargin: 1200,
|
intersectionObserverMargin: 1200,
|
||||||
@@ -472,14 +556,31 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
{renderableFiles.map((fileDiff) => {
|
{renderableFiles.map((fileDiff) => {
|
||||||
const filePath = resolveFileDiffPath(fileDiff);
|
const filePath = resolveFileDiffPath(fileDiff);
|
||||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||||
|
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
||||||
return (
|
return (
|
||||||
<div key={fileKey} data-diff-file-path={filePath} className="rounded-md">
|
<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);
|
||||||
|
}}
|
||||||
|
>
|
||||||
<FileDiff
|
<FileDiff
|
||||||
fileDiff={fileDiff}
|
fileDiff={fileDiff}
|
||||||
options={{
|
options={{
|
||||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||||
lineDiffType: "none",
|
lineDiffType: "none",
|
||||||
|
theme: resolveDiffThemeName(resolvedTheme),
|
||||||
themeType: resolvedTheme as DiffThemeType,
|
themeType: resolvedTheme as DiffThemeType,
|
||||||
|
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -487,7 +588,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
})}
|
})}
|
||||||
</Virtualizer>
|
</Virtualizer>
|
||||||
) : (
|
) : (
|
||||||
<div className="h-full overflow-auto px-3 py-2">
|
<div className="h-full overflow-auto p-2">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
<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">
|
<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">
|
||||||
|
|||||||
@@ -1,8 +1,36 @@
|
|||||||
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
|
import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||||
import { useMemo, type ReactNode } from "react";
|
import { useEffect, useMemo, type ReactNode } from "react";
|
||||||
|
import { useTheme } from "../hooks/useTheme";
|
||||||
|
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||||
|
|
||||||
|
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||||
|
const workerPool = useWorkerPool();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!workerPool) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = workerPool.getDiffRenderOptions();
|
||||||
|
if (current.theme === themeName) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
void workerPool
|
||||||
|
.setRenderOptions({
|
||||||
|
...current,
|
||||||
|
theme: themeName,
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
}, [themeName, workerPool]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||||
|
const { resolvedTheme } = useTheme();
|
||||||
|
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||||
const workerPoolSize = useMemo(() => {
|
const workerPoolSize = useMemo(() => {
|
||||||
const cores =
|
const cores =
|
||||||
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
||||||
@@ -17,9 +45,11 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
|||||||
totalASTLRUCacheSize: 240,
|
totalASTLRUCacheSize: 240,
|
||||||
}}
|
}}
|
||||||
highlighterOptions={{
|
highlighterOptions={{
|
||||||
|
theme: diffThemeName,
|
||||||
tokenizeMaxLineLength: 1_000,
|
tokenizeMaxLineLength: 1_000,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
<DiffWorkerThemeSync themeName={diffThemeName} />
|
||||||
{children}
|
{children}
|
||||||
</WorkerPoolContextProvider>
|
</WorkerPoolContextProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import {
|
|||||||
buildGitActionProgressStages,
|
buildGitActionProgressStages,
|
||||||
buildMenuItems,
|
buildMenuItems,
|
||||||
requiresDefaultBranchConfirmation,
|
requiresDefaultBranchConfirmation,
|
||||||
|
resolveAutoFeatureBranchName,
|
||||||
|
resolveDefaultBranchActionDialogCopy,
|
||||||
resolveQuickAction,
|
resolveQuickAction,
|
||||||
summarizeGitResult,
|
summarizeGitResult,
|
||||||
} from "./GitActionsControl.logic";
|
} from "./GitActionsControl.logic";
|
||||||
@@ -20,7 +22,7 @@ function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
|||||||
hasUpstream: true,
|
hasUpstream: true,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
openPr: null,
|
pr: null,
|
||||||
...overrides,
|
...overrides,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -29,12 +31,13 @@ describe("when: branch is clean and has an open PR", () => {
|
|||||||
it("resolveQuickAction opens the existing PR", () => {
|
it("resolveQuickAction opens the existing PR", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({
|
status({
|
||||||
openPr: {
|
pr: {
|
||||||
number: 10,
|
number: 10,
|
||||||
title: "Open PR",
|
title: "Open PR",
|
||||||
url: "https://example.com/pr/10",
|
url: "https://example.com/pr/10",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -45,12 +48,13 @@ describe("when: branch is clean and has an open PR", () => {
|
|||||||
it("buildMenuItems disables commit/push and enables open PR", () => {
|
it("buildMenuItems disables commit/push and enables open PR", () => {
|
||||||
const items = buildMenuItems(
|
const items = buildMenuItems(
|
||||||
status({
|
status({
|
||||||
openPr: {
|
pr: {
|
||||||
number: 11,
|
number: 11,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/11",
|
url: "https://example.com/pr/11",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -147,12 +151,13 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
|||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({
|
status({
|
||||||
aheadCount: 3,
|
aheadCount: 3,
|
||||||
openPr: {
|
pr: {
|
||||||
number: 13,
|
number: 13,
|
||||||
title: "Open PR",
|
title: "Open PR",
|
||||||
url: "https://example.com/pr/13",
|
url: "https://example.com/pr/13",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -164,12 +169,13 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
|||||||
const items = buildMenuItems(
|
const items = buildMenuItems(
|
||||||
status({
|
status({
|
||||||
aheadCount: 2,
|
aheadCount: 2,
|
||||||
openPr: {
|
pr: {
|
||||||
number: 12,
|
number: 12,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/12",
|
url: "https://example.com/pr/12",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -204,7 +210,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
|||||||
|
|
||||||
describe("when: branch is clean, ahead, and has no open PR", () => {
|
describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||||
it("resolveQuickAction pushes and creates a PR", () => {
|
it("resolveQuickAction pushes and creates a PR", () => {
|
||||||
const quick = resolveQuickAction(status({ aheadCount: 2, openPr: null }), false);
|
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
|
||||||
assert.deepInclude(quick, {
|
assert.deepInclude(quick, {
|
||||||
kind: "run_action",
|
kind: "run_action",
|
||||||
action: "commit_push_pr",
|
action: "commit_push_pr",
|
||||||
@@ -213,7 +219,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("buildMenuItems enables push and create PR, with commit disabled", () => {
|
it("buildMenuItems enables push and create PR, with commit disabled", () => {
|
||||||
const items = buildMenuItems(status({ aheadCount: 2, openPr: null }), false);
|
const items = buildMenuItems(status({ aheadCount: 2, pr: null }), false);
|
||||||
assert.deepEqual(items, [
|
assert.deepEqual(items, [
|
||||||
{
|
{
|
||||||
id: "commit",
|
id: "commit",
|
||||||
@@ -246,14 +252,14 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
|||||||
describe("when: branch is clean, up to date, and has no open PR", () => {
|
describe("when: branch is clean, up to date, and has no open PR", () => {
|
||||||
it("resolveQuickAction returns disabled no-action state", () => {
|
it("resolveQuickAction returns disabled no-action state", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, openPr: null }),
|
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("buildMenuItems disables commit, push, and create PR", () => {
|
it("buildMenuItems disables commit, push, and create PR", () => {
|
||||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, openPr: null }), false);
|
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, pr: null }), false);
|
||||||
assert.deepEqual(items, [
|
assert.deepEqual(items, [
|
||||||
{
|
{
|
||||||
id: "commit",
|
id: "commit",
|
||||||
@@ -290,7 +296,7 @@ describe("when: branch is behind upstream", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("buildMenuItems disables push and create PR", () => {
|
it("buildMenuItems disables push and create PR", () => {
|
||||||
const items = buildMenuItems(status({ behindCount: 1, openPr: null }), false);
|
const items = buildMenuItems(status({ behindCount: 1, pr: null }), false);
|
||||||
assert.deepEqual(items, [
|
assert.deepEqual(items, [
|
||||||
{
|
{
|
||||||
id: "commit",
|
id: "commit",
|
||||||
@@ -346,12 +352,13 @@ describe("when: working tree has local changes", () => {
|
|||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({
|
status({
|
||||||
hasWorkingTreeChanges: true,
|
hasWorkingTreeChanges: true,
|
||||||
openPr: {
|
pr: {
|
||||||
number: 16,
|
number: 16,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/16",
|
url: "https://example.com/pr/16",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -411,7 +418,7 @@ describe("when: on default branch without open PR", () => {
|
|||||||
|
|
||||||
it("resolveQuickAction returns push when branch is ahead", () => {
|
it("resolveQuickAction returns push when branch is ahead", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({ branch: "main", aheadCount: 2, openPr: null }),
|
status({ branch: "main", aheadCount: 2, pr: null }),
|
||||||
false,
|
false,
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
@@ -509,37 +516,39 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("when: branch has no upstream configured", () => {
|
describe("when: branch has no upstream configured", () => {
|
||||||
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
it("resolveQuickAction is disabled when clean, no upstream, and no local commits are ahead", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepInclude(quick, {
|
assert.deepInclude(quick, {
|
||||||
kind: "show_hint",
|
kind: "show_hint",
|
||||||
label: "Commit",
|
label: "Push",
|
||||||
|
hint: "No local commits to push.",
|
||||||
disabled: true,
|
disabled: true,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("resolveQuickAction remains disabled when clean, no upstream, and no local commits ahead", () => {
|
it("resolveQuickAction opens PR when clean, no upstream, no local commits are ahead, and PR exists", () => {
|
||||||
const quick = resolveQuickAction(
|
const quick = resolveQuickAction(
|
||||||
status({
|
status({
|
||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
openPr: {
|
pr: {
|
||||||
number: 14,
|
number: 14,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/14",
|
url: "https://example.com/pr/14",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepInclude(quick, {
|
assert.deepInclude(quick, {
|
||||||
kind: "show_hint",
|
kind: "open_pr",
|
||||||
label: "Commit",
|
label: "Open PR",
|
||||||
disabled: true,
|
disabled: false,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -548,12 +557,13 @@ describe("when: branch has no upstream configured", () => {
|
|||||||
status({
|
status({
|
||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 1,
|
aheadCount: 1,
|
||||||
openPr: {
|
pr: {
|
||||||
number: 15,
|
number: 15,
|
||||||
title: "Existing PR",
|
title: "Existing PR",
|
||||||
url: "https://example.com/pr/15",
|
url: "https://example.com/pr/15",
|
||||||
baseBranch: "main",
|
baseBranch: "main",
|
||||||
headBranch: "feature/test",
|
headBranch: "feature/test",
|
||||||
|
state: "open",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
false,
|
false,
|
||||||
@@ -568,7 +578,133 @@ describe("when: branch has no upstream configured", () => {
|
|||||||
|
|
||||||
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
||||||
const items = buildMenuItems(
|
const items = buildMenuItems(
|
||||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||||
|
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",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
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,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepEqual(items, [
|
assert.deepEqual(items, [
|
||||||
@@ -609,6 +745,53 @@ 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", () => {
|
describe("buildGitActionProgressStages", () => {
|
||||||
it("shows only push progress when push-only is forced", () => {
|
it("shows only push progress when push-only is forced", () => {
|
||||||
const stages = buildGitActionProgressStages({
|
const stages = buildGitActionProgressStages({
|
||||||
@@ -725,3 +908,20 @@ describe("summarizeGitResult", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("resolveAutoFeatureBranchName", () => {
|
||||||
|
const day = new Date("2026-03-01T12:00:00.000Z");
|
||||||
|
|
||||||
|
it("returns the base auto feature branch name when available", () => {
|
||||||
|
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], day);
|
||||||
|
assert.equal(branch, "feature/stacked-20260301");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("increments suffix when the base name already exists", () => {
|
||||||
|
const branch = resolveAutoFeatureBranchName(
|
||||||
|
["main", "feature/stacked-20260301", "feature/stacked-20260301-2"],
|
||||||
|
day,
|
||||||
|
);
|
||||||
|
assert.equal(branch, "feature/stacked-20260301-3");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -25,8 +25,17 @@ export interface GitQuickAction {
|
|||||||
hint?: string;
|
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 SHORT_SHA_LENGTH = 7;
|
||||||
const TOAST_DESCRIPTION_MAX = 72;
|
const TOAST_DESCRIPTION_MAX = 72;
|
||||||
|
const AUTO_FEATURE_BRANCH_PREFIX = "feature/stacked";
|
||||||
|
|
||||||
function shortenSha(sha: string | undefined): string | null {
|
function shortenSha(sha: string | undefined): string | null {
|
||||||
if (!sha) return null;
|
if (!sha) return null;
|
||||||
@@ -108,7 +117,7 @@ export function buildMenuItems(
|
|||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
const hasBranch = gitStatus.branch !== null;
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||||
const hasOpenPr = gitStatus.openPr !== null;
|
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
const isBehind = gitStatus.behindCount > 0;
|
||||||
const canCommit = !isBusy && hasChanges;
|
const canCommit = !isBusy && hasChanges;
|
||||||
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
||||||
@@ -118,7 +127,6 @@ export function buildMenuItems(
|
|||||||
!hasChanges &&
|
!hasChanges &&
|
||||||
!hasOpenPr &&
|
!hasOpenPr &&
|
||||||
gitStatus.aheadCount > 0 &&
|
gitStatus.aheadCount > 0 &&
|
||||||
gitStatus.hasUpstream &&
|
|
||||||
!isBehind;
|
!isBehind;
|
||||||
const canOpenPr = !isBusy && hasOpenPr;
|
const canOpenPr = !isBusy && hasOpenPr;
|
||||||
|
|
||||||
@@ -178,7 +186,7 @@ export function resolveQuickAction(
|
|||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
const hasBranch = gitStatus.branch !== null;
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||||
const hasOpenPr = gitStatus.openPr !== null;
|
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||||
const isAhead = gitStatus.aheadCount > 0;
|
const isAhead = gitStatus.aheadCount > 0;
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
const isBehind = gitStatus.behindCount > 0;
|
||||||
const isDiverged = isAhead && isBehind;
|
const isDiverged = isAhead && isBehind;
|
||||||
@@ -204,6 +212,29 @@ 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) {
|
if (isDiverged) {
|
||||||
return {
|
return {
|
||||||
label: "Sync branch",
|
label: "Sync branch",
|
||||||
@@ -252,3 +283,67 @@ export function requiresDefaultBranchConfirmation(
|
|||||||
if (!isDefaultBranch) return false;
|
if (!isDefaultBranch) return false;
|
||||||
return action === "commit_push" || action === "commit_push_pr";
|
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",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateForBranch(now: Date): string {
|
||||||
|
const year = now.getUTCFullYear();
|
||||||
|
const month = String(now.getUTCMonth() + 1).padStart(2, "0");
|
||||||
|
const day = String(now.getUTCDate()).padStart(2, "0");
|
||||||
|
return `${year}${month}${day}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveAutoFeatureBranchName(
|
||||||
|
existingBranchNames: readonly string[],
|
||||||
|
now = new Date(),
|
||||||
|
): string {
|
||||||
|
const daySlug = formatDateForBranch(now);
|
||||||
|
const base = `${AUTO_FEATURE_BRANCH_PREFIX}-${daySlug}`;
|
||||||
|
const existingNames = new Set(existingBranchNames);
|
||||||
|
|
||||||
|
if (!existingNames.has(base)) {
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
let suffix = 2;
|
||||||
|
while (existingNames.has(`${base}-${suffix}`)) {
|
||||||
|
suffix += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${base}-${suffix}`;
|
||||||
|
}
|
||||||
@@ -8,9 +8,11 @@ import {
|
|||||||
buildMenuItems,
|
buildMenuItems,
|
||||||
type GitActionIconName,
|
type GitActionIconName,
|
||||||
type GitActionMenuItem,
|
type GitActionMenuItem,
|
||||||
type GitDialogAction,
|
|
||||||
type GitQuickAction,
|
type GitQuickAction,
|
||||||
|
type DefaultBranchConfirmableAction,
|
||||||
requiresDefaultBranchConfirmation,
|
requiresDefaultBranchConfirmation,
|
||||||
|
resolveAutoFeatureBranchName,
|
||||||
|
resolveDefaultBranchActionDialogCopy,
|
||||||
resolveQuickAction,
|
resolveQuickAction,
|
||||||
summarizeGitResult,
|
summarizeGitResult,
|
||||||
} from "./GitActionsControl.logic";
|
} from "./GitActionsControl.logic";
|
||||||
@@ -32,6 +34,7 @@ import { Textarea } from "~/components/ui/textarea";
|
|||||||
import { toastManager } from "~/components/ui/toast";
|
import { toastManager } from "~/components/ui/toast";
|
||||||
import {
|
import {
|
||||||
gitBranchesQueryOptions,
|
gitBranchesQueryOptions,
|
||||||
|
gitCreateBranchAndCheckoutMutationOptions,
|
||||||
gitInitMutationOptions,
|
gitInitMutationOptions,
|
||||||
gitMutationKeys,
|
gitMutationKeys,
|
||||||
gitPullMutationOptions,
|
gitPullMutationOptions,
|
||||||
@@ -47,6 +50,17 @@ interface GitActionsControlProps {
|
|||||||
activeThreadId: ThreadId | null;
|
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(
|
function getMenuActionDisabledReason(
|
||||||
item: GitActionMenuItem,
|
item: GitActionMenuItem,
|
||||||
gitStatus: GitStatusResult | null,
|
gitStatus: GitStatusResult | null,
|
||||||
@@ -58,7 +72,7 @@ function getMenuActionDisabledReason(
|
|||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
const hasBranch = gitStatus.branch !== null;
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||||
const hasOpenPr = gitStatus.openPr !== null;
|
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||||
const isAhead = gitStatus.aheadCount > 0;
|
const isAhead = gitStatus.aheadCount > 0;
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
const isBehind = gitStatus.behindCount > 0;
|
||||||
|
|
||||||
@@ -97,26 +111,15 @@ function getMenuActionDisabledReason(
|
|||||||
if (!isAhead) {
|
if (!isAhead) {
|
||||||
return "No local commits to include in a PR.";
|
return "No local commits to include in a PR.";
|
||||||
}
|
}
|
||||||
if (!gitStatus.hasUpstream) {
|
|
||||||
return "Set an upstream branch before creating a PR.";
|
|
||||||
}
|
|
||||||
if (isBehind) {
|
if (isBehind) {
|
||||||
return "Branch is behind upstream. Pull/rebase before creating a PR.";
|
return "Branch is behind upstream. Pull/rebase before creating a PR.";
|
||||||
}
|
}
|
||||||
return "Create PR is currently unavailable.";
|
return "Create PR is currently unavailable.";
|
||||||
}
|
}
|
||||||
|
|
||||||
const DIALOG_TITLE_BY_ACTION = {
|
const COMMIT_DIALOG_TITLE = "Commit changes";
|
||||||
commit: "Commit changes",
|
const COMMIT_DIALOG_DESCRIPTION =
|
||||||
push: "Push branch",
|
"Review and confirm your commit. Leave the message blank to auto-generate one.";
|
||||||
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 }) {
|
function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
|
||||||
if (icon === "commit") return <GitCommitIcon />;
|
if (icon === "commit") return <GitCommitIcon />;
|
||||||
@@ -143,8 +146,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
[activeThreadId],
|
[activeThreadId],
|
||||||
);
|
);
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [activeDialogAction, setActiveDialogAction] = useState<GitDialogAction | null>(null);
|
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
|
||||||
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
||||||
|
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
|
||||||
|
useState<PendingDefaultBranchAction | null>(null);
|
||||||
|
|
||||||
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
|
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
|
||||||
|
|
||||||
@@ -167,12 +172,18 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
const runImmediateGitActionMutation = useMutation(
|
const runImmediateGitActionMutation = useMutation(
|
||||||
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
|
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
|
||||||
);
|
);
|
||||||
|
const createBranchAndCheckoutMutation = useMutation(
|
||||||
|
gitCreateBranchAndCheckoutMutationOptions({ cwd: gitCwd, queryClient }),
|
||||||
|
);
|
||||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||||
|
|
||||||
const isRunStackedActionRunning =
|
const isRunStackedActionRunning =
|
||||||
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
|
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
|
||||||
|
const isCreateBranchAndCheckoutRunning =
|
||||||
|
useIsMutating({ mutationKey: gitMutationKeys.createBranchAndCheckout(gitCwd) }) > 0;
|
||||||
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
|
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
|
||||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
const isGitActionRunning =
|
||||||
|
isRunStackedActionRunning || isCreateBranchAndCheckoutRunning || isPullRunning;
|
||||||
const isDefaultBranch = useMemo(() => {
|
const isDefaultBranch = useMemo(() => {
|
||||||
const branchName = gitStatusForActions?.branch;
|
const branchName = gitStatusForActions?.branch;
|
||||||
if (!branchName) return false;
|
if (!branchName) return false;
|
||||||
@@ -191,23 +202,13 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
const quickActionDisabledReason = quickAction.disabled
|
const quickActionDisabledReason = quickAction.disabled
|
||||||
? (quickAction.hint ?? "This action is currently unavailable.")
|
? (quickAction.hint ?? "This action is currently unavailable.")
|
||||||
: null;
|
: null;
|
||||||
|
const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
|
||||||
const maybeConfirmPushToDefaultBranch = useCallback(
|
? resolveDefaultBranchActionDialogCopy({
|
||||||
async (action: GitStackedAction): Promise<boolean> => {
|
action: pendingDefaultBranchAction.action,
|
||||||
const api = readNativeApi();
|
branchName: pendingDefaultBranchAction.branchName,
|
||||||
if (!api) return false;
|
includesCommit: pendingDefaultBranchAction.includesCommit,
|
||||||
if (
|
})
|
||||||
!requiresDefaultBranchConfirmation(action, isDefaultBranch) ||
|
: null;
|
||||||
!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 openExistingPr = useCallback(async () => {
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
@@ -219,7 +220,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const prUrl = gitStatusForActions?.openPr?.url ?? null;
|
const prUrl = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : null;
|
||||||
if (!prUrl) {
|
if (!prUrl) {
|
||||||
toastManager.add({
|
toastManager.add({
|
||||||
type: "error",
|
type: "error",
|
||||||
@@ -236,44 +237,83 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
data: threadToastData,
|
data: threadToastData,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}, [gitStatusForActions?.openPr?.url, threadToastData]);
|
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
||||||
|
|
||||||
const runGitActionWithToast = useCallback(
|
const runGitActionWithToast = useCallback(
|
||||||
async ({
|
async ({
|
||||||
action,
|
action,
|
||||||
commitMessage,
|
commitMessage,
|
||||||
forcePushOnlyProgress = false,
|
forcePushOnlyProgress = false,
|
||||||
onConfirmed,
|
onConfirmed,
|
||||||
|
skipDefaultBranchPrompt = false,
|
||||||
|
statusOverride,
|
||||||
|
isDefaultBranchOverride,
|
||||||
|
progressToastId,
|
||||||
}: {
|
}: {
|
||||||
action: GitStackedAction;
|
action: GitStackedAction;
|
||||||
commitMessage?: string;
|
commitMessage?: string;
|
||||||
forcePushOnlyProgress?: boolean;
|
forcePushOnlyProgress?: boolean;
|
||||||
onConfirmed?: () => void;
|
onConfirmed?: () => void;
|
||||||
|
skipDefaultBranchPrompt?: boolean;
|
||||||
|
statusOverride?: GitStatusResult | null;
|
||||||
|
isDefaultBranchOverride?: boolean;
|
||||||
|
progressToastId?: GitActionToastId;
|
||||||
}) => {
|
}) => {
|
||||||
const confirmed = await maybeConfirmPushToDefaultBranch(action);
|
const actionStatus = statusOverride ?? gitStatusForActions;
|
||||||
if (!confirmed) return;
|
const actionIsDefaultBranch = isDefaultBranchOverride ?? isDefaultBranch;
|
||||||
|
const actionBranch = actionStatus?.branch ?? null;
|
||||||
|
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;
|
||||||
|
}
|
||||||
onConfirmed?.();
|
onConfirmed?.();
|
||||||
|
|
||||||
const pushTarget = gitStatusForActions?.branch
|
const pushTarget = actionBranch ? `origin/${actionBranch}` : undefined;
|
||||||
? `origin/${gitStatusForActions.branch}`
|
|
||||||
: undefined;
|
|
||||||
const progressStages = buildGitActionProgressStages({
|
const progressStages = buildGitActionProgressStages({
|
||||||
action,
|
action,
|
||||||
hasCustomCommitMessage: !!commitMessage?.trim(),
|
hasCustomCommitMessage: !!commitMessage?.trim(),
|
||||||
hasWorkingTreeChanges: !!gitStatusForActions?.hasWorkingTreeChanges,
|
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
|
||||||
forcePushOnly: forcePushOnlyProgress,
|
forcePushOnly: forcePushOnlyProgress,
|
||||||
...(pushTarget ? { pushTarget } : {}),
|
...(pushTarget ? { pushTarget } : {}),
|
||||||
});
|
});
|
||||||
const progressToastId = toastManager.add({
|
const resolvedProgressToastId =
|
||||||
type: "loading",
|
progressToastId ??
|
||||||
title: progressStages[0] ?? "Running git action...",
|
toastManager.add({
|
||||||
timeout: 0,
|
type: "loading",
|
||||||
data: threadToastData,
|
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
let stageIndex = 0;
|
let stageIndex = 0;
|
||||||
const stageInterval = setInterval(() => {
|
const stageInterval = setInterval(() => {
|
||||||
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
|
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
|
||||||
toastManager.update(progressToastId, {
|
toastManager.update(resolvedProgressToastId, {
|
||||||
title: progressStages[stageIndex] ?? "Running git action...",
|
title: progressStages[stageIndex] ?? "Running git action...",
|
||||||
type: "loading",
|
type: "loading",
|
||||||
timeout: 0,
|
timeout: 0,
|
||||||
@@ -295,17 +335,23 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
stopProgressUpdates();
|
stopProgressUpdates();
|
||||||
const resultToast = summarizeGitResult(result);
|
const resultToast = summarizeGitResult(result);
|
||||||
|
|
||||||
const prUrl = result.pr.url ?? gitStatusForActions?.openPr?.url;
|
const existingOpenPrUrl = actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
|
||||||
|
const prUrl = result.pr.url ?? existingOpenPrUrl;
|
||||||
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
|
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
|
||||||
const shouldOfferOpenPrCta =
|
const shouldOfferOpenPrCta =
|
||||||
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
|
(action === "commit_push" || action === "commit_push_pr") &&
|
||||||
|
!!prUrl &&
|
||||||
|
!actionIsDefaultBranch;
|
||||||
const shouldOfferCreatePrCta =
|
const shouldOfferCreatePrCta =
|
||||||
action === "commit_push" && !prUrl && result.push.status === "pushed" && !isDefaultBranch;
|
action === "commit_push" &&
|
||||||
|
!prUrl &&
|
||||||
|
result.push.status === "pushed" &&
|
||||||
|
!actionIsDefaultBranch;
|
||||||
const closeResultToast = () => {
|
const closeResultToast = () => {
|
||||||
toastManager.close(progressToastId);
|
toastManager.close(resolvedProgressToastId);
|
||||||
};
|
};
|
||||||
|
|
||||||
toastManager.update(progressToastId, {
|
toastManager.update(resolvedProgressToastId, {
|
||||||
type: "success",
|
type: "success",
|
||||||
title: resultToast.title,
|
title: resultToast.title,
|
||||||
description: resultToast.description,
|
description: resultToast.description,
|
||||||
@@ -323,6 +369,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
action: "commit_push",
|
action: "commit_push",
|
||||||
forcePushOnlyProgress: true,
|
forcePushOnlyProgress: true,
|
||||||
onConfirmed: closeResultToast,
|
onConfirmed: closeResultToast,
|
||||||
|
statusOverride: actionStatus,
|
||||||
|
isDefaultBranchOverride: actionIsDefaultBranch,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -345,7 +393,11 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
children: "Create PR",
|
children: "Create PR",
|
||||||
onClick: () => {
|
onClick: () => {
|
||||||
closeResultToast();
|
closeResultToast();
|
||||||
setActiveDialogAction("create_pr");
|
void runGitActionWithToast({
|
||||||
|
action: "commit_push_pr",
|
||||||
|
statusOverride: actionStatus,
|
||||||
|
isDefaultBranchOverride: actionIsDefaultBranch,
|
||||||
|
});
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -353,7 +405,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
stopProgressUpdates();
|
stopProgressUpdates();
|
||||||
toastManager.update(progressToastId, {
|
toastManager.update(resolvedProgressToastId, {
|
||||||
type: "error",
|
type: "error",
|
||||||
title: "Action failed",
|
title: "Action failed",
|
||||||
description: err instanceof Error ? err.message : "An error occurred.",
|
description: err instanceof Error ? err.message : "An error occurred.",
|
||||||
@@ -363,17 +415,109 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
},
|
},
|
||||||
|
|
||||||
[
|
[
|
||||||
gitStatusForActions?.branch,
|
|
||||||
gitStatusForActions?.hasWorkingTreeChanges,
|
|
||||||
gitStatusForActions?.openPr?.url,
|
|
||||||
isDefaultBranch,
|
isDefaultBranch,
|
||||||
maybeConfirmPushToDefaultBranch,
|
|
||||||
runImmediateGitActionMutation,
|
runImmediateGitActionMutation,
|
||||||
setActiveDialogAction,
|
setPendingDefaultBranchAction,
|
||||||
|
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;
|
||||||
|
}) => {
|
||||||
|
const branchName = resolveAutoFeatureBranchName(
|
||||||
|
branchList?.branches.map((branch) => branch.name) ?? [],
|
||||||
|
);
|
||||||
|
|
||||||
|
const checkoutPromise = createBranchAndCheckoutMutation.mutateAsync(branchName);
|
||||||
|
const checkoutToastId = toastManager.add({
|
||||||
|
type: "loading",
|
||||||
|
title: `Creating ${branchName}...`,
|
||||||
|
timeout: 0,
|
||||||
|
data: threadToastData,
|
||||||
|
});
|
||||||
|
|
||||||
|
void checkoutPromise
|
||||||
|
.then(() => {
|
||||||
|
const statusOverride = gitStatusForActions
|
||||||
|
? {
|
||||||
|
...gitStatusForActions,
|
||||||
|
branch: branchName,
|
||||||
|
pr: null,
|
||||||
|
hasUpstream: false,
|
||||||
|
aheadCount: 0,
|
||||||
|
behindCount: 0,
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
return runGitActionWithToast({
|
||||||
|
...actionParams,
|
||||||
|
skipDefaultBranchPrompt: true,
|
||||||
|
statusOverride,
|
||||||
|
isDefaultBranchOverride: false,
|
||||||
|
progressToastId: checkoutToastId,
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
toastManager.update(checkoutToastId, {
|
||||||
|
type: "error",
|
||||||
|
title: "Failed to checkout feature branch",
|
||||||
|
description: error instanceof Error ? error.message : "An error occurred.",
|
||||||
|
data: threadToastData,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[
|
||||||
|
branchList?.branches,
|
||||||
|
createBranchAndCheckoutMutation,
|
||||||
|
gitStatusForActions,
|
||||||
|
runGitActionWithToast,
|
||||||
threadToastData,
|
threadToastData,
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
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(() => {
|
const runQuickAction = useCallback(() => {
|
||||||
if (quickAction.kind === "open_pr") {
|
if (quickAction.kind === "open_pr") {
|
||||||
void openExistingPr();
|
void openExistingPr();
|
||||||
@@ -425,30 +569,31 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
|
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (item.dialogAction) {
|
if (item.dialogAction === "create_pr") {
|
||||||
setActiveDialogAction(item.dialogAction);
|
void runGitActionWithToast({ action: "commit_push_pr" });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
setIsCommitDialogOpen(true);
|
||||||
},
|
},
|
||||||
[openExistingPr, runGitActionWithToast],
|
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
|
||||||
);
|
);
|
||||||
|
|
||||||
const runDialogAction = useCallback(() => {
|
const runDialogAction = useCallback(() => {
|
||||||
if (!activeDialogAction) return;
|
if (!isCommitDialogOpen) return;
|
||||||
const action: GitStackedAction =
|
const commitMessage = dialogCommitMessage.trim();
|
||||||
activeDialogAction === "commit"
|
setIsCommitDialogOpen(false);
|
||||||
? "commit"
|
setDialogCommitMessage("");
|
||||||
: activeDialogAction === "push"
|
|
||||||
? "commit_push"
|
|
||||||
: "commit_push_pr";
|
|
||||||
const commitMessage = activeDialogAction === "commit" ? dialogCommitMessage.trim() : "";
|
|
||||||
const forcePushOnlyProgress = activeDialogAction === "push";
|
|
||||||
setActiveDialogAction(null);
|
|
||||||
void runGitActionWithToast({
|
void runGitActionWithToast({
|
||||||
action,
|
action: "commit",
|
||||||
...(commitMessage ? { commitMessage } : {}),
|
...(commitMessage ? { commitMessage } : {}),
|
||||||
...(forcePushOnlyProgress ? { forcePushOnlyProgress } : {}),
|
|
||||||
});
|
});
|
||||||
}, [activeDialogAction, dialogCommitMessage, runGitActionWithToast]);
|
}, [
|
||||||
|
dialogCommitMessage,
|
||||||
|
isCommitDialogOpen,
|
||||||
|
runGitActionWithToast,
|
||||||
|
setDialogCommitMessage,
|
||||||
|
setIsCommitDialogOpen,
|
||||||
|
]);
|
||||||
|
|
||||||
const openChangedFileInEditor = useCallback(
|
const openChangedFileInEditor = useCallback(
|
||||||
(filePath: string) => {
|
(filePath: string) => {
|
||||||
@@ -604,68 +749,29 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<Dialog
|
<Dialog
|
||||||
open={activeDialogAction !== null}
|
open={isCommitDialogOpen}
|
||||||
onOpenChange={(open) => {
|
onOpenChange={(open) => {
|
||||||
if (!open) {
|
if (!open) {
|
||||||
setActiveDialogAction(null);
|
setIsCommitDialogOpen(false);
|
||||||
setDialogCommitMessage("");
|
setDialogCommitMessage("");
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<DialogPopup>
|
<DialogPopup>
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>{DIALOG_TITLE_BY_ACTION[activeDialogAction ?? "commit"]}</DialogTitle>
|
<DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
|
||||||
{DIALOG_DESCRIPTION_BY_ACTION[activeDialogAction ?? "commit"]}
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<DialogPanel className="space-y-4">
|
<DialogPanel className="space-y-4">
|
||||||
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
|
<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">
|
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
|
||||||
<span className="text-muted-foreground">Branch</span>
|
<span className="text-muted-foreground">Branch</span>
|
||||||
<span className="font-medium">
|
<span className="flex items-center justify-between gap-2">
|
||||||
{gitStatusForActions?.branch ?? "(detached HEAD)"}
|
<span className="font-medium">{gitStatusForActions?.branch ?? "(detached HEAD)"}</span>
|
||||||
|
{isDefaultBranch && (
|
||||||
|
<span className="text-right text-warning text-xs">Warning: default branch</span>
|
||||||
|
)}
|
||||||
</span>
|
</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>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<p className="text-muted-foreground">Files</p>
|
<p className="text-muted-foreground">Files</p>
|
||||||
@@ -705,35 +811,61 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{activeDialogAction === "commit" && (
|
<div className="space-y-1">
|
||||||
<div className="space-y-1">
|
<p className="text-xs font-medium">Commit message (optional)</p>
|
||||||
<p className="text-xs font-medium">Commit message (optional)</p>
|
<Textarea
|
||||||
<Textarea
|
value={dialogCommitMessage}
|
||||||
value={dialogCommitMessage}
|
onChange={(event) => setDialogCommitMessage(event.target.value)}
|
||||||
onChange={(event) => setDialogCommitMessage(event.target.value)}
|
placeholder="Leave empty to auto-generate"
|
||||||
placeholder="Leave empty to auto-generate"
|
size="sm"
|
||||||
size="sm"
|
/>
|
||||||
/>
|
</div>
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</DialogPanel>
|
</DialogPanel>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setActiveDialogAction(null);
|
setIsCommitDialogOpen(false);
|
||||||
setDialogCommitMessage("");
|
setDialogCommitMessage("");
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" onClick={runDialogActionOnNewBranch}>
|
||||||
|
Commit on new branch
|
||||||
|
</Button>
|
||||||
<Button size="sm" onClick={runDialogAction}>
|
<Button size="sm" onClick={runDialogAction}>
|
||||||
{activeDialogAction === "commit"
|
Commit
|
||||||
? "Commit"
|
</Button>
|
||||||
: activeDialogAction === "push"
|
</DialogFooter>
|
||||||
? "Push"
|
</DialogPopup>
|
||||||
: "Create PR"}
|
</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
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogPopup>
|
</DialogPopup>
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { ChevronRightIcon, TerminalIcon } from "lucide-react";
|
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import {
|
import {
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
|
type GitStatusResult,
|
||||||
type ResolvedKeybindingsConfig,
|
type ResolvedKeybindingsConfig,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||||
import { useAppSettings } from "../appSettings";
|
import { useAppSettings } from "../appSettings";
|
||||||
import { isElectron } from "../env";
|
import { isElectron } from "../env";
|
||||||
@@ -15,11 +16,14 @@ import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
|
|||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||||
import { type Thread } from "../types";
|
import { type Thread } from "../types";
|
||||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
import { derivePendingApprovals } from "../session-logic";
|
||||||
|
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||||
import { readNativeApi } from "../nativeApi";
|
import { readNativeApi } from "../nativeApi";
|
||||||
|
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
|
||||||
import { toastManager } from "./ui/toast";
|
import { toastManager } from "./ui/toast";
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
||||||
|
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||||
import {
|
import {
|
||||||
SidebarContent,
|
SidebarContent,
|
||||||
SidebarFooter,
|
SidebarFooter,
|
||||||
@@ -50,7 +54,7 @@ function formatRelativeTime(iso: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface ThreadStatusPill {
|
interface ThreadStatusPill {
|
||||||
label: "Working" | "Connecting" | "Completed" | "Awaiting response";
|
label: "Working" | "Connecting" | "Completed" | "Pending Approval";
|
||||||
colorClass: string;
|
colorClass: string;
|
||||||
dotClass: string;
|
dotClass: string;
|
||||||
pulse: boolean;
|
pulse: boolean;
|
||||||
@@ -62,9 +66,18 @@ interface TerminalStatusIndicator {
|
|||||||
pulse: boolean;
|
pulse: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface PrStatusIndicator {
|
||||||
|
label: "PR open" | "PR closed" | "PR merged";
|
||||||
|
colorClass: string;
|
||||||
|
tooltip: string;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type ThreadPr = GitStatusResult["pr"];
|
||||||
|
|
||||||
function hasUnseenCompletion(thread: Thread): boolean {
|
function hasUnseenCompletion(thread: Thread): boolean {
|
||||||
if (!thread.latestTurnCompletedAt) return false;
|
if (!thread.latestTurn?.completedAt) return false;
|
||||||
const completedAt = Date.parse(thread.latestTurnCompletedAt);
|
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||||
if (Number.isNaN(completedAt)) return false;
|
if (Number.isNaN(completedAt)) return false;
|
||||||
if (!thread.lastVisitedAt) return true;
|
if (!thread.lastVisitedAt) return true;
|
||||||
|
|
||||||
@@ -76,7 +89,7 @@ function hasUnseenCompletion(thread: Thread): boolean {
|
|||||||
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
|
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
|
||||||
if (hasPendingApprovals) {
|
if (hasPendingApprovals) {
|
||||||
return {
|
return {
|
||||||
label: "Awaiting response",
|
label: "Pending Approval",
|
||||||
colorClass: "text-amber-600 dark:text-amber-300/90",
|
colorClass: "text-amber-600 dark:text-amber-300/90",
|
||||||
dotClass: "bg-amber-500 dark:bg-amber-300/90",
|
dotClass: "bg-amber-500 dark:bg-amber-300/90",
|
||||||
pulse: false,
|
pulse: false,
|
||||||
@@ -124,11 +137,41 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
|
||||||
|
if (!pr) return null;
|
||||||
|
|
||||||
|
if (pr.state === "open") {
|
||||||
|
return {
|
||||||
|
label: "PR open",
|
||||||
|
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||||
|
tooltip: `#${pr.number} PR open: ${pr.title}`,
|
||||||
|
url: pr.url,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (pr.state === "closed") {
|
||||||
|
return {
|
||||||
|
label: "PR closed",
|
||||||
|
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||||
|
tooltip: `#${pr.number} PR closed: ${pr.title}`,
|
||||||
|
url: pr.url,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (pr.state === "merged") {
|
||||||
|
return {
|
||||||
|
label: "PR merged",
|
||||||
|
colorClass: "text-violet-600 dark:text-violet-300/90",
|
||||||
|
tooltip: `#${pr.number} PR merged: ${pr.title}`,
|
||||||
|
url: pr.url,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
function T3Wordmark() {
|
function T3Wordmark() {
|
||||||
return (
|
return (
|
||||||
<svg
|
<svg
|
||||||
aria-label="T3"
|
aria-label="T3"
|
||||||
className="h-3 w-auto shrink-0 text-foreground"
|
className="h-2.5 w-auto shrink-0 text-foreground"
|
||||||
viewBox="15.5309 37 94.3941 56.96"
|
viewBox="15.5309 37 94.3941 56.96"
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
>
|
>
|
||||||
@@ -140,8 +183,65 @@ function T3Wordmark() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derives the server's HTTP origin (scheme + host + port) from the same
|
||||||
|
* sources WsTransport uses, converting ws(s) to http(s).
|
||||||
|
*/
|
||||||
|
function getServerHttpOrigin(): string {
|
||||||
|
const bridgeUrl = window.desktopBridge?.getWsUrl();
|
||||||
|
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||||
|
const wsUrl =
|
||||||
|
bridgeUrl && bridgeUrl.length > 0
|
||||||
|
? bridgeUrl
|
||||||
|
: envUrl && envUrl.length > 0
|
||||||
|
? envUrl
|
||||||
|
: `ws://${window.location.hostname}:${window.location.port}`;
|
||||||
|
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
|
||||||
|
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
|
||||||
|
try {
|
||||||
|
return new URL(httpUrl).origin;
|
||||||
|
} catch {
|
||||||
|
return httpUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const serverHttpOrigin = getServerHttpOrigin();
|
||||||
|
|
||||||
|
function ProjectFavicon({ cwd }: { cwd: string }) {
|
||||||
|
const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
|
||||||
|
|
||||||
|
const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
|
||||||
|
|
||||||
|
if (status === "error") {
|
||||||
|
return <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<img
|
||||||
|
src={src}
|
||||||
|
alt=""
|
||||||
|
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loading" ? "hidden" : ""}`}
|
||||||
|
onLoad={() => setStatus("loaded")}
|
||||||
|
onError={() => setStatus("error")}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export default function Sidebar() {
|
export default function Sidebar() {
|
||||||
const { state, dispatch } = useStore();
|
const { state, dispatch } = useStore();
|
||||||
|
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
|
||||||
|
const getDraftThreadByProjectId = useComposerDraftStore(
|
||||||
|
(store) => store.getDraftThreadByProjectId,
|
||||||
|
);
|
||||||
|
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
|
||||||
|
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
|
||||||
|
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||||
|
const clearProjectDraftThreadId = useComposerDraftStore(
|
||||||
|
(store) => store.clearProjectDraftThreadId,
|
||||||
|
);
|
||||||
|
const clearProjectDraftThreadById = useComposerDraftStore(
|
||||||
|
(store) => store.clearProjectDraftThreadById,
|
||||||
|
);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { settings: appSettings } = useAppSettings();
|
const { settings: appSettings } = useAppSettings();
|
||||||
const routeThreadId = useParams({
|
const routeThreadId = useParams({
|
||||||
@@ -158,7 +258,86 @@ export default function Sidebar() {
|
|||||||
const [newCwd, setNewCwd] = useState("");
|
const [newCwd, setNewCwd] = useState("");
|
||||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||||
const [isAddingProject, setIsAddingProject] = useState(false);
|
const [isAddingProject, setIsAddingProject] = useState(false);
|
||||||
const pendingApprovalByThreadId = useMemo(() => new Map<ThreadId, boolean>(), []);
|
const pendingApprovalByThreadId = useMemo(() => {
|
||||||
|
const map = new Map<ThreadId, boolean>();
|
||||||
|
for (const thread of state.threads) {
|
||||||
|
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}, [state.threads]);
|
||||||
|
const projectCwdById = useMemo(
|
||||||
|
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
|
||||||
|
[state.projects],
|
||||||
|
);
|
||||||
|
const threadGitTargets = useMemo(
|
||||||
|
() =>
|
||||||
|
state.threads.map((thread) => ({
|
||||||
|
threadId: thread.id,
|
||||||
|
branch: thread.branch,
|
||||||
|
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
|
||||||
|
})),
|
||||||
|
[projectCwdById, state.threads],
|
||||||
|
);
|
||||||
|
const threadGitStatusCwds = useMemo(
|
||||||
|
() => [
|
||||||
|
...new Set(
|
||||||
|
threadGitTargets
|
||||||
|
.filter((target) => target.branch !== null)
|
||||||
|
.map((target) => target.cwd)
|
||||||
|
.filter((cwd): cwd is string => cwd !== null),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
[threadGitTargets],
|
||||||
|
);
|
||||||
|
const threadGitStatusQueries = useQueries({
|
||||||
|
queries: threadGitStatusCwds.map((cwd) => ({
|
||||||
|
...gitStatusQueryOptions(cwd),
|
||||||
|
staleTime: 30_000,
|
||||||
|
refetchInterval: 60_000,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
const prByThreadId = useMemo(() => {
|
||||||
|
const statusByCwd = new Map<string, GitStatusResult>();
|
||||||
|
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
||||||
|
const cwd = threadGitStatusCwds[index];
|
||||||
|
if (!cwd) continue;
|
||||||
|
const status = threadGitStatusQueries[index]?.data;
|
||||||
|
if (status) {
|
||||||
|
statusByCwd.set(cwd, status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const map = new Map<ThreadId, ThreadPr>();
|
||||||
|
for (const target of threadGitTargets) {
|
||||||
|
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
||||||
|
const branchMatches =
|
||||||
|
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
||||||
|
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
||||||
|
|
||||||
|
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
|
||||||
|
const api = readNativeApi();
|
||||||
|
if (!api) {
|
||||||
|
toastManager.add({
|
||||||
|
type: "error",
|
||||||
|
title: "Link opening is unavailable.",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
void api.shell.openExternal(prUrl).catch((error) => {
|
||||||
|
toastManager.add({
|
||||||
|
type: "error",
|
||||||
|
title: "Unable to open PR link",
|
||||||
|
description: error instanceof Error ? error.message : "An error occurred.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleNewThread = useCallback(
|
const handleNewThread = useCallback(
|
||||||
(
|
(
|
||||||
@@ -166,42 +345,71 @@ export default function Sidebar() {
|
|||||||
options?: {
|
options?: {
|
||||||
branch?: string | null;
|
branch?: string | null;
|
||||||
worktreePath?: string | null;
|
worktreePath?: string | null;
|
||||||
|
envMode?: DraftThreadEnvMode;
|
||||||
},
|
},
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
const api = readNativeApi();
|
const hasBranchOption = options?.branch !== undefined;
|
||||||
if (!api) return Promise.resolve();
|
const hasWorktreePathOption = options?.worktreePath !== undefined;
|
||||||
|
const hasEnvModeOption = options?.envMode !== undefined;
|
||||||
|
const storedDraftThread = getDraftThreadByProjectId(projectId);
|
||||||
|
if (storedDraftThread) {
|
||||||
|
return (async () => {
|
||||||
|
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
|
||||||
|
setDraftThreadContext(storedDraftThread.threadId, {
|
||||||
|
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
|
||||||
|
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
|
||||||
|
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setProjectDraftThreadId(projectId, storedDraftThread.threadId);
|
||||||
|
if (routeThreadId === storedDraftThread.threadId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await navigate({
|
||||||
|
to: "/$threadId",
|
||||||
|
params: { threadId: storedDraftThread.threadId },
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
clearProjectDraftThreadId(projectId);
|
||||||
|
|
||||||
|
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
|
||||||
|
if (activeDraftThread && routeThreadId && activeDraftThread.projectId === projectId) {
|
||||||
|
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
|
||||||
|
setDraftThreadContext(routeThreadId, {
|
||||||
|
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
|
||||||
|
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
|
||||||
|
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setProjectDraftThreadId(projectId, routeThreadId);
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
const threadId = newThreadId();
|
const threadId = newThreadId();
|
||||||
const createdAt = new Date().toISOString();
|
const createdAt = new Date().toISOString();
|
||||||
const model =
|
|
||||||
state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
|
|
||||||
return (async () => {
|
return (async () => {
|
||||||
await api.orchestration.dispatchCommand({
|
setProjectDraftThreadId(projectId, threadId, {
|
||||||
type: "thread.create",
|
createdAt,
|
||||||
commandId: newCommandId(),
|
|
||||||
threadId,
|
|
||||||
projectId,
|
|
||||||
title: "New thread",
|
|
||||||
model,
|
|
||||||
branch: options?.branch ?? null,
|
branch: options?.branch ?? null,
|
||||||
worktreePath: options?.worktreePath ?? null,
|
worktreePath: options?.worktreePath ?? null,
|
||||||
createdAt,
|
envMode: options?.envMode ?? "local",
|
||||||
});
|
});
|
||||||
|
|
||||||
// Ensure route guards can see the new thread before navigating.
|
|
||||||
try {
|
|
||||||
const snapshot = await api.orchestration.getSnapshot();
|
|
||||||
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
|
|
||||||
} catch {
|
|
||||||
// Event stream can still hydrate the thread shortly after dispatch.
|
|
||||||
}
|
|
||||||
|
|
||||||
await navigate({
|
await navigate({
|
||||||
to: "/$threadId",
|
to: "/$threadId",
|
||||||
params: { threadId },
|
params: { threadId },
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
},
|
},
|
||||||
[dispatch, navigate, state.projects],
|
[
|
||||||
|
clearProjectDraftThreadId,
|
||||||
|
getDraftThreadByProjectId,
|
||||||
|
navigate,
|
||||||
|
getDraftThread,
|
||||||
|
routeThreadId,
|
||||||
|
setDraftThreadContext,
|
||||||
|
setProjectDraftThreadId,
|
||||||
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
const focusMostRecentThreadForProject = useCallback(
|
const focusMostRecentThreadForProject = useCallback(
|
||||||
@@ -351,6 +559,8 @@ export default function Sidebar() {
|
|||||||
commandId: newCommandId(),
|
commandId: newCommandId(),
|
||||||
threadId,
|
threadId,
|
||||||
});
|
});
|
||||||
|
clearComposerDraftForThread(threadId);
|
||||||
|
clearProjectDraftThreadById(thread.projectId, thread.id);
|
||||||
if (shouldNavigateToFallback) {
|
if (shouldNavigateToFallback) {
|
||||||
if (fallbackThreadId) {
|
if (fallbackThreadId) {
|
||||||
void navigate({
|
void navigate({
|
||||||
@@ -390,6 +600,8 @@ export default function Sidebar() {
|
|||||||
},
|
},
|
||||||
[
|
[
|
||||||
appSettings.confirmThreadDelete,
|
appSettings.confirmThreadDelete,
|
||||||
|
clearComposerDraftForThread,
|
||||||
|
clearProjectDraftThreadById,
|
||||||
dispatch,
|
dispatch,
|
||||||
navigate,
|
navigate,
|
||||||
removeWorktreeMutation,
|
removeWorktreeMutation,
|
||||||
@@ -425,6 +637,11 @@ export default function Sidebar() {
|
|||||||
if (!confirmed) return;
|
if (!confirmed) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const projectDraftThread = getDraftThreadByProjectId(projectId);
|
||||||
|
if (projectDraftThread) {
|
||||||
|
clearComposerDraftForThread(projectDraftThread.threadId);
|
||||||
|
}
|
||||||
|
clearProjectDraftThreadId(projectId);
|
||||||
await api.orchestration.dispatchCommand({
|
await api.orchestration.dispatchCommand({
|
||||||
type: "project.delete",
|
type: "project.delete",
|
||||||
commandId: newCommandId(),
|
commandId: newCommandId(),
|
||||||
@@ -440,7 +657,13 @@ export default function Sidebar() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[state.projects, state.threads],
|
[
|
||||||
|
clearComposerDraftForThread,
|
||||||
|
clearProjectDraftThreadId,
|
||||||
|
getDraftThreadByProjectId,
|
||||||
|
state.projects,
|
||||||
|
state.threads,
|
||||||
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -448,8 +671,10 @@ export default function Sidebar() {
|
|||||||
const activeThread = routeThreadId
|
const activeThread = routeThreadId
|
||||||
? state.threads.find((thread) => thread.id === routeThreadId)
|
? state.threads.find((thread) => thread.id === routeThreadId)
|
||||||
: undefined;
|
: undefined;
|
||||||
|
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
|
||||||
if (isChatNewLocalShortcut(event, keybindings)) {
|
if (isChatNewLocalShortcut(event, keybindings)) {
|
||||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
const projectId =
|
||||||
|
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
|
||||||
if (!projectId) return;
|
if (!projectId) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
void handleNewThread(projectId);
|
void handleNewThread(projectId);
|
||||||
@@ -457,12 +682,14 @@ export default function Sidebar() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!isChatNewShortcut(event, keybindings)) return;
|
if (!isChatNewShortcut(event, keybindings)) return;
|
||||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
const projectId =
|
||||||
|
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
|
||||||
if (!projectId) return;
|
if (!projectId) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
void handleNewThread(projectId, {
|
void handleNewThread(projectId, {
|
||||||
branch: activeThread?.branch ?? null,
|
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
|
||||||
worktreePath: activeThread?.worktreePath ?? null,
|
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
|
||||||
|
envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -470,7 +697,7 @@ export default function Sidebar() {
|
|||||||
return () => {
|
return () => {
|
||||||
window.removeEventListener("keydown", onWindowKeyDown);
|
window.removeEventListener("keydown", onWindowKeyDown);
|
||||||
};
|
};
|
||||||
}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
|
}, [getDraftThread, handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
|
||||||
|
|
||||||
const onCreateThreadClick = () => {
|
const onCreateThreadClick = () => {
|
||||||
if (state.projects.length === 0) {
|
if (state.projects.length === 0) {
|
||||||
@@ -482,14 +709,14 @@ export default function Sidebar() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const wordmark = (
|
const wordmark = (
|
||||||
<div className={`flex items-center gap-2 ${isElectron ? "-translate-y-px" : ""}`}>
|
<div className="flex items-center gap-2">
|
||||||
<SidebarTrigger className="shrink-0 md:hidden" />
|
<SidebarTrigger className="shrink-0 md:hidden" />
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-1">
|
<div className="flex min-w-0 flex-1 items-center gap-1 mt-2 ml-1">
|
||||||
<T3Wordmark />
|
<T3Wordmark />
|
||||||
<span className="truncate text-base font-medium tracking-tight text-muted-foreground">
|
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
|
||||||
Code
|
Code
|
||||||
</span>
|
</span>
|
||||||
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">
|
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
|
||||||
{APP_STAGE_LABEL}
|
{APP_STAGE_LABEL}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -511,10 +738,10 @@ export default function Sidebar() {
|
|||||||
<>
|
<>
|
||||||
{isElectron ? (
|
{isElectron ? (
|
||||||
<>
|
<>
|
||||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[88px]">
|
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
|
||||||
{wordmark}
|
{wordmark}
|
||||||
</SidebarHeader>
|
</SidebarHeader>
|
||||||
<div className="px-4 pb-2">{newThreadButton}</div>
|
<div className="px-4 py-2">{newThreadButton}</div>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
|
<SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
|
||||||
@@ -527,7 +754,7 @@ export default function Sidebar() {
|
|||||||
<SidebarGroup className="px-2 py-2">
|
<SidebarGroup className="px-2 py-2">
|
||||||
<SidebarMenu>
|
<SidebarMenu>
|
||||||
{state.projects.map((project) => {
|
{state.projects.map((project) => {
|
||||||
const threads = state.threads
|
const visibleThreads = state.threads
|
||||||
.filter((thread) => thread.projectId === project.id)
|
.filter((thread) => thread.projectId === project.id)
|
||||||
.toSorted((a, b) => {
|
.toSorted((a, b) => {
|
||||||
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||||
@@ -566,26 +793,30 @@ export default function Sidebar() {
|
|||||||
project.expanded ? "rotate-90" : ""
|
project.expanded ? "rotate-90" : ""
|
||||||
}`}
|
}`}
|
||||||
/>
|
/>
|
||||||
|
<ProjectFavicon cwd={project.cwd} />
|
||||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||||
{project.name}
|
{project.name}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
|
<span className="text-[10px] text-muted-foreground/60">
|
||||||
|
{visibleThreads.length}
|
||||||
|
</span>
|
||||||
</CollapsibleTrigger>
|
</CollapsibleTrigger>
|
||||||
|
|
||||||
<CollapsibleContent>
|
<CollapsibleContent>
|
||||||
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
|
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
|
||||||
{threads.map((thread) => {
|
{visibleThreads.map((thread) => {
|
||||||
const isActive = routeThreadId === thread.id;
|
const isActive = routeThreadId === thread.id;
|
||||||
const threadStatus = threadStatusPill(
|
const threadStatus = threadStatusPill(
|
||||||
thread,
|
thread,
|
||||||
pendingApprovalByThreadId.get(thread.id) === true,
|
pendingApprovalByThreadId.get(thread.id) === true,
|
||||||
);
|
);
|
||||||
|
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
|
||||||
const terminalStatus = terminalStatusIndicator(thread);
|
const terminalStatus = terminalStatusIndicator(thread);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarMenuSubItem key={thread.id} className="w-full">
|
<SidebarMenuSubItem key={thread.id} className="w-full">
|
||||||
<SidebarMenuSubButton
|
<SidebarMenuSubButton
|
||||||
render={<button type="button" />}
|
render={<div role="button" tabIndex={0} />}
|
||||||
size="sm"
|
size="sm"
|
||||||
isActive={isActive}
|
isActive={isActive}
|
||||||
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
|
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
|
||||||
@@ -599,6 +830,14 @@ export default function Sidebar() {
|
|||||||
params: { threadId: thread.id },
|
params: { threadId: thread.id },
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key !== "Enter" && event.key !== " ") return;
|
||||||
|
event.preventDefault();
|
||||||
|
void navigate({
|
||||||
|
to: "/$threadId",
|
||||||
|
params: { threadId: thread.id },
|
||||||
|
});
|
||||||
|
}}
|
||||||
onContextMenu={(event) => {
|
onContextMenu={(event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
void handleThreadContextMenu(thread.id, {
|
void handleThreadContextMenu(thread.id, {
|
||||||
@@ -608,6 +847,25 @@ export default function Sidebar() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
|
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
|
||||||
|
{prStatus && (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger
|
||||||
|
render={
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={prStatus.tooltip}
|
||||||
|
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
|
||||||
|
onClick={(event) => {
|
||||||
|
openPrLink(event, prStatus.url);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<GitPullRequestIcon className="size-3" />
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
{threadStatus && (
|
{threadStatus && (
|
||||||
<span
|
<span
|
||||||
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
|
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ interface TerminalViewportProps {
|
|||||||
terminalId: string;
|
terminalId: string;
|
||||||
cwd: string;
|
cwd: string;
|
||||||
runtimeEnv?: Record<string, string>;
|
runtimeEnv?: Record<string, string>;
|
||||||
|
onSessionExited: () => void;
|
||||||
focusRequestId: number;
|
focusRequestId: number;
|
||||||
autoFocus: boolean;
|
autoFocus: boolean;
|
||||||
resizeEpoch: number;
|
resizeEpoch: number;
|
||||||
@@ -123,6 +124,7 @@ function TerminalViewport({
|
|||||||
terminalId,
|
terminalId,
|
||||||
cwd,
|
cwd,
|
||||||
runtimeEnv,
|
runtimeEnv,
|
||||||
|
onSessionExited,
|
||||||
focusRequestId,
|
focusRequestId,
|
||||||
autoFocus,
|
autoFocus,
|
||||||
resizeEpoch,
|
resizeEpoch,
|
||||||
@@ -131,6 +133,12 @@ function TerminalViewport({
|
|||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
const terminalRef = useRef<Terminal | null>(null);
|
const terminalRef = useRef<Terminal | null>(null);
|
||||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||||
|
const onSessionExitedRef = useRef(onSessionExited);
|
||||||
|
const hasHandledExitRef = useRef(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onSessionExitedRef.current = onSessionExited;
|
||||||
|
}, [onSessionExited]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const mount = containerRef.current;
|
const mount = containerRef.current;
|
||||||
@@ -306,6 +314,7 @@ function TerminalViewport({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "started" || event.type === "restarted") {
|
if (event.type === "started" || event.type === "restarted") {
|
||||||
|
hasHandledExitRef.current = false;
|
||||||
activeTerminal.write("\u001bc");
|
activeTerminal.write("\u001bc");
|
||||||
if (event.snapshot.history.length > 0) {
|
if (event.snapshot.history.length > 0) {
|
||||||
activeTerminal.write(event.snapshot.history);
|
activeTerminal.write(event.snapshot.history);
|
||||||
@@ -335,6 +344,16 @@ function TerminalViewport({
|
|||||||
activeTerminal,
|
activeTerminal,
|
||||||
details.length > 0 ? `Process exited (${details})` : "Process exited",
|
details.length > 0 ? `Process exited (${details})` : "Process exited",
|
||||||
);
|
);
|
||||||
|
if (hasHandledExitRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hasHandledExitRef.current = true;
|
||||||
|
window.setTimeout(() => {
|
||||||
|
if (!hasHandledExitRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onSessionExitedRef.current();
|
||||||
|
}, 0);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -783,6 +802,7 @@ export default function ThreadTerminalDrawer({
|
|||||||
terminalId={terminalId}
|
terminalId={terminalId}
|
||||||
cwd={cwd}
|
cwd={cwd}
|
||||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||||
|
onSessionExited={() => onCloseTerminal(terminalId)}
|
||||||
focusRequestId={focusRequestId}
|
focusRequestId={focusRequestId}
|
||||||
autoFocus={terminalId === resolvedActiveTerminalId}
|
autoFocus={terminalId === resolvedActiveTerminalId}
|
||||||
resizeEpoch={resizeEpoch}
|
resizeEpoch={resizeEpoch}
|
||||||
@@ -800,6 +820,7 @@ export default function ThreadTerminalDrawer({
|
|||||||
terminalId={resolvedActiveTerminalId}
|
terminalId={resolvedActiveTerminalId}
|
||||||
cwd={cwd}
|
cwd={cwd}
|
||||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||||
|
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||||
focusRequestId={focusRequestId}
|
focusRequestId={focusRequestId}
|
||||||
autoFocus
|
autoFocus
|
||||||
resizeEpoch={resizeEpoch}
|
resizeEpoch={resizeEpoch}
|
||||||
|
|||||||
@@ -0,0 +1,350 @@
|
|||||||
|
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,11 +1,16 @@
|
|||||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||||
|
|
||||||
type Theme = "light" | "dark" | "system";
|
type Theme = "light" | "dark" | "system";
|
||||||
|
type ThemeSnapshot = {
|
||||||
|
theme: Theme;
|
||||||
|
systemDark: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
const STORAGE_KEY = "t3code:theme";
|
const STORAGE_KEY = "t3code:theme";
|
||||||
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
||||||
|
|
||||||
let listeners: Array<() => void> = [];
|
let listeners: Array<() => void> = [];
|
||||||
|
let lastSnapshot: ThemeSnapshot | null = null;
|
||||||
function emitChange() {
|
function emitChange() {
|
||||||
for (const listener of listeners) listener();
|
for (const listener of listeners) listener();
|
||||||
}
|
}
|
||||||
@@ -39,8 +44,16 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
|
|||||||
// Apply immediately on module load to prevent flash
|
// Apply immediately on module load to prevent flash
|
||||||
applyTheme(getStored());
|
applyTheme(getStored());
|
||||||
|
|
||||||
function getSnapshot(): Theme {
|
function getSnapshot(): ThemeSnapshot {
|
||||||
return getStored();
|
const theme = getStored();
|
||||||
|
const systemDark = theme === "system" ? getSystemDark() : false;
|
||||||
|
|
||||||
|
if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
|
||||||
|
return lastSnapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
lastSnapshot = { theme, systemDark };
|
||||||
|
return lastSnapshot;
|
||||||
}
|
}
|
||||||
|
|
||||||
function subscribe(listener: () => void): () => void {
|
function subscribe(listener: () => void): () => void {
|
||||||
@@ -71,10 +84,11 @@ function subscribe(listener: () => void): () => void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useTheme() {
|
export function useTheme() {
|
||||||
const theme = useSyncExternalStore(subscribe, getSnapshot);
|
const snapshot = useSyncExternalStore(subscribe, getSnapshot);
|
||||||
|
const theme = snapshot.theme;
|
||||||
|
|
||||||
const resolvedTheme: "light" | "dark" =
|
const resolvedTheme: "light" | "dark" =
|
||||||
theme === "system" ? (getSystemDark() ? "dark" : "light") : theme;
|
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
|
||||||
|
|
||||||
const setTheme = useCallback((next: Theme) => {
|
const setTheme = useCallback((next: Theme) => {
|
||||||
localStorage.setItem(STORAGE_KEY, next);
|
localStorage.setItem(STORAGE_KEY, next);
|
||||||
|
|||||||
@@ -314,6 +314,52 @@ label:has(> select#reasoning-effort) select {
|
|||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.chat-markdown .chat-markdown-codeblock {
|
||||||
|
position: relative;
|
||||||
|
margin: 0.65rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-markdown .chat-markdown-codeblock pre {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-markdown .chat-markdown-copy-button {
|
||||||
|
position: absolute;
|
||||||
|
top: 0.5rem;
|
||||||
|
right: 0.5rem;
|
||||||
|
z-index: 1;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 1.5rem;
|
||||||
|
width: 1.5rem;
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: color-mix(in srgb, var(--background) 82%, transparent);
|
||||||
|
color: var(--muted-foreground);
|
||||||
|
opacity: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
transition:
|
||||||
|
opacity 120ms ease,
|
||||||
|
color 120ms ease,
|
||||||
|
border-color 120ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-markdown .chat-markdown-codeblock:hover .chat-markdown-copy-button,
|
||||||
|
.chat-markdown .chat-markdown-codeblock:focus-within .chat-markdown-copy-button {
|
||||||
|
opacity: 1;
|
||||||
|
pointer-events: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-markdown .chat-markdown-copy-button:hover {
|
||||||
|
color: var(--foreground);
|
||||||
|
border-color: color-mix(in srgb, var(--border) 70%, var(--foreground));
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-markdown .chat-markdown-shiki .shiki {
|
||||||
|
background: color-mix(in srgb, var(--muted) 78%, var(--background)) !important;
|
||||||
|
}
|
||||||
|
|
||||||
.chat-markdown table {
|
.chat-markdown table {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
border-collapse: collapse;
|
border-collapse: collapse;
|
||||||
@@ -325,3 +371,15 @@ label:has(> select#reasoning-effort) select {
|
|||||||
padding: 0.35rem 0.45rem;
|
padding: 0.35rem 0.45rem;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Diffs theme bridge (match diff surfaces to app palette) */
|
||||||
|
.diff-panel-viewport {
|
||||||
|
background: color-mix(in srgb, var(--background) 94%, var(--card));
|
||||||
|
}
|
||||||
|
|
||||||
|
.diff-render-file {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
overflow: clip;
|
||||||
|
background: color-mix(in srgb, var(--card) 92%, var(--background));
|
||||||
|
}
|
||||||
@@ -1,9 +1,24 @@
|
|||||||
|
export const DIFF_THEME_NAMES = {
|
||||||
|
light: "pierre-light",
|
||||||
|
dark: "pierre-dark",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type DiffThemeName = (typeof DIFF_THEME_NAMES)[keyof typeof DIFF_THEME_NAMES];
|
||||||
|
|
||||||
|
export function resolveDiffThemeName(theme: "light" | "dark"): DiffThemeName {
|
||||||
|
return theme === "dark" ? DIFF_THEME_NAMES.dark : DIFF_THEME_NAMES.light;
|
||||||
|
}
|
||||||
|
|
||||||
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
|
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
|
||||||
const FNV_PRIME_32 = 0x01000193;
|
const FNV_PRIME_32 = 0x01000193;
|
||||||
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
||||||
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
||||||
|
|
||||||
function fnv1a32(input: string, seed: number, multiplier: number): number {
|
export function fnv1a32(
|
||||||
|
input: string,
|
||||||
|
seed = FNV_OFFSET_BASIS_32,
|
||||||
|
multiplier = FNV_PRIME_32,
|
||||||
|
): number {
|
||||||
let hash = seed >>> 0;
|
let hash = seed >>> 0;
|
||||||
for (let index = 0; index < input.length; index += 1) {
|
for (let index = 0; index < input.length; index += 1) {
|
||||||
hash ^= input.charCodeAt(index);
|
hash ^= input.charCodeAt(index);
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { LRUCache } from "./lruCache";
|
||||||
|
|
||||||
|
describe("LRUCache", () => {
|
||||||
|
it("returns null for missing keys", () => {
|
||||||
|
const cache = new LRUCache<string>(2, 100);
|
||||||
|
expect(cache.get("missing")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("evicts oldest by max entries", () => {
|
||||||
|
const cache = new LRUCache<string>(2, 1_000);
|
||||||
|
cache.set("a", "A", 10);
|
||||||
|
cache.set("b", "B", 10);
|
||||||
|
cache.set("c", "C", 10);
|
||||||
|
|
||||||
|
expect(cache.get("a")).toBeNull();
|
||||||
|
expect(cache.get("b")).toBe("B");
|
||||||
|
expect(cache.get("c")).toBe("C");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("promotes on get and evicts least recently used", () => {
|
||||||
|
const cache = new LRUCache<string>(2, 1_000);
|
||||||
|
cache.set("a", "A", 10);
|
||||||
|
cache.set("b", "B", 10);
|
||||||
|
expect(cache.get("a")).toBe("A");
|
||||||
|
|
||||||
|
cache.set("c", "C", 10);
|
||||||
|
expect(cache.get("a")).toBe("A");
|
||||||
|
expect(cache.get("b")).toBeNull();
|
||||||
|
expect(cache.get("c")).toBe("C");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("evicts by memory budget", () => {
|
||||||
|
const cache = new LRUCache<string>(10, 25);
|
||||||
|
cache.set("a", "A", 10);
|
||||||
|
cache.set("b", "B", 10);
|
||||||
|
cache.set("c", "C", 10);
|
||||||
|
|
||||||
|
expect(cache.get("a")).toBeNull();
|
||||||
|
expect(cache.get("b")).toBe("B");
|
||||||
|
expect(cache.get("c")).toBe("C");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
interface CacheEntry<T> {
|
||||||
|
value: T;
|
||||||
|
approximateSize: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LRUCache<T> {
|
||||||
|
private cache = new Map<string, CacheEntry<T>>();
|
||||||
|
private totalSize = 0;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly maxEntries: number,
|
||||||
|
private readonly maxMemoryBytes: number,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
get(key: string): T | null {
|
||||||
|
const entry = this.cache.get(key);
|
||||||
|
if (!entry) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.promote(key, entry);
|
||||||
|
return entry.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
set(key: string, value: T, approximateSize: number): void {
|
||||||
|
const existing = this.cache.get(key);
|
||||||
|
if (existing) {
|
||||||
|
this.totalSize -= existing.approximateSize;
|
||||||
|
this.cache.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.evictIfNeeded(approximateSize);
|
||||||
|
this.cache.set(key, { value, approximateSize });
|
||||||
|
this.totalSize += approximateSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(): void {
|
||||||
|
this.cache.clear();
|
||||||
|
this.totalSize = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private promote(key: string, entry: CacheEntry<T>): void {
|
||||||
|
this.cache.delete(key);
|
||||||
|
this.cache.set(key, entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
private evictIfNeeded(incomingSize: number): void {
|
||||||
|
while (
|
||||||
|
(this.cache.size >= this.maxEntries || this.totalSize + incomingSize > this.maxMemoryBytes) &&
|
||||||
|
this.cache.size > 0
|
||||||
|
) {
|
||||||
|
const oldestKey = this.cache.keys().next().value;
|
||||||
|
if (oldestKey === undefined) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldestEntry = this.cache.get(oldestKey);
|
||||||
|
if (oldestEntry) {
|
||||||
|
this.totalSize -= oldestEntry.approximateSize;
|
||||||
|
}
|
||||||
|
this.cache.delete(oldestKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,7 +6,6 @@ import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack
|
|||||||
import { StoreProvider } from "./store";
|
import { StoreProvider } from "./store";
|
||||||
|
|
||||||
import "@xterm/xterm/css/xterm.css";
|
import "@xterm/xterm/css/xterm.css";
|
||||||
import "highlight.js/styles/github-dark.css";
|
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
|
||||||
import { APP_DISPLAY_NAME } from "./branding";
|
import { APP_DISPLAY_NAME } from "./branding";
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import { ThreadId } from "@t3tools/contracts";
|
import { ThreadId } from "@t3tools/contracts";
|
||||||
import { Outlet, createRootRouteWithContext, type ErrorComponentProps } from "@tanstack/react-router";
|
import {
|
||||||
|
Outlet,
|
||||||
|
createRootRouteWithContext,
|
||||||
|
type ErrorComponentProps,
|
||||||
|
useNavigate,
|
||||||
|
useRouterState,
|
||||||
|
} from "@tanstack/react-router";
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
@@ -119,7 +125,12 @@ function errorDetails(error: unknown): string {
|
|||||||
function EventRouter() {
|
function EventRouter() {
|
||||||
const { dispatch } = useStore();
|
const { dispatch } = useStore();
|
||||||
const queryClient = useQueryClient();
|
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 lastConfigIssuesSignatureRef = useRef<string | null>(null);
|
||||||
|
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||||
|
pathnameRef.current = pathname;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
@@ -180,8 +191,35 @@ function EventRouter() {
|
|||||||
hasRunningSubprocess,
|
hasRunningSubprocess,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
const unsubWelcome = onServerWelcome(() => {
|
const unsubWelcome = onServerWelcome((payload) => {
|
||||||
void syncSnapshot();
|
void (async () => {
|
||||||
|
await syncSnapshot();
|
||||||
|
if (disposed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dispatch({
|
||||||
|
type: "SET_PROJECT_EXPANDED",
|
||||||
|
projectId: payload.bootstrapProjectId,
|
||||||
|
expanded: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (pathnameRef.current !== "/") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await navigate({
|
||||||
|
to: "/$threadId",
|
||||||
|
params: { threadId: payload.bootstrapThreadId },
|
||||||
|
replace: true,
|
||||||
|
});
|
||||||
|
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
|
||||||
|
})().catch(() => undefined);
|
||||||
});
|
});
|
||||||
const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
|
const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
|
||||||
const signature = JSON.stringify(payload.issues);
|
const signature = JSON.stringify(payload.issues);
|
||||||
@@ -232,7 +270,7 @@ function EventRouter() {
|
|||||||
unsubWelcome();
|
unsubWelcome();
|
||||||
unsubServerConfigUpdated();
|
unsubServerConfigUpdated();
|
||||||
};
|
};
|
||||||
}, [dispatch, queryClient]);
|
}, [dispatch, navigate, queryClient]);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { createFileRoute, useNavigate } from "@tanstack/react-router";
|
|||||||
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
|
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
|
||||||
|
|
||||||
import ChatView from "../components/ChatView";
|
import ChatView from "../components/ChatView";
|
||||||
|
import { useComposerDraftStore } from "../composerDraftStore";
|
||||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
@@ -139,6 +140,10 @@ function ChatThreadRouteView() {
|
|||||||
});
|
});
|
||||||
const search = Route.useSearch();
|
const search = Route.useSearch();
|
||||||
const threadExists = state.threads.some((thread) => thread.id === threadId);
|
const threadExists = state.threads.some((thread) => thread.id === threadId);
|
||||||
|
const draftThreadExists = useComposerDraftStore(
|
||||||
|
(store) => Object.hasOwn(store.draftThreadsByThreadId, threadId),
|
||||||
|
);
|
||||||
|
const routeThreadExists = threadExists || draftThreadExists;
|
||||||
const diffOpen = search.diff === "1";
|
const diffOpen = search.diff === "1";
|
||||||
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
|
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
|
||||||
const closeDiff = useCallback(() => {
|
const closeDiff = useCallback(() => {
|
||||||
@@ -166,20 +171,20 @@ function ChatThreadRouteView() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!threadExists) {
|
if (!routeThreadExists) {
|
||||||
void navigate({ to: "/", replace: true });
|
void navigate({ to: "/", replace: true });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}, [navigate, state.threadsHydrated, threadExists, threadId]);
|
}, [navigate, routeThreadExists, state.threadsHydrated, threadId]);
|
||||||
|
|
||||||
if (!state.threadsHydrated || !threadExists) {
|
if (!state.threadsHydrated || !routeThreadExists) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!shouldUseDiffSheet) {
|
if (!shouldUseDiffSheet) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||||
<ChatView threadId={threadId} />
|
<ChatView threadId={threadId} />
|
||||||
</SidebarInset>
|
</SidebarInset>
|
||||||
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
|
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
|
||||||
@@ -189,7 +194,7 @@ function ChatThreadRouteView() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||||
<ChatView threadId={threadId} />
|
<ChatView threadId={threadId} />
|
||||||
</SidebarInset>
|
</SidebarInset>
|
||||||
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { createFileRoute } from "@tanstack/react-router";
|
import { createFileRoute } from "@tanstack/react-router";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { useCallback, useState } from "react";
|
import { useCallback, useState } from "react";
|
||||||
|
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||||
|
|
||||||
import { useAppSettings } from "../appSettings";
|
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||||
import { isElectron } from "../env";
|
import { isElectron } from "../env";
|
||||||
import { useTheme } from "../hooks/useTheme";
|
import { useTheme } from "../hooks/useTheme";
|
||||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||||
@@ -52,9 +53,12 @@ function SettingsRouteView() {
|
|||||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||||
|
const [customModelInput, setCustomModelInput] = useState("");
|
||||||
|
const [customModelError, setCustomModelError] = useState<string | null>(null);
|
||||||
|
|
||||||
const codexBinaryPath = settings.codexBinaryPath;
|
const codexBinaryPath = settings.codexBinaryPath;
|
||||||
const codexHomePath = settings.codexHomePath;
|
const codexHomePath = settings.codexHomePath;
|
||||||
|
const customCodexModels = settings.customCodexModels;
|
||||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||||
|
|
||||||
const openKeybindingsFile = useCallback(() => {
|
const openKeybindingsFile = useCallback(() => {
|
||||||
@@ -74,6 +78,42 @@ function SettingsRouteView() {
|
|||||||
});
|
});
|
||||||
}, [keybindingsConfigPath]);
|
}, [keybindingsConfigPath]);
|
||||||
|
|
||||||
|
const addCustomModel = useCallback(() => {
|
||||||
|
const normalized = normalizeModelSlug(customModelInput);
|
||||||
|
if (!normalized) {
|
||||||
|
setCustomModelError("Enter a model slug.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (MODEL_OPTIONS.some((option) => option.slug === normalized)) {
|
||||||
|
setCustomModelError("That model is already built in.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {
|
||||||
|
setCustomModelError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (customCodexModels.includes(normalized)) {
|
||||||
|
setCustomModelError("That custom model is already saved.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateSettings({
|
||||||
|
customCodexModels: [...customCodexModels, normalized],
|
||||||
|
});
|
||||||
|
setCustomModelInput("");
|
||||||
|
setCustomModelError(null);
|
||||||
|
}, [customCodexModels, customModelInput, updateSettings]);
|
||||||
|
|
||||||
|
const removeCustomModel = useCallback(
|
||||||
|
(slug: string) => {
|
||||||
|
updateSettings({
|
||||||
|
customCodexModels: customCodexModels.filter((model) => model !== slug),
|
||||||
|
});
|
||||||
|
setCustomModelError(null);
|
||||||
|
},
|
||||||
|
[customCodexModels, updateSettings],
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||||
@@ -193,6 +233,96 @@ function SettingsRouteView() {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section className="rounded-2xl border border-border bg-card p-5">
|
||||||
|
<div className="mb-4">
|
||||||
|
<h2 className="text-sm font-medium text-foreground">Models</h2>
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">
|
||||||
|
Save additional Codex model slugs so they appear in the chat model picker.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<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
|
||||||
|
value={customModelInput}
|
||||||
|
onChange={(event) => {
|
||||||
|
setCustomModelInput(event.target.value);
|
||||||
|
if (customModelError) {
|
||||||
|
setCustomModelError(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder="your-model-slug"
|
||||||
|
spellCheck={false}
|
||||||
|
/>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
Example: <code>gpt-6.7-codex-ultra-preview</code>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<Button className="sm:mt-6" type="submit">
|
||||||
|
Add model
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{customModelError ? (
|
||||||
|
<p className="text-xs text-destructive">{customModelError}</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||||
|
<p>Saved custom models: {customCodexModels.length}</p>
|
||||||
|
{customCodexModels.length > 0 ? (
|
||||||
|
<Button
|
||||||
|
size="xs"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
updateSettings({
|
||||||
|
customCodexModels: defaults.customCodexModels,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Reset custom models
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{customCodexModels.length > 0 ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{customCodexModels.map((slug) => (
|
||||||
|
<div
|
||||||
|
key={slug}
|
||||||
|
className="flex items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2"
|
||||||
|
>
|
||||||
|
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
|
||||||
|
{slug}
|
||||||
|
</code>
|
||||||
|
<Button
|
||||||
|
size="xs"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => removeCustomModel(slug)}
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="rounded-lg border border-dashed border-border bg-background px-3 py-4 text-xs text-muted-foreground">
|
||||||
|
No custom models saved yet.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section className="rounded-2xl border border-border bg-card p-5">
|
<section className="rounded-2xl border border-border bg-card p-5">
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
|
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
|
import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { derivePendingApprovals, deriveWorkLogEntries } from "./session-logic";
|
import {
|
||||||
|
derivePendingApprovals,
|
||||||
|
deriveWorkLogEntries,
|
||||||
|
hasToolActivityForTurn,
|
||||||
|
isLatestTurnSettled,
|
||||||
|
} from "./session-logic";
|
||||||
|
|
||||||
function makeActivity(overrides: {
|
function makeActivity(overrides: {
|
||||||
id?: string;
|
id?: string;
|
||||||
@@ -126,3 +131,72 @@ describe("deriveWorkLogEntries", () => {
|
|||||||
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
|
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("hasToolActivityForTurn", () => {
|
||||||
|
it("returns false when turn id is missing", () => {
|
||||||
|
const activities: OrchestrationThreadActivity[] = [
|
||||||
|
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(hasToolActivityForTurn(activities, undefined)).toBe(false);
|
||||||
|
expect(hasToolActivityForTurn(activities, null)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns true only for matching tool activity in the target turn", () => {
|
||||||
|
const activities: OrchestrationThreadActivity[] = [
|
||||||
|
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
|
||||||
|
makeActivity({ id: "info-1", turnId: "turn-2", kind: "turn.completed", tone: "info" }),
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(hasToolActivityForTurn(activities, TurnId.makeUnsafe("turn-1"))).toBe(true);
|
||||||
|
expect(hasToolActivityForTurn(activities, TurnId.makeUnsafe("turn-2"))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("isLatestTurnSettled", () => {
|
||||||
|
const latestTurn = {
|
||||||
|
turnId: TurnId.makeUnsafe("turn-1"),
|
||||||
|
startedAt: "2026-02-27T21:10:00.000Z",
|
||||||
|
completedAt: "2026-02-27T21:10:06.000Z",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
it("returns false while the same turn is still active in a running session", () => {
|
||||||
|
expect(
|
||||||
|
isLatestTurnSettled(latestTurn, {
|
||||||
|
orchestrationStatus: "running",
|
||||||
|
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false while any turn is running to avoid stale latest-turn banners", () => {
|
||||||
|
expect(
|
||||||
|
isLatestTurnSettled(latestTurn, {
|
||||||
|
orchestrationStatus: "running",
|
||||||
|
activeTurnId: TurnId.makeUnsafe("turn-2"),
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns true once the session is no longer running that turn", () => {
|
||||||
|
expect(
|
||||||
|
isLatestTurnSettled(latestTurn, {
|
||||||
|
orchestrationStatus: "ready",
|
||||||
|
activeTurnId: undefined,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false when turn timestamps are incomplete", () => {
|
||||||
|
expect(
|
||||||
|
isLatestTurnSettled(
|
||||||
|
{
|
||||||
|
turnId: TurnId.makeUnsafe("turn-1"),
|
||||||
|
startedAt: null,
|
||||||
|
completedAt: "2026-02-27T21:10:06.000Z",
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
|
type OrchestrationLatestTurn,
|
||||||
type OrchestrationThreadActivity,
|
type OrchestrationThreadActivity,
|
||||||
type ProviderKind,
|
type ProviderKind,
|
||||||
type TurnId,
|
type TurnId,
|
||||||
@@ -75,6 +76,17 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str
|
|||||||
return formatDuration(endedAt - startedAt);
|
return formatDuration(endedAt - startedAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isLatestTurnSettled(
|
||||||
|
latestTurn: Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt"> | null,
|
||||||
|
session: Pick<ThreadSession, "orchestrationStatus" | "activeTurnId"> | null,
|
||||||
|
): boolean {
|
||||||
|
if (!latestTurn?.startedAt) return false;
|
||||||
|
if (!latestTurn.completedAt) return false;
|
||||||
|
if (!session) return true;
|
||||||
|
if (session.orchestrationStatus === "running") return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
export function derivePendingApprovals(
|
export function derivePendingApprovals(
|
||||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||||
): PendingApproval[] {
|
): PendingApproval[] {
|
||||||
@@ -147,6 +159,14 @@ export function deriveWorkLogEntries(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function hasToolActivityForTurn(
|
||||||
|
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||||
|
turnId: TurnId | null | undefined,
|
||||||
|
): boolean {
|
||||||
|
if (!turnId) return false;
|
||||||
|
return activities.some((activity) => activity.turnId === turnId && activity.tone === "tool");
|
||||||
|
}
|
||||||
|
|
||||||
export function deriveTimelineEntries(
|
export function deriveTimelineEntries(
|
||||||
messages: ChatMessage[],
|
messages: ChatMessage[],
|
||||||
workEntries: WorkLogEntry[],
|
workEntries: WorkLogEntry[],
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { reducer, type AppState } from "./store";
|
import { reducer, type AppState } from "./store";
|
||||||
@@ -29,6 +29,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
|||||||
activities: [],
|
activities: [],
|
||||||
error: null,
|
error: null,
|
||||||
createdAt: "2026-02-13T00:00:00.000Z",
|
createdAt: "2026-02-13T00:00:00.000Z",
|
||||||
|
latestTurn: null,
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
...overrides,
|
...overrides,
|
||||||
@@ -58,7 +59,14 @@ describe("store reducer", () => {
|
|||||||
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
|
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
|
||||||
const initialState = makeState(
|
const initialState = makeState(
|
||||||
makeThread({
|
makeThread({
|
||||||
latestTurnCompletedAt,
|
latestTurn: {
|
||||||
|
turnId: TurnId.makeUnsafe("turn-1"),
|
||||||
|
state: "completed",
|
||||||
|
requestedAt: "2026-02-25T12:28:00.000Z",
|
||||||
|
startedAt: "2026-02-25T12:28:30.000Z",
|
||||||
|
completedAt: latestTurnCompletedAt,
|
||||||
|
assistantMessageId: null,
|
||||||
|
},
|
||||||
lastVisitedAt: "2026-02-25T12:35:00.000Z",
|
lastVisitedAt: "2026-02-25T12:35:00.000Z",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -79,7 +87,7 @@ describe("store reducer", () => {
|
|||||||
it("does not change a thread without a completed turn", () => {
|
it("does not change a thread without a completed turn", () => {
|
||||||
const initialState = makeState(
|
const initialState = makeState(
|
||||||
makeThread({
|
makeThread({
|
||||||
latestTurnCompletedAt: undefined,
|
latestTurn: null,
|
||||||
lastVisitedAt: "2026-02-25T12:35:00.000Z",
|
lastVisitedAt: "2026-02-25T12:35:00.000Z",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
+56
-22
@@ -41,6 +41,7 @@ type Action =
|
|||||||
terminalId: string;
|
terminalId: string;
|
||||||
hasRunningSubprocess: boolean;
|
hasRunningSubprocess: boolean;
|
||||||
}
|
}
|
||||||
|
| { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
|
||||||
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
|
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
|
||||||
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
|
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
|
||||||
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
|
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
|
||||||
@@ -191,6 +192,47 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
|
|||||||
return providerName === "claudeCode" ? "claudeCode" : "codex";
|
return providerName === "claudeCode" ? "claudeCode" : "codex";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function resolveWsHttpOrigin(): string {
|
||||||
|
if (typeof window === "undefined") {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||||
|
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||||
|
const wsCandidate =
|
||||||
|
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||||
|
? bridgeWsUrl
|
||||||
|
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||||
|
? envWsUrl
|
||||||
|
: null;
|
||||||
|
if (!wsCandidate) {
|
||||||
|
return window.location.origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const wsUrl = new URL(wsCandidate);
|
||||||
|
const protocol =
|
||||||
|
wsUrl.protocol === "wss:"
|
||||||
|
? "https:"
|
||||||
|
: wsUrl.protocol === "ws:"
|
||||||
|
? "http:"
|
||||||
|
: wsUrl.protocol;
|
||||||
|
return `${protocol}//${wsUrl.host}`;
|
||||||
|
} catch {
|
||||||
|
return window.location.origin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toAttachmentPreviewUrl(rawUrl: string): string {
|
||||||
|
if (rawUrl.startsWith("/")) {
|
||||||
|
return `${resolveWsHttpOrigin()}${rawUrl}`;
|
||||||
|
}
|
||||||
|
return rawUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
function attachmentPreviewRoutePath(attachmentId: string): string {
|
||||||
|
return `/attachments/${encodeURIComponent(attachmentId)}`;
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||||
@@ -413,19 +455,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
.filter((thread) => thread.deletedAt === null)
|
.filter((thread) => thread.deletedAt === null)
|
||||||
.map((thread) => {
|
.map((thread) => {
|
||||||
const existing = existingThreadById.get(thread.id);
|
const existing = existingThreadById.get(thread.id);
|
||||||
const latestTurnStartedAt =
|
|
||||||
thread.latestTurnId === null
|
|
||||||
? undefined
|
|
||||||
: thread.messages.find(
|
|
||||||
(message) => message.turnId === thread.latestTurnId && message.role === "user",
|
|
||||||
)?.createdAt;
|
|
||||||
const latestTurnCompletedAt = thread.checkpoints.find(
|
|
||||||
(checkpoint) => checkpoint.turnId === thread.latestTurnId,
|
|
||||||
)?.completedAt;
|
|
||||||
const latestTurnDurationMs =
|
|
||||||
latestTurnStartedAt && latestTurnCompletedAt
|
|
||||||
? Math.max(0, Date.parse(latestTurnCompletedAt) - Date.parse(latestTurnStartedAt))
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
return normalizeThreadTerminals({
|
return normalizeThreadTerminals({
|
||||||
id: thread.id,
|
id: thread.id,
|
||||||
@@ -462,13 +491,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
messages: thread.messages.map((message) => {
|
messages: thread.messages.map((message) => {
|
||||||
const attachments = message.attachments?.map((attachment, index) => ({
|
const attachments = message.attachments?.map((attachment) => ({
|
||||||
type: "image" as const,
|
type: "image" as const,
|
||||||
id: `${message.id}:${index}`,
|
id: attachment.id,
|
||||||
name: attachment.name,
|
name: attachment.name,
|
||||||
mimeType: attachment.mimeType,
|
mimeType: attachment.mimeType,
|
||||||
sizeBytes: attachment.sizeBytes,
|
sizeBytes: attachment.sizeBytes,
|
||||||
previewUrl: attachment.dataUrl,
|
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
|
||||||
}));
|
}));
|
||||||
const normalizedMessage: ChatMessage = {
|
const normalizedMessage: ChatMessage = {
|
||||||
id: message.id,
|
id: message.id,
|
||||||
@@ -483,10 +512,7 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
}),
|
}),
|
||||||
error: thread.session?.lastError ?? null,
|
error: thread.session?.lastError ?? null,
|
||||||
createdAt: thread.createdAt,
|
createdAt: thread.createdAt,
|
||||||
latestTurnId: thread.latestTurnId ?? undefined,
|
latestTurn: thread.latestTurn,
|
||||||
latestTurnStartedAt,
|
|
||||||
latestTurnCompletedAt,
|
|
||||||
latestTurnDurationMs,
|
|
||||||
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
||||||
branch: thread.branch,
|
branch: thread.branch,
|
||||||
worktreePath: thread.worktreePath,
|
worktreePath: thread.worktreePath,
|
||||||
@@ -536,10 +562,10 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||||
if (!thread.latestTurnCompletedAt) {
|
if (!thread.latestTurn?.completedAt) {
|
||||||
return thread;
|
return thread;
|
||||||
}
|
}
|
||||||
const latestTurnCompletedAtMs = Date.parse(thread.latestTurnCompletedAt);
|
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
|
||||||
if (Number.isNaN(latestTurnCompletedAtMs)) {
|
if (Number.isNaN(latestTurnCompletedAtMs)) {
|
||||||
return thread;
|
return thread;
|
||||||
}
|
}
|
||||||
@@ -571,6 +597,14 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
case "SET_PROJECT_EXPANDED":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
projects: state.projects.map((p) =>
|
||||||
|
p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
case "TOGGLE_THREAD_TERMINAL":
|
case "TOGGLE_THREAD_TERMINAL":
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type {
|
import type {
|
||||||
|
OrchestrationLatestTurn,
|
||||||
OrchestrationSessionStatus,
|
OrchestrationSessionStatus,
|
||||||
OrchestrationThreadActivity,
|
OrchestrationThreadActivity,
|
||||||
ProjectScript as ContractProjectScript,
|
ProjectScript as ContractProjectScript,
|
||||||
@@ -89,10 +90,7 @@ export interface Thread {
|
|||||||
messages: ChatMessage[];
|
messages: ChatMessage[];
|
||||||
error: string | null;
|
error: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
latestTurnId?: TurnId | undefined;
|
latestTurn: OrchestrationLatestTurn | null;
|
||||||
latestTurnStartedAt?: string | undefined;
|
|
||||||
latestTurnCompletedAt?: string | undefined;
|
|
||||||
latestTurnDurationMs?: number | undefined;
|
|
||||||
lastVisitedAt?: string | undefined;
|
lastVisitedAt?: string | undefined;
|
||||||
branch: string | null;
|
branch: string | null;
|
||||||
worktreePath: string | null;
|
worktreePath: string | null;
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
|||||||
activities: [],
|
activities: [],
|
||||||
error: null,
|
error: null,
|
||||||
createdAt: "2026-02-13T00:00:00.000Z",
|
createdAt: "2026-02-13T00:00:00.000Z",
|
||||||
|
latestTurn: null,
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
...overrides,
|
...overrides,
|
||||||
@@ -87,16 +88,16 @@ describe("getOrphanedWorktreePathForThread", () => {
|
|||||||
describe("formatWorktreePathForDisplay", () => {
|
describe("formatWorktreePathForDisplay", () => {
|
||||||
it("shows only the last path segment for unix-like paths", () => {
|
it("shows only the last path segment for unix-like paths", () => {
|
||||||
const result = formatWorktreePathForDisplay(
|
const result = formatWorktreePathForDisplay(
|
||||||
"/Users/julius/.t3/worktrees/codething-mvp/codething-4e609bb8",
|
"/Users/julius/.t3/worktrees/t3code-mvp/t3code-4e609bb8",
|
||||||
);
|
);
|
||||||
expect(result).toBe("codething-4e609bb8");
|
expect(result).toBe("t3code-4e609bb8");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("normalizes windows separators before selecting the final segment", () => {
|
it("normalizes windows separators before selecting the final segment", () => {
|
||||||
const result = formatWorktreePathForDisplay(
|
const result = formatWorktreePathForDisplay(
|
||||||
"C:\\Users\\julius\\.t3\\worktrees\\codething-mvp\\codething-4e609bb8",
|
"C:\\Users\\julius\\.t3\\worktrees\\t3code-mvp\\t3code-4e609bb8",
|
||||||
);
|
);
|
||||||
expect(result).toBe("codething-4e609bb8");
|
expect(result).toBe("t3code-4e609bb8");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uses the final segment even when outside ~/.t3/worktrees", () => {
|
it("uses the final segment even when outside ~/.t3/worktrees", () => {
|
||||||
|
|||||||
@@ -65,16 +65,41 @@ describe("wsNativeApi", () => {
|
|||||||
emitPush(WS_CHANNELS.serverWelcome, payload);
|
emitPush(WS_CHANNELS.serverWelcome, payload);
|
||||||
|
|
||||||
expect(listener).toHaveBeenCalledTimes(1);
|
expect(listener).toHaveBeenCalledTimes(1);
|
||||||
expect(listener).toHaveBeenCalledWith(payload);
|
expect(listener).toHaveBeenCalledWith(expect.objectContaining(payload));
|
||||||
|
|
||||||
const lateListener = vi.fn();
|
const lateListener = vi.fn();
|
||||||
onServerWelcome(lateListener);
|
onServerWelcome(lateListener);
|
||||||
|
|
||||||
expect(lateListener).toHaveBeenCalledTimes(1);
|
expect(lateListener).toHaveBeenCalledTimes(1);
|
||||||
expect(lateListener).toHaveBeenCalledWith(payload);
|
expect(lateListener).toHaveBeenCalledWith(expect.objectContaining(payload));
|
||||||
expect(warnSpy).not.toHaveBeenCalled();
|
expect(warnSpy).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("preserves bootstrap ids from server.welcome payloads", async () => {
|
||||||
|
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
||||||
|
|
||||||
|
createWsNativeApi();
|
||||||
|
const listener = vi.fn();
|
||||||
|
onServerWelcome(listener);
|
||||||
|
|
||||||
|
emitPush(WS_CHANNELS.serverWelcome, {
|
||||||
|
cwd: "/tmp/workspace",
|
||||||
|
projectName: "t3-code",
|
||||||
|
bootstrapProjectId: "project-1",
|
||||||
|
bootstrapThreadId: "thread-1",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(listener).toHaveBeenCalledTimes(1);
|
||||||
|
expect(listener).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
cwd: "/tmp/workspace",
|
||||||
|
projectName: "t3-code",
|
||||||
|
bootstrapProjectId: "project-1",
|
||||||
|
bootstrapThreadId: "thread-1",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it("ignores invalid server.welcome payloads and keeps subscription active", async () => {
|
it("ignores invalid server.welcome payloads and keeps subscription active", async () => {
|
||||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||||
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
||||||
@@ -87,7 +112,9 @@ describe("wsNativeApi", () => {
|
|||||||
emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" });
|
emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" });
|
||||||
|
|
||||||
expect(listener).toHaveBeenCalledTimes(1);
|
expect(listener).toHaveBeenCalledTimes(1);
|
||||||
expect(listener).toHaveBeenCalledWith({ cwd: "/tmp/workspace", projectName: "t3-code" });
|
expect(listener).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ cwd: "/tmp/workspace", projectName: "t3-code" }),
|
||||||
|
);
|
||||||
expect(warnSpy).toHaveBeenCalledTimes(1);
|
expect(warnSpy).toHaveBeenCalledTimes(1);
|
||||||
expect(warnSpy).toHaveBeenCalledWith("Dropped inbound WebSocket push payload", {
|
expect(warnSpy).toHaveBeenCalledWith("Dropped inbound WebSocket push payload", {
|
||||||
reason: "decode-failed",
|
reason: "decode-failed",
|
||||||
|
|||||||
@@ -153,10 +153,9 @@ export function createWsNativeApi(): NativeApi {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const popup = window.open(url, "_blank", "noopener,noreferrer");
|
// Some mobile browsers can return null here even when the tab opens.
|
||||||
if (!popup) {
|
// Avoid false negatives and let the browser handle popup policy.
|
||||||
throw new Error("Unable to open link. Allow popups and try again.");
|
window.open(url, "_blank", "noopener,noreferrer");
|
||||||
}
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
git: {
|
git: {
|
||||||
|
|||||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user